Skip to main content

mz_ore/
bytes.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License in the LICENSE file at the
6// root of this repository, or online at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! One bytes type to rule them all!
17//!
18//! TODO(parkertimmerman): Ideally we don't implement this "bytes type" on our own
19//! and use something else, e.g. `SegmentedBuf` from the `bytes-utils` crate. Currently
20//! that type, nor anything else, implement std::io::Read and std::io::Seek, which
21//! we need. We have an open issue with the `bytes-utils` crate, <https://github.com/vorner/bytes-utils/issues/16>
22//! to add these trait impls.
23//!
24
25#[cfg(feature = "parquet")]
26use std::io::Seek;
27
28use bytes::{Buf, BufMut, Bytes, BytesMut};
29use internal::SegmentedReader;
30#[cfg(feature = "parquet")]
31use parquet::errors::ParquetError;
32use serde::{Deserialize, Serialize};
33use smallvec::SmallVec;
34
35#[cfg(feature = "parquet")]
36use crate::cast::CastFrom;
37
38/// A cheaply clonable collection of possibly non-contiguous bytes.
39///
40/// `Vec<u8>` or `Bytes` are contiguous chunks of memory, which are fast (e.g. better cache
41/// locality) and easier to work with (e.g. can take a slice), but can cause problems (e.g.
42/// memory fragmentation) if you try to allocate a single very large chunk. Depending on the
43/// application, you probably don't need a contiguous chunk of memory, just a way to store and
44/// iterate over a collection of bytes.
45///
46/// Note: [`SegmentedBytes`] is generic over a `const N: usize`. Internally we use a
47/// [`smallvec::SmallVec`] to store our [`Bytes`] segments, and `N` is how many `Bytes` we'll
48/// store inline before spilling to the heap. We default `N = 1`, so in the case of a single
49/// `Bytes` segment, we avoid one layer of indirection.
50#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
51pub struct SegmentedBytes<const N: usize = 1> {
52    /// Collection of non-contiguous segments, each segment is guaranteed to be non-empty.
53    segments: SmallVec<[(Bytes, Padding); N]>,
54    /// Pre-computed length of all the segments.
55    len: usize,
56}
57
58/// We add [`Padding`] to segments to prevent needing to re-allocate our
59/// collection when creating a [`SegmentedReader`].
60type Padding = usize;
61
62/// Default value used for [`Padding`].
63const PADDING_DEFAULT: usize = 0;
64
65impl Default for SegmentedBytes {
66    fn default() -> Self {
67        SegmentedBytes {
68            segments: SmallVec::new(),
69            len: 0,
70        }
71    }
72}
73
74impl SegmentedBytes {
75    /// Creates a new empty [`SegmentedBytes`], reserving space inline for `N` **segments**.
76    ///
77    /// Note: If you don't know how many segments you have, you should use [`SegmentedBytes::default`].
78    pub fn new<const N: usize>() -> SegmentedBytes<N> {
79        SegmentedBytes {
80            segments: SmallVec::new(),
81            len: 0,
82        }
83    }
84}
85
86impl<const N: usize> SegmentedBytes<N> {
87    /// Creates a new empty [`SegmentedBytes`] with space for `capacity` **segments**.
88    pub fn with_capacity(capacity: usize) -> SegmentedBytes<N> {
89        SegmentedBytes {
90            segments: SmallVec::with_capacity(capacity),
91            len: 0,
92        }
93    }
94
95    /// Returns the number of bytes contained in this [`SegmentedBytes`].
96    pub fn len(&self) -> usize {
97        self.len
98    }
99
100    /// Returns if this [`SegmentedBytes`] is empty.
101    pub fn is_empty(&self) -> bool {
102        self.len() == 0
103    }
104
105    /// Consumes `self` returning an [`Iterator`] over all of the non-contiguous segments
106    /// that make up this buffer.
107    pub fn into_segments(self) -> impl Iterator<Item = Bytes> {
108        self.segments.into_iter().map(|(bytes, _len)| bytes)
109    }
110
111    /// Copies all of the bytes from `self` returning one contiguous blob.
112    pub fn into_contiguous(mut self) -> Vec<u8> {
113        self.copy_to_bytes(self.remaining()).into()
114    }
115
116    /// Extends the buffer by one more segment of [`Bytes`].
117    ///
118    /// If the provided [`Bytes`] is empty, we skip appending it.
119    #[inline]
120    pub fn push<B: Into<Bytes>>(&mut self, b: B) {
121        let b: Bytes = b.into();
122        if !b.is_empty() {
123            self.len += b.len();
124            self.segments.push((b, PADDING_DEFAULT));
125        }
126    }
127
128    /// Consumes `self` returning a type that implements [`io::Read`] and [`io::Seek`].
129    ///
130    /// Note: [`Clone`]-ing a [`SegmentedBytes`] is cheap, so if you need to retain the original
131    /// [`SegmentedBytes`] you should clone it.
132    ///
133    /// [`io::Read`]: std::io::Read
134    /// [`io::Seek`]: std::io::Seek
135    pub fn reader(self) -> SegmentedReader<N> {
136        SegmentedReader::new(self)
137    }
138}
139
140impl<const N: usize> Buf for SegmentedBytes<N> {
141    fn remaining(&self) -> usize {
142        self.len()
143    }
144
145    fn chunk(&self) -> &[u8] {
146        // Return the first non-empty segment.
147        self.segments
148            .iter()
149            .filter(|(c, _len)| !c.is_empty())
150            .map(|(c, _len)| Buf::chunk(c))
151            .next()
152            .unwrap_or_default()
153    }
154
155    fn advance(&mut self, mut cnt: usize) {
156        assert!(cnt <= self.len, "Advance past the end of buffer");
157        self.len -= cnt;
158
159        let mut consumed = 0;
160        for (seg, _len) in self.segments.iter_mut() {
161            if seg.remaining() > cnt {
162                seg.advance(cnt);
163                break;
164            }
165            cnt -= seg.remaining();
166            consumed += 1;
167        }
168        self.segments.drain(..consumed);
169    }
170
171    fn copy_to_bytes(&mut self, len: usize) -> Bytes {
172        // If possible, use the zero-copy implementation on individual segments.
173        if let Some((seg, _len)) = self.segments.first_mut() {
174            if len <= seg.len() {
175                self.len -= len;
176                return seg.copy_to_bytes(len);
177            }
178        }
179        // Otherwise, fall back to a generic implementation.
180        assert!(
181            len <= self.len(),
182            "tried to copy {len} bytes with {} remaining",
183            self.len()
184        );
185        let mut out = BytesMut::with_capacity(len);
186        out.put(self.take(len));
187        out.freeze()
188    }
189}
190
191#[cfg(feature = "parquet")]
192impl parquet::file::reader::Length for SegmentedBytes {
193    fn len(&self) -> u64 {
194        u64::cast_from(self.len)
195    }
196}
197
198#[cfg(feature = "parquet")]
199impl parquet::file::reader::ChunkReader for SegmentedBytes {
200    type T = internal::SegmentedReader;
201
202    fn get_read(&self, start: u64) -> parquet::errors::Result<Self::T> {
203        let mut reader = self.clone().reader();
204        reader.seek(std::io::SeekFrom::Start(start))?;
205        Ok(reader)
206    }
207
208    fn get_bytes(&self, start: u64, length: usize) -> parquet::errors::Result<Bytes> {
209        let start = usize::cast_from(start);
210        let mut buf = self.clone();
211        if start > buf.remaining() {
212            return Err(ParquetError::EOF(format!(
213                "seeking {start} bytes ahead, but only {} remaining",
214                buf.remaining()
215            )));
216        }
217        buf.advance(start);
218        if length > buf.remaining() {
219            return Err(ParquetError::EOF(format!(
220                "copying {length} bytes, but only {} remaining",
221                buf.remaining()
222            )));
223        }
224        let bytes = buf.copy_to_bytes(length);
225        Ok(bytes)
226    }
227}
228
229impl From<Bytes> for SegmentedBytes {
230    fn from(value: Bytes) -> Self {
231        let mut s = SegmentedBytes::default();
232        s.push(value);
233        s
234    }
235}
236
237impl From<Vec<u8>> for SegmentedBytes {
238    fn from(value: Vec<u8>) -> Self {
239        let b = Bytes::from(value);
240        SegmentedBytes::from(b)
241    }
242}
243
244impl From<Vec<Bytes>> for SegmentedBytes {
245    fn from(value: Vec<Bytes>) -> Self {
246        let mut s = SegmentedBytes::with_capacity(value.len());
247        for segment in value {
248            s.push(segment);
249        }
250        s
251    }
252}
253
254impl<const N: usize> FromIterator<Bytes> for SegmentedBytes<N> {
255    fn from_iter<T: IntoIterator<Item = Bytes>>(iter: T) -> Self {
256        let mut s = SegmentedBytes::new();
257        for segment in iter {
258            s.push(segment);
259        }
260        s
261    }
262}
263
264impl<const N: usize> FromIterator<Vec<u8>> for SegmentedBytes<N> {
265    fn from_iter<T: IntoIterator<Item = Vec<u8>>>(iter: T) -> Self {
266        iter.into_iter().map(Bytes::from).collect()
267    }
268}
269
270mod internal {
271    use std::io;
272
273    use smallvec::SmallVec;
274
275    use crate::bytes::{Bytes, SegmentedBytes};
276    use crate::cast::CastFrom;
277
278    /// Provides efficient reading and seeking across a collection of segmented bytes.
279    #[derive(Debug)]
280    pub struct SegmentedReader<const N: usize = 1> {
281        segments: SmallVec<[(Bytes, usize); N]>,
282        /// Total length of all segments.
283        len: usize,
284        // Overall byte position we're currently pointing at.
285        overall_ptr: usize,
286        /// Current segement that we'd read from.
287        segment_ptr: usize,
288    }
289
290    impl<const N: usize> SegmentedReader<N> {
291        pub fn new(mut bytes: SegmentedBytes<N>) -> Self {
292            // Re-adjust our accumlated lengths.
293            //
294            // Note: `SegmentedBytes` could track the accumulated lengths, but
295            // it's complicated by the impl of `Buf::advance`.
296            let mut accum_length = 0;
297            for (segment, len) in &mut bytes.segments {
298                accum_length += segment.len();
299                *len = accum_length;
300            }
301
302            SegmentedReader {
303                segments: bytes.segments,
304                len: bytes.len,
305                overall_ptr: 0,
306                segment_ptr: 0,
307            }
308        }
309
310        /// The total number of bytes this [`SegmentedReader`] is mapped over.
311        pub fn len(&self) -> usize {
312            self.len
313        }
314
315        /// The current position of the internal cursor for this [`SegmentedReader`].
316        ///
317        /// Note: It's possible for the current position to be greater than the length,
318        /// as [`std::io::Seek`] allows you to seek past the end of the stream.
319        pub fn position(&self) -> usize {
320            self.overall_ptr
321        }
322    }
323
324    impl<const N: usize> io::Read for SegmentedReader<N> {
325        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
326            // We've seeked past the end, return nothing.
327            if self.overall_ptr >= self.len {
328                return Ok(0);
329            }
330
331            let (segment, accum_length) = &self.segments[self.segment_ptr];
332
333            // How many bytes we have left in this segment.
334            let remaining_len = accum_length.checked_sub(self.overall_ptr).unwrap();
335            // Position within the segment to begin reading.
336            let segment_pos = segment.len().checked_sub(remaining_len).unwrap();
337
338            // How many bytes we'll read.
339            let len = core::cmp::min(remaining_len, buf.len());
340            // Copy bytes from the current segment into the buffer.
341            let segment_buf = &segment[..];
342            buf[..len].copy_from_slice(&segment_buf[segment_pos..segment_pos + len]);
343
344            // Advance our pointers.
345            self.overall_ptr += len;
346
347            // Advance to the next segment if we've reached the end of the current.
348            if self.overall_ptr == *accum_length {
349                self.segment_ptr += 1;
350            }
351
352            Ok(len)
353        }
354    }
355
356    impl<const N: usize> io::Seek for SegmentedReader<N> {
357        fn seek(&mut self, pos: io::SeekFrom) -> io::Result<u64> {
358            use io::SeekFrom;
359
360            // Get an offset from the start.
361            let maybe_offset = match pos {
362                SeekFrom::Start(n) => Some(usize::cast_from(n)),
363                SeekFrom::End(n) => {
364                    let n = isize::cast_from(n);
365                    self.len().checked_add_signed(n)
366                }
367                SeekFrom::Current(n) => {
368                    let n = isize::cast_from(n);
369                    self.overall_ptr.checked_add_signed(n)
370                }
371            };
372
373            // Check for integer overflow, but we don't check our bounds!
374            //
375            // The contract for io::Seek denotes that seeking beyond the end
376            // of the stream is allowed. If we're beyond the end of the stream
377            // then we won't read back any bytes, but it won't be an error.
378            let offset = maybe_offset.ok_or_else(|| {
379                io::Error::new(
380                    io::ErrorKind::InvalidInput,
381                    "Invalid seek to an overflowing position",
382                )
383            })?;
384
385            // Special case we want to be fast, seeking back to the beginning.
386            if offset == 0 {
387                self.overall_ptr = 0;
388                self.segment_ptr = 0;
389
390                return Ok(u64::cast_from(offset));
391            }
392
393            // Seek through our segments until we get to the correct offset.
394            let result = self
395                .segments
396                .binary_search_by(|(_s, accum_len)| accum_len.cmp(&offset));
397
398            self.segment_ptr = match result {
399                Ok(segment_ptr) => segment_ptr + 1,
400                Err(segment_ptr) => segment_ptr,
401            };
402            self.overall_ptr = offset;
403
404            Ok(u64::cast_from(offset))
405        }
406    }
407}
408
409#[cfg(test)]
410mod tests {
411    use std::io::{Read, Seek, SeekFrom};
412
413    use bytes::{Buf, Bytes};
414    use proptest::prelude::*;
415
416    use super::SegmentedBytes;
417    use crate::cast::CastFrom;
418
419    #[crate::test]
420    fn test_empty() {
421        let s = SegmentedBytes::default();
422
423        // We should report as empty.
424        assert!(s.is_empty());
425        assert_eq!(s.len(), 0);
426
427        // An iterator of segments should return nothing.
428        let mut i = s.clone().into_segments();
429        assert_eq!(i.next(), None);
430
431        // bytes::Buf shouldn't report anything as remaining.
432        assert_eq!(s.remaining(), 0);
433        // We should get back an empty chunk if we try to read anything.
434        assert!(s.chunk().is_empty());
435
436        // Turn ourselves into a type that impls io::Read.
437        let mut reader = s.reader();
438
439        // We shouldn't panic, but we shouldn't get back any bytes.
440        let mut buf = Vec::new();
441        let bytes_read = reader.read(&mut buf[..]).unwrap();
442        assert_eq!(bytes_read, 0);
443
444        // We should be able to seek past the end without panicking.
445        reader.seek(SeekFrom::Current(20)).unwrap();
446        let bytes_read = reader.read(&mut buf[..]).unwrap();
447        assert_eq!(bytes_read, 0);
448    }
449
450    #[crate::test]
451    fn test_bytes_buf() {
452        let mut s = SegmentedBytes::from(vec![0, 1, 2, 3, 4, 5, 6, 7]);
453
454        assert_eq!(s.len(), 8);
455        assert_eq!(s.len(), s.remaining());
456        assert_eq!(s.chunk(), &[0, 1, 2, 3, 4, 5, 6, 7]);
457
458        // Advance far into the buffer.
459        s.advance(6);
460        assert_eq!(s.len(), 2);
461        assert_eq!(s.len(), s.remaining());
462        assert_eq!(s.chunk(), &[6, 7]);
463    }
464
465    #[crate::test]
466    fn test_bytes_buf_multi() {
467        let segments = vec![vec![0, 1, 2, 3], vec![4, 5, 6, 7], vec![8, 9, 10, 11]];
468        let mut s: SegmentedBytes<2> = segments.into_iter().collect();
469
470        assert_eq!(s.len(), 12);
471        assert_eq!(s.len(), s.remaining());
472
473        // Chunk should return the entirety of the first segment.
474        assert_eq!(s.chunk(), &[0, 1, 2, 3]);
475
476        // Advance into the middle segment
477        s.advance(6);
478        assert_eq!(s.len(), 6);
479        assert_eq!(s.len(), s.remaining());
480
481        // Chunk should return the rest of the second segment.
482        assert_eq!(s.chunk(), &[6, 7]);
483
484        // Read across two segments.
485        let x = s.get_u32();
486        assert_eq!(x, u32::from_be_bytes([6, 7, 8, 9]));
487
488        // Only two bytes remaining.
489        assert_eq!(s.len(), 2);
490        assert_eq!(s.len(), s.remaining());
491
492        let mut s = s.chain(&[12, 13, 14, 15][..]);
493
494        // Should have 6 bytes total now.
495        assert_eq!(s.remaining(), 6);
496        // We'll read out the last two bytes from the last segment.
497        assert_eq!(s.chunk(), &[10, 11]);
498
499        // Advance into the chained segment.
500        s.advance(3);
501        // Read the remaining bytes.
502        assert_eq!(s.chunk(), &[13, 14, 15]);
503    }
504
505    #[crate::test]
506    fn test_io_read() {
507        let s = SegmentedBytes::from(vec![0, 1, 2, 3, 4, 5, 6, 7]);
508        let mut reader = s.reader();
509
510        assert_eq!(reader.len(), 8);
511        assert_eq!(reader.position(), 0);
512
513        // Read a small amount.
514        let mut buf = [0; 4];
515        let bytes_read = reader.read(&mut buf).unwrap();
516        assert_eq!(bytes_read, 4);
517        assert_eq!(buf, [0, 1, 2, 3]);
518
519        // We should still report our original length.
520        assert_eq!(reader.len(), 8);
521        // But our position has moved.
522        assert_eq!(reader.position(), 4);
523
524        // We can seek forwards and read bytes.
525        reader.seek(SeekFrom::Current(1)).unwrap();
526        let bytes_read = reader.read(&mut buf).unwrap();
527        assert_eq!(bytes_read, 3);
528        assert_eq!(buf, [5, 6, 7, 3]);
529
530        assert_eq!(reader.len(), 8);
531        // We've read to the end!
532        assert_eq!(reader.position(), 8);
533
534        // We shouldn't read any bytes
535        let bytes_read = reader.read(&mut buf).unwrap();
536        assert_eq!(bytes_read, 0);
537        // Buffer shouldn't change from what it was last.
538        assert_eq!(buf, [5, 6, 7, 3]);
539
540        // Seek backwards and re-read bytes.
541        reader.seek(SeekFrom::Start(2)).unwrap();
542        let bytes_read = reader.read(&mut buf).unwrap();
543        assert_eq!(bytes_read, 4);
544        assert_eq!(buf, [2, 3, 4, 5]);
545    }
546
547    #[crate::test]
548    fn test_io_read_multi() {
549        let segments = vec![vec![0, 1, 2, 3], vec![4, 5, 6, 7, 8, 9], vec![10, 11]];
550        let s: SegmentedBytes<2> = segments.into_iter().collect();
551        let mut reader = s.reader();
552
553        assert_eq!(reader.len(), 12);
554        assert_eq!(reader.position(), 0);
555
556        // Read up to the first segment.
557        let mut buf = [0; 6];
558        let bytes_read = reader.read(&mut buf).unwrap();
559        assert_eq!(bytes_read, 4);
560        assert_eq!(buf, [0, 1, 2, 3, 0, 0]);
561
562        // Read 5 bytes, which should come from the second segment.
563        let bytes_read = reader.read(&mut buf[1..]).unwrap();
564        assert_eq!(bytes_read, 5);
565        assert_eq!(buf, [0, 4, 5, 6, 7, 8]);
566
567        // Seek backwards to the middle of the first segment.
568        reader.seek(SeekFrom::Start(2)).unwrap();
569        let bytes_read = reader.read(&mut buf).unwrap();
570        assert_eq!(bytes_read, 2);
571        assert_eq!(buf, [2, 3, 5, 6, 7, 8]);
572
573        // Seek past the end.
574        reader.seek(SeekFrom::Start(1000)).unwrap();
575        let bytes_read = reader.read(&mut buf).unwrap();
576        assert_eq!(bytes_read, 0);
577
578        assert_eq!(reader.len(), 12);
579        assert_eq!(reader.position(), 1000);
580
581        // Seek back to the middle.
582        reader.seek(SeekFrom::Start(6)).unwrap();
583        // Read the entire bufffer.
584        let mut buf = Vec::new();
585        let bytes_read = reader.read_to_end(&mut buf).unwrap();
586        assert_eq!(bytes_read, 6);
587        assert_eq!(buf, &[6, 7, 8, 9, 10, 11]);
588    }
589
590    #[crate::test]
591    fn test_multi() {
592        let segments = vec![vec![0, 1, 2, 3], vec![4, 5, 6, 7, 8, 9], vec![10, 11]];
593        let mut s: SegmentedBytes<2> = segments.into_iter().collect();
594
595        assert_eq!(s.len(), 12);
596        assert_eq!(s.remaining(), 12);
597
598        // Read the first chunk.
599        assert_eq!(s.chunk(), [0, 1, 2, 3]);
600
601        // Advance to the middle.
602        s.advance(6);
603        assert_eq!(s.remaining(), 6);
604
605        // Convert to a reader.
606        let mut reader = s.reader();
607        // We should be at the beginning, and only see the remaining 6 bytes.
608        assert_eq!(reader.len(), 6);
609        assert_eq!(reader.position(), 0);
610
611        // Read to the end of the second segment.
612        let mut buf = [0; 8];
613        let bytes_read = reader.read(&mut buf).unwrap();
614        assert_eq!(bytes_read, 4);
615        assert_eq!(buf, [6, 7, 8, 9, 0, 0, 0, 0]);
616
617        // Read again to get the final segment.
618        let bytes_read = reader.read(&mut buf[4..]).unwrap();
619        assert_eq!(bytes_read, 2);
620        assert_eq!(buf, [6, 7, 8, 9, 10, 11, 0, 0]);
621
622        // Seek back to the beginning.
623        reader.seek(SeekFrom::Start(0)).unwrap();
624        // Read everything.
625        reader.read_exact(&mut buf[..6]).unwrap();
626        assert_eq!(buf, [6, 7, 8, 9, 10, 11, 0, 0]);
627    }
628
629    #[crate::test]
630    fn test_single_empty_segment() {
631        let s = SegmentedBytes::from(Vec::<u8>::new());
632
633        // Everything should comeback empty.
634        assert_eq!(s.len(), 0);
635        assert_eq!(s.remaining(), 0);
636        assert!(s.chunk().is_empty());
637
638        let mut reader = s.reader();
639
640        // Reading shouldn't fail, but it also shouldn't yield any bytes.
641        let mut buf = [0; 4];
642        let bytes_read = reader.read(&mut buf).unwrap();
643        assert_eq!(bytes_read, 0);
644        assert_eq!(buf, [0, 0, 0, 0]);
645    }
646
647    #[crate::test]
648    fn test_middle_segment_empty() {
649        let segments = vec![vec![1, 2], vec![], vec![3, 4, 5, 6]];
650        let mut s: SegmentedBytes = segments.clone().into_iter().collect();
651
652        assert_eq!(s.len(), 6);
653        assert_eq!(s.remaining(), 6);
654
655        // Read and advanced past the first chunk.
656        let first_chunk = s.chunk();
657        assert_eq!(first_chunk, [1, 2]);
658        s.advance(first_chunk.len());
659
660        assert_eq!(s.remaining(), 4);
661
662        // We should skip the empty segment and continue to the next.
663        let second_chunk = s.chunk();
664        assert_eq!(second_chunk, [3, 4, 5, 6]);
665
666        // Recreate SegmentedBytes.
667        let s: SegmentedBytes = segments.into_iter().collect();
668        let mut reader = s.reader();
669
670        // We should be able to read the first chunk.
671        let mut buf = [0; 4];
672        let bytes_read = reader.read(&mut buf).unwrap();
673        assert_eq!(bytes_read, 2);
674        assert_eq!(buf, [1, 2, 0, 0]);
675
676        // And we should be able to read the second chunk without issue.
677        let bytes_read = reader.read(&mut buf).unwrap();
678        assert_eq!(bytes_read, 4);
679        assert_eq!(buf, [3, 4, 5, 6]);
680
681        // Seek backwards and read again.
682        reader.seek(SeekFrom::Current(-2)).unwrap();
683        let bytes_read = reader.read(&mut buf).unwrap();
684        assert_eq!(bytes_read, 2);
685        assert_eq!(buf, [5, 6, 5, 6]);
686    }
687
688    #[crate::test]
689    fn test_last_segment_empty() {
690        let segments = vec![vec![1, 2], vec![3, 4, 5, 6], vec![]];
691        let mut s: SegmentedBytes = segments.clone().into_iter().collect();
692
693        assert_eq!(s.len(), 6);
694        assert_eq!(s.remaining(), 6);
695
696        // Read and advanced past the first chunk.
697        let first_chunk = s.chunk();
698        assert_eq!(first_chunk, [1, 2]);
699        s.advance(first_chunk.len());
700
701        assert_eq!(s.remaining(), 4);
702
703        // Read and advance past the second chunk.
704        let second_chunk = s.chunk();
705        assert_eq!(second_chunk, [3, 4, 5, 6]);
706        s.advance(second_chunk.len());
707
708        // No bytes should remain.
709        assert_eq!(s.remaining(), 0);
710        assert!(s.chunk().is_empty());
711
712        // Recreate SegmentedBytes.
713        let s: SegmentedBytes = segments.into_iter().collect();
714        let mut reader = s.reader();
715
716        // We should be able to read the first chunk.
717        let mut buf = [0; 4];
718        let bytes_read = reader.read(&mut buf).unwrap();
719        assert_eq!(bytes_read, 2);
720        assert_eq!(buf, [1, 2, 0, 0]);
721
722        // And we should be able to read the second chunk without issue.
723        let bytes_read = reader.read(&mut buf).unwrap();
724        assert_eq!(bytes_read, 4);
725        assert_eq!(buf, [3, 4, 5, 6]);
726
727        // Reading again shouldn't provide any bytes.
728        let bytes_read = reader.read(&mut buf).unwrap();
729        assert_eq!(bytes_read, 0);
730        // Buffer shouldn't change.
731        assert_eq!(buf, [3, 4, 5, 6]);
732
733        // Seek backwards and read again.
734        reader.seek(SeekFrom::Current(-2)).unwrap();
735        let bytes_read = reader.read(&mut buf).unwrap();
736        assert_eq!(bytes_read, 2);
737        assert_eq!(buf, [5, 6, 5, 6]);
738    }
739
740    #[crate::test]
741    #[cfg_attr(miri, ignore)] // slow
742    fn proptest_copy_to_bytes() {
743        fn test(segments: Vec<Vec<u8>>, num_bytes: usize) {
744            let contiguous: Vec<u8> = segments.clone().into_iter().flatten().collect();
745            let mut contiguous = Bytes::from(contiguous);
746            let mut segmented: SegmentedBytes = segments.into_iter().map(Bytes::from).collect();
747
748            // Cap num_bytes at the size of contiguous.
749            let num_bytes = contiguous.len() % num_bytes;
750            let remaining = contiguous.len() - num_bytes;
751
752            let copied_c = contiguous.copy_to_bytes(num_bytes);
753            let copied_s = segmented.copy_to_bytes(num_bytes);
754
755            assert_eq!(copied_c, copied_s);
756
757            let copied_c = contiguous.copy_to_bytes(remaining);
758            let copied_s = segmented.copy_to_bytes(remaining);
759
760            assert_eq!(copied_c, copied_s);
761        }
762
763        proptest!(|(segments in any::<Vec<Vec<u8>>>(), num_bytes in any::<usize>())| {
764            test(segments, num_bytes);
765        })
766    }
767
768    #[crate::test]
769    #[cfg_attr(miri, ignore)] // slow
770    fn proptest_read_to_end() {
771        fn test(segments: Vec<Vec<u8>>) {
772            let contiguous: Vec<u8> = segments.clone().into_iter().flatten().collect();
773            let contiguous = Bytes::from(contiguous);
774            let segmented: SegmentedBytes = segments.into_iter().map(Bytes::from).collect();
775
776            let mut reader_c = contiguous.reader();
777            let mut reader_s = segmented.reader();
778
779            let mut buf_c = Vec::new();
780            reader_c.read_to_end(&mut buf_c).unwrap();
781
782            let mut buf_s = Vec::new();
783            reader_s.read_to_end(&mut buf_s).unwrap();
784
785            assert_eq!(buf_c, buf_s);
786        }
787
788        proptest!(|(segments in any::<Vec<Vec<u8>>>())| {
789            test(segments);
790        })
791    }
792
793    #[crate::test]
794    #[cfg_attr(miri, ignore)] // slow
795    fn proptest_read_and_seek() {
796        fn test(segments: Vec<Vec<u8>>, from_start: u64, from_current: i64, from_end: i64) {
797            let contiguous: Vec<u8> = segments.clone().into_iter().flatten().collect();
798            let total_len = contiguous.len();
799            let contiguous = std::io::Cursor::new(&contiguous[..]);
800            let segmented: SegmentedBytes = segments.into_iter().map(Bytes::from).collect();
801
802            let mut reader_c = contiguous;
803            let mut reader_s = segmented.reader();
804
805            let mut buf_c = Vec::new();
806            let mut buf_s = Vec::new();
807
808            // Seek from the start.
809
810            let from_start = from_start % (u64::cast_from(total_len).max(1));
811            reader_c.seek(SeekFrom::Start(from_start)).unwrap();
812            reader_s.seek(SeekFrom::Start(from_start)).unwrap();
813
814            reader_c.read_to_end(&mut buf_c).unwrap();
815            reader_s.read_to_end(&mut buf_s).unwrap();
816
817            assert_eq!(&buf_c, &buf_s);
818            buf_c.clear();
819            buf_s.clear();
820
821            // Seek from the current position.
822
823            let from_current = from_current % i64::try_from(total_len).unwrap().max(1);
824            reader_c.seek(SeekFrom::Current(from_current)).unwrap();
825            reader_s.seek(SeekFrom::Current(from_current)).unwrap();
826
827            reader_c.read_to_end(&mut buf_c).unwrap();
828            reader_s.read_to_end(&mut buf_s).unwrap();
829
830            assert_eq!(&buf_c, &buf_s);
831            buf_c.clear();
832            buf_s.clear();
833
834            // Seek from the end.
835
836            let from_end = from_end % i64::try_from(total_len).unwrap().max(1);
837            reader_c.seek(SeekFrom::End(from_end)).unwrap();
838            reader_s.seek(SeekFrom::End(from_end)).unwrap();
839
840            reader_c.read_to_end(&mut buf_c).unwrap();
841            reader_s.read_to_end(&mut buf_s).unwrap();
842
843            assert_eq!(&buf_c, &buf_s);
844            buf_c.clear();
845            buf_s.clear();
846        }
847
848        proptest!(|(
849            segments in any::<Vec<Vec<u8>>>(),
850            s in any::<u64>(),
851            c in any::<i64>(),
852            e in any::<i64>(),
853        )| {
854            test(segments, s, c, e);
855        })
856    }
857
858    #[crate::test]
859    #[cfg_attr(miri, ignore)] // slow
860    fn proptest_non_empty_segments() {
861        fn test(segments: Vec<Vec<u8>>) {
862            // Vec
863            let segment = segments.first().cloned().unwrap_or_default();
864            let s = SegmentedBytes::from(segment.clone());
865            assert!(s.into_segments().all(|segment| !segment.is_empty()));
866
867            // Bytes
868            let bytes = Bytes::from(segment.clone());
869            let s = SegmentedBytes::from(bytes);
870            assert!(s.into_segments().all(|segment| !segment.is_empty()));
871
872            // SegmentedBytes::push
873            let mut s = SegmentedBytes::default();
874            s.push(Bytes::from(segment));
875            assert!(s.into_segments().all(|segment| !segment.is_empty()));
876
877            // Vec<Vec<u8>>
878            let s: SegmentedBytes = segments.clone().into_iter().collect();
879            assert!(s.into_segments().all(|segment| !segment.is_empty()));
880
881            // Vec<Bytes>
882            let s: SegmentedBytes = segments.clone().into_iter().map(Bytes::from).collect();
883            assert!(s.into_segments().all(|segment| !segment.is_empty()));
884
885            // Vec<Bytes>
886            let segments: Vec<_> = segments.into_iter().map(Bytes::from).collect();
887            let s = SegmentedBytes::from(segments);
888            assert!(s.into_segments().all(|segment| !segment.is_empty()));
889        }
890
891        proptest!(|(segments in any::<Vec<Vec<u8>>>())| {
892            test(segments);
893        })
894    }
895}