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