vortex_array/arrays/primitive/vtable/
mod.rs1use kernel::PARENT_KERNELS;
5use vortex_error::VortexResult;
6use vortex_error::vortex_bail;
7use vortex_error::vortex_ensure;
8use vortex_error::vortex_panic;
9
10use crate::ArrayRef;
11use crate::ExecutionCtx;
12use crate::ExecutionResult;
13use crate::array::Array;
14use crate::array::ArrayView;
15use crate::array::VTable;
16use crate::arrays::primitive::PrimitiveData;
17use crate::buffer::BufferHandle;
18use crate::dtype::DType;
19use crate::dtype::PType;
20use crate::serde::ArrayChildren;
21use crate::validity::Validity;
22mod kernel;
23mod operations;
24mod validity;
25
26use std::hash::Hasher;
27
28use vortex_buffer::Alignment;
29use vortex_session::VortexSession;
30
31use crate::Precision;
32use crate::array::ArrayId;
33use crate::arrays::primitive::array::SLOT_NAMES;
34use crate::arrays::primitive::compute::rules::RULES;
35use crate::hash::ArrayEq;
36use crate::hash::ArrayHash;
37
38pub type PrimitiveArray = Array<Primitive>;
40
41impl ArrayHash for PrimitiveData {
42 fn array_hash<H: Hasher>(&self, state: &mut H, precision: Precision) {
43 self.buffer.array_hash(state, precision);
44 }
45}
46
47impl ArrayEq for PrimitiveData {
48 fn array_eq(&self, other: &Self, precision: Precision) -> bool {
49 self.buffer.array_eq(&other.buffer, precision)
50 }
51}
52
53impl VTable for Primitive {
54 type ArrayData = PrimitiveData;
55
56 type OperationsVTable = Self;
57 type ValidityVTable = Self;
58
59 fn id(&self) -> ArrayId {
60 Self::ID
61 }
62
63 fn nbuffers(_array: ArrayView<'_, Self>) -> usize {
64 1
65 }
66
67 fn buffer(array: ArrayView<'_, Self>, idx: usize) -> BufferHandle {
68 match idx {
69 0 => array.buffer_handle().clone(),
70 _ => vortex_panic!("PrimitiveArray buffer index {idx} out of bounds"),
71 }
72 }
73
74 fn buffer_name(_array: ArrayView<'_, Self>, idx: usize) -> Option<String> {
75 match idx {
76 0 => Some("values".to_string()),
77 _ => None,
78 }
79 }
80
81 fn serialize(
82 _array: ArrayView<'_, Self>,
83 _session: &VortexSession,
84 ) -> VortexResult<Option<Vec<u8>>> {
85 Ok(Some(vec![]))
86 }
87
88 fn validate(
89 &self,
90 data: &PrimitiveData,
91 dtype: &DType,
92 len: usize,
93 slots: &[Option<ArrayRef>],
94 ) -> VortexResult<()> {
95 let DType::Primitive(_, nullability) = dtype else {
96 vortex_bail!("Expected primitive dtype, got {dtype:?}");
97 };
98 vortex_ensure!(
99 data.len() == len,
100 "PrimitiveArray length {} does not match outer length {}",
101 data.len(),
102 len
103 );
104 let validity = crate::array::child_to_validity(&slots[0], *nullability);
105 if let Some(validity_len) = validity.maybe_len() {
106 vortex_ensure!(
107 validity_len == len,
108 "PrimitiveArray validity len {} does not match outer length {}",
109 validity_len,
110 len
111 );
112 }
113
114 Ok(())
115 }
116
117 fn deserialize(
118 &self,
119 dtype: &DType,
120 len: usize,
121 metadata: &[u8],
122
123 buffers: &[BufferHandle],
124 children: &dyn ArrayChildren,
125 _session: &VortexSession,
126 ) -> VortexResult<crate::array::ArrayParts<Self>> {
127 if !metadata.is_empty() {
128 vortex_bail!(
129 "PrimitiveArray expects empty metadata, got {} bytes",
130 metadata.len()
131 );
132 }
133 if buffers.len() != 1 {
134 vortex_bail!("Expected 1 buffer, got {}", buffers.len());
135 }
136 let buffer = buffers[0].clone();
137
138 let validity = if children.is_empty() {
139 Validity::from(dtype.nullability())
140 } else if children.len() == 1 {
141 let validity = children.get(0, &Validity::DTYPE, len)?;
142 Validity::Array(validity)
143 } else {
144 vortex_bail!("Expected 0 or 1 child, got {}", children.len());
145 };
146
147 let ptype = PType::try_from(dtype)?;
148
149 vortex_ensure!(
150 buffer.is_aligned_to(Alignment::new(ptype.byte_width())),
151 "Misaligned buffer cannot be used to build PrimitiveArray of {ptype}"
152 );
153
154 if buffer.len() != ptype.byte_width() * len {
155 vortex_bail!(
156 "Buffer length {} does not match expected length {} for {}, {}",
157 buffer.len(),
158 ptype.byte_width() * len,
159 ptype.byte_width(),
160 len,
161 );
162 }
163
164 vortex_ensure!(
165 buffer.is_aligned_to(Alignment::new(ptype.byte_width())),
166 "PrimitiveArray::build: Buffer (align={}) must be aligned to {}",
167 buffer.alignment(),
168 ptype.byte_width()
169 );
170
171 let slots = PrimitiveData::make_slots(&validity, len);
173 let data = unsafe { PrimitiveData::new_unchecked_from_handle(buffer, ptype, validity) };
174 Ok(crate::array::ArrayParts::new(self.clone(), dtype.clone(), len, data).with_slots(slots))
175 }
176
177 fn slot_name(_array: ArrayView<'_, Self>, idx: usize) -> String {
178 SLOT_NAMES[idx].to_string()
179 }
180
181 fn execute(array: Array<Self>, _ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
182 Ok(ExecutionResult::done(array))
183 }
184
185 fn reduce_parent(
186 array: ArrayView<'_, Self>,
187 parent: &ArrayRef,
188 child_idx: usize,
189 ) -> VortexResult<Option<ArrayRef>> {
190 RULES.evaluate(array, parent, child_idx)
191 }
192
193 fn execute_parent(
194 array: ArrayView<'_, Self>,
195 parent: &ArrayRef,
196 child_idx: usize,
197 ctx: &mut ExecutionCtx,
198 ) -> VortexResult<Option<ArrayRef>> {
199 PARENT_KERNELS.execute(array, parent, child_idx, ctx)
200 }
201}
202
203#[derive(Clone, Debug)]
204pub struct Primitive;
205
206impl Primitive {
207 pub const ID: ArrayId = ArrayId::new_ref("vortex.primitive");
208}
209
210#[cfg(test)]
211mod tests {
212 use vortex_buffer::ByteBufferMut;
213 use vortex_buffer::buffer;
214 use vortex_session::registry::ReadContext;
215
216 use crate::ArrayContext;
217 use crate::IntoArray;
218 use crate::LEGACY_SESSION;
219 use crate::arrays::PrimitiveArray;
220 use crate::assert_arrays_eq;
221 use crate::serde::SerializeOptions;
222 use crate::serde::SerializedArray;
223 use crate::validity::Validity;
224
225 #[test]
226 fn test_nullable_primitive_serde_roundtrip() {
227 let array = PrimitiveArray::new(
228 buffer![1i32, 2, 3, 4],
229 Validity::from_iter([true, false, true, false]),
230 );
231 let dtype = array.dtype().clone();
232 let len = array.len();
233
234 let ctx = ArrayContext::empty();
235 let serialized = array
236 .clone()
237 .into_array()
238 .serialize(&ctx, &LEGACY_SESSION, &SerializeOptions::default())
239 .unwrap();
240
241 let mut concat = ByteBufferMut::empty();
242 for buf in serialized {
243 concat.extend_from_slice(buf.as_ref());
244 }
245 let parts = SerializedArray::try_from(concat.freeze()).unwrap();
246 let decoded = parts
247 .decode(
248 &dtype,
249 len,
250 &ReadContext::new(ctx.to_ids()),
251 &LEGACY_SESSION,
252 )
253 .unwrap();
254
255 assert_arrays_eq!(decoded, array);
256 }
257}