Skip to main content

zu_vector/
vector.rs

1//! Typed value vectors (perf/02 section 1).
2
3use std::sync::Arc;
4
5use zu_common::GROUP_ROWS;
6
7use crate::arena::{MorselArena, Pod, RawBuf};
8use crate::bitmap::Bitmap;
9use crate::str::{Dictionary, StrBuffers, StrView};
10
11/// Physical types. A cell is one machine word or one 16-byte view, never
12/// a tagged enum: the tag lives once per vector, not once per value.
13#[derive(Clone, Copy, PartialEq, Eq, Debug)]
14pub enum PhysType {
15    /// One bit per row, packed in u64 words like a bitmap.
16    Bool,
17    Int64,
18    Float64,
19    /// Packed node reference: table in the top 16 bits, table row in the
20    /// low 48. One word where the old Value::Node was 32 bytes.
21    NodeRef,
22    /// Rel row id; (table, src, dst) resolve through context, not the cell.
23    RelRef,
24    /// 16-byte StrView.
25    Str,
26    /// Offsets into a child vector; entry i spans offsets[i]..offsets[i+1].
27    List,
28    /// i64 microseconds.
29    Interval,
30    /// i64 days.
31    Date,
32    /// i64 microseconds since epoch, UTC.
33    Timestamp,
34}
35
36impl PhysType {
37    /// Bytes per value for word-addressed types; None for Bool, which is
38    /// bit-packed.
39    pub fn width(self) -> Option<usize> {
40        match self {
41            PhysType::Bool => None,
42            PhysType::Str => Some(16),
43            _ => Some(8),
44        }
45    }
46}
47
48/// Pack a node reference. Row is the table row (group * GROUP_ROWS + row
49/// within group), which fits 48 bits with 2^48 rows per table to spare.
50#[inline]
51pub fn node_ref(table: u16, row: u64) -> u64 {
52    debug_assert!(row < 1 << 48);
53    (u64::from(table) << 48) | row
54}
55
56#[inline]
57pub fn node_table(r: u64) -> u16 {
58    (r >> 48) as u16
59}
60
61#[inline]
62pub fn node_row(r: u64) -> u64 {
63    r & ((1 << 48) - 1)
64}
65
66/// The storage group a node reference falls in, for gather radix splits.
67#[inline]
68pub fn node_group(r: u64) -> u32 {
69    (node_row(r) / u64::from(GROUP_ROWS)) as u32
70}
71
72#[derive(Clone, Copy, PartialEq, Eq, Debug)]
73pub enum VecEncoding {
74    /// data holds len values of the physical width.
75    Flat,
76    /// data holds one value standing for len logical copies.
77    Constant,
78    /// data holds integer codes; the dictionary lives in aux. Strings
79    /// flow as codes end to end and materialize only at the result
80    /// boundary.
81    Dict { codes_width: u8 },
82}
83
84/// Side data a vector may carry.
85pub enum Aux {
86    None,
87    /// Buffers backing long string views.
88    Str(Arc<StrBuffers>),
89    /// Dictionary for code-encoded vectors, plus the buffers its views
90    /// need if it is ever materialized.
91    Dict(Arc<Dictionary>),
92    /// Child vector for List entries.
93    List(Box<ValueVector>),
94}
95
96pub struct ValueVector {
97    pub phys: PhysType,
98    pub encoding: VecEncoding,
99    pub data: RawBuf,
100    /// Absent means all valid, the common case; kernels skip the AND.
101    pub validity: Option<Bitmap>,
102    pub aux: Aux,
103    pub len: u32,
104}
105
106impl ValueVector {
107    /// Flat vector filled from a slice.
108    pub fn flat_from<T: Pod>(arena: &mut MorselArena, phys: PhysType, values: &[T]) -> Self {
109        debug_assert_eq!(phys.width(), Some(size_of::<T>()));
110        let mut data = arena.alloc_of::<T>(values.len());
111        data.as_mut_slice::<T>().copy_from_slice(values);
112        Self {
113            phys,
114            encoding: VecEncoding::Flat,
115            data,
116            validity: None,
117            aux: Aux::None,
118            len: values.len() as u32,
119        }
120    }
121
122    /// Flat vector with room for `len` values, to be filled by a kernel.
123    pub fn flat_uninit(arena: &mut MorselArena, phys: PhysType, len: usize) -> Self {
124        let width = phys.width().expect("word-addressed type");
125        Self {
126            phys,
127            encoding: VecEncoding::Flat,
128            data: arena.alloc(len * width, width.min(8)),
129            validity: None,
130            aux: Aux::None,
131            len: len as u32,
132        }
133    }
134
135    /// Constant vector: one stored value, `len` logical copies.
136    pub fn constant<T: Pod>(arena: &mut MorselArena, phys: PhysType, value: T, len: usize) -> Self {
137        debug_assert_eq!(phys.width(), Some(size_of::<T>()));
138        let mut data = arena.alloc_of::<T>(1);
139        data.as_mut_slice::<T>()[0] = value;
140        Self {
141            phys,
142            encoding: VecEncoding::Constant,
143            data,
144            validity: None,
145            aux: Aux::None,
146            len: len as u32,
147        }
148    }
149
150    /// Dict-encoded string vector: u16 codes into a shared dictionary.
151    pub fn dict_str(arena: &mut MorselArena, codes: &[u16], dict: Arc<Dictionary>) -> Self {
152        let mut data = arena.alloc_of::<u16>(codes.len());
153        data.as_mut_slice::<u16>().copy_from_slice(codes);
154        Self {
155            phys: PhysType::Str,
156            encoding: VecEncoding::Dict { codes_width: 2 },
157            data,
158            validity: None,
159            aux: Aux::Dict(dict),
160            len: codes.len() as u32,
161        }
162    }
163
164    pub fn len(&self) -> usize {
165        self.len as usize
166    }
167
168    pub fn is_empty(&self) -> bool {
169        self.len == 0
170    }
171
172    /// Flat values as a typed slice.
173    pub fn values<T: Pod>(&self) -> &[T] {
174        debug_assert_eq!(self.encoding, VecEncoding::Flat);
175        debug_assert_eq!(self.phys.width(), Some(size_of::<T>()));
176        &self.data.as_slice::<T>()[..self.len as usize]
177    }
178
179    pub fn values_mut<T: Pod>(&mut self) -> &mut [T] {
180        debug_assert_eq!(self.encoding, VecEncoding::Flat);
181        debug_assert_eq!(self.phys.width(), Some(size_of::<T>()));
182        let len = self.len as usize;
183        &mut self.data.as_mut_slice::<T>()[..len]
184    }
185
186    /// The single value of a Constant vector.
187    pub fn constant_value<T: Pod>(&self) -> T {
188        debug_assert_eq!(self.encoding, VecEncoding::Constant);
189        self.data.as_slice::<T>()[0]
190    }
191
192    /// Codes of a dict vector (u16 width today; u8/u32 when a writer
193    /// needs them).
194    pub fn codes_u16(&self) -> &[u16] {
195        debug_assert!(matches!(
196            self.encoding,
197            VecEncoding::Dict { codes_width: 2 }
198        ));
199        &self.data.as_slice::<u16>()[..self.len as usize]
200    }
201
202    pub fn dictionary(&self) -> &Dictionary {
203        match &self.aux {
204            Aux::Dict(d) => d,
205            _ => panic!("not a dict vector"),
206        }
207    }
208
209    pub fn str_buffers(&self) -> Option<&StrBuffers> {
210        match &self.aux {
211            Aux::Str(b) => Some(b),
212            _ => None,
213        }
214    }
215
216    /// Row validity, honoring the absent-means-valid convention.
217    #[inline]
218    pub fn is_valid(&self, i: usize) -> bool {
219        self.validity.as_ref().is_none_or(|v| v.get(i))
220    }
221}
222
223/// Write the views of `it` into `vec`, answering the bytes of whatever
224/// was too long to sit in its own view.
225///
226/// One pass and one buffer: a long string is appended as it is met, so
227/// the offset it needs is where the buffer has got to and nothing has
228/// to be remembered between the two. There is only ever the one buffer
229/// here, so its id is zero and no id has to be carried either.
230fn fill_str<'a>(vec: &mut ValueVector, it: impl Iterator<Item = &'a [u8]>) -> Vec<u8> {
231    let mut long_bytes = Vec::new();
232    let views = vec.values_mut::<StrView>();
233    for (i, v) in it.enumerate() {
234        views[i] = if v.len() > crate::str::INLINE_LEN {
235            let start = long_bytes.len() as u32;
236            long_bytes.extend_from_slice(v);
237            StrView::long(v, 0, start)
238        } else {
239            StrView::inline(v)
240        };
241    }
242    long_bytes
243}
244
245/// Hand `long_bytes` to `vec`, or leave it with no buffers at all when
246/// every one of its strings was short enough to live in its own view.
247///
248/// The empty case is the common one on a scan and it is worth not
249/// allocating for: a vector that carries no long string carries no
250/// [`StrBuffers`] and no `Arc` around one, and a kernel that resolves a
251/// view of it reaches [`crate::str::NO_BUFFERS`] instead.
252fn attach_str(vec: &mut ValueVector, long_bytes: Vec<u8>) {
253    if long_bytes.is_empty() {
254        return;
255    }
256    let mut bufs = StrBuffers::new();
257    let id = bufs.push(Arc::from(long_bytes.into_boxed_slice()));
258    debug_assert_eq!(id, 0, "the first buffer of a fresh set is buffer zero");
259    vec.aux = Aux::Str(Arc::new(bufs));
260}
261
262/// Convenience constructor for tests and result building: a flat string
263/// vector from byte slices, short ones inline, long ones packed into one
264/// shared buffer.
265pub fn str_vector<B: AsRef<[u8]>>(arena: &mut MorselArena, values: &[B]) -> ValueVector {
266    let mut vec = ValueVector::flat_uninit(arena, PhysType::Str, values.len());
267    let long_bytes = fill_str(&mut vec, values.iter().map(AsRef::as_ref));
268    attach_str(&mut vec, long_bytes);
269    vec
270}
271
272/// A flat string vector over the `bytes` and `ends` a decoded string
273/// column arrives in, where `ends` is the offset one past each string.
274///
275/// This is the read path's constructor and it exists because the
276/// general one above wants a slice of slices, which a scan would have
277/// to build first: sixteen bytes a row written and read again to get at
278/// bytes that are already laid out end to end. Here the ends walk
279/// straight into the views.
280pub fn str_vector_from_ends(arena: &mut MorselArena, bytes: &[u8], ends: &[u64]) -> ValueVector {
281    let mut lo = 0usize;
282    let mut vec = ValueVector::flat_uninit(arena, PhysType::Str, ends.len());
283    let long_bytes = fill_str(
284        &mut vec,
285        ends.iter().map(move |&e| {
286            let s = &bytes[lo..e as usize];
287            lo = e as usize;
288            s
289        }),
290    );
291    attach_str(&mut vec, long_bytes);
292    vec
293}
294
295#[cfg(test)]
296mod tests {
297    use super::*;
298
299    #[test]
300    fn node_ref_packs() {
301        let r = node_ref(3, (5 << 17) + 42);
302        assert_eq!(node_table(r), 3);
303        assert_eq!(node_row(r), (5 << 17) + 42);
304        assert_eq!(node_group(r), 5);
305    }
306
307    #[test]
308    fn flat_and_constant() {
309        let mut arena = MorselArena::new();
310        let v = ValueVector::flat_from(&mut arena, PhysType::Int64, &[1i64, 2, 3]);
311        assert_eq!(v.values::<i64>(), &[1, 2, 3]);
312        let c = ValueVector::constant(&mut arena, PhysType::Int64, 9i64, 100);
313        assert_eq!(c.constant_value::<i64>(), 9);
314        assert_eq!(c.len(), 100);
315    }
316
317    #[test]
318    fn str_vector_roundtrip() {
319        let mut arena = MorselArena::new();
320        let vals = [
321            "short",
322            "a considerably longer string than twelve bytes",
323            "",
324        ];
325        let v = str_vector(&mut arena, &vals);
326        let bufs = v.str_buffers().unwrap();
327        let views = v.values::<StrView>();
328        for (view, want) in views.iter().zip(vals) {
329            assert_eq!(view.bytes(bufs), want.as_bytes());
330        }
331    }
332
333    #[test]
334    fn ends_build_the_same_vector_as_slices() {
335        let mut arena = MorselArena::new();
336        let vals: [&str; 5] = [
337            "",
338            "short",
339            "a considerably longer string than twelve bytes",
340            "twelve bytes",
341            "another long one, well past the inline limit",
342        ];
343        let mut bytes = Vec::new();
344        let mut ends = Vec::new();
345        for v in vals {
346            bytes.extend_from_slice(v.as_bytes());
347            ends.push(bytes.len() as u64);
348        }
349        let v = str_vector_from_ends(&mut arena, &bytes, &ends);
350        let bufs = v.str_buffers().expect("two of them are long");
351        assert_eq!(v.len(), vals.len());
352        for (view, want) in v.values::<StrView>().iter().zip(vals) {
353            assert_eq!(view.bytes(bufs), want.as_bytes());
354        }
355    }
356
357    #[test]
358    fn a_vector_of_short_strings_carries_no_buffers() {
359        let mut arena = MorselArena::new();
360        let vals = ["ann", "bo", "", "twelve bytes"];
361        let mut bytes = Vec::new();
362        let mut ends = Vec::new();
363        for v in vals {
364            bytes.extend_from_slice(v.as_bytes());
365            ends.push(bytes.len() as u64);
366        }
367        let v = str_vector_from_ends(&mut arena, &bytes, &ends);
368        assert!(v.str_buffers().is_none(), "nothing needed a buffer");
369        for (view, want) in v.values::<StrView>().iter().zip(vals) {
370            assert_eq!(view.bytes(&crate::str::NO_BUFFERS), want.as_bytes());
371        }
372    }
373}