vortex_array/arrays/primitive/vtable/
mod.rs1use vortex_error::VortexResult;
5use vortex_error::vortex_bail;
6use vortex_error::vortex_ensure_eq;
7
8use crate::ArrayParts;
9use crate::ArrayRef;
10use crate::ExecutionCtx;
11use crate::ExecutionResult;
12use crate::array::Array;
13use crate::array::ArrayView;
14use crate::array::VTable;
15use crate::arrays::fixed_width::vtable as fixed_width;
16use crate::arrays::primitive::PrimitiveData;
17use crate::buffer::BufferHandle;
18use crate::builders::ArrayBuilder;
19use crate::builders::PrimitiveBuilder;
20use crate::dtype::DType;
21use crate::match_each_native_ptype;
22mod kernel;
23mod operations;
24mod plugin;
25mod validity;
26
27use std::hash::Hasher;
28
29use vortex_session::VortexSession;
30use vortex_session::registry::CachedId;
31
32use crate::EqMode;
33use crate::array::ArrayId;
34use crate::arrays::primitive::array::PrimitiveSlots;
35use crate::hash::ArrayEq;
36use crate::hash::ArrayHash;
37
38pub type PrimitiveArray = Array<Primitive>;
40
41pub(crate) fn initialize(session: &VortexSession) {
42 kernel::initialize(session);
43}
44
45impl ArrayHash for PrimitiveData {
46 fn array_hash<H: Hasher>(&self, state: &mut H, accuracy: EqMode) {
47 self.buffer.array_hash(state, accuracy);
48 }
49}
50
51impl ArrayEq for PrimitiveData {
52 fn array_eq(&self, other: &Self, accuracy: EqMode) -> bool {
53 self.buffer.array_eq(&other.buffer, accuracy)
54 }
55}
56
57impl VTable for Primitive {
58 type TypedArrayData = PrimitiveData;
59
60 type OperationsVTable = Self;
61 type ValidityVTable = Self;
62
63 fn id(&self) -> ArrayId {
64 static ID: CachedId = CachedId::new("vortex.primitive");
65 *ID
66 }
67
68 fn nbuffers(_array: ArrayView<'_, Self>) -> usize {
69 1
70 }
71
72 fn buffer(array: ArrayView<'_, Self>, idx: usize) -> BufferHandle {
73 fixed_width::buffer("PrimitiveArray", array.buffer_handle(), idx)
74 }
75
76 fn buffer_name(_array: ArrayView<'_, Self>, idx: usize) -> Option<String> {
77 fixed_width::buffer_name(idx)
78 }
79
80 fn with_buffers(
81 &self,
82 array: ArrayView<'_, Self>,
83 buffers: &[BufferHandle],
84 ) -> VortexResult<ArrayParts<Self>> {
85 let mut data = array.data().clone();
86 data.buffer = fixed_width::single_buffer(buffers)?;
87 Ok(ArrayParts::new(
88 self.clone(),
89 array.dtype().clone(),
90 array.len(),
91 data,
92 array.slots().iter().cloned().collect(),
93 ))
94 }
95
96 fn validate(
97 &self,
98 data: &PrimitiveData,
99 dtype: &DType,
100 len: usize,
101 slots: &[Option<ArrayRef>],
102 ) -> VortexResult<()> {
103 let DType::Primitive(_, nullability) = dtype else {
104 vortex_bail!("Expected primitive dtype, got {dtype:?}");
105 };
106 vortex_ensure_eq!(
107 data.len(),
108 len,
109 "PrimitiveArray length does not match outer length",
110 );
111 let validity = crate::array::child_to_validity(
112 slots[PrimitiveSlots::VALIDITY_CHILD].as_ref(),
113 *nullability,
114 );
115 if let Some(validity_len) = validity.maybe_len() {
116 vortex_ensure_eq!(
117 validity_len,
118 len,
119 "PrimitiveArray validity len does not match outer length",
120 );
121 }
122
123 Ok(())
124 }
125
126 fn slot_name(_array: ArrayView<'_, Self>, idx: usize) -> String {
127 PrimitiveSlots::NAMES[idx].to_string()
128 }
129
130 fn execute(array: Array<Self>, _ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
131 Ok(ExecutionResult::done(array))
132 }
133
134 fn append_to_builder(
135 array: ArrayView<'_, Self>,
136 builder: &mut dyn ArrayBuilder,
137 ctx: &mut ExecutionCtx,
138 ) -> VortexResult<()> {
139 match_each_native_ptype!(array.ptype(), |P| {
140 if let Some(builder) = builder.as_any_mut().downcast_mut::<PrimitiveBuilder<P>>() {
141 return builder.append_primitive_array(array, ctx);
142 }
143 });
144
145 vortex_bail!("append_to_builder for Primitive requires a matching PrimitiveBuilder");
146 }
147}
148
149#[derive(Clone, Debug)]
150pub struct Primitive;
151
152#[cfg(test)]
153mod tests {
154 use std::sync::LazyLock;
155
156 use vortex_buffer::ByteBufferMut;
157 use vortex_buffer::buffer;
158 use vortex_error::VortexResult;
159 use vortex_session::VortexSession;
160 use vortex_session::registry::ReadContext;
161
162 use crate::ArrayContext;
163 use crate::IntoArray;
164 use crate::VortexSessionExecute;
165 use crate::arrays::PrimitiveArray;
166 use crate::assert_arrays_eq;
167 use crate::buffer::BufferHandle;
168 use crate::serde::SerializeOptions;
169 use crate::serde::SerializedArray;
170 use crate::validity::Validity;
171
172 static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
173
174 #[test]
175 fn test_nullable_primitive_serde_roundtrip() {
176 let session = VortexSession::empty();
177 let mut ctx = session.create_execution_ctx();
178 let array = PrimitiveArray::new(
179 buffer![1i32, 2, 3, 4],
180 Validity::from_iter([true, false, true, false]),
181 );
182 let dtype = array.dtype().clone();
183 let len = array.len();
184
185 let array_ctx = ArrayContext::empty();
186 let serialized = array
187 .clone()
188 .into_array()
189 .serialize(&array_ctx, &session, &SerializeOptions::default())
190 .unwrap();
191
192 let mut concat = ByteBufferMut::empty();
193 for buf in serialized {
194 concat.extend_from_slice(buf.as_ref());
195 }
196 let parts = SerializedArray::try_from(concat.freeze()).unwrap();
197 let decoded = parts
198 .decode(&dtype, len, &ReadContext::new(array_ctx.to_ids()), &session)
199 .unwrap();
200
201 assert_arrays_eq!(decoded, array, &mut ctx);
202 }
203
204 #[test]
205 fn test_with_buffers_replaces_primitive_buffer_with_equivalent_contents() -> VortexResult<()> {
206 let mut ctx = SESSION.create_execution_ctx();
207
208 let array = PrimitiveArray::from_iter([1i32, 2, 3, 4]).into_array();
209 let replacement = BufferHandle::new_host(buffer![1i32, 2, 3, 4].into_byte_buffer());
210 let replacement_ptr = replacement.as_host().as_ptr();
213 let rewritten = unsafe { array.with_buffers([replacement]) }?;
214 assert_eq!(
215 rewritten.buffer_handles()[0].as_host().as_ptr(),
216 replacement_ptr
217 );
218 let expected = PrimitiveArray::from_iter([1i32, 2, 3, 4]);
219
220 assert_arrays_eq!(rewritten, expected, &mut ctx);
221 Ok(())
222 }
223
224 #[test]
225 fn test_with_buffers_rejects_length_change() {
226 let array = PrimitiveArray::from_iter([1i32, 2, 3, 4]).into_array();
227 let replacement = BufferHandle::new_host(buffer![10i32, 20, 30].into_byte_buffer());
228
229 assert!(unsafe { array.with_buffers([replacement]) }.is_err());
232 }
233}