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_panic;
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::buffer::BufferHandle;
23use crate::builders::ArrayBuilder;
24use crate::builders::DecimalBuilder;
25use crate::dtype::DType;
26use crate::dtype::DecimalType;
27use crate::dtype::NativeDecimalType;
28use crate::match_each_decimal_value_type;
29use crate::serde::ArrayChildren;
30use crate::validity::Validity;
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::SLOT_NAMES;
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        match idx {
89            0 => array.values.clone(),
90            _ => vortex_panic!("DecimalArray buffer index {idx} out of bounds"),
91        }
92    }
93
94    fn buffer_name(_array: ArrayView<'_, Self>, idx: usize) -> Option<String> {
95        match idx {
96            0 => Some("values".to_string()),
97            _ => None,
98        }
99    }
100
101    fn with_buffers(
102        &self,
103        array: ArrayView<'_, Self>,
104        buffers: &[BufferHandle],
105    ) -> VortexResult<ArrayParts<Self>> {
106        vortex_ensure!(
107            buffers.len() == 1,
108            "Expected 1 buffer, got {}",
109            buffers.len()
110        );
111        let mut data = array.data().clone();
112        data.values = buffers[0].clone();
113        Ok(
114            ArrayParts::new(self.clone(), array.dtype().clone(), array.len(), data)
115                .with_slots(array.slots().iter().cloned().collect()),
116        )
117    }
118
119    fn serialize(
120        array: ArrayView<'_, Self>,
121        _session: &VortexSession,
122    ) -> VortexResult<Option<Vec<u8>>> {
123        Ok(Some(
124            DecimalMetadata {
125                values_type: array.values_type() as i32,
126            }
127            .encode_to_vec(),
128        ))
129    }
130
131    fn validate(
132        &self,
133        data: &DecimalData,
134        dtype: &DType,
135        len: usize,
136        slots: &[Option<ArrayRef>],
137    ) -> VortexResult<()> {
138        let DType::Decimal(_, nullability) = dtype else {
139            vortex_bail!("Expected decimal dtype, got {dtype:?}");
140        };
141        vortex_ensure!(
142            data.len() == len,
143            InvalidArgument:
144            "DecimalArray length {} does not match outer length {}",
145            data.len(),
146            len
147        );
148        let validity = crate::array::child_to_validity(slots[0].as_ref(), *nullability);
149        if let Some(validity_len) = validity.maybe_len() {
150            vortex_ensure!(
151                validity_len == len,
152                InvalidArgument:
153                "DecimalArray validity len {} does not match outer length {}",
154                validity_len,
155                len
156            );
157        }
158
159        Ok(())
160    }
161
162    fn deserialize(
163        &self,
164        dtype: &DType,
165        len: usize,
166        metadata: &[u8],
167
168        buffers: &[BufferHandle],
169        children: &dyn ArrayChildren,
170        _session: &VortexSession,
171    ) -> VortexResult<ArrayParts<Self>> {
172        let metadata = DecimalMetadata::decode(metadata)?;
173        if buffers.len() != 1 {
174            vortex_bail!("Expected 1 buffer, got {}", buffers.len());
175        }
176        let values = buffers[0].clone();
177
178        let validity = if children.is_empty() {
179            Validity::from(dtype.nullability())
180        } else if children.len() == 1 {
181            let validity = children.get(0, &Validity::DTYPE, len)?;
182            Validity::Array(validity)
183        } else {
184            vortex_bail!("Expected 0 or 1 child, got {}", children.len());
185        };
186
187        let Some(decimal_dtype) = dtype.as_decimal_opt() else {
188            vortex_bail!("Expected Decimal dtype, got {:?}", dtype)
189        };
190
191        let slots = DecimalData::make_slots(&validity, len);
192        let data = match_each_decimal_value_type!(metadata.values_type(), |D| {
193            // Check and reinterpret-cast the buffer
194            vortex_ensure!(
195                values.is_aligned_to(Alignment::of::<D>()),
196                "DecimalArray buffer not aligned for values type {:?}",
197                D::DECIMAL_TYPE
198            );
199            DecimalData::try_new_handle(values, metadata.values_type(), *decimal_dtype)
200        })?;
201        Ok(ArrayParts::new(self.clone(), dtype.clone(), len, data).with_slots(slots))
202    }
203
204    fn slot_name(_array: ArrayView<'_, Self>, idx: usize) -> String {
205        SLOT_NAMES[idx].to_string()
206    }
207
208    fn execute(array: Array<Self>, _ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
209        Ok(ExecutionResult::done(array))
210    }
211
212    fn append_to_builder(
213        array: ArrayView<'_, Self>,
214        builder: &mut dyn ArrayBuilder,
215        ctx: &mut ExecutionCtx,
216    ) -> VortexResult<()> {
217        let Some(builder) = builder.as_any_mut().downcast_mut::<DecimalBuilder>() else {
218            vortex_bail!("append_to_builder for Decimal requires a DecimalBuilder");
219        };
220        builder.append_decimal_array(&array.into_owned(), ctx)
221    }
222
223    fn reduce_parent(
224        array: ArrayView<'_, Self>,
225        parent: &ArrayRef,
226        child_idx: usize,
227    ) -> VortexResult<Option<ArrayRef>> {
228        RULES.evaluate(array, parent, child_idx)
229    }
230}
231
232#[derive(Clone, Debug)]
233pub struct Decimal;
234
235#[cfg(test)]
236mod tests {
237    use vortex_buffer::ByteBufferMut;
238    use vortex_buffer::buffer;
239    use vortex_session::registry::ReadContext;
240
241    use crate::ArrayContext;
242    use crate::IntoArray;
243    use crate::VortexSessionExecute;
244    use crate::array_session;
245    use crate::arrays::Decimal;
246    use crate::arrays::DecimalArray;
247    use crate::assert_arrays_eq;
248    use crate::dtype::DecimalDType;
249    use crate::serde::SerializeOptions;
250    use crate::serde::SerializedArray;
251    use crate::validity::Validity;
252
253    #[test]
254    fn test_array_serde() {
255        let session = array_session();
256        let array = DecimalArray::new(
257            buffer![100i128, 200i128, 300i128, 400i128, 500i128],
258            DecimalDType::new(10, 2),
259            Validity::NonNullable,
260        );
261        let dtype = array.dtype().clone();
262
263        let array_ctx = ArrayContext::empty();
264        let out = array
265            .into_array()
266            .serialize(&array_ctx, &session, &SerializeOptions::default())
267            .unwrap();
268        // Concat into a single buffer
269        let mut concat = ByteBufferMut::empty();
270        for buf in out {
271            concat.extend_from_slice(buf.as_ref());
272        }
273
274        let concat = concat.freeze();
275
276        let parts = SerializedArray::try_from(concat).unwrap();
277        let decoded = parts
278            .decode(&dtype, 5, &ReadContext::new(array_ctx.to_ids()), &session)
279            .unwrap();
280        assert!(decoded.is::<Decimal>());
281    }
282
283    #[test]
284    fn test_nullable_decimal_serde_roundtrip() {
285        let session = array_session();
286        let mut ctx = session.create_execution_ctx();
287        let array = DecimalArray::new(
288            buffer![1234567i32, 0i32, -9999999i32],
289            DecimalDType::new(7, 3),
290            Validity::from_iter([true, false, true]),
291        );
292        let dtype = array.dtype().clone();
293        let len = array.len();
294
295        let array_ctx = ArrayContext::empty();
296        let out = array
297            .clone()
298            .into_array()
299            .serialize(&array_ctx, &session, &SerializeOptions::default())
300            .unwrap();
301        let mut concat = ByteBufferMut::empty();
302        for buf in out {
303            concat.extend_from_slice(buf.as_ref());
304        }
305
306        let parts = SerializedArray::try_from(concat.freeze()).unwrap();
307        let decoded = parts
308            .decode(&dtype, len, &ReadContext::new(array_ctx.to_ids()), &session)
309            .unwrap();
310
311        assert_arrays_eq!(decoded, array, &mut ctx);
312    }
313}