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