Skip to main content

zu_vector/
str.rs

1//! String views, buffers, and dictionaries (perf/02 sections 1.1, 1.2).
2//!
3//! A string cell is a fixed 16-byte view: length, a 4-byte prefix, and
4//! either the remaining bytes inline (len <= 12) or a buffer id plus
5//! offset into shared buffers. Comparisons check the prefix word first,
6//! which settles most inequality without touching the payload. A buffer
7//! is a byte range and a handle that keeps it alive: a decoded segment
8//! chunk straight from storage, bytes a kernel computed, or the data
9//! buffer of a registered frame, which the engine reads where it lies
10//! and never owns. No String allocation and no UTF-8 revalidation
11//! happen on the read path; FSST and FullZip chunks are validated once
12//! at decode.
13
14use std::sync::Arc;
15
16use crate::arena::Pod;
17
18/// Longest string held entirely inside the view.
19pub const INLINE_LEN: usize = 12;
20
21#[repr(C)]
22#[derive(Clone, Copy)]
23pub struct StrView {
24    len: u32,
25    prefix: [u8; 4],
26    tail: [u8; 8],
27}
28
29unsafe impl Pod for StrView {}
30
31const _: () = assert!(size_of::<StrView>() == 16);
32
33/// Up to eight bytes as a word, zero above them, in loads of a width
34/// the compiler knows.
35///
36/// A copy of a length only known at run time is a `memcpy` call, and a
37/// call is more than the whole of this for eight bytes. Four or more
38/// bytes is a load of the first four and a load of the last four
39/// shifted up to where they belong, which overlap and cost nothing for
40/// overlapping. Under four there is nowhere to overlap, so it is the
41/// three bytes a string that short can have.
42#[inline(always)]
43fn load_short(s: &[u8]) -> u64 {
44    let n = s.len();
45    debug_assert!(n <= 8, "one word holds eight bytes");
46    if n >= 4 {
47        let head = u32::from_le_bytes(s[..4].try_into().expect("four bytes")) as u64;
48        let tail = u32::from_le_bytes(s[n - 4..].try_into().expect("four bytes")) as u64;
49        let above = if n > 4 { tail >> ((8 - n) * 8) } else { 0 };
50        head | above << 32
51    } else if n > 0 {
52        u64::from(s[0]) | u64::from(s[n / 2]) << (n / 2 * 8) | u64::from(s[n - 1]) << ((n - 1) * 8)
53    } else {
54        0
55    }
56}
57
58impl StrView {
59    /// Build a view over a short string, bytes stored inline.
60    ///
61    /// The payload arrives as two words rather than as two copies of a
62    /// run time length, because a copy of a run time length is a
63    /// `memcpy` call and this runs once per row of every string column
64    /// the engine reads.
65    #[inline]
66    pub fn inline(bytes: &[u8]) -> Self {
67        let n = bytes.len();
68        debug_assert!(n <= INLINE_LEN);
69        let (lo, hi) = if n >= 8 {
70            let lo = u64::from_le_bytes(bytes[..8].try_into().expect("eight bytes"));
71            let tail = u32::from_le_bytes(bytes[n - 4..].try_into().expect("four bytes"));
72            (lo, if n > 8 { tail >> ((12 - n) * 8) } else { 0 })
73        } else {
74            (load_short(bytes), 0)
75        };
76        let w = lo.to_le_bytes();
77        let h = hi.to_le_bytes();
78        Self {
79            len: n as u32,
80            prefix: [w[0], w[1], w[2], w[3]],
81            tail: [w[4], w[5], w[6], w[7], h[0], h[1], h[2], h[3]],
82        }
83    }
84
85    /// Build a view over a long string living in `StrBuffers` buffer
86    /// `buffer` at `offset`. The caller passes the full bytes so the
87    /// prefix can be captured.
88    pub fn long(bytes: &[u8], buffer: u16, offset: u32) -> Self {
89        debug_assert!(bytes.len() > INLINE_LEN);
90        let mut prefix = [0u8; 4];
91        prefix.copy_from_slice(&bytes[..4]);
92        let mut tail = [0u8; 8];
93        tail[..2].copy_from_slice(&buffer.to_le_bytes());
94        tail[2..6].copy_from_slice(&offset.to_le_bytes());
95        Self {
96            len: bytes.len() as u32,
97            prefix,
98            tail,
99        }
100    }
101
102    pub fn len(&self) -> usize {
103        self.len as usize
104    }
105
106    pub fn is_empty(&self) -> bool {
107        self.len == 0
108    }
109
110    pub fn is_inline(&self) -> bool {
111        self.len as usize <= INLINE_LEN
112    }
113
114    fn buffer_id(&self) -> u16 {
115        u16::from_le_bytes([self.tail[0], self.tail[1]])
116    }
117
118    fn offset(&self) -> u32 {
119        u32::from_le_bytes([self.tail[2], self.tail[3], self.tail[4], self.tail[5]])
120    }
121
122    /// The bytes of an inline view, read out of the view itself.
123    pub fn inline_bytes(&self) -> &[u8] {
124        debug_assert!(self.is_inline());
125        // prefix and tail are adjacent under repr(C), so the inline
126        // payload is the 12 bytes starting at the prefix.
127        let base = std::ptr::from_ref(self).cast::<u8>();
128        unsafe { std::slice::from_raw_parts(base.add(4), self.len as usize) }
129    }
130
131    /// The string bytes. Inline views read out of the view itself;
132    /// long views resolve through the shared buffers.
133    pub fn bytes<'a>(&'a self, bufs: &'a StrBuffers) -> &'a [u8] {
134        if self.is_inline() {
135            self.inline_bytes()
136        } else {
137            bufs.slice(self.buffer_id(), self.offset(), self.len as usize)
138        }
139    }
140
141    /// A view over `len` bytes of this string starting at `start`,
142    /// where `bytes` is what [`Self::bytes`] answered for it.
143    ///
144    /// A part of a string is bytes that are already somewhere, so this
145    /// makes no bytes and copies none: a part short enough goes inline
146    /// and a longer one names the buffer and offset this view names,
147    /// moved along by where the part begins. That is what a trim wants,
148    /// since what a trim answers is always a part of what it was
149    /// handed, and it is why a chunk of trimmed strings can cost no
150    /// bytes at all beyond the views themselves.
151    ///
152    /// A part longer than the inline limit can only have come from a
153    /// view that was already long, so the buffer it names is there to
154    /// name.
155    pub fn sub(&self, bytes: &[u8], start: usize, len: usize) -> Self {
156        debug_assert!(start + len <= self.len());
157        let part = &bytes[start..start + len];
158        if len <= INLINE_LEN {
159            Self::inline(part)
160        } else {
161            Self::long(part, self.buffer_id(), self.offset() + start as u32)
162        }
163    }
164
165    /// Equality without materializing either side. The length and prefix
166    /// word reject most non-equal pairs before any buffer is touched.
167    pub fn eq_with(&self, a_bufs: &StrBuffers, other: &StrView, b_bufs: &StrBuffers) -> bool {
168        if self.len != other.len || self.prefix != other.prefix {
169            return false;
170        }
171        if self.is_inline() {
172            return self.tail == other.tail;
173        }
174        self.bytes(a_bufs) == other.bytes(b_bufs)
175    }
176}
177
178/// One byte range long views resolve through, and whatever keeps it
179/// alive.
180///
181/// A pointer and a length, with the owner beside them rather than in
182/// the way of them. Bytes worth pointing at do not all come from the
183/// engine's allocator: the columns of a registered frame are buffers
184/// somebody else owns, and copying them to make them addressable here
185/// would be the copy the registration exists to avoid. Resolving a
186/// view is a bounds check and an add whichever kind of bytes it is.
187struct Buf {
188    ptr: *const u8,
189    len: usize,
190    /// Held, never read. What it is is what its drop is: freeing an
191    /// engine allocation, or calling the release callback a frame
192    /// arrived with.
193    _owner: Owner,
194}
195
196/// What a buffer's bytes belong to.
197enum Owner {
198    /// An allocation of the engine's own.
199    Held(#[allow(dead_code)] Arc<[u8]>),
200    /// Bytes from outside the engine, alive for as long as this handle
201    /// is. Nothing here knows what it is and nothing here needs to.
202    Lent(#[allow(dead_code)] Arc<dyn std::any::Any + Send + Sync>),
203}
204
205// The bytes are immutable for as long as the owner lives and the owner
206// is itself `Send + Sync`, so the pointer beside it carries no thread
207// affinity of its own. Every buffer a vector reads through is read
208// only: writing one is what `RawBuf::borrowed` refuses.
209unsafe impl Send for Buf {}
210unsafe impl Sync for Buf {}
211
212/// Shared byte buffers backing long string views. A vector holding
213/// views into a decoded segment chunk, or into a frame's Arrow data
214/// buffer, keeps what it points at alive without copying it.
215#[derive(Default)]
216pub struct StrBuffers {
217    bufs: Vec<Buf>,
218}
219
220/// A vector whose views are all short carries no buffers at all, and a
221/// kernel resolving one still has to hand something to `bytes`. This is
222/// that something, and being a constant it costs nothing to have.
223pub static NO_BUFFERS: StrBuffers = StrBuffers::empty();
224
225impl StrBuffers {
226    pub fn new() -> Self {
227        Self::default()
228    }
229
230    /// No buffers at all, in a form a static can hold.
231    pub const fn empty() -> Self {
232        Self { bufs: Vec::new() }
233    }
234
235    /// Register an allocation of the engine's own and get its id.
236    pub fn push(&mut self, buf: Arc<[u8]>) -> u16 {
237        let (ptr, len) = (buf.as_ptr(), buf.len());
238        self.add(Buf {
239            ptr,
240            len,
241            _owner: Owner::Held(buf),
242        })
243    }
244
245    /// Register bytes from outside the engine and get their id.
246    ///
247    /// # Safety
248    ///
249    /// `ptr` must point at `len` initialized bytes that nobody writes
250    /// or frees for as long as `owner` lives, and dropping `owner`
251    /// must be what releases them. Holding it here is what makes that
252    /// last as long as the views do.
253    pub unsafe fn push_lent(
254        &mut self,
255        ptr: *const u8,
256        len: usize,
257        owner: Arc<dyn std::any::Any + Send + Sync>,
258    ) -> u16 {
259        self.add(Buf {
260            ptr,
261            len,
262            _owner: Owner::Lent(owner),
263        })
264    }
265
266    fn add(&mut self, buf: Buf) -> u16 {
267        let id = u16::try_from(self.bufs.len()).expect("string buffer count fits u16");
268        self.bufs.push(buf);
269        id
270    }
271
272    /// How many buffers are registered, which is the id the next one
273    /// will take.
274    pub fn len(&self) -> usize {
275        self.bufs.len()
276    }
277
278    pub fn is_empty(&self) -> bool {
279        self.bufs.is_empty()
280    }
281
282    pub fn slice(&self, id: u16, offset: u32, len: usize) -> &[u8] {
283        let buf = &self.bufs[id as usize];
284        let start = offset as usize;
285        // The same bounds check indexing an `Arc<[u8]>` did, kept in
286        // release as well: a view that has run past its buffer is a bug
287        // in whoever built it, and the other answer is reading whatever
288        // is next in the address space.
289        assert!(
290            start + len <= buf.len,
291            "string view {start}..{} runs past its {}-byte buffer",
292            start + len,
293            buf.len
294        );
295        // Safe by `Buf`'s own contract: the bytes are alive while the
296        // owner is, the owner is held here, and the range is checked.
297        unsafe { std::slice::from_raw_parts(buf.ptr.add(start), len) }
298    }
299}
300
301/// Where a kernel puts the bytes of the strings it makes.
302///
303/// A kernel that answers a number writes into a register the arena
304/// already sized for it. A kernel that answers a string has no such
305/// room, because how many bytes a chunk of answers comes to is not
306/// known until the answers are made, so the bytes go here instead and
307/// the vector's views point back into them. Short answers never reach
308/// the buffer at all, a view of twelve bytes or fewer carrying its own
309/// payload, so a column of words costs one vector and nothing else.
310///
311/// The whole chunk shares one buffer, which is one allocation for a
312/// call rather than one per row, and the views hold offsets rather
313/// than pointers so the buffer may grow underneath them.
314#[derive(Default)]
315pub struct StrBuilder {
316    long: Vec<u8>,
317}
318
319impl StrBuilder {
320    pub fn new() -> Self {
321        Self::default()
322    }
323
324    /// Room for the long answers of a chunk, when the caller can say
325    /// what that comes to. An answer no longer than what it was made
326    /// from is the common case, so the input's byte count is the usual
327    /// argument and the usual outcome is that the buffer never grows.
328    pub fn with_capacity(bytes: usize) -> Self {
329        Self {
330            long: Vec::with_capacity(bytes),
331        }
332    }
333
334    /// Room for a string of `len` bytes, filled by `fill`, answered as
335    /// the view that reads it back.
336    ///
337    /// The caller writes into the answer rather than handing one over,
338    /// so a fold or a trim costs no working string of its own.
339    pub fn push_with(&mut self, len: usize, fill: impl FnOnce(&mut [u8])) -> StrView {
340        if len <= INLINE_LEN {
341            let mut inline = [0u8; INLINE_LEN];
342            fill(&mut inline[..len]);
343            StrView::inline(&inline[..len])
344        } else {
345            let start = self.long.len();
346            self.long.resize(start + len, 0);
347            fill(&mut self.long[start..]);
348            // Buffer nought, which is the only buffer `finish` makes.
349            StrView::long(&self.long[start..], 0, start as u32)
350        }
351    }
352
353    /// A string already in hand, copied in.
354    pub fn push(&mut self, bytes: &[u8]) -> StrView {
355        self.push_with(bytes.len(), |dst| dst.copy_from_slice(bytes))
356    }
357
358    /// The buffers the views this handed out read through. A chunk
359    /// whose answers were all short leaves no buffer behind.
360    pub fn finish(self) -> StrBuffers {
361        let mut bufs = StrBuffers::new();
362        if !self.long.is_empty() {
363            bufs.push(Arc::from(self.long.into_boxed_slice()));
364        }
365        bufs
366    }
367}
368
369/// A sorted, deduplicated string dictionary, matching the on-disk dict
370/// encoding's order so range predicates map to code ranges. Entry bytes
371/// are concatenated; `ends[i]` is the exclusive end of entry i.
372pub struct Dictionary {
373    bytes: Vec<u8>,
374    ends: Vec<u32>,
375}
376
377impl Dictionary {
378    /// Build from entries that are already sorted and unique, which is
379    /// what the storage dict guarantees.
380    pub fn from_sorted<I, B>(entries: I) -> Self
381    where
382        I: IntoIterator<Item = B>,
383        B: AsRef<[u8]>,
384    {
385        let mut bytes = Vec::new();
386        let mut ends = Vec::new();
387        for e in entries {
388            let e = e.as_ref();
389            debug_assert!(
390                ends.is_empty() || {
391                    let start = if ends.len() == 1 {
392                        0
393                    } else {
394                        ends[ends.len() - 2] as usize
395                    };
396                    let prev = &bytes[start..*ends.last().unwrap() as usize];
397                    prev < e
398                },
399                "dictionary entries must be sorted and unique"
400            );
401            bytes.extend_from_slice(e);
402            ends.push(bytes.len() as u32);
403        }
404        Self { bytes, ends }
405    }
406
407    pub fn len(&self) -> usize {
408        self.ends.len()
409    }
410
411    pub fn is_empty(&self) -> bool {
412        self.ends.is_empty()
413    }
414
415    pub fn get(&self, code: u32) -> &[u8] {
416        let i = code as usize;
417        let start = if i == 0 { 0 } else { self.ends[i - 1] as usize };
418        &self.bytes[start..self.ends[i] as usize]
419    }
420
421    /// Binary-search a value. `Ok(code)` when present; `Err(insertion)`
422    /// otherwise, which range compares use directly: `x < needle` in the
423    /// value domain is `code < insertion` in the code domain.
424    pub fn code_of(&self, needle: &[u8]) -> Result<u32, u32> {
425        let mut lo = 0usize;
426        let mut hi = self.len();
427        while lo < hi {
428            let mid = (lo + hi) / 2;
429            match self.get(mid as u32).cmp(needle) {
430                std::cmp::Ordering::Less => lo = mid + 1,
431                std::cmp::Ordering::Greater => hi = mid,
432                std::cmp::Ordering::Equal => return Ok(mid as u32),
433            }
434        }
435        Err(lo as u32)
436    }
437}
438
439#[cfg(test)]
440mod tests {
441    use super::*;
442
443    #[test]
444    fn inline_roundtrip() {
445        let bufs = StrBuffers::new();
446        for s in ["", "a", "abcd", "abcdefgh", "twelve chars"] {
447            let v = StrView::inline(s.as_bytes());
448            assert_eq!(v.bytes(&bufs), s.as_bytes(), "{s:?}");
449        }
450    }
451
452    #[test]
453    fn long_roundtrip_and_eq() {
454        let mut bufs = StrBuffers::new();
455        let payload: Arc<[u8]> =
456            Arc::from(&b"hello, this is a longer string sitting in a buffer"[..]);
457        let id = bufs.push(Arc::clone(&payload));
458        let a = StrView::long(&payload, id, 0);
459        assert_eq!(a.bytes(&bufs), &payload[..]);
460        let b = StrView::long(&payload, id, 0);
461        assert!(a.eq_with(&bufs, &b, &bufs));
462        let short = StrView::inline(b"hello");
463        assert!(!a.eq_with(&bufs, &short, &bufs));
464    }
465
466    /// A part of a long string keeps pointing at the bytes it was
467    /// always pointing at, and a part short enough to sit in a view
468    /// stops needing the buffer at all.
469    #[test]
470    fn a_part_of_a_string_points_back_at_it() {
471        let mut bufs = StrBuffers::new();
472        let payload: Arc<[u8]> = Arc::from(&b"  a string long enough to need a buffer  "[..]);
473        let id = bufs.push(Arc::clone(&payload));
474        let whole = StrView::long(&payload, id, 0);
475        let bytes = whole.bytes(&bufs);
476        let inner = whole.sub(bytes, 2, payload.len() - 4);
477        assert!(!inner.is_inline());
478        assert_eq!(inner.bytes(&bufs), b"a string long enough to need a buffer");
479        let head = whole.sub(bytes, 2, 8);
480        assert!(head.is_inline(), "a short part carries its own bytes");
481        assert_eq!(head.bytes(&StrBuffers::new()), b"a string");
482    }
483
484    #[test]
485    fn prefix_rejects_before_buffer_touch() {
486        let mut bufs = StrBuffers::new();
487        let p1: Arc<[u8]> = Arc::from(&b"aaaaaaaaaaaaaaaaaaaa"[..]);
488        let p2: Arc<[u8]> = Arc::from(&b"bbbbbbbbbbbbbbbbbbbb"[..]);
489        let i1 = bufs.push(Arc::clone(&p1));
490        let i2 = bufs.push(Arc::clone(&p2));
491        let a = StrView::long(&p1, i1, 0);
492        let b = StrView::long(&p2, i2, 0);
493        assert!(!a.eq_with(&bufs, &b, &bufs));
494    }
495
496    #[test]
497    fn lent_bytes_read_where_they_lie() {
498        // What a registered frame hands over: an allocation somebody
499        // else made, pointed at rather than copied, kept alive by the
500        // handle it arrived with.
501        let outside: Arc<Vec<u8>> = Arc::new(b"a string long enough to need a buffer".to_vec());
502        let (ptr, len) = (outside.as_ptr(), outside.len());
503        let mut bufs = StrBuffers::new();
504        let id = unsafe { bufs.push_lent(ptr, len, Arc::clone(&outside) as Arc<_>) };
505        let view = StrView::long(&outside, id, 0);
506        assert_eq!(view.bytes(&bufs), &outside[..]);
507        // The buffers hold it, so the last handle out here is not the
508        // last handle anywhere.
509        assert_eq!(Arc::strong_count(&outside), 2);
510        drop(outside);
511        assert_eq!(view.bytes(&bufs), b"a string long enough to need a buffer");
512    }
513
514    #[test]
515    #[should_panic(expected = "runs past its")]
516    fn a_view_past_its_buffer_is_caught() {
517        let mut bufs = StrBuffers::new();
518        let id = bufs.push(Arc::from(&b"twenty bytes exactly"[..]));
519        bufs.slice(id, 16, 8);
520    }
521
522    #[test]
523    fn every_inline_length_round_trips() {
524        // The packing loads whole words and masks, so the lengths
525        // either side of four and eight are where it would go wrong.
526        let all = b"abcdefghijkl";
527        for n in 0..=INLINE_LEN {
528            let want = &all[..n];
529            let view = StrView::inline(want);
530            assert_eq!(view.len(), n, "length of {n}");
531            assert_eq!(view.inline_bytes(), want, "bytes of {n}");
532            assert!(view.is_inline(), "{n} bytes should be inline");
533            // Two views of the same string are the same sixteen bytes,
534            // which is what the word compare in `eq_with` rests on.
535            assert!(view.eq_with(&NO_BUFFERS, &StrView::inline(want), &NO_BUFFERS));
536        }
537    }
538
539    #[test]
540    fn inline_views_of_different_lengths_stay_apart() {
541        let a = StrView::inline(b"abcdefgh");
542        let b = StrView::inline(b"abcdefghi");
543        assert!(!a.eq_with(&NO_BUFFERS, &b, &NO_BUFFERS));
544        // Nothing above the length leaks in from the load either.
545        assert_eq!(a.tail[4..], [0, 0, 0, 0]);
546    }
547
548    #[test]
549    fn dictionary_codes() {
550        let d = Dictionary::from_sorted(["apple", "banana", "cherry"]);
551        assert_eq!(d.code_of(b"banana"), Ok(1));
552        assert_eq!(d.code_of(b"blueberry"), Err(2));
553        assert_eq!(d.get(2), b"cherry");
554    }
555}