Skip to main content

quiche/stream/
recv_buf.rs

1// Copyright (C) 2023, Cloudflare, Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright notice,
9//       this list of conditions and the following disclaimer.
10//
11//     * Redistributions in binary form must reproduce the above copyright
12//       notice, this list of conditions and the following disclaimer in the
13//       documentation and/or other materials provided with the distribution.
14//
15// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
16// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
17// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
19// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
23// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
24// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26
27use std::cmp;
28
29use std::collections::BTreeMap;
30use std::collections::VecDeque;
31
32use std::time::Duration;
33use std::time::Instant;
34
35use crate::stream::RecvAction;
36use crate::stream::RecvBufResetReturn;
37use crate::Error;
38use crate::Result;
39
40use crate::flowcontrol;
41
42use crate::range_buf::RangeBuf;
43
44/// Receive-side stream buffer.
45///
46/// Stream data received by the peer is buffered in a list of data chunks
47/// ordered by offset in ascending order. Contiguous data can then be read
48/// into a slice.
49#[derive(Debug, Default)]
50pub struct RecvBuf {
51    /// Chunks of data received from the peer that have not yet been read by
52    /// the application, ordered by offset.
53    data: BTreeMap<u64, RangeBuf>,
54
55    /// The lowest data offset that has yet to be read by the application.
56    off: u64,
57
58    /// The total length of data received on this stream.
59    len: u64,
60
61    /// Receiver flow controller.
62    flow_control: flowcontrol::FlowControl,
63
64    /// The final stream offset received from the peer, if any.
65    fin_off: Option<u64>,
66
67    /// The error code received via RESET_STREAM.
68    error: Option<u64>,
69
70    /// Whether incoming data is validated but not buffered.
71    drain: bool,
72}
73
74impl RecvBuf {
75    /// Creates a new receive buffer.
76    pub fn new(max_data: u64, initial_window: u64, max_window: u64) -> RecvBuf {
77        RecvBuf {
78            flow_control: flowcontrol::FlowControl::new(
79                max_data,
80                initial_window,
81                max_window,
82            ),
83            ..RecvBuf::default()
84        }
85    }
86
87    /// Inserts the given chunk of data in the buffer.
88    ///
89    /// This also takes care of enforcing stream flow control limits, as well
90    /// as handling incoming data that overlaps data that is already in the
91    /// buffer.
92    pub fn write(&mut self, buf: RangeBuf) -> Result<()> {
93        if buf.max_off() > self.max_data() {
94            return Err(Error::FlowControl);
95        }
96
97        if let Some(fin_off) = self.fin_off {
98            // Stream's size is known, forbid data beyond that point.
99            if buf.max_off() > fin_off {
100                return Err(Error::FinalSize);
101            }
102
103            // Stream's size is already known, forbid changing it.
104            if buf.fin() && fin_off != buf.max_off() {
105                return Err(Error::FinalSize);
106            }
107        }
108
109        // Stream's known size is lower than data already received.
110        if buf.fin() && buf.max_off() < self.len {
111            return Err(Error::FinalSize);
112        }
113
114        // We already saved the final offset, so there's nothing else we
115        // need to keep from the RangeBuf if it's empty.
116        if self.fin_off.is_some() && buf.is_empty() {
117            return Ok(());
118        }
119
120        if buf.fin() {
121            self.fin_off = Some(buf.max_off());
122        }
123
124        // No need to store empty buffer that doesn't carry the fin flag.
125        if !buf.fin() && buf.is_empty() {
126            return Ok(());
127        }
128
129        // Check if data is fully duplicate, that is the buffer's max offset is
130        // lower or equal to the offset already stored in the recv buffer.
131        if self.off >= buf.max_off() {
132            // An exception is applied to empty range buffers, because an empty
133            // buffer's max offset matches the max offset of the recv buffer.
134            //
135            // By this point all spurious empty buffers should have already been
136            // discarded, so allowing empty buffers here should be safe.
137            if !buf.is_empty() {
138                return Ok(());
139            }
140        }
141
142        let mut tmp_bufs = VecDeque::with_capacity(2);
143        tmp_bufs.push_back(buf);
144
145        'tmp: while let Some(mut buf) = tmp_bufs.pop_front() {
146            // Discard incoming data below current stream offset. Bytes up to
147            // `self.off` have already been received so we should not buffer
148            // them again. This is also important to make sure `ready()` doesn't
149            // get stuck when a buffer with lower offset than the stream's is
150            // buffered.
151            if self.off_front() > buf.off() {
152                buf = buf.split_off((self.off_front() - buf.off()) as usize);
153            }
154
155            // Handle overlapping data. If the incoming data's starting offset
156            // is above the previous maximum received offset, there is clearly
157            // no overlap so this logic can be skipped. However do still try to
158            // merge an empty final buffer (i.e. an empty buffer with the fin
159            // flag set, which is the only kind of empty buffer that should
160            // reach this point).
161            if buf.off() < self.max_off() || buf.is_empty() {
162                for (_, b) in self.data.range(buf.off()..) {
163                    let off = buf.off();
164
165                    // We are past the current buffer.
166                    if b.off() > buf.max_off() {
167                        break;
168                    }
169
170                    // New buffer is fully contained in existing buffer.
171                    if off >= b.off() && buf.max_off() <= b.max_off() {
172                        continue 'tmp;
173                    }
174
175                    // New buffer's start overlaps existing buffer.
176                    if off >= b.off() && off < b.max_off() {
177                        buf = buf.split_off((b.max_off() - off) as usize);
178                    }
179
180                    // New buffer's end overlaps existing buffer.
181                    if off < b.off() && buf.max_off() > b.off() {
182                        tmp_bufs
183                            .push_back(buf.split_off((b.off() - off) as usize));
184                    }
185                }
186            }
187
188            self.len = cmp::max(self.len, buf.max_off());
189
190            if !self.drain {
191                self.data.insert(buf.max_off(), buf);
192            } else {
193                // we are not storing any data, off == len
194                self.off = self.len;
195            }
196        }
197
198        Ok(())
199    }
200
201    /// Reads contiguous data from the receive buffer.
202    ///
203    /// Data is written into the given `out` buffer, up to the length of `out`.
204    ///
205    /// Only contiguous data is removed, starting from offset 0. The offset is
206    /// incremented as data is taken out of the receive buffer. If there is no
207    /// data at the expected read offset, the `Done` error is returned.
208    ///
209    /// On success the amount of data read and a flag indicating
210    /// if there is no more data in the buffer, are returned as a tuple.
211    #[inline]
212    pub fn emit(&mut self, mut out: &mut [u8]) -> Result<(usize, bool)> {
213        self.emit_or_discard(RecvAction::Emit { out: &mut out })
214    }
215
216    /// Reads or discards contiguous data from the receive buffer.
217    ///
218    /// Passing an `action` of `StreamRecvAction::Emit` results in data being
219    /// written into the provided buffer, up to its length.
220    ///
221    /// Passing an `action` of `StreamRecvAction::Discard` results in up to
222    /// the indicated number of bytes being discarded without copying.
223    ///
224    /// Only contiguous data is removed, starting from offset 0. The offset is
225    /// incremented as data is taken out of the receive buffer. If there is no
226    /// data at the expected read offset, the `Done` error is returned.
227    ///
228    /// On success the amount of data read or discarded, and a flag indicating
229    /// if there is no more data in the buffer, are returned as a tuple.
230    pub fn emit_or_discard<B: bytes::BufMut>(
231        &mut self, mut action: RecvAction<B>,
232    ) -> Result<(usize, bool)> {
233        let mut len = 0;
234        let mut cap = match &action {
235            RecvAction::Emit { out } => out.remaining_mut(),
236            RecvAction::Discard { len } => *len,
237        };
238
239        if !self.ready() {
240            return Err(Error::Done);
241        }
242
243        // The stream was reset, so clear its data and return the error code
244        // instead.
245        if let Some(e) = self.error {
246            self.data.clear();
247            return Err(Error::StreamReset(e));
248        }
249
250        while cap > 0 && self.ready() {
251            let mut entry = match self.data.first_entry() {
252                Some(entry) => entry,
253                None => break,
254            };
255
256            let buf = entry.get_mut();
257
258            let buf_len = cmp::min(buf.len(), cap);
259
260            // Only copy data if we're emitting, not discarding.
261            if let RecvAction::Emit { ref mut out } = action {
262                // Note: `BufMut::remaining_mut()` cannot "shrink", but BufMut
263                // impls are allowed to grow the buffer, so we
264                // check here that we still have at least
265                // `cap` bytes, but we can't require equality
266                debug_assert!(
267                    cap <= out.remaining_mut(),
268                    "We updated `cap` incorrectly"
269                );
270                out.put_slice(&buf[..buf_len])
271            }
272
273            self.off += buf_len as u64;
274
275            len += buf_len;
276            cap -= buf_len;
277
278            if buf_len < buf.len() {
279                buf.consume(buf_len);
280
281                // We reached the maximum capacity, so end here.
282                break;
283            }
284
285            entry.remove();
286        }
287
288        // Update consumed bytes for flow control.
289        self.flow_control.add_consumed(len as u64);
290
291        Ok((len, self.is_fin()))
292    }
293
294    /// Resets the stream at the given offset.
295    pub fn reset(
296        &mut self, error_code: u64, final_size: u64,
297    ) -> Result<RecvBufResetReturn> {
298        // Stream's size is already known, forbid changing it.
299        if let Some(fin_off) = self.fin_off {
300            if fin_off != final_size {
301                return Err(Error::FinalSize);
302            }
303        }
304
305        // Stream's known size is lower than data already received.
306        if final_size < self.len {
307            return Err(Error::FinalSize);
308        }
309
310        if self.error.is_some() {
311            // We already verified that the final size matches
312            return Ok(RecvBufResetReturn::zero());
313        }
314
315        // Calculate how many bytes need to be removed from the connection flow
316        // control.
317        let result = RecvBufResetReturn {
318            max_data_delta: final_size - self.len,
319            consumed_flowcontrol: final_size - self.off,
320        };
321
322        self.error = Some(error_code);
323
324        // Clear all data already buffered.
325        self.off = final_size;
326
327        self.data.clear();
328
329        // In order to ensure the application is notified when the stream is
330        // reset, enqueue a zero-length buffer at the final size offset.
331        let buf = RangeBuf::from(b"", final_size, true);
332        self.write(buf)?;
333
334        Ok(result)
335    }
336
337    /// Commits the new max_data limit.
338    pub fn update_max_data(&mut self, now: Instant) {
339        self.flow_control.update_max_data(now);
340    }
341
342    /// Return the new max_data limit.
343    pub fn max_data_next(&mut self) -> u64 {
344        self.flow_control.max_data_next()
345    }
346
347    /// Return the current flow control limit.
348    pub fn max_data(&self) -> u64 {
349        self.flow_control.max_data()
350    }
351
352    /// Return the current window.
353    pub fn window(&self) -> u64 {
354        self.flow_control.window()
355    }
356
357    /// Autotune the window size.
358    pub fn autotune_window(&mut self, now: Instant, rtt: Duration) {
359        self.flow_control.autotune_window(now, rtt);
360    }
361
362    /// Shuts down receiving data and returns the number of bytes
363    /// that should be returned to the connection level flow
364    /// control
365    pub fn shutdown(&mut self) -> Result<u64> {
366        if self.drain {
367            return Err(Error::Done);
368        }
369
370        self.drain = true;
371
372        self.data.clear();
373
374        let consumed = self.max_off() - self.off;
375        self.off = self.max_off();
376
377        Ok(consumed)
378    }
379
380    /// Returns the lowest offset of data buffered.
381    pub fn off_front(&self) -> u64 {
382        self.off
383    }
384
385    /// Returns true if we need to update the local flow control limit.
386    pub fn almost_full(&self) -> bool {
387        self.fin_off.is_none() && self.flow_control.should_update_max_data()
388    }
389
390    /// Returns the largest offset ever received.
391    pub fn max_off(&self) -> u64 {
392        self.len
393    }
394
395    /// Returns true if the receive-side of the stream is complete.
396    ///
397    /// This happens when the stream's receive final size is known, and the
398    /// application has read all data from the stream.
399    pub fn is_fin(&self) -> bool {
400        if self.fin_off == Some(self.off) {
401            return true;
402        }
403
404        false
405    }
406
407    /// Returns true if the stream is not storing incoming data.
408    pub fn is_draining(&self) -> bool {
409        self.drain
410    }
411
412    /// Returns true if the stream has data to be read.
413    pub fn ready(&self) -> bool {
414        let (_, buf) = match self.data.first_key_value() {
415            Some(v) => v,
416            None => return false,
417        };
418
419        buf.off() == self.off
420    }
421
422    /// Returns the number of bytes that can be read contiguously from the
423    /// current read offset.
424    ///
425    /// This is the amount of in-order data available to read right now, up to
426    /// 64 KiB. Data buffered behind a gap (received out of order) is not
427    /// counted, so this never reports bytes that are not yet readable. The cost
428    /// is proportional to the number of contiguous buffered chunks at the front
429    /// of the buffer, up to 64 KiB; no data is copied.
430    pub fn readable_len(&self) -> usize {
431        const MAX_READABLE_LEN: usize = 64 * 1024;
432
433        let mut contiguous = 0;
434        let mut next_off = self.off;
435
436        // `data` is ordered by offset, so walk from the front and stop at the
437        // first gap (a chunk that does not start where the contiguous run so
438        // far leaves off).
439        for buf in self.data.values() {
440            if buf.off() != next_off {
441                break;
442            }
443
444            contiguous = (contiguous + buf.len()).min(MAX_READABLE_LEN);
445            next_off = buf.max_off();
446
447            if contiguous == MAX_READABLE_LEN {
448                break;
449            }
450        }
451
452        contiguous
453    }
454
455    #[cfg(test)]
456    pub(crate) fn flow_control_for_tests(&self) -> &flowcontrol::FlowControl {
457        &self.flow_control
458    }
459}
460
461#[cfg(test)]
462mod tests {
463    use super::*;
464
465    /// The default size of the receiver stream flow control window.
466    const DEFAULT_STREAM_WINDOW: u64 = 32 * 1024;
467    use bytes::BufMut as _;
468    use rstest::rstest;
469
470    // Helper function for testing either buffer emit or discard.
471    //
472    // The `emit` parameter controls whether data is emitted or discarded from
473    // `recv`.
474    //
475    // The `target_len` parameter controls the maximum amount of bytes that
476    // could be read, up to the capacity of `recv`. The `result_len` is the
477    // actual number of bytes that were taken out of `recv`. An assert is
478    // performed on `result_len` to ensure the number of bytes read meets the
479    // caller expectations.
480    //
481    // The `is_fin` parameter relates to the buffer's finished status. An assert
482    // is performed on it to ensure the status meet the caller expectations.
483    //
484    // The `test_bytes` parameter carries an optional slice of bytes. Is set, an
485    // assert is performed against the bytes that were read out of the buffer,
486    // to ensure caller expectations are met.
487    fn assert_emit_discard(
488        recv: &mut RecvBuf, emit: bool, target_len: usize, result_len: usize,
489        is_fin: bool, test_bytes: Option<&[u8]>,
490    ) {
491        let mut buf = Vec::<u8>::with_capacity(512).limit(target_len);
492        let action = if emit {
493            RecvAction::Emit { out: &mut buf }
494        } else {
495            RecvAction::Discard { len: target_len }
496        };
497
498        let (read, fin) = recv.emit_or_discard(action).unwrap();
499
500        let buf = buf.into_inner();
501        if emit {
502            assert_eq!(buf.len(), read);
503            if let Some(v) = test_bytes {
504                assert_eq!(&buf, v);
505            }
506        }
507
508        assert_eq!(read, result_len);
509        assert_eq!(is_fin, fin);
510    }
511
512    // Helper function for testing buffer status for either emit or discard.
513    fn assert_emit_discard_done(recv: &mut RecvBuf, emit: bool) {
514        let mut buf = [0u8; 32];
515        let action = if emit {
516            RecvAction::Emit {
517                out: &mut buf.as_mut_slice(),
518            }
519        } else {
520            RecvAction::Discard { len: 32 }
521        };
522        assert_eq!(recv.emit_or_discard(action), Err(Error::Done));
523    }
524
525    #[rstest]
526    fn empty_read(#[values(true, false)] emit: bool) {
527        let mut recv =
528            RecvBuf::new(u64::MAX, DEFAULT_STREAM_WINDOW, DEFAULT_STREAM_WINDOW);
529        assert_eq!(recv.len, 0);
530
531        assert_emit_discard_done(&mut recv, emit);
532    }
533
534    #[rstest]
535    fn empty_stream_frame(#[values(true, false)] emit: bool) {
536        let mut recv =
537            RecvBuf::new(15, DEFAULT_STREAM_WINDOW, DEFAULT_STREAM_WINDOW);
538        assert_eq!(recv.len, 0);
539
540        let buf = RangeBuf::from(b"hello", 0, false);
541        assert!(recv.write(buf).is_ok());
542        assert_eq!(recv.len, 5);
543        assert_eq!(recv.off, 0);
544        assert_eq!(recv.data.len(), 1);
545
546        assert_emit_discard(&mut recv, emit, 32, 5, false, None);
547
548        // Don't store non-fin empty buffer.
549        let buf = RangeBuf::from(b"", 10, false);
550        assert!(recv.write(buf).is_ok());
551        assert_eq!(recv.len, 5);
552        assert_eq!(recv.off, 5);
553        assert_eq!(recv.data.len(), 0);
554
555        // Check flow control for empty buffer.
556        let buf = RangeBuf::from(b"", 16, false);
557        assert_eq!(recv.write(buf), Err(Error::FlowControl));
558
559        // Store fin empty buffer.
560        let buf = RangeBuf::from(b"", 5, true);
561        assert!(recv.write(buf).is_ok());
562        assert_eq!(recv.len, 5);
563        assert_eq!(recv.off, 5);
564        assert_eq!(recv.data.len(), 1);
565
566        // Don't store additional fin empty buffers.
567        let buf = RangeBuf::from(b"", 5, true);
568        assert!(recv.write(buf).is_ok());
569        assert_eq!(recv.len, 5);
570        assert_eq!(recv.off, 5);
571        assert_eq!(recv.data.len(), 1);
572
573        // Don't store additional fin non-empty buffers.
574        let buf = RangeBuf::from(b"aa", 3, true);
575        assert!(recv.write(buf).is_ok());
576        assert_eq!(recv.len, 5);
577        assert_eq!(recv.off, 5);
578        assert_eq!(recv.data.len(), 1);
579
580        // Validate final size with fin empty buffers.
581        let buf = RangeBuf::from(b"", 6, true);
582        assert_eq!(recv.write(buf), Err(Error::FinalSize));
583        let buf = RangeBuf::from(b"", 4, true);
584        assert_eq!(recv.write(buf), Err(Error::FinalSize));
585
586        assert_emit_discard(&mut recv, emit, 32, 0, true, None);
587    }
588
589    #[rstest]
590    fn ordered_read(#[values(true, false)] emit: bool) {
591        let mut recv =
592            RecvBuf::new(u64::MAX, DEFAULT_STREAM_WINDOW, DEFAULT_STREAM_WINDOW);
593        assert_eq!(recv.len, 0);
594
595        let first = RangeBuf::from(b"hello", 0, false);
596        let second = RangeBuf::from(b"world", 5, false);
597        let third = RangeBuf::from(b"something", 10, true);
598
599        assert!(recv.write(second).is_ok());
600        assert_eq!(recv.len, 10);
601        assert_eq!(recv.off, 0);
602
603        assert_emit_discard_done(&mut recv, emit);
604
605        assert!(recv.write(third).is_ok());
606        assert_eq!(recv.len, 19);
607        assert_eq!(recv.off, 0);
608
609        assert_emit_discard_done(&mut recv, emit);
610
611        assert!(recv.write(first).is_ok());
612        assert_eq!(recv.len, 19);
613        assert_eq!(recv.off, 0);
614
615        assert_emit_discard(
616            &mut recv,
617            emit,
618            32,
619            19,
620            true,
621            Some(b"helloworldsomething"),
622        );
623        assert_eq!(recv.len, 19);
624        assert_eq!(recv.off, 19);
625
626        assert_emit_discard_done(&mut recv, emit);
627    }
628
629    #[test]
630    /// `readable_len` counts only contiguous in-order data, ignoring bytes
631    /// buffered behind a gap.
632    fn readable_len() {
633        let mut recv =
634            RecvBuf::new(u64::MAX, DEFAULT_STREAM_WINDOW, DEFAULT_STREAM_WINDOW);
635
636        // Empty buffer: nothing readable.
637        assert_eq!(recv.readable_len(), 0);
638
639        // Contiguous data at the front is readable.
640        assert!(recv.write(RangeBuf::from(b"hello", 0, false)).is_ok());
641        assert_eq!(recv.readable_len(), 5);
642
643        // Data buffered behind a gap ([5, 10) is missing) is NOT counted, even
644        // though `max_off` has advanced to 19.
645        assert!(recv.write(RangeBuf::from(b"something", 10, false)).is_ok());
646        assert_eq!(recv.max_off(), 19);
647        assert_eq!(recv.readable_len(), 5);
648
649        // Filling the gap makes the whole range contiguous and readable.
650        assert!(recv.write(RangeBuf::from(b"world", 5, false)).is_ok());
651        assert_eq!(recv.readable_len(), 19);
652
653        // Reading part of the data shrinks the readable count accordingly.
654        let mut buf = [0; 4];
655        assert_eq!(recv.emit(&mut buf), Ok((4, false)));
656        assert_eq!(recv.readable_len(), 15);
657
658        // Traversal stops at the maximum body receive buffer size.
659        let mut recv =
660            RecvBuf::new(u64::MAX, DEFAULT_STREAM_WINDOW, DEFAULT_STREAM_WINDOW);
661        assert!(recv
662            .write(RangeBuf::from(&[0; 64 * 1024], 0, false))
663            .is_ok());
664        assert!(recv.write(RangeBuf::from(&[0], 64 * 1024, false)).is_ok());
665        assert_eq!(recv.readable_len(), 64 * 1024);
666    }
667
668    /// Test shutdown behavior
669    #[rstest]
670    fn shutdown(#[values(true, false)] emit: bool) {
671        let mut recv =
672            RecvBuf::new(u64::MAX, DEFAULT_STREAM_WINDOW, DEFAULT_STREAM_WINDOW);
673        assert_eq!(recv.len, 0);
674
675        let first = RangeBuf::from(b"hello", 0, false);
676        let second = RangeBuf::from(b"world", 5, false);
677        let third = RangeBuf::from(b"something", 10, false);
678
679        assert!(recv.write(second).is_ok());
680        assert_eq!(recv.len, 10);
681        assert_eq!(recv.off, 0);
682
683        assert_emit_discard_done(&mut recv, emit);
684
685        // shutdown the buffer. Buffer is dropped.
686        assert_eq!(recv.shutdown(), Ok(10));
687        assert_eq!(recv.len, 10);
688        assert_eq!(recv.off, 10);
689        assert_eq!(recv.data.len(), 0);
690
691        assert_emit_discard_done(&mut recv, emit);
692
693        // subsequent writes are validated but not added to the buffer
694        assert!(recv.write(first).is_ok());
695        assert_eq!(recv.len, 10);
696        assert_eq!(recv.off, 10);
697        assert_eq!(recv.data.len(), 0);
698
699        // the max offset of received data can increase and
700        // the recv.off must increase with it
701        assert!(recv.write(third).is_ok());
702        assert_eq!(recv.len, 19);
703        assert_eq!(recv.off, 19);
704        assert_eq!(recv.data.len(), 0);
705
706        // Send a reset
707        assert_emit_discard_done(&mut recv, emit);
708        assert_eq!(
709            recv.reset(42, 123),
710            Ok(RecvBufResetReturn {
711                max_data_delta: 104,
712                consumed_flowcontrol: 104,
713            })
714        );
715        assert_eq!(recv.len, 123);
716        assert_eq!(recv.off, 123);
717        assert_eq!(recv.data.len(), 0);
718
719        assert_emit_discard_done(&mut recv, emit);
720    }
721
722    #[rstest]
723    fn split_read(#[values(true, false)] emit: bool) {
724        let mut recv =
725            RecvBuf::new(u64::MAX, DEFAULT_STREAM_WINDOW, DEFAULT_STREAM_WINDOW);
726        assert_eq!(recv.len, 0);
727
728        let first = RangeBuf::from(b"something", 0, false);
729        let second = RangeBuf::from(b"helloworld", 9, true);
730
731        assert!(recv.write(first).is_ok());
732        assert_eq!(recv.len, 9);
733        assert_eq!(recv.off, 0);
734
735        assert!(recv.write(second).is_ok());
736        assert_eq!(recv.len, 19);
737        assert_eq!(recv.off, 0);
738
739        assert_emit_discard(&mut recv, emit, 10, 10, false, Some(b"somethingh"));
740        assert_eq!(recv.len, 19);
741        assert_eq!(recv.off, 10);
742
743        assert_emit_discard(&mut recv, emit, 5, 5, false, Some(b"ellow"));
744        assert_eq!(recv.len, 19);
745        assert_eq!(recv.off, 15);
746
747        assert_emit_discard(&mut recv, emit, 5, 4, true, Some(b"orld"));
748        assert_eq!(recv.len, 19);
749        assert_eq!(recv.off, 19);
750    }
751
752    #[test]
753    fn split_read_incremental_buf() {
754        let mut recv =
755            RecvBuf::new(u64::MAX, DEFAULT_STREAM_WINDOW, DEFAULT_STREAM_WINDOW);
756        assert_eq!(recv.len, 0);
757
758        let first = RangeBuf::from(b"something", 0, false);
759        let second = RangeBuf::from(b"helloworld", 9, true);
760
761        assert!(recv.write(first).is_ok());
762        assert_eq!(recv.len, 9);
763        assert_eq!(recv.off, 0);
764
765        assert!(recv.write(second).is_ok());
766        assert_eq!(recv.len, 19);
767        assert_eq!(recv.off, 0);
768
769        let mut buf = Vec::new().limit(10);
770        assert_eq!(
771            recv.emit_or_discard(RecvAction::Emit { out: &mut buf }),
772            Ok((10, false))
773        );
774        assert_eq!(recv.len, 19);
775        assert_eq!(recv.off, 10);
776        assert_eq!(buf.get_ref().len(), 10);
777        assert_eq!(buf.get_ref().as_slice(), b"somethingh");
778
779        buf.set_limit(5);
780        assert_eq!(
781            recv.emit_or_discard(RecvAction::Emit { out: &mut buf }),
782            Ok((5, false))
783        );
784        assert_eq!(recv.len, 19);
785        assert_eq!(recv.off, 15);
786        assert_eq!(buf.get_ref().len(), 15);
787        assert_eq!(buf.get_ref().as_slice(), b"somethinghellow");
788
789        buf.set_limit(42);
790        assert_eq!(
791            recv.emit_or_discard(RecvAction::Emit { out: &mut buf }),
792            Ok((4, true))
793        );
794        assert_eq!(recv.len, 19);
795        assert_eq!(recv.off, 19);
796        assert_eq!(buf.get_ref().len(), 19);
797        assert_eq!(buf.get_ref().as_slice(), b"somethinghelloworld");
798    }
799
800    #[rstest]
801    fn incomplete_read(#[values(true, false)] emit: bool) {
802        let mut recv =
803            RecvBuf::new(u64::MAX, DEFAULT_STREAM_WINDOW, DEFAULT_STREAM_WINDOW);
804        assert_eq!(recv.len, 0);
805
806        let mut buf = [0u8; 32];
807
808        let first = RangeBuf::from(b"something", 0, false);
809        let second = RangeBuf::from(b"helloworld", 9, true);
810
811        assert!(recv.write(second).is_ok());
812        assert_eq!(recv.len, 19);
813        assert_eq!(recv.off, 0);
814
815        let action = if emit {
816            RecvAction::Emit {
817                out: &mut buf.as_mut_slice(),
818            }
819        } else {
820            RecvAction::Discard { len: 32 }
821        };
822        assert_eq!(recv.emit_or_discard(action), Err(Error::Done));
823
824        assert!(recv.write(first).is_ok());
825        assert_eq!(recv.len, 19);
826        assert_eq!(recv.off, 0);
827
828        assert_emit_discard(
829            &mut recv,
830            emit,
831            32,
832            19,
833            true,
834            Some(b"somethinghelloworld"),
835        );
836        assert_eq!(recv.len, 19);
837        assert_eq!(recv.off, 19);
838    }
839
840    #[rstest]
841    fn zero_len_read(#[values(true, false)] emit: bool) {
842        let mut recv =
843            RecvBuf::new(u64::MAX, DEFAULT_STREAM_WINDOW, DEFAULT_STREAM_WINDOW);
844        assert_eq!(recv.len, 0);
845
846        let first = RangeBuf::from(b"something", 0, false);
847        let second = RangeBuf::from(b"", 9, true);
848
849        assert!(recv.write(first).is_ok());
850        assert_eq!(recv.len, 9);
851        assert_eq!(recv.off, 0);
852        assert_eq!(recv.data.len(), 1);
853
854        assert!(recv.write(second).is_ok());
855        assert_eq!(recv.len, 9);
856        assert_eq!(recv.off, 0);
857        assert_eq!(recv.data.len(), 1);
858
859        assert_emit_discard(&mut recv, emit, 32, 9, true, Some(b"something"));
860        assert_eq!(recv.len, 9);
861        assert_eq!(recv.off, 9);
862    }
863
864    #[rstest]
865    fn past_read(#[values(true, false)] emit: bool) {
866        let mut recv =
867            RecvBuf::new(u64::MAX, DEFAULT_STREAM_WINDOW, DEFAULT_STREAM_WINDOW);
868        assert_eq!(recv.len, 0);
869
870        let first = RangeBuf::from(b"something", 0, false);
871        let second = RangeBuf::from(b"hello", 3, false);
872        let third = RangeBuf::from(b"ello", 4, true);
873        let fourth = RangeBuf::from(b"ello", 5, true);
874
875        assert!(recv.write(first).is_ok());
876        assert_eq!(recv.len, 9);
877        assert_eq!(recv.off, 0);
878        assert_eq!(recv.data.len(), 1);
879
880        assert_emit_discard(&mut recv, emit, 32, 9, false, Some(b"something"));
881        assert_eq!(recv.len, 9);
882        assert_eq!(recv.off, 9);
883
884        assert!(recv.write(second).is_ok());
885        assert_eq!(recv.len, 9);
886        assert_eq!(recv.off, 9);
887        assert_eq!(recv.data.len(), 0);
888
889        assert_eq!(recv.write(third), Err(Error::FinalSize));
890
891        assert!(recv.write(fourth).is_ok());
892        assert_eq!(recv.len, 9);
893        assert_eq!(recv.off, 9);
894        assert_eq!(recv.data.len(), 0);
895
896        assert_emit_discard_done(&mut recv, emit);
897    }
898
899    #[rstest]
900    fn fully_overlapping_read(#[values(true, false)] emit: bool) {
901        let mut recv =
902            RecvBuf::new(u64::MAX, DEFAULT_STREAM_WINDOW, DEFAULT_STREAM_WINDOW);
903        assert_eq!(recv.len, 0);
904
905        let first = RangeBuf::from(b"something", 0, false);
906        let second = RangeBuf::from(b"hello", 4, false);
907
908        assert!(recv.write(first).is_ok());
909        assert_eq!(recv.len, 9);
910        assert_eq!(recv.off, 0);
911        assert_eq!(recv.data.len(), 1);
912
913        assert!(recv.write(second).is_ok());
914        assert_eq!(recv.len, 9);
915        assert_eq!(recv.off, 0);
916        assert_eq!(recv.data.len(), 1);
917
918        assert_emit_discard(&mut recv, emit, 32, 9, false, Some(b"something"));
919        assert_eq!(recv.len, 9);
920        assert_eq!(recv.off, 9);
921        assert_eq!(recv.data.len(), 0);
922
923        assert_emit_discard_done(&mut recv, emit);
924    }
925
926    #[rstest]
927    fn fully_overlapping_read2(#[values(true, false)] emit: bool) {
928        let mut recv =
929            RecvBuf::new(u64::MAX, DEFAULT_STREAM_WINDOW, DEFAULT_STREAM_WINDOW);
930        assert_eq!(recv.len, 0);
931
932        let first = RangeBuf::from(b"something", 0, false);
933        let second = RangeBuf::from(b"hello", 4, false);
934
935        assert!(recv.write(second).is_ok());
936        assert_eq!(recv.len, 9);
937        assert_eq!(recv.off, 0);
938        assert_eq!(recv.data.len(), 1);
939
940        assert!(recv.write(first).is_ok());
941        assert_eq!(recv.len, 9);
942        assert_eq!(recv.off, 0);
943        assert_eq!(recv.data.len(), 2);
944
945        assert_emit_discard(&mut recv, emit, 32, 9, false, Some(b"somehello"));
946        assert_eq!(recv.len, 9);
947        assert_eq!(recv.off, 9);
948        assert_eq!(recv.data.len(), 0);
949
950        assert_emit_discard_done(&mut recv, emit);
951    }
952
953    #[rstest]
954    fn fully_overlapping_read3(#[values(true, false)] emit: bool) {
955        let mut recv =
956            RecvBuf::new(u64::MAX, DEFAULT_STREAM_WINDOW, DEFAULT_STREAM_WINDOW);
957        assert_eq!(recv.len, 0);
958
959        let first = RangeBuf::from(b"something", 0, false);
960        let second = RangeBuf::from(b"hello", 3, false);
961
962        assert!(recv.write(second).is_ok());
963        assert_eq!(recv.len, 8);
964        assert_eq!(recv.off, 0);
965        assert_eq!(recv.data.len(), 1);
966
967        assert!(recv.write(first).is_ok());
968        assert_eq!(recv.len, 9);
969        assert_eq!(recv.off, 0);
970        assert_eq!(recv.data.len(), 3);
971
972        assert_emit_discard(&mut recv, emit, 32, 9, false, Some(b"somhellog"));
973        assert_eq!(recv.len, 9);
974        assert_eq!(recv.off, 9);
975        assert_eq!(recv.data.len(), 0);
976
977        assert_emit_discard_done(&mut recv, emit);
978    }
979
980    #[rstest]
981    fn fully_overlapping_read_multi(#[values(true, false)] emit: bool) {
982        let mut recv =
983            RecvBuf::new(u64::MAX, DEFAULT_STREAM_WINDOW, DEFAULT_STREAM_WINDOW);
984        assert_eq!(recv.len, 0);
985
986        let first = RangeBuf::from(b"somethingsomething", 0, false);
987        let second = RangeBuf::from(b"hello", 3, false);
988        let third = RangeBuf::from(b"hello", 12, false);
989
990        assert!(recv.write(second).is_ok());
991        assert_eq!(recv.len, 8);
992        assert_eq!(recv.off, 0);
993        assert_eq!(recv.data.len(), 1);
994
995        assert!(recv.write(third).is_ok());
996        assert_eq!(recv.len, 17);
997        assert_eq!(recv.off, 0);
998        assert_eq!(recv.data.len(), 2);
999
1000        assert!(recv.write(first).is_ok());
1001        assert_eq!(recv.len, 18);
1002        assert_eq!(recv.off, 0);
1003        assert_eq!(recv.data.len(), 5);
1004
1005        assert_emit_discard(
1006            &mut recv,
1007            emit,
1008            32,
1009            18,
1010            false,
1011            Some(b"somhellogsomhellog"),
1012        );
1013        assert_eq!(recv.len, 18);
1014        assert_eq!(recv.off, 18);
1015        assert_eq!(recv.data.len(), 0);
1016
1017        assert_emit_discard_done(&mut recv, emit);
1018    }
1019
1020    #[rstest]
1021    fn overlapping_start_read(#[values(true, false)] emit: bool) {
1022        let mut recv =
1023            RecvBuf::new(u64::MAX, DEFAULT_STREAM_WINDOW, DEFAULT_STREAM_WINDOW);
1024        assert_eq!(recv.len, 0);
1025
1026        let first = RangeBuf::from(b"something", 0, false);
1027        let second = RangeBuf::from(b"hello", 8, true);
1028
1029        assert!(recv.write(first).is_ok());
1030        assert_eq!(recv.len, 9);
1031        assert_eq!(recv.off, 0);
1032        assert_eq!(recv.data.len(), 1);
1033
1034        assert!(recv.write(second).is_ok());
1035        assert_eq!(recv.len, 13);
1036        assert_eq!(recv.off, 0);
1037        assert_eq!(recv.data.len(), 2);
1038
1039        assert_emit_discard(
1040            &mut recv,
1041            emit,
1042            32,
1043            13,
1044            true,
1045            Some(b"somethingello"),
1046        );
1047
1048        assert_eq!(recv.len, 13);
1049        assert_eq!(recv.off, 13);
1050
1051        assert_emit_discard_done(&mut recv, emit);
1052    }
1053
1054    #[rstest]
1055    fn overlapping_end_read(#[values(true, false)] emit: bool) {
1056        let mut recv =
1057            RecvBuf::new(u64::MAX, DEFAULT_STREAM_WINDOW, DEFAULT_STREAM_WINDOW);
1058        assert_eq!(recv.len, 0);
1059
1060        let first = RangeBuf::from(b"hello", 0, false);
1061        let second = RangeBuf::from(b"something", 3, true);
1062
1063        assert!(recv.write(second).is_ok());
1064        assert_eq!(recv.len, 12);
1065        assert_eq!(recv.off, 0);
1066        assert_eq!(recv.data.len(), 1);
1067
1068        assert!(recv.write(first).is_ok());
1069        assert_eq!(recv.len, 12);
1070        assert_eq!(recv.off, 0);
1071        assert_eq!(recv.data.len(), 2);
1072
1073        assert_emit_discard(&mut recv, emit, 32, 12, true, Some(b"helsomething"));
1074        assert_eq!(recv.len, 12);
1075        assert_eq!(recv.off, 12);
1076
1077        assert_emit_discard_done(&mut recv, emit);
1078    }
1079
1080    #[rstest]
1081    fn overlapping_end_twice_read(#[values(true, false)] emit: bool) {
1082        let mut recv =
1083            RecvBuf::new(u64::MAX, DEFAULT_STREAM_WINDOW, DEFAULT_STREAM_WINDOW);
1084        assert_eq!(recv.len, 0);
1085
1086        let first = RangeBuf::from(b"he", 0, false);
1087        let second = RangeBuf::from(b"ow", 4, false);
1088        let third = RangeBuf::from(b"rl", 7, false);
1089        let fourth = RangeBuf::from(b"helloworld", 0, true);
1090
1091        assert!(recv.write(third).is_ok());
1092        assert_eq!(recv.len, 9);
1093        assert_eq!(recv.off, 0);
1094        assert_eq!(recv.data.len(), 1);
1095
1096        assert!(recv.write(second).is_ok());
1097        assert_eq!(recv.len, 9);
1098        assert_eq!(recv.off, 0);
1099        assert_eq!(recv.data.len(), 2);
1100
1101        assert!(recv.write(first).is_ok());
1102        assert_eq!(recv.len, 9);
1103        assert_eq!(recv.off, 0);
1104        assert_eq!(recv.data.len(), 3);
1105
1106        assert!(recv.write(fourth).is_ok());
1107        assert_eq!(recv.len, 10);
1108        assert_eq!(recv.off, 0);
1109        assert_eq!(recv.data.len(), 6);
1110
1111        assert_emit_discard(&mut recv, emit, 32, 10, true, Some(b"helloworld"));
1112        assert_eq!(recv.len, 10);
1113        assert_eq!(recv.off, 10);
1114
1115        assert_emit_discard_done(&mut recv, emit);
1116    }
1117
1118    #[rstest]
1119    fn overlapping_end_twice_and_contained_read(
1120        #[values(true, false)] emit: bool,
1121    ) {
1122        let mut recv =
1123            RecvBuf::new(u64::MAX, DEFAULT_STREAM_WINDOW, DEFAULT_STREAM_WINDOW);
1124        assert_eq!(recv.len, 0);
1125
1126        let first = RangeBuf::from(b"hellow", 0, false);
1127        let second = RangeBuf::from(b"barfoo", 10, true);
1128        let third = RangeBuf::from(b"rl", 7, false);
1129        let fourth = RangeBuf::from(b"elloworldbarfoo", 1, true);
1130
1131        assert!(recv.write(third).is_ok());
1132        assert_eq!(recv.len, 9);
1133        assert_eq!(recv.off, 0);
1134        assert_eq!(recv.data.len(), 1);
1135
1136        assert!(recv.write(second).is_ok());
1137        assert_eq!(recv.len, 16);
1138        assert_eq!(recv.off, 0);
1139        assert_eq!(recv.data.len(), 2);
1140
1141        assert!(recv.write(first).is_ok());
1142        assert_eq!(recv.len, 16);
1143        assert_eq!(recv.off, 0);
1144        assert_eq!(recv.data.len(), 3);
1145
1146        assert!(recv.write(fourth).is_ok());
1147        assert_eq!(recv.len, 16);
1148        assert_eq!(recv.off, 0);
1149        assert_eq!(recv.data.len(), 5);
1150
1151        assert_emit_discard(
1152            &mut recv,
1153            emit,
1154            32,
1155            16,
1156            true,
1157            Some(b"helloworldbarfoo"),
1158        );
1159        assert_eq!(recv.len, 16);
1160        assert_eq!(recv.off, 16);
1161
1162        assert_emit_discard_done(&mut recv, emit);
1163    }
1164
1165    #[rstest]
1166    fn partially_multi_overlapping_reordered_read(
1167        #[values(true, false)] emit: bool,
1168    ) {
1169        let mut recv =
1170            RecvBuf::new(u64::MAX, DEFAULT_STREAM_WINDOW, DEFAULT_STREAM_WINDOW);
1171        assert_eq!(recv.len, 0);
1172
1173        let first = RangeBuf::from(b"hello", 8, false);
1174        let second = RangeBuf::from(b"something", 0, false);
1175        let third = RangeBuf::from(b"moar", 11, true);
1176
1177        assert!(recv.write(first).is_ok());
1178        assert_eq!(recv.len, 13);
1179        assert_eq!(recv.off, 0);
1180        assert_eq!(recv.data.len(), 1);
1181
1182        assert!(recv.write(second).is_ok());
1183        assert_eq!(recv.len, 13);
1184        assert_eq!(recv.off, 0);
1185        assert_eq!(recv.data.len(), 2);
1186
1187        assert!(recv.write(third).is_ok());
1188        assert_eq!(recv.len, 15);
1189        assert_eq!(recv.off, 0);
1190        assert_eq!(recv.data.len(), 3);
1191
1192        assert_emit_discard(
1193            &mut recv,
1194            emit,
1195            32,
1196            15,
1197            true,
1198            Some(b"somethinhelloar"),
1199        );
1200        assert_eq!(recv.len, 15);
1201        assert_eq!(recv.off, 15);
1202        assert_eq!(recv.data.len(), 0);
1203
1204        assert_emit_discard_done(&mut recv, emit);
1205    }
1206
1207    #[rstest]
1208    fn partially_multi_overlapping_reordered_read2(
1209        #[values(true, false)] emit: bool,
1210    ) {
1211        let mut recv =
1212            RecvBuf::new(u64::MAX, DEFAULT_STREAM_WINDOW, DEFAULT_STREAM_WINDOW);
1213        assert_eq!(recv.len, 0);
1214
1215        let first = RangeBuf::from(b"aaa", 0, false);
1216        let second = RangeBuf::from(b"bbb", 2, false);
1217        let third = RangeBuf::from(b"ccc", 4, false);
1218        let fourth = RangeBuf::from(b"ddd", 6, false);
1219        let fifth = RangeBuf::from(b"eee", 9, false);
1220        let sixth = RangeBuf::from(b"fff", 11, false);
1221
1222        assert!(recv.write(second).is_ok());
1223        assert_eq!(recv.len, 5);
1224        assert_eq!(recv.off, 0);
1225        assert_eq!(recv.data.len(), 1);
1226
1227        assert!(recv.write(fourth).is_ok());
1228        assert_eq!(recv.len, 9);
1229        assert_eq!(recv.off, 0);
1230        assert_eq!(recv.data.len(), 2);
1231
1232        assert!(recv.write(third).is_ok());
1233        assert_eq!(recv.len, 9);
1234        assert_eq!(recv.off, 0);
1235        assert_eq!(recv.data.len(), 3);
1236
1237        assert!(recv.write(first).is_ok());
1238        assert_eq!(recv.len, 9);
1239        assert_eq!(recv.off, 0);
1240        assert_eq!(recv.data.len(), 4);
1241
1242        assert!(recv.write(sixth).is_ok());
1243        assert_eq!(recv.len, 14);
1244        assert_eq!(recv.off, 0);
1245        assert_eq!(recv.data.len(), 5);
1246
1247        assert!(recv.write(fifth).is_ok());
1248        assert_eq!(recv.len, 14);
1249        assert_eq!(recv.off, 0);
1250        assert_eq!(recv.data.len(), 6);
1251
1252        assert_emit_discard(
1253            &mut recv,
1254            emit,
1255            32,
1256            14,
1257            false,
1258            Some(b"aabbbcdddeefff"),
1259        );
1260        assert_eq!(recv.len, 14);
1261        assert_eq!(recv.off, 14);
1262        assert_eq!(recv.data.len(), 0);
1263
1264        assert_emit_discard_done(&mut recv, emit);
1265    }
1266
1267    #[test]
1268    fn mixed_read_actions() {
1269        let mut recv =
1270            RecvBuf::new(u64::MAX, DEFAULT_STREAM_WINDOW, DEFAULT_STREAM_WINDOW);
1271        assert_eq!(recv.len, 0);
1272
1273        let first = RangeBuf::from(b"hello", 0, false);
1274        let second = RangeBuf::from(b"world", 5, false);
1275        let third = RangeBuf::from(b"something", 10, true);
1276
1277        assert!(recv.write(second).is_ok());
1278        assert_eq!(recv.len, 10);
1279        assert_eq!(recv.off, 0);
1280
1281        assert_emit_discard_done(&mut recv, true);
1282        assert_emit_discard_done(&mut recv, false);
1283
1284        assert!(recv.write(third).is_ok());
1285        assert_eq!(recv.len, 19);
1286        assert_eq!(recv.off, 0);
1287
1288        assert_emit_discard_done(&mut recv, true);
1289        assert_emit_discard_done(&mut recv, false);
1290
1291        assert!(recv.write(first).is_ok());
1292        assert_eq!(recv.len, 19);
1293        assert_eq!(recv.off, 0);
1294
1295        assert_emit_discard(&mut recv, true, 5, 5, false, Some(b"hello"));
1296        assert_eq!(recv.len, 19);
1297        assert_eq!(recv.off, 5);
1298
1299        assert_emit_discard(&mut recv, false, 5, 5, false, None);
1300        assert_eq!(recv.len, 19);
1301        assert_eq!(recv.off, 10);
1302
1303        assert_emit_discard(&mut recv, true, 9, 9, true, Some(b"something"));
1304        assert_eq!(recv.len, 19);
1305        assert_eq!(recv.off, 19);
1306
1307        assert_emit_discard_done(&mut recv, true);
1308        assert_emit_discard_done(&mut recv, false);
1309    }
1310}