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
346pub struct SeqBytesIter<'a> {
347    data: &'a [u8],
348    offsets: &'a [usize],
349}
350
351impl<'a> Iterator for SeqBytesIter<'a> {
352    type Item = &'a [u8];
353
354    fn next(&mut self) -> Option<&'a [u8]> {
355        let first = self.offsets.first()?;
356        self.offsets = &self.offsets[1..];
357
358        let second = self.offsets.first().cloned().unwrap_or(self.data.len());
359        Some(&self.data[*first..second])
360    }
361
362    fn size_hint(&self) -> (usize, Option<usize>) {
363        let remaining = self.offsets.len();
364        (remaining, Some(remaining))
365    }
366}
367
368impl<'a> ExactSizeIterator for SeqBytesIter<'a> {}
369
370impl<'a> DoubleEndedIterator for SeqBytesIter<'a> {
371    fn next_back(&mut self) -> Option<&'a [u8]> {
372        let last = *self.offsets.last()?;
373        self.offsets = &self.offsets[..self.offsets.len() - 1];
374
375        let (left, right) = self.data.split_at(last);
376        self.data = left;
377
378        Some(right)
379    }
380}
381
382/// A mutable iterator over a SeqBytes object
383pub struct SeqBytesIterMut<'a> {
384    data: &'a mut [u8],
385    offsets: &'a [usize],
386}
387
388impl<'a> Iterator for SeqBytesIterMut<'a> {
389    type Item = &'a mut [u8];
390
391    fn next(&mut self) -> Option<&'a mut [u8]> {
392        let first = self.offsets.first()?;
393        self.offsets = &self.offsets[1..];
394
395        let second = self.offsets.first().cloned().unwrap_or(self.data.len());
396
397        // Some(&mut self.data[*first..second])
398        // Work around borrow checker issue
399        let slice = unsafe {
400            let start = self.data.as_mut_ptr().add(*first);
401            core::slice::from_raw_parts_mut(start, second - first)
402        };
403
404        Some(slice)
405    }
406
407    fn size_hint(&self) -> (usize, Option<usize>) {
408        let remaining = self.offsets.len();
409        (remaining, Some(remaining))
410    }
411}
412
413impl<'a> ExactSizeIterator for SeqBytesIterMut<'a> {}
414
415impl<'a> DoubleEndedIterator for SeqBytesIterMut<'a> {
416    fn next_back(&mut self) -> Option<&'a mut [u8]> {
417        let last = *self.offsets.last()?;
418        self.offsets = &self.offsets[..self.offsets.len() - 1];
419
420        let (left, right) = self.data.split_at_mut(last);
421        // Work around borrow checker issue
422        self.data = unsafe {
423            let len = left.len();
424            let ptr = left.as_mut_ptr();
425            core::slice::from_raw_parts_mut(ptr, len)
426        };
427
428        // Work around borrow checker issue
429        let slice = unsafe {
430            let len = right.len();
431            let ptr = right.as_mut_ptr();
432            core::slice::from_raw_parts_mut(ptr, len)
433        };
434
435        Some(slice)
436    }
437}
438
439impl<A: AsRef<[u8]>> Extend<A> for SeqBytes {
440    fn extend<T>(&mut self, iter: T)
441    where
442        T: IntoIterator<Item = A>,
443    {
444        let iter = iter.into_iter();
445        self.reserve(iter.size_hint().0);
446        for item in iter {
447            self.push(item);
448        }
449    }
450}
451
452impl<A: AsRef<[u8]>> FromIterator<A> for SeqBytes {
453    // Required method
454    fn from_iter<T>(iter: T) -> Self
455    where
456        T: IntoIterator<Item = A>,
457    {
458        let mut result = SeqBytes::default();
459        result.extend(iter);
460        result
461    }
462}
463
464// IntoIterator can only be implemented for &'a SeqBytes,
465// otherwise the buffer doesn't live long enough.
466impl<'a> IntoIterator for &'a SeqBytes {
467    type Item = &'a [u8];
468    type IntoIter = SeqBytesIter<'a>;
469
470    fn into_iter(self) -> Self::IntoIter {
471        self.iter()
472    }
473}
474
475#[cfg(test)]
476mod tests {
477    use super::*;
478    use alloc::{borrow::ToOwned, vec};
479
480    #[test]
481    fn vec_slice_conversions() {
482        let vec_b = vec![b"1", b"2", b"3"];
483
484        let seq_b: SeqBytes = vec_b.into_iter().collect();
485
486        assert_eq!(seq_b.len(), 3);
487        assert_eq!(&seq_b[0], b"1");
488        assert_eq!(&seq_b[1], b"2");
489        assert_eq!(&seq_b[2], b"3");
490
491        let vec_str2 = seq_b.iter().map(ToOwned::to_owned).collect::<Vec<_>>();
492
493        assert_eq!(vec_str2.len(), 3);
494        assert_eq!(vec_str2[0], b"1");
495        assert_eq!(vec_str2[1], b"2");
496        assert_eq!(vec_str2[2], b"3");
497    }
498
499    #[test]
500    fn vec_vec_b_conversions() {
501        let vec_string = vec![b"1".to_owned(), b"2".to_owned(), b"3".to_owned()];
502
503        let seq_b: SeqBytes = vec_string.into_iter().collect();
504
505        assert_eq!(seq_b.len(), 3);
506        assert_eq!(&seq_b[0], b"1");
507        assert_eq!(&seq_b[1], b"2");
508        assert_eq!(&seq_b[2], b"3");
509
510        let vec_str2 = seq_b.iter().map(ToOwned::to_owned).collect::<Vec<_>>();
511
512        assert_eq!(vec_str2.len(), 3);
513        assert_eq!(vec_str2[0], b"1");
514        assert_eq!(vec_str2[1], b"2");
515        assert_eq!(vec_str2[2], b"3");
516    }
517
518    #[test]
519    fn iter_rev() {
520        let vec_b = vec![b"1", b"2", b"3"];
521
522        let seq_b: SeqBytes = vec_b.into_iter().collect();
523
524        assert_eq!(seq_b.len(), 3);
525        assert_eq!(&seq_b[0], b"1");
526        assert_eq!(&seq_b[1], b"2");
527        assert_eq!(&seq_b[2], b"3");
528
529        let seq_b2: SeqBytes = seq_b.into_iter().rev().collect();
530
531        assert_eq!(seq_b2.len(), 3);
532        assert_eq!(&seq_b2[0], b"3");
533        assert_eq!(&seq_b2[1], b"2");
534        assert_eq!(&seq_b2[2], b"1");
535    }
536
537    #[test]
538    fn contains() {
539        let vec_b: Vec<&[u8]> = vec![b"123", b"45", b"6", b"", b"7", b"89"];
540        let seq_b: SeqBytes = vec_b.iter().collect();
541
542        assert!(seq_b.contains(b"123"));
543        assert!(!seq_b.contains(b"12"));
544        assert!(!seq_b.contains(b"1"));
545        assert!(seq_b.contains(b""));
546        assert!(seq_b.contains(b"6"));
547    }
548
549    #[test]
550    fn iter_mut() {
551        let vec_b: Vec<&[u8]> = vec![b"123", b"45", b"6", b"", b"7", b"89"];
552        let mut seq_b: SeqBytes = vec_b.iter().collect();
553
554        for b in seq_b.iter_mut() {
555            if b.len() > 0 {
556                b[0] = b"a"[0];
557            }
558        }
559
560        assert_eq!(seq_b.len(), 6);
561        assert_eq!(&seq_b[0], b"a23");
562        assert_eq!(&seq_b[1], b"a5");
563        assert_eq!(&seq_b[2], b"a");
564        assert_eq!(&seq_b[3], b"");
565        assert_eq!(&seq_b[4], b"a");
566        assert_eq!(&seq_b[5], b"a9");
567    }
568
569    #[test]
570    fn retain() {
571        let vec_b: Vec<&[u8]> = vec![b"123", b"45", b"6", b"", b"7", b"89"];
572        let mut seq_b: SeqBytes = vec_b.iter().collect();
573
574        assert_eq!(seq_b.len(), 6);
575        assert_eq!(&seq_b[0], b"123");
576        assert_eq!(&seq_b[1], b"45");
577        assert_eq!(&seq_b[2], b"6");
578        assert_eq!(&seq_b[3], b"");
579        assert_eq!(&seq_b[4], b"7");
580        assert_eq!(&seq_b[5], b"89");
581
582        seq_b.retain(|b| !b.is_empty());
583
584        assert_eq!(seq_b.len(), 5);
585        assert_eq!(&seq_b[0], b"123");
586        assert_eq!(&seq_b[1], b"45");
587        assert_eq!(&seq_b[2], b"6");
588        assert_eq!(&seq_b[3], b"7");
589        assert_eq!(&seq_b[4], b"89");
590
591        seq_b.retain(|b| b.len() >= 2);
592
593        assert_eq!(seq_b.len(), 3);
594        assert_eq!(&seq_b[0], b"123");
595        assert_eq!(&seq_b[1], b"45");
596        assert_eq!(&seq_b[2], b"89");
597
598        seq_b.retain(|b| b.len() <= 2);
599
600        assert_eq!(seq_b.len(), 2);
601        assert_eq!(&seq_b[0], b"45");
602        assert_eq!(&seq_b[1], b"89");
603
604        seq_b.push(b"123");
605
606        assert_eq!(seq_b.len(), 3);
607        assert_eq!(&seq_b[0], b"45");
608        assert_eq!(&seq_b[1], b"89");
609        assert_eq!(&seq_b[2], b"123");
610
611        seq_b.retain(|b| b.len() >= 3);
612
613        assert_eq!(seq_b.len(), 1);
614        assert_eq!(&seq_b[0], b"123");
615
616        seq_b.resize(3);
617
618        assert_eq!(seq_b.len(), 3);
619        assert_eq!(&seq_b[0], b"123");
620        assert_eq!(&seq_b[1], b"");
621        assert_eq!(&seq_b[2], b"");
622
623        seq_b.truncate(5);
624
625        assert_eq!(seq_b.len(), 3);
626        assert_eq!(&seq_b[0], b"123");
627        assert_eq!(&seq_b[1], b"");
628        assert_eq!(&seq_b[2], b"");
629
630        seq_b.truncate(2);
631
632        assert_eq!(seq_b.len(), 2);
633        assert_eq!(&seq_b[0], b"123");
634        assert_eq!(&seq_b[1], b"");
635    }
636}