Skip to main content

vortex_array/arrays/varbin/vtable/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::hash::Hasher;
5
6use vortex_error::VortexExpect;
7use vortex_error::VortexResult;
8use vortex_error::vortex_bail;
9use vortex_error::vortex_ensure;
10use vortex_error::vortex_ensure_eq;
11use vortex_error::vortex_err;
12use vortex_error::vortex_panic;
13use vortex_session::registry::CachedId;
14
15use crate::ArrayParts;
16use crate::ArrayRef;
17use crate::ExecutionCtx;
18use crate::ExecutionResult;
19use crate::IntoArray;
20use crate::array::Array;
21use crate::array::ArrayId;
22use crate::array::ArrayView;
23use crate::array::VTable;
24use crate::arrays::Primitive;
25use crate::arrays::PrimitiveArray;
26use crate::arrays::varbin::VarBinArrayExt;
27use crate::arrays::varbin::VarBinArraySlotsExt;
28use crate::arrays::varbin::VarBinData;
29use crate::arrays::varbin::VarBinSlots;
30use crate::buffer::BufferHandle;
31use crate::builders::ArrayBuilder;
32use crate::builders::VarBinViewBuilder;
33use crate::dtype::DType;
34use crate::dtype::PType;
35use crate::match_each_integer_ptype;
36use crate::match_each_varbin_builder;
37use crate::require_child;
38pub(crate) mod canonical;
39mod kernel;
40mod operations;
41mod plugin;
42mod validity;
43
44use canonical::varbin_to_canonical;
45use vortex_session::VortexSession;
46
47use crate::EqMode;
48use crate::hash::ArrayEq;
49use crate::hash::ArrayHash;
50
51/// A [`VarBin`]-encoded Vortex array.
52pub type VarBinArray = Array<VarBin>;
53
54pub(crate) fn initialize(session: &VortexSession) {
55    kernel::initialize(session);
56}
57
58#[derive(Clone, prost::Message)]
59pub struct VarBinMetadata {
60    #[prost(int32, tag = "1")]
61    pub(crate) offsets_ptype: i32,
62}
63
64impl VarBinMetadata {
65    fn get_offsets_ptype(&self) -> VortexResult<PType> {
66        PType::try_from(self.offsets_ptype).map_err(|_| {
67            vortex_err!(
68                "VarBinMetadata offsets_ptype must be a known PType, got {}",
69                self.offsets_ptype
70            )
71        })
72    }
73}
74
75impl ArrayHash for VarBinData {
76    fn array_hash<H: Hasher>(&self, state: &mut H, accuracy: EqMode) {
77        self.bytes().array_hash(state, accuracy);
78    }
79}
80
81impl ArrayEq for VarBinData {
82    fn array_eq(&self, other: &Self, accuracy: EqMode) -> bool {
83        self.bytes().array_eq(other.bytes(), accuracy)
84    }
85}
86
87impl VTable for VarBin {
88    type TypedArrayData = VarBinData;
89
90    type OperationsVTable = Self;
91    type ValidityVTable = Self;
92    fn id(&self) -> ArrayId {
93        static ID: CachedId = CachedId::new("vortex.varbin");
94        *ID
95    }
96
97    fn nbuffers(_array: ArrayView<'_, Self>) -> usize {
98        1
99    }
100
101    fn validate(
102        &self,
103        _data: &VarBinData,
104        dtype: &DType,
105        len: usize,
106        slots: &[Option<ArrayRef>],
107    ) -> VortexResult<()> {
108        vortex_ensure_eq!(slots.len(), VarBinSlots::COUNT);
109        let offsets = slots[VarBinSlots::OFFSETS]
110            .as_ref()
111            .vortex_expect("VarBinArray offsets slot");
112        vortex_ensure_eq!(
113            offsets.len().saturating_sub(1),
114            len,
115            "VarBinArray length does not match outer length",
116        );
117        vortex_ensure!(
118            matches!(dtype, DType::Binary(_) | DType::Utf8(_)),
119            "VarBinArray dtype must be binary or utf8, got {dtype}"
120        );
121        Ok(())
122    }
123
124    fn buffer(array: ArrayView<'_, Self>, idx: usize) -> BufferHandle {
125        match idx {
126            0 => array.bytes_handle().clone(),
127            _ => vortex_panic!("VarBinArray buffer index {idx} out of bounds"),
128        }
129    }
130
131    fn buffer_name(_array: ArrayView<'_, Self>, idx: usize) -> Option<String> {
132        match idx {
133            0 => Some("bytes".to_string()),
134            _ => vortex_panic!("VarBinArray buffer_name index {idx} out of bounds"),
135        }
136    }
137
138    fn with_buffers(
139        &self,
140        array: ArrayView<'_, Self>,
141        buffers: &[BufferHandle],
142    ) -> VortexResult<ArrayParts<Self>> {
143        vortex_ensure_eq!(buffers.len(), 1);
144        let mut data = array.data().clone();
145        data.bytes = buffers[0].clone();
146        Ok(ArrayParts::new(
147            self.clone(),
148            array.dtype().clone(),
149            array.len(),
150            data,
151            array.slots().iter().cloned().collect(),
152        ))
153    }
154
155    fn slot_name(_array: ArrayView<'_, Self>, idx: usize) -> String {
156        VarBinSlots::NAMES[idx].to_string()
157    }
158
159    fn append_to_builder(
160        array: ArrayView<'_, Self>,
161        builder: &mut dyn ArrayBuilder,
162        ctx: &mut ExecutionCtx,
163    ) -> VortexResult<()> {
164        if let Some(result) =
165            match_each_varbin_builder!(builder, |builder| builder.append_varbin(array, ctx))
166        {
167            return result;
168        }
169
170        // The two arms here are every builder a `Utf8`/`Binary` dtype has: all four
171        // `VarBinBuilder` widths above, and `VarBinViewBuilder` below.
172        let Some(builder) = builder.as_any_mut().downcast_mut::<VarBinViewBuilder>() else {
173            vortex_bail!("append_to_builder for VarBin requires a variable-binary builder")
174        };
175        append_to_varbinview(array, builder, ctx)
176    }
177
178    fn execute(array: Array<Self>, _ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
179        let array = require_child!(array, array.offsets(), VarBinSlots::OFFSETS => Primitive);
180
181        Ok(ExecutionResult::done(
182            varbin_to_canonical(array)?.into_array(),
183        ))
184    }
185}
186
187/// Hands the value bytes to `builder` as a data buffer with views built over them.
188///
189/// Canonicalizing first would build the same views, then pay for them twice more: once to wrap
190/// them in a `VarBinViewArray` the builder immediately unwraps, and once for
191/// `append_varbinview_array` to rewrite every view so its buffer index is rebased onto the
192/// builder's. Handing the heap and offsets to the builder instead makes the whole append one view
193/// per row with no byte copy — the builder adopts the referenced range of the heap as it is. That
194/// range is fully covered by the new views, so this stays valid for a compacting builder too.
195fn append_to_varbinview(
196    array: ArrayView<'_, VarBin>,
197    builder: &mut VarBinViewBuilder,
198    ctx: &mut ExecutionCtx,
199) -> VortexResult<()> {
200    let len = array.as_ref().len();
201    let validity = array.varbin_validity().execute_mask(len, ctx)?;
202
203    let parts = array.into_owned().into_data_parts();
204    let offsets = parts.offsets.execute::<PrimitiveArray>(ctx)?;
205    match_each_integer_ptype!(offsets.ptype(), |P| {
206        builder.append_buffer_with_offsets(
207            parts.bytes.unwrap_host(),
208            offsets.as_slice::<P>(),
209            &validity,
210        )
211    });
212    Ok(())
213}
214
215#[derive(Clone, Debug)]
216pub struct VarBin;
217
218#[cfg(test)]
219mod tests {
220    use std::sync::LazyLock;
221
222    use prost::Message;
223    use vortex_error::VortexResult;
224    use vortex_session::VortexSession;
225
226    use super::VarBin;
227    use super::VarBinMetadata;
228    use crate::ArrayRef;
229    use crate::array::ArrayDeserialization;
230    use crate::array::ArrayPlugin;
231    use crate::array::VTable;
232    use crate::dtype::DType;
233    use crate::dtype::Nullability;
234    use crate::dtype::PType;
235
236    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
237
238    #[test]
239    fn test_deserialize_rejects_unknown_offsets_ptype() -> VortexResult<()> {
240        let metadata = VarBinMetadata { offsets_ptype: 11 }.encode_to_vec();
241        let children: Vec<ArrayRef> = Vec::new();
242        let result = ArrayPlugin::deserialize(
243            &VarBin,
244            ArrayDeserialization::new(
245                VTable::id(&VarBin),
246                &DType::Utf8(Nullability::NonNullable),
247                0,
248                &metadata,
249                &[],
250                &children,
251            ),
252            &SESSION,
253        );
254        assert!(result.is_err_and(|err| {
255            err.to_string()
256                .contains("VarBinMetadata offsets_ptype must be a known PType, got 11")
257        }));
258
259        let known = VarBinMetadata {
260            offsets_ptype: PType::U32 as i32,
261        };
262        assert_eq!(known.get_offsets_ptype()?, PType::U32);
263
264        Ok(())
265    }
266}