vortex_array/arrays/varbinview/vtable/
mod.rs1use std::hash::Hasher;
5use std::sync::Arc;
6
7use vortex_error::VortexResult;
8use vortex_error::vortex_bail;
9use vortex_error::vortex_ensure;
10use vortex_error::vortex_ensure_eq;
11use vortex_error::vortex_panic;
12use vortex_session::VortexSession;
13use vortex_session::registry::CachedId;
14
15use crate::ArrayParts;
16use crate::ArrayRef;
17use crate::EqMode;
18use crate::ExecutionCtx;
19use crate::ExecutionResult;
20use crate::array::Array;
21use crate::array::ArrayId;
22use crate::array::ArrayView;
23use crate::array::VTable;
24use crate::arrays::varbinview::VarBinViewData;
25use crate::arrays::varbinview::array::VarBinViewSlots;
26use crate::buffer::BufferHandle;
27use crate::builders::ArrayBuilder;
28use crate::builders::VarBinViewBuilder;
29use crate::dtype::DType;
30use crate::hash::ArrayEq;
31use crate::hash::ArrayHash;
32use crate::match_each_varbin_builder;
33mod kernel;
34mod operations;
35mod plugin;
36mod validity;
37pub type VarBinViewArray = Array<VarBinView>;
39
40pub(crate) fn initialize(session: &VortexSession) {
41 kernel::initialize(session);
42}
43
44#[derive(Clone, Debug)]
45pub struct VarBinView;
46
47impl ArrayHash for VarBinViewData {
48 fn array_hash<H: Hasher>(&self, state: &mut H, accuracy: EqMode) {
49 for buffer in self.buffers.iter() {
50 buffer.array_hash(state, accuracy);
51 }
52 self.views.array_hash(state, accuracy);
53 }
54}
55
56impl ArrayEq for VarBinViewData {
57 fn array_eq(&self, other: &Self, accuracy: EqMode) -> bool {
58 self.buffers.len() == other.buffers.len()
59 && self
60 .buffers
61 .iter()
62 .zip(other.buffers.iter())
63 .all(|(a, b)| a.array_eq(b, accuracy))
64 && self.views.array_eq(&other.views, accuracy)
65 }
66}
67
68impl VTable for VarBinView {
69 type TypedArrayData = VarBinViewData;
70
71 type OperationsVTable = Self;
72 type ValidityVTable = Self;
73
74 fn id(&self) -> ArrayId {
75 static ID: CachedId = CachedId::new("vortex.varbinview");
76 *ID
77 }
78
79 fn nbuffers(array: ArrayView<'_, Self>) -> usize {
80 array.data_buffers().len() + 1
81 }
82
83 fn validate(
84 &self,
85 data: &VarBinViewData,
86 dtype: &DType,
87 len: usize,
88 slots: &[Option<ArrayRef>],
89 ) -> VortexResult<()> {
90 vortex_ensure_eq!(slots.len(), VarBinViewSlots::COUNT);
91 vortex_ensure_eq!(
92 data.len(),
93 len,
94 "VarBinViewArray length does not match outer length",
95 );
96 vortex_ensure!(
97 matches!(dtype, DType::Binary(_) | DType::Utf8(_)),
98 "VarBinViewArray dtype must be binary or utf8, got {dtype}"
99 );
100 Ok(())
101 }
102
103 fn buffer(array: ArrayView<'_, Self>, idx: usize) -> BufferHandle {
104 let ndata = array.data_buffers().len();
105 if idx < ndata {
106 array.data_buffers()[idx].clone()
107 } else if idx == ndata {
108 array.views_handle().clone()
109 } else {
110 vortex_panic!("VarBinViewArray buffer index {idx} out of bounds")
111 }
112 }
113
114 fn buffer_name(array: ArrayView<'_, Self>, idx: usize) -> Option<String> {
115 let ndata = array.data_buffers().len();
116 if idx < ndata {
117 Some(format!("buffer_{idx}"))
118 } else if idx == ndata {
119 Some("views".to_string())
120 } else {
121 vortex_panic!("VarBinViewArray buffer_name index {idx} out of bounds")
122 }
123 }
124
125 fn with_buffers(
126 &self,
127 array: ArrayView<'_, Self>,
128 buffers: &[BufferHandle],
129 ) -> VortexResult<ArrayParts<Self>> {
130 let Some((views, data_buffers)) = buffers.split_last() else {
131 vortex_bail!("Expected at least 1 buffer, got 0");
132 };
133 let data = VarBinViewData::try_new_handle(
134 views.clone(),
135 Arc::from(data_buffers.to_vec()),
136 array.dtype().clone(),
137 array.validity()?,
138 )?;
139 Ok(ArrayParts::new(
140 self.clone(),
141 array.dtype().clone(),
142 array.len(),
143 data,
144 array.slots().iter().cloned().collect(),
145 ))
146 }
147
148 fn slot_name(_array: ArrayView<'_, Self>, idx: usize) -> String {
149 VarBinViewSlots::NAMES[idx].to_string()
150 }
151
152 fn append_to_builder(
153 array: ArrayView<'_, Self>,
154 builder: &mut dyn ArrayBuilder,
155 ctx: &mut ExecutionCtx,
156 ) -> VortexResult<()> {
157 if let Some(builder) = builder.as_any_mut().downcast_mut::<VarBinViewBuilder>() {
158 return builder.append_varbinview_array(array, ctx);
159 }
160 if let Some(result) =
161 match_each_varbin_builder!(builder, |builder| builder.append_varbinview(array, ctx))
162 {
163 return result;
164 }
165 vortex_bail!("append_to_builder for VarBinView requires a variable-binary builder")
166 }
167
168 fn execute(array: Array<Self>, _ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
169 Ok(ExecutionResult::done(array))
170 }
171}
172
173#[cfg(test)]
174mod tests {
175 use std::sync::LazyLock;
176
177 use vortex_buffer::ByteBufferMut;
178 use vortex_session::VortexSession;
179 use vortex_session::registry::ReadContext;
180
181 use super::*;
182 use crate::ArrayContext;
183 use crate::IntoArray;
184 use crate::VortexSessionExecute;
185 use crate::assert_arrays_eq;
186 use crate::serde::SerializeOptions;
187 use crate::serde::SerializedArray;
188
189 static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
190
191 #[test]
192 fn test_nullable_varbinview_serde_roundtrip() {
193 let array = VarBinViewArray::from_iter_nullable_str([
194 Some("hello"),
195 None,
196 Some("world"),
197 None,
198 Some("a moderately long string for testing"),
199 ]);
200 let dtype = array.dtype().clone();
201 let len = array.len();
202
203 let mut ctx = SESSION.create_execution_ctx();
204 let array_ctx = ArrayContext::empty();
205 let serialized = array
206 .clone()
207 .into_array()
208 .serialize(&array_ctx, &SESSION, &SerializeOptions::default())
209 .unwrap();
210
211 let mut concat = ByteBufferMut::empty();
212 for buf in serialized {
213 concat.extend_from_slice(buf.as_ref());
214 }
215 let parts = SerializedArray::try_from(concat.freeze()).unwrap();
216 let decoded = parts
217 .decode(&dtype, len, &ReadContext::new(array_ctx.to_ids()), &SESSION)
218 .unwrap();
219
220 assert_arrays_eq!(decoded, array, &mut ctx);
221 }
222}