1use 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#[derive(Clone, Copy, PartialEq, Eq, Debug)]
14pub enum PhysType {
15 Bool,
17 Int64,
18 Float64,
19 NodeRef,
22 RelRef,
24 Str,
26 List,
28 Interval,
30 Date,
32 Timestamp,
34}
35
36impl PhysType {
37 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#[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#[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 Flat,
76 Constant,
78 Dict { codes_width: u8 },
82}
83
84pub enum Aux {
86 None,
87 Str(Arc<StrBuffers>),
89 Dict(Arc<Dictionary>),
92 List(Box<ValueVector>),
94}
95
96pub struct ValueVector {
97 pub phys: PhysType,
98 pub encoding: VecEncoding,
99 pub data: RawBuf,
100 pub validity: Option<Bitmap>,
102 pub aux: Aux,
103 pub len: u32,
104}
105
106impl ValueVector {
107 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 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 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 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 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 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 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 #[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
223fn 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
245fn 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
262pub 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
272pub 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}