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