Skip to main content

vortex_array/arrays/decimal/vtable/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use kernel::PARENT_KERNELS;
5use vortex_buffer::Alignment;
6use vortex_error::VortexExpect;
7use vortex_error::VortexResult;
8use vortex_error::vortex_bail;
9use vortex_error::vortex_ensure;
10use vortex_error::vortex_panic;
11use vortex_session::VortexSession;
12
13use crate::ArrayRef;
14use crate::DeserializeMetadata;
15use crate::ExecutionCtx;
16use crate::ProstMetadata;
17use crate::SerializeMetadata;
18use crate::arrays::DecimalArray;
19use crate::buffer::BufferHandle;
20use crate::dtype::DType;
21use crate::dtype::DecimalType;
22use crate::dtype::NativeDecimalType;
23use crate::match_each_decimal_value_type;
24use crate::serde::ArrayChildren;
25use crate::validity::Validity;
26use crate::vtable;
27use crate::vtable::VTable;
28use crate::vtable::ValidityVTableFromValidityHelper;
29use crate::vtable::validity_nchildren;
30use crate::vtable::validity_to_child;
31mod kernel;
32mod operations;
33mod validity;
34
35use std::hash::Hash;
36
37use crate::Precision;
38use crate::arrays::decimal::compute::rules::RULES;
39use crate::hash::ArrayEq;
40use crate::hash::ArrayHash;
41use crate::stats::StatsSetRef;
42use crate::vtable::ArrayId;
43vtable!(Decimal);
44
45// The type of the values can be determined by looking at the type info...right?
46#[derive(prost::Message)]
47pub struct DecimalMetadata {
48    #[prost(enumeration = "DecimalType", tag = "1")]
49    pub(super) values_type: i32,
50}
51
52impl VTable for DecimalVTable {
53    type Array = DecimalArray;
54
55    type Metadata = ProstMetadata<DecimalMetadata>;
56    type OperationsVTable = Self;
57    type ValidityVTable = ValidityVTableFromValidityHelper;
58
59    fn id(_array: &Self::Array) -> ArrayId {
60        Self::ID
61    }
62
63    fn len(array: &DecimalArray) -> usize {
64        let divisor = match array.values_type {
65            DecimalType::I8 => 1,
66            DecimalType::I16 => 2,
67            DecimalType::I32 => 4,
68            DecimalType::I64 => 8,
69            DecimalType::I128 => 16,
70            DecimalType::I256 => 32,
71        };
72        array.values.len() / divisor
73    }
74
75    fn dtype(array: &DecimalArray) -> &DType {
76        &array.dtype
77    }
78
79    fn stats(array: &DecimalArray) -> StatsSetRef<'_> {
80        array.stats_set.to_ref(array.as_ref())
81    }
82
83    fn array_hash<H: std::hash::Hasher>(array: &DecimalArray, state: &mut H, precision: Precision) {
84        array.dtype.hash(state);
85        array.values.array_hash(state, precision);
86        std::mem::discriminant(&array.values_type).hash(state);
87        array.validity.array_hash(state, precision);
88    }
89
90    fn array_eq(array: &DecimalArray, other: &DecimalArray, precision: Precision) -> bool {
91        array.dtype == other.dtype
92            && array.values.array_eq(&other.values, precision)
93            && array.values_type == other.values_type
94            && array.validity.array_eq(&other.validity, precision)
95    }
96
97    fn nbuffers(_array: &DecimalArray) -> usize {
98        1
99    }
100
101    fn buffer(array: &DecimalArray, idx: usize) -> BufferHandle {
102        match idx {
103            0 => array.values.clone(),
104            _ => vortex_panic!("DecimalArray buffer index {idx} out of bounds"),
105        }
106    }
107
108    fn buffer_name(_array: &DecimalArray, idx: usize) -> Option<String> {
109        match idx {
110            0 => Some("values".to_string()),
111            _ => None,
112        }
113    }
114
115    fn nchildren(array: &DecimalArray) -> usize {
116        validity_nchildren(&array.validity)
117    }
118
119    fn child(array: &DecimalArray, idx: usize) -> ArrayRef {
120        match idx {
121            0 => validity_to_child(&array.validity, array.len())
122                .vortex_expect("DecimalArray child index out of bounds"),
123            _ => vortex_panic!("DecimalArray child index {idx} out of bounds"),
124        }
125    }
126
127    fn child_name(_array: &DecimalArray, _idx: usize) -> String {
128        "validity".to_string()
129    }
130
131    fn metadata(array: &DecimalArray) -> VortexResult<Self::Metadata> {
132        Ok(ProstMetadata(DecimalMetadata {
133            values_type: array.values_type() as i32,
134        }))
135    }
136
137    fn serialize(metadata: Self::Metadata) -> VortexResult<Option<Vec<u8>>> {
138        Ok(Some(metadata.serialize()))
139    }
140
141    fn deserialize(
142        bytes: &[u8],
143        _dtype: &DType,
144        _len: usize,
145        _buffers: &[BufferHandle],
146        _session: &VortexSession,
147    ) -> VortexResult<Self::Metadata> {
148        let metadata = ProstMetadata::<DecimalMetadata>::deserialize(bytes)?;
149        Ok(ProstMetadata(metadata))
150    }
151
152    fn build(
153        dtype: &DType,
154        len: usize,
155        metadata: &Self::Metadata,
156        buffers: &[BufferHandle],
157        children: &dyn ArrayChildren,
158    ) -> VortexResult<DecimalArray> {
159        if buffers.len() != 1 {
160            vortex_bail!("Expected 1 buffer, got {}", buffers.len());
161        }
162        let values = buffers[0].clone();
163
164        let validity = if children.is_empty() {
165            Validity::from(dtype.nullability())
166        } else if children.len() == 1 {
167            let validity = children.get(0, &Validity::DTYPE, len)?;
168            Validity::Array(validity)
169        } else {
170            vortex_bail!("Expected 0 or 1 child, got {}", children.len());
171        };
172
173        let Some(decimal_dtype) = dtype.as_decimal_opt() else {
174            vortex_bail!("Expected Decimal dtype, got {:?}", dtype)
175        };
176
177        match_each_decimal_value_type!(metadata.values_type(), |D| {
178            // Check and reinterpret-cast the buffer
179            vortex_ensure!(
180                values.is_aligned_to(Alignment::of::<D>()),
181                "DecimalArray buffer not aligned for values type {:?}",
182                D::DECIMAL_TYPE
183            );
184            DecimalArray::try_new_handle(values, metadata.values_type(), *decimal_dtype, validity)
185        })
186    }
187
188    fn with_children(array: &mut Self::Array, children: Vec<ArrayRef>) -> VortexResult<()> {
189        vortex_ensure!(
190            children.len() <= 1,
191            "DecimalArray expects 0 or 1 child (validity), got {}",
192            children.len()
193        );
194
195        if children.is_empty() {
196            array.validity = Validity::from(array.dtype.nullability());
197        } else {
198            array.validity = Validity::Array(
199                children
200                    .into_iter()
201                    .next()
202                    .vortex_expect("children length already validated"),
203            );
204        }
205        Ok(())
206    }
207
208    fn execute(array: &Self::Array, _ctx: &mut ExecutionCtx) -> VortexResult<ArrayRef> {
209        Ok(array.to_array())
210    }
211
212    fn reduce_parent(
213        array: &Self::Array,
214        parent: &ArrayRef,
215        child_idx: usize,
216    ) -> VortexResult<Option<ArrayRef>> {
217        RULES.evaluate(array, parent, child_idx)
218    }
219
220    fn execute_parent(
221        array: &Self::Array,
222        parent: &ArrayRef,
223        child_idx: usize,
224        ctx: &mut ExecutionCtx,
225    ) -> VortexResult<Option<ArrayRef>> {
226        PARENT_KERNELS.execute(array, parent, child_idx, ctx)
227    }
228}
229
230#[derive(Debug)]
231pub struct DecimalVTable;
232
233impl DecimalVTable {
234    pub const ID: ArrayId = ArrayId::new_ref("vortex.decimal");
235}
236
237#[cfg(test)]
238mod tests {
239    use vortex_buffer::ByteBufferMut;
240    use vortex_buffer::buffer;
241
242    use crate::ArrayContext;
243    use crate::IntoArray;
244    use crate::LEGACY_SESSION;
245    use crate::arrays::DecimalArray;
246    use crate::arrays::DecimalVTable;
247    use crate::dtype::DecimalDType;
248    use crate::serde::ArrayParts;
249    use crate::serde::SerializeOptions;
250    use crate::validity::Validity;
251
252    #[test]
253    fn test_array_serde() {
254        let array = DecimalArray::new(
255            buffer![100i128, 200i128, 300i128, 400i128, 500i128],
256            DecimalDType::new(10, 2),
257            Validity::NonNullable,
258        );
259        let dtype = array.dtype().clone();
260
261        let ctx = ArrayContext::empty();
262        let out = array
263            .into_array()
264            .serialize(&ctx, &SerializeOptions::default())
265            .unwrap();
266        // Concat into a single buffer
267        let mut concat = ByteBufferMut::empty();
268        for buf in out {
269            concat.extend_from_slice(buf.as_ref());
270        }
271
272        let concat = concat.freeze();
273
274        let parts = ArrayParts::try_from(concat).unwrap();
275        let decoded = parts.decode(&dtype, 5, &ctx, &LEGACY_SESSION).unwrap();
276        assert!(decoded.is::<DecimalVTable>());
277    }
278}