seq_str/
seq_bytes.rs

1use alloc::vec::Vec;
2use core::fmt;
3
4/// A sequence of `&[u8]`, stored contiguously
5///
6/// This can be used as a drop-in replacement for `Vec<Vec<u8>>` in some cases,
7/// with better memory locality and fewer memory allocations.
8///
9/// When using `SeqBytes` instead of `Vec<Vec<u8>>`, the individual byte strings
10/// cannot be resized, but when this isn't needed there isn't much downside otherwise.
11///
12/// The container also supports "emplace"-style APIs like `in_place_writer`, which allow you to
13/// write the next element directly into the contiguous buffer with minimal overhead.
14#[derive(Clone, Default, Eq, PartialEq, Hash)]
15pub struct SeqBytes {
16    data: Vec<u8>,
17    offsets: Vec<usize>,
18}
19
20impl SeqBytes {
21    /// Create a new SeqBytes
22    pub fn new() -> Self {
23        Self::default()
24    }
25
26    /// Check if the sequence is empty
27    pub fn is_empty(&self) -> bool {
28        self.len() == 0
29    }
30
31    /// Get the number of slices in the sequence
32    pub fn len(&self) -> usize {
33        self.offsets.len()
34    }
35
36    /// Reserve capacity for more slices
37    pub fn reserve(&mut self, extra: usize) {
38        self.offsets.reserve(extra);
39        // Guess how much data to reserve based on existing usage
40        if !self.is_empty() && extra > 0 {
41            let a = extra * 4;
42            let b = self.data.len() * 4;
43            // estimate data.len * extra / offsets.len
44            let c = (self.data.len() * extra)
45                >> ((usize::BITS - 1) - self.offsets.len().leading_zeros());
46
47            #[allow(clippy::collapsible_else_if)]
48            let median = if a <= b {
49                if a <= c { core::cmp::min(b, c) } else { a }
50            } else {
51                if a <= c { a } else { core::cmp::max(b, c) }
52            };
53
54            self.data.reserve(median);
55        } else {
56            self.data.reserve(4 * extra);
57        }
58    }
59
60    /// Shrink container to fit the current data
61    pub fn shrink_to_fit(&mut self) {
62        self.data.shrink_to_fit();
63        self.offsets.shrink_to_fit();
64    }
65
66    /// Get the sum of the lengths of the byte strings
67    pub fn num_bytes(&self) -> usize {
68        self.data.len()
69    }
70
71    /// Get the i'th element of the sequence in a checked manner
72    pub fn get(&self, idx: usize) -> Option<&[u8]> {
73        let first = self.offsets.get(idx)?;
74        match self.offsets.get(idx + 1) {
75            Some(second) => Some(&self.data[*first..*second]),
76            None => Some(&self.data[*first..]),
77        }
78    }
79
80    /// Get the i'th element of the sequence in a checked manner
81    pub fn get_mut(&mut self, idx: usize) -> Option<&mut [u8]> {
82        let first = self.offsets.get(idx)?;
83        match self.offsets.get(idx + 1) {
84            Some(second) => Some(&mut self.data[*first..*second]),
85            None => Some(&mut self.data[*first..]),
86        }
87    }
88
89    /// Check if the sequence contains a particular element
90    pub fn contains(&self, s: impl AsRef<[u8]>) -> bool {
91        let s = s.as_ref();
92        self.iter().any(|b| b == s)
93    }
94
95    /// Push a &[u8] onto the sequence
96    pub fn push(&mut self, s: impl AsRef<[u8]>) {
97        self.offsets.push(self.data.len());
98        self.data.extend(s.as_ref().iter());
99    }
100
101    /// Get the last &[u8] of the sequence
102    pub fn last(&self) -> Option<&[u8]> {
103        match self.offsets.last() {
104            Some(o) => Some(&self.data[*o..]),
105            None => None,
106        }
107    }
108
109    /// Pop the last element of the container
110    /// Note that we can't return it because of lifetimes, so call [last] before popping.
111    pub fn pop(&mut self) {
112        if let Some(o) = self.offsets.pop() {
113            self.data.truncate(o);
114        }
115    }
116
117    /// Iterate over the sequence of &[u8]
118    pub fn iter(&self) -> SeqBytesIter<'_> // impl ExactSizeIterator<Item = &[u8]>
119    {
120        SeqBytesIter {
121            data: &self.data[..],
122            offsets: &self.offsets[..],
123        }
124    }
125
126    /// Iterate over the sequence of &mut [u8]
127    pub fn iter_mut(&mut self) -> SeqBytesIterMut<'_> // impl ExactSizeIterator<Item = &mut[u8]>
128    {
129        SeqBytesIterMut {
130            data: &mut self.data[..],
131            offsets: &self.offsets[..],
132        }
133    }
134
135    // Helper to convert range bounds object to a range
136    fn range_bounds_to_range(
137        &self,
138        range_bounds: impl core::ops::RangeBounds<usize>,
139    ) -> (usize, usize) {
140        use core::ops::Bound;
141
142        let start_idx = match range_bounds.start_bound() {
143            Bound::Included(s) => *s,
144            Bound::Excluded(s) => s + 1,
145            Bound::Unbounded => 0,
146        };
147
148        let end_idx = match range_bounds.end_bound() {
149            Bound::Included(e) => e + 1,
150            Bound::Excluded(e) => *e,
151            Bound::Unbounded => self.offsets.len(),
152        };
153
154        (start_idx, end_idx)
155    }
156
157    /// Iterate over a range of the sequence of `&[u8]`
158    ///
159    /// This resembles [std::collections::BTreeMap::range], and is needed becuase like `BTreeMap`,
160    /// we can't implement `Deref` or `SliceIndex<Range>` and produce a slice of our contents.
161    /// See also [as_vec].
162    pub fn range(&self, range_bounds: impl core::ops::RangeBounds<usize>) -> SeqBytesIter<'_> {
163        let (start_idx, end_idx) = self.range_bounds_to_range(range_bounds);
164        let data_end = self
165            .offsets
166            .get(end_idx)
167            .cloned()
168            .unwrap_or(self.data.len());
169
170        SeqBytesIter {
171            data: &self.data[0..data_end],
172            offsets: &self.offsets[start_idx..end_idx],
173        }
174    }
175
176    /// Iterate over a range of the sequence of `&mut [u8]`
177    pub fn range_mut(
178        &mut self,
179        range_bounds: impl core::ops::RangeBounds<usize>,
180    ) -> SeqBytesIterMut<'_> {
181        let (start_idx, end_idx) = self.range_bounds_to_range(range_bounds);
182        let data_end = self
183            .offsets
184            .get(end_idx)
185            .cloned()
186            .unwrap_or(self.data.len());
187
188        SeqBytesIterMut {
189            data: &mut self.data[0..data_end],
190            offsets: &self.offsets[start_idx..end_idx],
191        }
192    }
193
194    /// Truncate to at most the first n slices
195    pub fn truncate(&mut self, new_size: usize) {
196        if let Some(off) = self.offsets.get(new_size) {
197            self.data.truncate(*off);
198            self.offsets.truncate(new_size);
199        }
200    }
201
202    /// Resize to contain only the first n `&[u8]`, or pad up to n slices, with empty slices added
203    pub fn resize(&mut self, new_size: usize) {
204        if let Some(off) = self.offsets.get(new_size) {
205            self.data.truncate(*off);
206            self.offsets.truncate(new_size);
207        } else {
208            // Push empty slices until offsets has length new_size
209            let d = new_size - self.offsets.len();
210            self.offsets.reserve(d);
211            for _ in 0..d {
212                self.offsets.push(self.data.len());
213            }
214        }
215    }
216
217    /// Retain only those slices satisfying a predicate.
218    /// The slices are always visited in order, similar to [std::vec::Vec::retain].
219    pub fn retain(&mut self, mut pred: impl FnMut(&[u8]) -> bool) {
220        self.retain_mut(|elem| pred(elem))
221    }
222
223    /// Retain only those slices satisfying a predicate.
224    /// The slices are always visited in order, similar to [std::vec::Vec::retain_mut].
225    pub fn retain_mut(&mut self, mut pred: impl FnMut(&mut [u8]) -> bool) {
226        let (data, offsets) = (&mut self.data, &mut self.offsets);
227
228        let mut offset_write_idx = 0;
229        let mut kept_bytes = 0;
230
231        // Invariant:
232        // Offsets is not reduced in length during this loop
233        // Data is not reduced in length during this loop
234        for offset_idx in 0..offsets.len() {
235            let start = offsets[offset_idx];
236            let end = offsets.get(offset_idx + 1).cloned().unwrap_or(data.len());
237
238            let outcome = pred(&mut data[start..end]);
239            if outcome {
240                // We will preserve kept_len additional bytes,
241                // write their starting offset first.
242                let kept_len = end - start;
243                offsets[offset_write_idx] = kept_bytes;
244                offset_write_idx += 1;
245
246                // Move from data[start..end] to
247                // data[kept_bytes, kept_bytes + kept_len]
248                // if start == kept bytes we don't have to do anything
249                if kept_bytes != start {
250                    for byte_idx in 0..kept_len {
251                        data[kept_bytes + byte_idx] = data[start + byte_idx];
252                    }
253                }
254                kept_bytes += kept_len;
255            }
256        }
257        drop(pred);
258
259        // Truncate both offsets and data to what was actually retained
260        offsets.truncate(offset_write_idx);
261        data.truncate(kept_bytes);
262    }
263
264    /// Get an `impl std::io::Write` which can be used to write the next slice
265    /// directly into the buffer without copying.
266    #[cfg(feature = "std")]
267    pub fn in_place_writer(&mut self) -> impl std::io::Write {
268        // Correctness:
269        // If we push a new offset on, then we have conceptually added a new string.
270        // If the only thing that happens after that is that data is appended to self.data,
271        // then the final state is correct and offsets doesn't need further adjusting.
272        //
273        // The only thing they can do with std::io::Write is push more bytes.
274        // And no other changes can be made to SeqBytes until that writer is dropped,
275        // because it captures &mut self.
276        //
277        // So we don't need to return an object with a Drop impl, we will always end
278        // up in the correct state.
279        self.offsets.push(self.data.len());
280        &mut self.data
281    }
282
283    /// Version of `in_place_writer` that doesn't require `std::io::Write` trait
284    ///
285    /// Any bytes passed to the result of this function get concatenated to produce the
286    /// newest byte string in the sequence. The new item is final when the writer is dropped.
287    pub fn in_place_writer_no_std(&mut self) -> impl FnMut(&[u8]) {
288        self.offsets.push(self.data.len());
289
290        let dat = &mut self.data;
291
292        move |b: &[u8]| {
293            dat.extend(b);
294        }
295    }
296
297    /// Express as a Vec<&[u8]>. The main reason that this may be useful is that there are
298    /// useful methods on slice types `&[&[u8]]`, for example, [core::slice::binary_search],
299    /// but `SeqBytes` itself doesn't implement `Deref` the way that `Vec` does and can
300    /// only produce such a slice by allocating.
301    ///
302    /// Note: The trade-offs are that we would need more memory and `in_place_writer` would have
303    /// to be more complicated and slower if we wanted our internal representation of the offsets
304    /// to be a `Vec<&[u8]>`, which would allow such a `Deref` implementation.
305    /// The direction we've taken is to add useful functions from `Vec` and slice
306    /// as needed directly to this type instead, if they can't be obtained in a simpler way.
307    pub fn as_vec(&self) -> Vec<&[u8]> {
308        self.iter().collect()
309    }
310
311    /// Concatenate the `&[u8]` in the sequence into one `&[u8]`
312    pub fn concat(&self) -> &[u8] {
313        &self.data[..]
314    }
315}
316
317impl core::ops::Index<usize> for SeqBytes {
318    type Output = [u8];
319
320    fn index(&self, index: usize) -> &[u8] {
321        let first = self.offsets[index];
322        match self.offsets.get(index + 1) {
323            Some(second) => &self.data[first..*second],
324            None => &self.data[first..],
325        }
326    }
327}
328
329impl core::ops::IndexMut<usize> for SeqBytes {
330    fn index_mut(&mut self, index: usize) -> &mut [u8] {
331        let first = self.offsets[index];
332        match self.offsets.get(index + 1) {
333            Some(second) => &mut self.data[first..*second],
334            None => &mut self.data[first..],
335        }
336    }
337}
338
339impl fmt::Debug for SeqBytes {
340    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
341        f.debug_list().entries(self.iter()).finish()
342    }
343}
344
345/// An iterator over a SeqBytes object
346#[derive(Clone)]
347pub struct SeqBytesIter<'a> {
348    data: &'a [u8],
349    offsets: &'a [usize],
350}
351
352impl<'a> Iterator for SeqBytesIter<'a> {
353    type Item = &'a [u8];
354
355    fn next(&mut self) -> Option<&'a [u8]> {
356        let first = self.offsets.first()?;
357        self.offsets = &self.offsets[1..];
358
359        let second = self.offsets.first().cloned().unwrap_or(self.data.len());
360        Some(&self.data[*first..second])
361    }
362
363    fn size_hint(&self) -> (usize, Option<usize>) {
364        let remaining = self.offsets.len();
365        (remaining, Some(remaining))
366    }
367}
368
369impl<'a> ExactSizeIterator for SeqBytesIter<'a> {}
370
371impl<'a> DoubleEndedIterator for SeqBytesIter<'a> {
372    fn next_back(&mut self) -> Option<&'a [u8]> {
373        let last = *self.offsets.last()?;
374        self.offsets = &self.offsets[..self.offsets.len() - 1];
375
376        let (left, right) = self.data.split_at(last);
377        self.data = left;
378
379        Some(right)
380    }
381}
382
383/// A mutable iterator over a SeqBytes object
384pub struct SeqBytesIterMut<'a> {
385    data: &'a mut [u8],
386    offsets: &'a [usize],
387}
388
389impl<'a> Iterator for SeqBytesIterMut<'a> {
390    type Item = &'a mut [u8];
391
392    fn next(&mut self) -> Option<&'a mut [u8]> {
393        let first = self.offsets.first()?;
394        self.offsets = &self.offsets[1..];
395
396        let second = self.offsets.first().cloned().unwrap_or(self.data.len());
397
398        // Some(&mut self.data[*first..second])
399        // Work around borrow checker issue
400        let slice = unsafe {
401            let start = self.data.as_mut_ptr().add(*first);
402            core::slice::from_raw_parts_mut(start, second - first)
403        };
404
405        Some(slice)
406    }
407
408    fn size_hint(&self) -> (usize, Option<usize>) {
409        let remaining = self.offsets.len();
410        (remaining, Some(remaining))
411    }
412}
413
414impl<'a> ExactSizeIterator for SeqBytesIterMut<'a> {}
415
416impl<'a> DoubleEndedIterator for SeqBytesIterMut<'a> {
417    fn next_back(&mut self) -> Option<&'a mut [u8]> {
418        let last = *self.offsets.last()?;
419        self.offsets = &self.offsets[..self.offsets.len() - 1];
420
421        let (left, right) = self.data.split_at_mut(last);
422        // Work around borrow checker issue
423        self.data = unsafe {
424            let len = left.len();
425            let ptr = left.as_mut_ptr();
426            core::slice::from_raw_parts_mut(ptr, len)
427        };
428
429        // Work around borrow checker issue
430        let slice = unsafe {
431            let len = right.len();
432            let ptr = right.as_mut_ptr();
433            core::slice::from_raw_parts_mut(ptr, len)
434        };
435
436        Some(slice)
437    }
438}
439
440impl<A: AsRef<[u8]>> Extend<A> for SeqBytes {
441    fn extend<T>(&mut self, iter: T)
442    where
443        T: IntoIterator<Item = A>,
444    {
445        let iter = iter.into_iter();
446        self.reserve(iter.size_hint().0);
447        for item in iter {
448            self.push(item);
449        }
450    }
451}
452
453impl<A: AsRef<[u8]>> FromIterator<A> for SeqBytes {
454    // Required method
455    fn from_iter<T>(iter: T) -> Self
456    where
457        T: IntoIterator<Item = A>,
458    {
459        let mut result = SeqBytes::default();
460        result.extend(iter);
461        result
462    }
463}
464
465// IntoIterator can only be implemented for &'a SeqBytes,
466// otherwise the buffer doesn't live long enough.
467impl<'a> IntoIterator for &'a SeqBytes {
468    type Item = &'a [u8];
469    type IntoIter = SeqBytesIter<'a>;
470
471    fn into_iter(self) -> Self::IntoIter {
472        self.iter()
473    }
474}
475
476#[cfg(test)]
477mod tests {
478    use super::*;
479    use alloc::{borrow::ToOwned, vec};
480
481    #[test]
482    fn vec_slice_conversions() {
483        let vec_b = vec![b"1", b"2", b"3"];
484
485        let seq_b: SeqBytes = vec_b.into_iter().collect();
486
487        assert_eq!(seq_b.len(), 3);
488        assert_eq!(&seq_b[0], b"1");
489        assert_eq!(&seq_b[1], b"2");
490        assert_eq!(&seq_b[2], b"3");
491
492        let vec_str2 = seq_b.iter().map(ToOwned::to_owned).collect::<Vec<_>>();
493
494        assert_eq!(vec_str2.len(), 3);
495        assert_eq!(vec_str2[0], b"1");
496        assert_eq!(vec_str2[1], b"2");
497        assert_eq!(vec_str2[2], b"3");
498    }
499
500    #[test]
501    fn vec_vec_b_conversions() {
502        let vec_string = vec![b"1".to_owned(), b"2".to_owned(), b"3".to_owned()];
503
504        let seq_b: SeqBytes = vec_string.into_iter().collect();
505
506        assert_eq!(seq_b.len(), 3);
507        assert_eq!(&seq_b[0], b"1");
508        assert_eq!(&seq_b[1], b"2");
509        assert_eq!(&seq_b[2], b"3");
510
511        let vec_str2 = seq_b.iter().map(ToOwned::to_owned).collect::<Vec<_>>();
512
513        assert_eq!(vec_str2.len(), 3);
514        assert_eq!(vec_str2[0], b"1");
515        assert_eq!(vec_str2[1], b"2");
516        assert_eq!(vec_str2[2], b"3");
517    }
518
519    #[test]
520    fn iter_rev() {
521        let vec_b = vec![b"1", b"2", b"3"];
522
523        let seq_b: SeqBytes = vec_b.into_iter().collect();
524
525        assert_eq!(seq_b.len(), 3);
526        assert_eq!(&seq_b[0], b"1");
527        assert_eq!(&seq_b[1], b"2");
528        assert_eq!(&seq_b[2], b"3");
529
530        let seq_b2: SeqBytes = seq_b.into_iter().rev().collect();
531
532        assert_eq!(seq_b2.len(), 3);
533        assert_eq!(&seq_b2[0], b"3");
534        assert_eq!(&seq_b2[1], b"2");
535        assert_eq!(&seq_b2[2], b"1");
536    }
537
538    #[test]
539    fn contains() {
540        let vec_b: Vec<&[u8]> = vec![b"123", b"45", b"6", b"", b"7", b"89"];
541        let seq_b: SeqBytes = vec_b.iter().collect();
542
543        assert!(seq_b.contains(b"123"));
544        assert!(!seq_b.contains(b"12"));
545        assert!(!seq_b.contains(b"1"));
546        assert!(seq_b.contains(b""));
547        assert!(seq_b.contains(b"6"));
548    }
549
550    #[test]
551    fn iter_mut() {
552        let vec_b: Vec<&[u8]> = vec![b"123", b"45", b"6", b"", b"7", b"89"];
553        let mut seq_b: SeqBytes = vec_b.iter().collect();
554
555        for b in seq_b.iter_mut() {
556            if b.len() > 0 {
557                b[0] = b"a"[0];
558            }
559        }
560
561        assert_eq!(seq_b.len(), 6);
562        assert_eq!(&seq_b[0], b"a23");
563        assert_eq!(&seq_b[1], b"a5");
564        assert_eq!(&seq_b[2], b"a");
565        assert_eq!(&seq_b[3], b"");
566        assert_eq!(&seq_b[4], b"a");
567        assert_eq!(&seq_b[5], b"a9");
568    }
569
570    #[test]
571    fn retain() {
572        let vec_b: Vec<&[u8]> = vec![b"123", b"45", b"6", b"", b"7", b"89"];
573        let mut seq_b: SeqBytes = vec_b.iter().collect();
574
575        assert_eq!(seq_b.len(), 6);
576        assert_eq!(&seq_b[0], b"123");
577        assert_eq!(&seq_b[1], b"45");
578        assert_eq!(&seq_b[2], b"6");
579        assert_eq!(&seq_b[3], b"");
580        assert_eq!(&seq_b[4], b"7");
581        assert_eq!(&seq_b[5], b"89");
582
583        seq_b.retain(|b| !b.is_empty());
584
585        assert_eq!(seq_b.len(), 5);
586        assert_eq!(&seq_b[0], b"123");
587        assert_eq!(&seq_b[1], b"45");
588        assert_eq!(&seq_b[2], b"6");
589        assert_eq!(&seq_b[3], b"7");
590        assert_eq!(&seq_b[4], b"89");
591
592        seq_b.retain(|b| b.len() >= 2);
593
594        assert_eq!(seq_b.len(), 3);
595        assert_eq!(&seq_b[0], b"123");
596        assert_eq!(&seq_b[1], b"45");
597        assert_eq!(&seq_b[2], b"89");
598
599        seq_b.retain(|b| b.len() <= 2);
600
601        assert_eq!(seq_b.len(), 2);
602        assert_eq!(&seq_b[0], b"45");
603        assert_eq!(&seq_b[1], b"89");
604
605        seq_b.push(b"123");
606
607        assert_eq!(seq_b.len(), 3);
608        assert_eq!(&seq_b[0], b"45");
609        assert_eq!(&seq_b[1], b"89");
610        assert_eq!(&seq_b[2], b"123");
611
612        seq_b.retain(|b| b.len() >= 3);
613
614        assert_eq!(seq_b.len(), 1);
615        assert_eq!(&seq_b[0], b"123");
616
617        seq_b.resize(3);
618
619        assert_eq!(seq_b.len(), 3);
620        assert_eq!(&seq_b[0], b"123");
621        assert_eq!(&seq_b[1], b"");
622        assert_eq!(&seq_b[2], b"");
623
624        seq_b.truncate(5);
625
626        assert_eq!(seq_b.len(), 3);
627        assert_eq!(&seq_b[0], b"123");
628        assert_eq!(&seq_b[1], b"");
629        assert_eq!(&seq_b[2], b"");
630
631        seq_b.truncate(2);
632
633        assert_eq!(seq_b.len(), 2);
634        assert_eq!(&seq_b[0], b"123");
635        assert_eq!(&seq_b[1], b"");
636    }
637}