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 vortex_error::VortexExpect;
5use vortex_error::VortexResult;
6use vortex_error::vortex_bail;
7use vortex_error::vortex_err;
8use vortex_error::vortex_panic;
9
10use crate::ArrayRef;
11use crate::DeserializeMetadata;
12use crate::ExecutionCtx;
13use crate::IntoArray;
14use crate::ProstMetadata;
15use crate::SerializeMetadata;
16use crate::arrays::varbin::VarBinArray;
17use crate::buffer::BufferHandle;
18use crate::dtype::DType;
19use crate::dtype::Nullability;
20use crate::dtype::PType;
21use crate::serde::ArrayChildren;
22use crate::validity::Validity;
23use crate::vtable;
24use crate::vtable::ArrayId;
25use crate::vtable::VTable;
26use crate::vtable::ValidityVTableFromValidityHelper;
27use crate::vtable::validity_nchildren;
28use crate::vtable::validity_to_child;
29mod canonical;
30mod kernel;
31mod operations;
32mod validity;
33use std::hash::Hash;
34
35use canonical::varbin_to_canonical;
36use kernel::PARENT_KERNELS;
37use vortex_session::VortexSession;
38
39use crate::Precision;
40use crate::arrays::varbin::compute::rules::PARENT_RULES;
41use crate::hash::ArrayEq;
42use crate::hash::ArrayHash;
43use crate::stats::StatsSetRef;
44
45vtable!(VarBin);
46
47#[derive(Clone, prost::Message)]
48pub struct VarBinMetadata {
49    #[prost(enumeration = "PType", tag = "1")]
50    pub(crate) offsets_ptype: i32,
51}
52
53impl VTable for VarBinVTable {
54    type Array = VarBinArray;
55
56    type Metadata = ProstMetadata<VarBinMetadata>;
57    type OperationsVTable = Self;
58    type ValidityVTable = ValidityVTableFromValidityHelper;
59    fn id(_array: &Self::Array) -> ArrayId {
60        Self::ID
61    }
62
63    fn len(array: &VarBinArray) -> usize {
64        array.offsets().len().saturating_sub(1)
65    }
66
67    fn dtype(array: &VarBinArray) -> &DType {
68        &array.dtype
69    }
70
71    fn stats(array: &VarBinArray) -> StatsSetRef<'_> {
72        array.stats_set.to_ref(array.as_ref())
73    }
74
75    fn array_hash<H: std::hash::Hasher>(array: &VarBinArray, state: &mut H, precision: Precision) {
76        array.dtype.hash(state);
77        array.bytes().array_hash(state, precision);
78        array.offsets().array_hash(state, precision);
79        array.validity.array_hash(state, precision);
80    }
81
82    fn array_eq(array: &VarBinArray, other: &VarBinArray, precision: Precision) -> bool {
83        array.dtype == other.dtype
84            && array.bytes().array_eq(other.bytes(), precision)
85            && array.offsets().array_eq(other.offsets(), precision)
86            && array.validity.array_eq(&other.validity, precision)
87    }
88
89    fn nbuffers(_array: &VarBinArray) -> usize {
90        1
91    }
92
93    fn buffer(array: &VarBinArray, idx: usize) -> BufferHandle {
94        match idx {
95            0 => array.bytes_handle().clone(),
96            _ => vortex_panic!("VarBinArray buffer index {idx} out of bounds"),
97        }
98    }
99
100    fn buffer_name(_array: &VarBinArray, idx: usize) -> Option<String> {
101        match idx {
102            0 => Some("bytes".to_string()),
103            _ => vortex_panic!("VarBinArray buffer_name index {idx} out of bounds"),
104        }
105    }
106
107    fn nchildren(array: &VarBinArray) -> usize {
108        1 + validity_nchildren(&array.validity)
109    }
110
111    fn child(array: &VarBinArray, idx: usize) -> ArrayRef {
112        match idx {
113            0 => array.offsets().clone(),
114            1 => validity_to_child(&array.validity, array.len())
115                .vortex_expect("VarBinArray validity child out of bounds"),
116            _ => vortex_panic!("VarBinArray child index {idx} out of bounds"),
117        }
118    }
119
120    fn child_name(_array: &VarBinArray, idx: usize) -> String {
121        match idx {
122            0 => "offsets".to_string(),
123            1 => "validity".to_string(),
124            _ => vortex_panic!("VarBinArray child_name index {idx} out of bounds"),
125        }
126    }
127
128    fn metadata(array: &VarBinArray) -> VortexResult<Self::Metadata> {
129        Ok(ProstMetadata(VarBinMetadata {
130            offsets_ptype: PType::try_from(array.offsets().dtype())
131                .vortex_expect("Must be a valid PType") as i32,
132        }))
133    }
134
135    fn serialize(metadata: Self::Metadata) -> VortexResult<Option<Vec<u8>>> {
136        Ok(Some(metadata.serialize()))
137    }
138
139    fn deserialize(
140        bytes: &[u8],
141        _dtype: &DType,
142        _len: usize,
143        _buffers: &[BufferHandle],
144        _session: &VortexSession,
145    ) -> VortexResult<Self::Metadata> {
146        Ok(ProstMetadata(ProstMetadata::<VarBinMetadata>::deserialize(
147            bytes,
148        )?))
149    }
150
151    fn build(
152        dtype: &DType,
153        len: usize,
154        metadata: &Self::Metadata,
155        buffers: &[BufferHandle],
156        children: &dyn ArrayChildren,
157    ) -> VortexResult<VarBinArray> {
158        let validity = if children.len() == 1 {
159            Validity::from(dtype.nullability())
160        } else if children.len() == 2 {
161            let validity = children.get(1, &Validity::DTYPE, len)?;
162            Validity::Array(validity)
163        } else {
164            vortex_bail!("Expected 1 or 2 children, got {}", children.len());
165        };
166
167        let offsets = children.get(
168            0,
169            &DType::Primitive(metadata.offsets_ptype(), Nullability::NonNullable),
170            len + 1,
171        )?;
172
173        if buffers.len() != 1 {
174            vortex_bail!("Expected 1 buffer, got {}", buffers.len());
175        }
176        let bytes = buffers[0].clone().try_to_host_sync()?;
177
178        VarBinArray::try_new(offsets, bytes, dtype.clone(), validity)
179    }
180
181    fn with_children(array: &mut Self::Array, children: Vec<ArrayRef>) -> VortexResult<()> {
182        match children.len() {
183            1 => {
184                let [offsets]: [ArrayRef; 1] = children
185                    .try_into()
186                    .map_err(|_| vortex_err!("Failed to convert children to array"))?;
187                array.offsets = offsets;
188            }
189            2 => {
190                let [offsets, validity]: [ArrayRef; 2] = children
191                    .try_into()
192                    .map_err(|_| vortex_err!("Failed to convert children to array"))?;
193                array.offsets = offsets;
194                array.validity = Validity::Array(validity);
195            }
196            _ => vortex_bail!(
197                "VarBinArray expects 1 or 2 children (offsets, validity?), got {}",
198                children.len()
199            ),
200        }
201        Ok(())
202    }
203
204    fn reduce_parent(
205        array: &Self::Array,
206        parent: &ArrayRef,
207        child_idx: usize,
208    ) -> VortexResult<Option<ArrayRef>> {
209        PARENT_RULES.evaluate(array, parent, child_idx)
210    }
211
212    fn execute_parent(
213        array: &Self::Array,
214        parent: &ArrayRef,
215        child_idx: usize,
216        ctx: &mut ExecutionCtx,
217    ) -> VortexResult<Option<ArrayRef>> {
218        PARENT_KERNELS.execute(array, parent, child_idx, ctx)
219    }
220
221    fn execute(array: &Self::Array, ctx: &mut ExecutionCtx) -> VortexResult<ArrayRef> {
222        Ok(varbin_to_canonical(array, ctx)?.into_array())
223    }
224}
225
226#[derive(Debug)]
227pub struct VarBinVTable;
228
229impl VarBinVTable {
230    pub const ID: ArrayId = ArrayId::new_ref("vortex.varbin");
231}