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