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, up to `max_len`.
424    ///
425    /// Data buffered behind a gap (received out of order) is not counted, so
426    /// this never reports bytes that are not yet readable. The cost is
427    /// proportional to the number of contiguous buffered chunks at the front
428    /// of the buffer, up to `max_len`; no data is copied.
429    pub fn readable_len(&self, max_len: usize) -> usize {
430        let mut contiguous = 0usize;
431        let mut next_off = self.off;
432
433        // `data` is ordered by offset, so walk from the front and stop at the
434        // first gap (a chunk that does not start where the contiguous run so
435        // far leaves off).
436        for buf in self.data.values() {
437            if buf.off() != next_off {
438                break;
439            }
440
441            contiguous = contiguous.saturating_add(buf.len()).min(max_len);
442            next_off = buf.max_off();
443
444            if contiguous == max_len {
445                break;
446            }
447        }
448
449        contiguous
450    }
451
452    #[cfg(test)]
453    pub(crate) fn flow_control_for_tests(&self) -> &flowcontrol::FlowControl {
454        &self.flow_control
455    }
456}
457
458#[cfg(test)]
459mod tests {
460    use super::*;
461
462    /// The default size of the receiver stream flow control window.
463    const DEFAULT_STREAM_WINDOW: u64 = 32 * 1024;
464    use bytes::BufMut as _;
465    use rstest::rstest;
466
467    // Helper function for testing either buffer emit or discard.
468    //
469    // The `emit` parameter controls whether data is emitted or discarded from
470    // `recv`.
471    //
472    // The `target_len` parameter controls the maximum amount of bytes that
473    // could be read, up to the capacity of `recv`. The `result_len` is the
474    // actual number of bytes that were taken out of `recv`. An assert is
475    // performed on `result_len` to ensure the number of bytes read meets the
476    // caller expectations.
477    //
478    // The `is_fin` parameter relates to the buffer's finished status. An assert
479    // is performed on it to ensure the status meet the caller expectations.
480    //
481    // The `test_bytes` parameter carries an optional slice of bytes. Is set, an
482    // assert is performed against the bytes that were read out of the buffer,
483    // to ensure caller expectations are met.
484    fn assert_emit_discard(
485        recv: &mut RecvBuf, emit: bool, target_len: usize, result_len: usize,
486        is_fin: bool, test_bytes: Option<&[u8]>,
487    ) {
488        let mut buf = Vec::<u8>::with_capacity(512).limit(target_len);
489        let action = if emit {
490            RecvAction::Emit { out: &mut buf }
491        } else {
492            RecvAction::Discard { len: target_len }
493        };
494
495        let (read, fin) = recv.emit_or_discard(action).unwrap();
496
497        let buf = buf.into_inner();
498        if emit {
499            assert_eq!(buf.len(), read);
500            if let Some(v) = test_bytes {
501                assert_eq!(&buf, v);
502            }
503        }
504
505        assert_eq!(read, result_len);
506        assert_eq!(is_fin, fin);
507    }
508
509    // Helper function for testing buffer status for either emit or discard.
510    fn assert_emit_discard_done(recv: &mut RecvBuf, emit: bool) {
511        let mut buf = [0u8; 32];
512        let action = if emit {
513            RecvAction::Emit {
514                out: &mut buf.as_mut_slice(),
515            }
516        } else {
517            RecvAction::Discard { len: 32 }
518        };
519        assert_eq!(recv.emit_or_discard(action), Err(Error::Done));
520    }
521
522    #[rstest]
523    fn empty_read(#[values(true, false)] emit: bool) {
524        let mut recv =
525            RecvBuf::new(u64::MAX, DEFAULT_STREAM_WINDOW, DEFAULT_STREAM_WINDOW);
526        assert_eq!(recv.len, 0);
527
528        assert_emit_discard_done(&mut recv, emit);
529    }
530
531    #[rstest]
532    fn empty_stream_frame(#[values(true, false)] emit: bool) {
533        let mut recv =
534            RecvBuf::new(15, DEFAULT_STREAM_WINDOW, DEFAULT_STREAM_WINDOW);
535        assert_eq!(recv.len, 0);
536
537        let buf = RangeBuf::from(b"hello", 0, false);
538        assert!(recv.write(buf).is_ok());
539        assert_eq!(recv.len, 5);
540        assert_eq!(recv.off, 0);
541        assert_eq!(recv.data.len(), 1);
542
543        assert_emit_discard(&mut recv, emit, 32, 5, false, None);
544
545        // Don't store non-fin empty buffer.
546        let buf = RangeBuf::from(b"", 10, false);
547        assert!(recv.write(buf).is_ok());
548        assert_eq!(recv.len, 5);
549        assert_eq!(recv.off, 5);
550        assert_eq!(recv.data.len(), 0);
551
552        // Check flow control for empty buffer.
553        let buf = RangeBuf::from(b"", 16, false);
554        assert_eq!(recv.write(buf), Err(Error::FlowControl));
555
556        // Store fin empty buffer.
557        let buf = RangeBuf::from(b"", 5, true);
558        assert!(recv.write(buf).is_ok());
559        assert_eq!(recv.len, 5);
560        assert_eq!(recv.off, 5);
561        assert_eq!(recv.data.len(), 1);
562
563        // Don't store additional fin empty buffers.
564        let buf = RangeBuf::from(b"", 5, true);
565        assert!(recv.write(buf).is_ok());
566        assert_eq!(recv.len, 5);
567        assert_eq!(recv.off, 5);
568        assert_eq!(recv.data.len(), 1);
569
570        // Don't store additional fin non-empty buffers.
571        let buf = RangeBuf::from(b"aa", 3, true);
572        assert!(recv.write(buf).is_ok());
573        assert_eq!(recv.len, 5);
574        assert_eq!(recv.off, 5);
575        assert_eq!(recv.data.len(), 1);
576
577        // Validate final size with fin empty buffers.
578        let buf = RangeBuf::from(b"", 6, true);
579        assert_eq!(recv.write(buf), Err(Error::FinalSize));
580        let buf = RangeBuf::from(b"", 4, true);
581        assert_eq!(recv.write(buf), Err(Error::FinalSize));
582
583        assert_emit_discard(&mut recv, emit, 32, 0, true, None);
584    }
585
586    #[rstest]
587    fn ordered_read(#[values(true, false)] emit: bool) {
588        let mut recv =
589            RecvBuf::new(u64::MAX, DEFAULT_STREAM_WINDOW, DEFAULT_STREAM_WINDOW);
590        assert_eq!(recv.len, 0);
591
592        let first = RangeBuf::from(b"hello", 0, false);
593        let second = RangeBuf::from(b"world", 5, false);
594        let third = RangeBuf::from(b"something", 10, true);
595
596        assert!(recv.write(second).is_ok());
597        assert_eq!(recv.len, 10);
598        assert_eq!(recv.off, 0);
599
600        assert_emit_discard_done(&mut recv, emit);
601
602        assert!(recv.write(third).is_ok());
603        assert_eq!(recv.len, 19);
604        assert_eq!(recv.off, 0);
605
606        assert_emit_discard_done(&mut recv, emit);
607
608        assert!(recv.write(first).is_ok());
609        assert_eq!(recv.len, 19);
610        assert_eq!(recv.off, 0);
611
612        assert_emit_discard(
613            &mut recv,
614            emit,
615            32,
616            19,
617            true,
618            Some(b"helloworldsomething"),
619        );
620        assert_eq!(recv.len, 19);
621        assert_eq!(recv.off, 19);
622
623        assert_emit_discard_done(&mut recv, emit);
624    }
625
626    #[test]
627    /// `readable_len` counts only contiguous in-order data, up to its limit.
628    fn readable_len() {
629        let mut recv =
630            RecvBuf::new(u64::MAX, DEFAULT_STREAM_WINDOW, DEFAULT_STREAM_WINDOW);
631
632        // Empty buffer: nothing readable.
633        assert_eq!(recv.readable_len(64 * 1024), 0);
634
635        // Data buffered behind a gap is not readable.
636        assert!(recv.write(RangeBuf::from(b"hello", 0, false)).is_ok());
637        assert!(recv.write(RangeBuf::from(b"something", 10, false)).is_ok());
638        assert_eq!(recv.readable_len(64 * 1024), 5);
639
640        // Filling the gap makes the full range readable, bounded by the limit.
641        assert!(recv.write(RangeBuf::from(b"world", 5, false)).is_ok());
642        assert_eq!(recv.readable_len(64 * 1024), 19);
643        assert_eq!(recv.readable_len(10), 10);
644    }
645
646    /// Test shutdown behavior
647    #[rstest]
648    fn shutdown(#[values(true, false)] emit: bool) {
649        let mut recv =
650            RecvBuf::new(u64::MAX, DEFAULT_STREAM_WINDOW, DEFAULT_STREAM_WINDOW);
651        assert_eq!(recv.len, 0);
652
653        let first = RangeBuf::from(b"hello", 0, false);
654        let second = RangeBuf::from(b"world", 5, false);
655        let third = RangeBuf::from(b"something", 10, false);
656
657        assert!(recv.write(second).is_ok());
658        assert_eq!(recv.len, 10);
659        assert_eq!(recv.off, 0);
660
661        assert_emit_discard_done(&mut recv, emit);
662
663        // shutdown the buffer. Buffer is dropped.
664        assert_eq!(recv.shutdown(), Ok(10));
665        assert_eq!(recv.len, 10);
666        assert_eq!(recv.off, 10);
667        assert_eq!(recv.data.len(), 0);
668
669        assert_emit_discard_done(&mut recv, emit);
670
671        // subsequent writes are validated but not added to the buffer
672        assert!(recv.write(first).is_ok());
673        assert_eq!(recv.len, 10);
674        assert_eq!(recv.off, 10);
675        assert_eq!(recv.data.len(), 0);
676
677        // the max offset of received data can increase and
678        // the recv.off must increase with it
679        assert!(recv.write(third).is_ok());
680        assert_eq!(recv.len, 19);
681        assert_eq!(recv.off, 19);
682        assert_eq!(recv.data.len(), 0);
683
684        // Send a reset
685        assert_emit_discard_done(&mut recv, emit);
686        assert_eq!(
687            recv.reset(42, 123),
688            Ok(RecvBufResetReturn {
689                max_data_delta: 104,
690                consumed_flowcontrol: 104,
691            })
692        );
693        assert_eq!(recv.len, 123);
694        assert_eq!(recv.off, 123);
695        assert_eq!(recv.data.len(), 0);
696
697        assert_emit_discard_done(&mut recv, emit);
698    }
699
700    #[rstest]
701    fn split_read(#[values(true, false)] emit: bool) {
702        let mut recv =
703            RecvBuf::new(u64::MAX, DEFAULT_STREAM_WINDOW, DEFAULT_STREAM_WINDOW);
704        assert_eq!(recv.len, 0);
705
706        let first = RangeBuf::from(b"something", 0, false);
707        let second = RangeBuf::from(b"helloworld", 9, true);
708
709        assert!(recv.write(first).is_ok());
710        assert_eq!(recv.len, 9);
711        assert_eq!(recv.off, 0);
712
713        assert!(recv.write(second).is_ok());
714        assert_eq!(recv.len, 19);
715        assert_eq!(recv.off, 0);
716
717        assert_emit_discard(&mut recv, emit, 10, 10, false, Some(b"somethingh"));
718        assert_eq!(recv.len, 19);
719        assert_eq!(recv.off, 10);
720
721        assert_emit_discard(&mut recv, emit, 5, 5, false, Some(b"ellow"));
722        assert_eq!(recv.len, 19);
723        assert_eq!(recv.off, 15);
724
725        assert_emit_discard(&mut recv, emit, 5, 4, true, Some(b"orld"));
726        assert_eq!(recv.len, 19);
727        assert_eq!(recv.off, 19);
728    }
729
730    #[test]
731    fn split_read_incremental_buf() {
732        let mut recv =
733            RecvBuf::new(u64::MAX, DEFAULT_STREAM_WINDOW, DEFAULT_STREAM_WINDOW);
734        assert_eq!(recv.len, 0);
735
736        let first = RangeBuf::from(b"something", 0, false);
737        let second = RangeBuf::from(b"helloworld", 9, true);
738
739        assert!(recv.write(first).is_ok());
740        assert_eq!(recv.len, 9);
741        assert_eq!(recv.off, 0);
742
743        assert!(recv.write(second).is_ok());
744        assert_eq!(recv.len, 19);
745        assert_eq!(recv.off, 0);
746
747        let mut buf = Vec::new().limit(10);
748        assert_eq!(
749            recv.emit_or_discard(RecvAction::Emit { out: &mut buf }),
750            Ok((10, false))
751        );
752        assert_eq!(recv.len, 19);
753        assert_eq!(recv.off, 10);
754        assert_eq!(buf.get_ref().len(), 10);
755        assert_eq!(buf.get_ref().as_slice(), b"somethingh");
756
757        buf.set_limit(5);
758        assert_eq!(
759            recv.emit_or_discard(RecvAction::Emit { out: &mut buf }),
760            Ok((5, false))
761        );
762        assert_eq!(recv.len, 19);
763        assert_eq!(recv.off, 15);
764        assert_eq!(buf.get_ref().len(), 15);
765        assert_eq!(buf.get_ref().as_slice(), b"somethinghellow");
766
767        buf.set_limit(42);
768        assert_eq!(
769            recv.emit_or_discard(RecvAction::Emit { out: &mut buf }),
770            Ok((4, true))
771        );
772        assert_eq!(recv.len, 19);
773        assert_eq!(recv.off, 19);
774        assert_eq!(buf.get_ref().len(), 19);
775        assert_eq!(buf.get_ref().as_slice(), b"somethinghelloworld");
776    }
777
778    #[rstest]
779    fn incomplete_read(#[values(true, false)] emit: bool) {
780        let mut recv =
781            RecvBuf::new(u64::MAX, DEFAULT_STREAM_WINDOW, DEFAULT_STREAM_WINDOW);
782        assert_eq!(recv.len, 0);
783
784        let mut buf = [0u8; 32];
785
786        let first = RangeBuf::from(b"something", 0, false);
787        let second = RangeBuf::from(b"helloworld", 9, true);
788
789        assert!(recv.write(second).is_ok());
790        assert_eq!(recv.len, 19);
791        assert_eq!(recv.off, 0);
792
793        let action = if emit {
794            RecvAction::Emit {
795                out: &mut buf.as_mut_slice(),
796            }
797        } else {
798            RecvAction::Discard { len: 32 }
799        };
800        assert_eq!(recv.emit_or_discard(action), Err(Error::Done));
801
802        assert!(recv.write(first).is_ok());
803        assert_eq!(recv.len, 19);
804        assert_eq!(recv.off, 0);
805
806        assert_emit_discard(
807            &mut recv,
808            emit,
809            32,
810            19,
811            true,
812            Some(b"somethinghelloworld"),
813        );
814        assert_eq!(recv.len, 19);
815        assert_eq!(recv.off, 19);
816    }
817
818    #[rstest]
819    fn zero_len_read(#[values(true, false)] emit: bool) {
820        let mut recv =
821            RecvBuf::new(u64::MAX, DEFAULT_STREAM_WINDOW, DEFAULT_STREAM_WINDOW);
822        assert_eq!(recv.len, 0);
823
824        let first = RangeBuf::from(b"something", 0, false);
825        let second = RangeBuf::from(b"", 9, true);
826
827        assert!(recv.write(first).is_ok());
828        assert_eq!(recv.len, 9);
829        assert_eq!(recv.off, 0);
830        assert_eq!(recv.data.len(), 1);
831
832        assert!(recv.write(second).is_ok());
833        assert_eq!(recv.len, 9);
834        assert_eq!(recv.off, 0);
835        assert_eq!(recv.data.len(), 1);
836
837        assert_emit_discard(&mut recv, emit, 32, 9, true, Some(b"something"));
838        assert_eq!(recv.len, 9);
839        assert_eq!(recv.off, 9);
840    }
841
842    #[rstest]
843    fn past_read(#[values(true, false)] emit: bool) {
844        let mut recv =
845            RecvBuf::new(u64::MAX, DEFAULT_STREAM_WINDOW, DEFAULT_STREAM_WINDOW);
846        assert_eq!(recv.len, 0);
847
848        let first = RangeBuf::from(b"something", 0, false);
849        let second = RangeBuf::from(b"hello", 3, false);
850        let third = RangeBuf::from(b"ello", 4, true);
851        let fourth = RangeBuf::from(b"ello", 5, true);
852
853        assert!(recv.write(first).is_ok());
854        assert_eq!(recv.len, 9);
855        assert_eq!(recv.off, 0);
856        assert_eq!(recv.data.len(), 1);
857
858        assert_emit_discard(&mut recv, emit, 32, 9, false, Some(b"something"));
859        assert_eq!(recv.len, 9);
860        assert_eq!(recv.off, 9);
861
862        assert!(recv.write(second).is_ok());
863        assert_eq!(recv.len, 9);
864        assert_eq!(recv.off, 9);
865        assert_eq!(recv.data.len(), 0);
866
867        assert_eq!(recv.write(third), Err(Error::FinalSize));
868
869        assert!(recv.write(fourth).is_ok());
870        assert_eq!(recv.len, 9);
871        assert_eq!(recv.off, 9);
872        assert_eq!(recv.data.len(), 0);
873
874        assert_emit_discard_done(&mut recv, emit);
875    }
876
877    #[rstest]
878    fn fully_overlapping_read(#[values(true, false)] emit: bool) {
879        let mut recv =
880            RecvBuf::new(u64::MAX, DEFAULT_STREAM_WINDOW, DEFAULT_STREAM_WINDOW);
881        assert_eq!(recv.len, 0);
882
883        let first = RangeBuf::from(b"something", 0, false);
884        let second = RangeBuf::from(b"hello", 4, false);
885
886        assert!(recv.write(first).is_ok());
887        assert_eq!(recv.len, 9);
888        assert_eq!(recv.off, 0);
889        assert_eq!(recv.data.len(), 1);
890
891        assert!(recv.write(second).is_ok());
892        assert_eq!(recv.len, 9);
893        assert_eq!(recv.off, 0);
894        assert_eq!(recv.data.len(), 1);
895
896        assert_emit_discard(&mut recv, emit, 32, 9, false, Some(b"something"));
897        assert_eq!(recv.len, 9);
898        assert_eq!(recv.off, 9);
899        assert_eq!(recv.data.len(), 0);
900
901        assert_emit_discard_done(&mut recv, emit);
902    }
903
904    #[rstest]
905    fn fully_overlapping_read2(#[values(true, false)] emit: bool) {
906        let mut recv =
907            RecvBuf::new(u64::MAX, DEFAULT_STREAM_WINDOW, DEFAULT_STREAM_WINDOW);
908        assert_eq!(recv.len, 0);
909
910        let first = RangeBuf::from(b"something", 0, false);
911        let second = RangeBuf::from(b"hello", 4, false);
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!(recv.write(first).is_ok());
919        assert_eq!(recv.len, 9);
920        assert_eq!(recv.off, 0);
921        assert_eq!(recv.data.len(), 2);
922
923        assert_emit_discard(&mut recv, emit, 32, 9, false, Some(b"somehello"));
924        assert_eq!(recv.len, 9);
925        assert_eq!(recv.off, 9);
926        assert_eq!(recv.data.len(), 0);
927
928        assert_emit_discard_done(&mut recv, emit);
929    }
930
931    #[rstest]
932    fn fully_overlapping_read3(#[values(true, false)] emit: bool) {
933        let mut recv =
934            RecvBuf::new(u64::MAX, DEFAULT_STREAM_WINDOW, DEFAULT_STREAM_WINDOW);
935        assert_eq!(recv.len, 0);
936
937        let first = RangeBuf::from(b"something", 0, false);
938        let second = RangeBuf::from(b"hello", 3, false);
939
940        assert!(recv.write(second).is_ok());
941        assert_eq!(recv.len, 8);
942        assert_eq!(recv.off, 0);
943        assert_eq!(recv.data.len(), 1);
944
945        assert!(recv.write(first).is_ok());
946        assert_eq!(recv.len, 9);
947        assert_eq!(recv.off, 0);
948        assert_eq!(recv.data.len(), 3);
949
950        assert_emit_discard(&mut recv, emit, 32, 9, false, Some(b"somhellog"));
951        assert_eq!(recv.len, 9);
952        assert_eq!(recv.off, 9);
953        assert_eq!(recv.data.len(), 0);
954
955        assert_emit_discard_done(&mut recv, emit);
956    }
957
958    #[rstest]
959    fn fully_overlapping_read_multi(#[values(true, false)] emit: bool) {
960        let mut recv =
961            RecvBuf::new(u64::MAX, DEFAULT_STREAM_WINDOW, DEFAULT_STREAM_WINDOW);
962        assert_eq!(recv.len, 0);
963
964        let first = RangeBuf::from(b"somethingsomething", 0, false);
965        let second = RangeBuf::from(b"hello", 3, false);
966        let third = RangeBuf::from(b"hello", 12, false);
967
968        assert!(recv.write(second).is_ok());
969        assert_eq!(recv.len, 8);
970        assert_eq!(recv.off, 0);
971        assert_eq!(recv.data.len(), 1);
972
973        assert!(recv.write(third).is_ok());
974        assert_eq!(recv.len, 17);
975        assert_eq!(recv.off, 0);
976        assert_eq!(recv.data.len(), 2);
977
978        assert!(recv.write(first).is_ok());
979        assert_eq!(recv.len, 18);
980        assert_eq!(recv.off, 0);
981        assert_eq!(recv.data.len(), 5);
982
983        assert_emit_discard(
984            &mut recv,
985            emit,
986            32,
987            18,
988            false,
989            Some(b"somhellogsomhellog"),
990        );
991        assert_eq!(recv.len, 18);
992        assert_eq!(recv.off, 18);
993        assert_eq!(recv.data.len(), 0);
994
995        assert_emit_discard_done(&mut recv, emit);
996    }
997
998    #[rstest]
999    fn overlapping_start_read(#[values(true, false)] emit: bool) {
1000        let mut recv =
1001            RecvBuf::new(u64::MAX, DEFAULT_STREAM_WINDOW, DEFAULT_STREAM_WINDOW);
1002        assert_eq!(recv.len, 0);
1003
1004        let first = RangeBuf::from(b"something", 0, false);
1005        let second = RangeBuf::from(b"hello", 8, true);
1006
1007        assert!(recv.write(first).is_ok());
1008        assert_eq!(recv.len, 9);
1009        assert_eq!(recv.off, 0);
1010        assert_eq!(recv.data.len(), 1);
1011
1012        assert!(recv.write(second).is_ok());
1013        assert_eq!(recv.len, 13);
1014        assert_eq!(recv.off, 0);
1015        assert_eq!(recv.data.len(), 2);
1016
1017        assert_emit_discard(
1018            &mut recv,
1019            emit,
1020            32,
1021            13,
1022            true,
1023            Some(b"somethingello"),
1024        );
1025
1026        assert_eq!(recv.len, 13);
1027        assert_eq!(recv.off, 13);
1028
1029        assert_emit_discard_done(&mut recv, emit);
1030    }
1031
1032    #[rstest]
1033    fn overlapping_end_read(#[values(true, false)] emit: bool) {
1034        let mut recv =
1035            RecvBuf::new(u64::MAX, DEFAULT_STREAM_WINDOW, DEFAULT_STREAM_WINDOW);
1036        assert_eq!(recv.len, 0);
1037
1038        let first = RangeBuf::from(b"hello", 0, false);
1039        let second = RangeBuf::from(b"something", 3, true);
1040
1041        assert!(recv.write(second).is_ok());
1042        assert_eq!(recv.len, 12);
1043        assert_eq!(recv.off, 0);
1044        assert_eq!(recv.data.len(), 1);
1045
1046        assert!(recv.write(first).is_ok());
1047        assert_eq!(recv.len, 12);
1048        assert_eq!(recv.off, 0);
1049        assert_eq!(recv.data.len(), 2);
1050
1051        assert_emit_discard(&mut recv, emit, 32, 12, true, Some(b"helsomething"));
1052        assert_eq!(recv.len, 12);
1053        assert_eq!(recv.off, 12);
1054
1055        assert_emit_discard_done(&mut recv, emit);
1056    }
1057
1058    #[rstest]
1059    fn overlapping_end_twice_read(#[values(true, false)] emit: bool) {
1060        let mut recv =
1061            RecvBuf::new(u64::MAX, DEFAULT_STREAM_WINDOW, DEFAULT_STREAM_WINDOW);
1062        assert_eq!(recv.len, 0);
1063
1064        let first = RangeBuf::from(b"he", 0, false);
1065        let second = RangeBuf::from(b"ow", 4, false);
1066        let third = RangeBuf::from(b"rl", 7, false);
1067        let fourth = RangeBuf::from(b"helloworld", 0, true);
1068
1069        assert!(recv.write(third).is_ok());
1070        assert_eq!(recv.len, 9);
1071        assert_eq!(recv.off, 0);
1072        assert_eq!(recv.data.len(), 1);
1073
1074        assert!(recv.write(second).is_ok());
1075        assert_eq!(recv.len, 9);
1076        assert_eq!(recv.off, 0);
1077        assert_eq!(recv.data.len(), 2);
1078
1079        assert!(recv.write(first).is_ok());
1080        assert_eq!(recv.len, 9);
1081        assert_eq!(recv.off, 0);
1082        assert_eq!(recv.data.len(), 3);
1083
1084        assert!(recv.write(fourth).is_ok());
1085        assert_eq!(recv.len, 10);
1086        assert_eq!(recv.off, 0);
1087        assert_eq!(recv.data.len(), 6);
1088
1089        assert_emit_discard(&mut recv, emit, 32, 10, true, Some(b"helloworld"));
1090        assert_eq!(recv.len, 10);
1091        assert_eq!(recv.off, 10);
1092
1093        assert_emit_discard_done(&mut recv, emit);
1094    }
1095
1096    #[rstest]
1097    fn overlapping_end_twice_and_contained_read(
1098        #[values(true, false)] emit: bool,
1099    ) {
1100        let mut recv =
1101            RecvBuf::new(u64::MAX, DEFAULT_STREAM_WINDOW, DEFAULT_STREAM_WINDOW);
1102        assert_eq!(recv.len, 0);
1103
1104        let first = RangeBuf::from(b"hellow", 0, false);
1105        let second = RangeBuf::from(b"barfoo", 10, true);
1106        let third = RangeBuf::from(b"rl", 7, false);
1107        let fourth = RangeBuf::from(b"elloworldbarfoo", 1, true);
1108
1109        assert!(recv.write(third).is_ok());
1110        assert_eq!(recv.len, 9);
1111        assert_eq!(recv.off, 0);
1112        assert_eq!(recv.data.len(), 1);
1113
1114        assert!(recv.write(second).is_ok());
1115        assert_eq!(recv.len, 16);
1116        assert_eq!(recv.off, 0);
1117        assert_eq!(recv.data.len(), 2);
1118
1119        assert!(recv.write(first).is_ok());
1120        assert_eq!(recv.len, 16);
1121        assert_eq!(recv.off, 0);
1122        assert_eq!(recv.data.len(), 3);
1123
1124        assert!(recv.write(fourth).is_ok());
1125        assert_eq!(recv.len, 16);
1126        assert_eq!(recv.off, 0);
1127        assert_eq!(recv.data.len(), 5);
1128
1129        assert_emit_discard(
1130            &mut recv,
1131            emit,
1132            32,
1133            16,
1134            true,
1135            Some(b"helloworldbarfoo"),
1136        );
1137        assert_eq!(recv.len, 16);
1138        assert_eq!(recv.off, 16);
1139
1140        assert_emit_discard_done(&mut recv, emit);
1141    }
1142
1143    #[rstest]
1144    fn partially_multi_overlapping_reordered_read(
1145        #[values(true, false)] emit: bool,
1146    ) {
1147        let mut recv =
1148            RecvBuf::new(u64::MAX, DEFAULT_STREAM_WINDOW, DEFAULT_STREAM_WINDOW);
1149        assert_eq!(recv.len, 0);
1150
1151        let first = RangeBuf::from(b"hello", 8, false);
1152        let second = RangeBuf::from(b"something", 0, false);
1153        let third = RangeBuf::from(b"moar", 11, true);
1154
1155        assert!(recv.write(first).is_ok());
1156        assert_eq!(recv.len, 13);
1157        assert_eq!(recv.off, 0);
1158        assert_eq!(recv.data.len(), 1);
1159
1160        assert!(recv.write(second).is_ok());
1161        assert_eq!(recv.len, 13);
1162        assert_eq!(recv.off, 0);
1163        assert_eq!(recv.data.len(), 2);
1164
1165        assert!(recv.write(third).is_ok());
1166        assert_eq!(recv.len, 15);
1167        assert_eq!(recv.off, 0);
1168        assert_eq!(recv.data.len(), 3);
1169
1170        assert_emit_discard(
1171            &mut recv,
1172            emit,
1173            32,
1174            15,
1175            true,
1176            Some(b"somethinhelloar"),
1177        );
1178        assert_eq!(recv.len, 15);
1179        assert_eq!(recv.off, 15);
1180        assert_eq!(recv.data.len(), 0);
1181
1182        assert_emit_discard_done(&mut recv, emit);
1183    }
1184
1185    #[rstest]
1186    fn partially_multi_overlapping_reordered_read2(
1187        #[values(true, false)] emit: bool,
1188    ) {
1189        let mut recv =
1190            RecvBuf::new(u64::MAX, DEFAULT_STREAM_WINDOW, DEFAULT_STREAM_WINDOW);
1191        assert_eq!(recv.len, 0);
1192
1193        let first = RangeBuf::from(b"aaa", 0, false);
1194        let second = RangeBuf::from(b"bbb", 2, false);
1195        let third = RangeBuf::from(b"ccc", 4, false);
1196        let fourth = RangeBuf::from(b"ddd", 6, false);
1197        let fifth = RangeBuf::from(b"eee", 9, false);
1198        let sixth = RangeBuf::from(b"fff", 11, false);
1199
1200        assert!(recv.write(second).is_ok());
1201        assert_eq!(recv.len, 5);
1202        assert_eq!(recv.off, 0);
1203        assert_eq!(recv.data.len(), 1);
1204
1205        assert!(recv.write(fourth).is_ok());
1206        assert_eq!(recv.len, 9);
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, 9);
1212        assert_eq!(recv.off, 0);
1213        assert_eq!(recv.data.len(), 3);
1214
1215        assert!(recv.write(first).is_ok());
1216        assert_eq!(recv.len, 9);
1217        assert_eq!(recv.off, 0);
1218        assert_eq!(recv.data.len(), 4);
1219
1220        assert!(recv.write(sixth).is_ok());
1221        assert_eq!(recv.len, 14);
1222        assert_eq!(recv.off, 0);
1223        assert_eq!(recv.data.len(), 5);
1224
1225        assert!(recv.write(fifth).is_ok());
1226        assert_eq!(recv.len, 14);
1227        assert_eq!(recv.off, 0);
1228        assert_eq!(recv.data.len(), 6);
1229
1230        assert_emit_discard(
1231            &mut recv,
1232            emit,
1233            32,
1234            14,
1235            false,
1236            Some(b"aabbbcdddeefff"),
1237        );
1238        assert_eq!(recv.len, 14);
1239        assert_eq!(recv.off, 14);
1240        assert_eq!(recv.data.len(), 0);
1241
1242        assert_emit_discard_done(&mut recv, emit);
1243    }
1244
1245    #[test]
1246    fn mixed_read_actions() {
1247        let mut recv =
1248            RecvBuf::new(u64::MAX, DEFAULT_STREAM_WINDOW, DEFAULT_STREAM_WINDOW);
1249        assert_eq!(recv.len, 0);
1250
1251        let first = RangeBuf::from(b"hello", 0, false);
1252        let second = RangeBuf::from(b"world", 5, false);
1253        let third = RangeBuf::from(b"something", 10, true);
1254
1255        assert!(recv.write(second).is_ok());
1256        assert_eq!(recv.len, 10);
1257        assert_eq!(recv.off, 0);
1258
1259        assert_emit_discard_done(&mut recv, true);
1260        assert_emit_discard_done(&mut recv, false);
1261
1262        assert!(recv.write(third).is_ok());
1263        assert_eq!(recv.len, 19);
1264        assert_eq!(recv.off, 0);
1265
1266        assert_emit_discard_done(&mut recv, true);
1267        assert_emit_discard_done(&mut recv, false);
1268
1269        assert!(recv.write(first).is_ok());
1270        assert_eq!(recv.len, 19);
1271        assert_eq!(recv.off, 0);
1272
1273        assert_emit_discard(&mut recv, true, 5, 5, false, Some(b"hello"));
1274        assert_eq!(recv.len, 19);
1275        assert_eq!(recv.off, 5);
1276
1277        assert_emit_discard(&mut recv, false, 5, 5, false, None);
1278        assert_eq!(recv.len, 19);
1279        assert_eq!(recv.off, 10);
1280
1281        assert_emit_discard(&mut recv, true, 9, 9, true, Some(b"something"));
1282        assert_eq!(recv.len, 19);
1283        assert_eq!(recv.off, 19);
1284
1285        assert_emit_discard_done(&mut recv, true);
1286        assert_emit_discard_done(&mut recv, false);
1287    }
1288}