vortex_array/arrays/varbinview/vtable/
mod.rs1use std::hash::Hasher;
5use std::mem::size_of;
6use std::sync::Arc;
7
8use kernel::PARENT_KERNELS;
9use vortex_buffer::Buffer;
10use vortex_error::VortexResult;
11use vortex_error::vortex_bail;
12use vortex_error::vortex_ensure;
13use vortex_error::vortex_err;
14use vortex_error::vortex_panic;
15use vortex_session::VortexSession;
16
17use crate::ArrayRef;
18use crate::ExecutionCtx;
19use crate::ExecutionResult;
20use crate::Precision;
21use crate::array::Array;
22use crate::array::ArrayId;
23use crate::array::ArrayView;
24use crate::array::VTable;
25use crate::arrays::varbinview::BinaryView;
26use crate::arrays::varbinview::VarBinViewData;
27use crate::arrays::varbinview::array::NUM_SLOTS;
28use crate::arrays::varbinview::array::SLOT_NAMES;
29use crate::arrays::varbinview::compute::rules::PARENT_RULES;
30use crate::buffer::BufferHandle;
31use crate::dtype::DType;
32use crate::hash::ArrayEq;
33use crate::hash::ArrayHash;
34use crate::serde::ArrayChildren;
35use crate::validity::Validity;
36mod kernel;
37mod operations;
38mod validity;
39pub type VarBinViewArray = Array<VarBinView>;
41
42#[derive(Clone, Debug)]
43pub struct VarBinView;
44
45impl VarBinView {
46 pub const ID: ArrayId = ArrayId::new_ref("vortex.varbinview");
47}
48
49impl ArrayHash for VarBinViewData {
50 fn array_hash<H: Hasher>(&self, state: &mut H, precision: Precision) {
51 for buffer in self.buffers.iter() {
52 buffer.array_hash(state, precision);
53 }
54 self.views.array_hash(state, precision);
55 }
56}
57
58impl ArrayEq for VarBinViewData {
59 fn array_eq(&self, other: &Self, precision: Precision) -> bool {
60 self.buffers.len() == other.buffers.len()
61 && self
62 .buffers
63 .iter()
64 .zip(other.buffers.iter())
65 .all(|(a, b)| a.array_eq(b, precision))
66 && self.views.array_eq(&other.views, precision)
67 }
68}
69
70impl VTable for VarBinView {
71 type ArrayData = VarBinViewData;
72
73 type OperationsVTable = Self;
74 type ValidityVTable = Self;
75
76 fn id(&self) -> ArrayId {
77 Self::ID
78 }
79
80 fn nbuffers(array: ArrayView<'_, Self>) -> usize {
81 array.data_buffers().len() + 1
82 }
83
84 fn validate(
85 &self,
86 data: &VarBinViewData,
87 dtype: &DType,
88 len: usize,
89 slots: &[Option<ArrayRef>],
90 ) -> VortexResult<()> {
91 vortex_ensure!(
92 slots.len() == NUM_SLOTS,
93 "VarBinViewArray expected {NUM_SLOTS} slots, found {}",
94 slots.len()
95 );
96 vortex_ensure!(
97 data.len() == len,
98 "VarBinViewArray length {} does not match outer length {}",
99 data.len(),
100 len
101 );
102 vortex_ensure!(
103 matches!(dtype, DType::Binary(_) | DType::Utf8(_)),
104 "VarBinViewArray dtype must be binary or utf8, got {dtype}"
105 );
106 Ok(())
107 }
108
109 fn buffer(array: ArrayView<'_, Self>, idx: usize) -> BufferHandle {
110 let ndata = array.data_buffers().len();
111 if idx < ndata {
112 array.data_buffers()[idx].clone()
113 } else if idx == ndata {
114 array.views_handle().clone()
115 } else {
116 vortex_panic!("VarBinViewArray buffer index {idx} out of bounds")
117 }
118 }
119
120 fn buffer_name(array: ArrayView<'_, Self>, idx: usize) -> Option<String> {
121 let ndata = array.data_buffers().len();
122 if idx < ndata {
123 Some(format!("buffer_{idx}"))
124 } else if idx == ndata {
125 Some("views".to_string())
126 } else {
127 vortex_panic!("VarBinViewArray buffer_name index {idx} out of bounds")
128 }
129 }
130
131 fn serialize(
132 _array: ArrayView<'_, Self>,
133 _session: &VortexSession,
134 ) -> VortexResult<Option<Vec<u8>>> {
135 Ok(Some(vec![]))
136 }
137
138 fn deserialize(
139 &self,
140 dtype: &DType,
141 len: usize,
142 metadata: &[u8],
143
144 buffers: &[BufferHandle],
145 children: &dyn ArrayChildren,
146 _session: &VortexSession,
147 ) -> VortexResult<crate::array::ArrayParts<Self>> {
148 if !metadata.is_empty() {
149 vortex_bail!(
150 "VarBinViewArray expects empty metadata, got {} bytes",
151 metadata.len()
152 );
153 }
154 let Some((views_handle, data_handles)) = buffers.split_last() else {
155 vortex_bail!("Expected at least 1 buffer, got 0");
156 };
157
158 let validity = if children.is_empty() {
159 Validity::from(dtype.nullability())
160 } else if children.len() == 1 {
161 let validity = children.get(0, &Validity::DTYPE, len)?;
162 Validity::Array(validity)
163 } else {
164 vortex_bail!("Expected 0 or 1 children, got {}", children.len());
165 };
166
167 let views_nbytes = views_handle.len();
168 let expected_views_nbytes = len
169 .checked_mul(size_of::<BinaryView>())
170 .ok_or_else(|| vortex_err!("views byte length overflow for len={len}"))?;
171 if views_nbytes != expected_views_nbytes {
172 vortex_bail!(
173 "Expected views buffer length {} bytes, got {} bytes",
174 expected_views_nbytes,
175 views_nbytes
176 );
177 }
178
179 if buffers.iter().any(|b| b.is_on_device()) {
181 let data = VarBinViewData::try_new_handle(
182 views_handle.clone(),
183 Arc::from(data_handles.to_vec()),
184 dtype.clone(),
185 validity.clone(),
186 )?;
187 let slots = VarBinViewData::make_slots(&validity, len);
188 return Ok(
189 crate::array::ArrayParts::new(self.clone(), dtype.clone(), len, data)
190 .with_slots(slots),
191 );
192 }
193
194 let data_buffers = data_handles
195 .iter()
196 .map(|b| b.as_host().clone())
197 .collect::<Vec<_>>();
198 let views = Buffer::<BinaryView>::from_byte_buffer(views_handle.clone().as_host().clone());
199
200 let data = VarBinViewData::try_new(
201 views,
202 Arc::from(data_buffers),
203 dtype.clone(),
204 validity.clone(),
205 )?;
206 let slots = VarBinViewData::make_slots(&validity, len);
207 Ok(crate::array::ArrayParts::new(self.clone(), dtype.clone(), len, data).with_slots(slots))
208 }
209
210 fn slot_name(_array: ArrayView<'_, Self>, idx: usize) -> String {
211 SLOT_NAMES[idx].to_string()
212 }
213
214 fn reduce_parent(
215 array: ArrayView<'_, Self>,
216 parent: &ArrayRef,
217 child_idx: usize,
218 ) -> VortexResult<Option<ArrayRef>> {
219 PARENT_RULES.evaluate(array, parent, child_idx)
220 }
221
222 fn execute_parent(
223 array: ArrayView<'_, Self>,
224 parent: &ArrayRef,
225 child_idx: usize,
226 ctx: &mut ExecutionCtx,
227 ) -> VortexResult<Option<ArrayRef>> {
228 PARENT_KERNELS.execute(array, parent, child_idx, ctx)
229 }
230
231 fn execute(array: Array<Self>, _ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
232 Ok(ExecutionResult::done(array))
233 }
234}
235
236#[cfg(test)]
237mod tests {
238 use vortex_buffer::ByteBufferMut;
239 use vortex_session::registry::ReadContext;
240
241 use super::*;
242 use crate::ArrayContext;
243 use crate::IntoArray;
244 use crate::LEGACY_SESSION;
245 use crate::assert_arrays_eq;
246 use crate::serde::SerializeOptions;
247 use crate::serde::SerializedArray;
248
249 #[test]
250 fn test_nullable_varbinview_serde_roundtrip() {
251 let array = VarBinViewArray::from_iter_nullable_str([
252 Some("hello"),
253 None,
254 Some("world"),
255 None,
256 Some("a moderately long string for testing"),
257 ]);
258 let dtype = array.dtype().clone();
259 let len = array.len();
260
261 let ctx = ArrayContext::empty();
262 let serialized = array
263 .clone()
264 .into_array()
265 .serialize(&ctx, &LEGACY_SESSION, &SerializeOptions::default())
266 .unwrap();
267
268 let mut concat = ByteBufferMut::empty();
269 for buf in serialized {
270 concat.extend_from_slice(buf.as_ref());
271 }
272 let parts = SerializedArray::try_from(concat.freeze()).unwrap();
273 let decoded = parts
274 .decode(
275 &dtype,
276 len,
277 &ReadContext::new(ctx.to_ids()),
278 &LEGACY_SESSION,
279 )
280 .unwrap();
281
282 assert_arrays_eq!(decoded, array);
283 }
284}