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_dtype::DType;
7use vortex_dtype::DecimalType;
8use vortex_dtype::NativeDecimalType;
9use vortex_dtype::match_each_decimal_value_type;
10use vortex_error::VortexExpect;
11use vortex_error::VortexResult;
12use vortex_error::vortex_bail;
13use vortex_error::vortex_ensure;
14use vortex_session::VortexSession;
15
16use crate::ArrayRef;
17use crate::DeserializeMetadata;
18use crate::ExecutionCtx;
19use crate::ProstMetadata;
20use crate::SerializeMetadata;
21use crate::arrays::DecimalArray;
22use crate::buffer::BufferHandle;
23use crate::serde::ArrayChildren;
24use crate::validity::Validity;
25use crate::vtable;
26use crate::vtable::VTable;
27use crate::vtable::ValidityVTableFromValidityHelper;
28
29mod array;
30mod kernel;
31mod operations;
32mod validity;
33mod visitor;
34
35use crate::arrays::decimal::compute::rules::RULES;
36use crate::vtable::ArrayId;
37
38vtable!(Decimal);
39
40// The type of the values can be determined by looking at the type info...right?
41#[derive(prost::Message)]
42pub struct DecimalMetadata {
43    #[prost(enumeration = "DecimalType", tag = "1")]
44    pub(super) values_type: i32,
45}
46
47impl VTable for DecimalVTable {
48    type Array = DecimalArray;
49
50    type Metadata = ProstMetadata<DecimalMetadata>;
51
52    type ArrayVTable = Self;
53    type OperationsVTable = Self;
54    type ValidityVTable = ValidityVTableFromValidityHelper;
55    type VisitorVTable = Self;
56
57    fn id(_array: &Self::Array) -> ArrayId {
58        Self::ID
59    }
60
61    fn metadata(array: &DecimalArray) -> VortexResult<Self::Metadata> {
62        Ok(ProstMetadata(DecimalMetadata {
63            values_type: array.values_type() as i32,
64        }))
65    }
66
67    fn serialize(metadata: Self::Metadata) -> VortexResult<Option<Vec<u8>>> {
68        Ok(Some(metadata.serialize()))
69    }
70
71    fn deserialize(
72        bytes: &[u8],
73        _dtype: &DType,
74        _len: usize,
75        _buffers: &[BufferHandle],
76        _session: &VortexSession,
77    ) -> VortexResult<Self::Metadata> {
78        let metadata = ProstMetadata::<DecimalMetadata>::deserialize(bytes)?;
79        Ok(ProstMetadata(metadata))
80    }
81
82    fn build(
83        dtype: &DType,
84        len: usize,
85        metadata: &Self::Metadata,
86        buffers: &[BufferHandle],
87        children: &dyn ArrayChildren,
88    ) -> VortexResult<DecimalArray> {
89        if buffers.len() != 1 {
90            vortex_bail!("Expected 1 buffer, got {}", buffers.len());
91        }
92        let values = buffers[0].clone();
93
94        let validity = if children.is_empty() {
95            Validity::from(dtype.nullability())
96        } else if children.len() == 1 {
97            let validity = children.get(0, &Validity::DTYPE, len)?;
98            Validity::Array(validity)
99        } else {
100            vortex_bail!("Expected 0 or 1 child, got {}", children.len());
101        };
102
103        let Some(decimal_dtype) = dtype.as_decimal_opt() else {
104            vortex_bail!("Expected Decimal dtype, got {:?}", dtype)
105        };
106
107        match_each_decimal_value_type!(metadata.values_type(), |D| {
108            // Check and reinterpret-cast the buffer
109            vortex_ensure!(
110                values.is_aligned_to(Alignment::of::<D>()),
111                "DecimalArray buffer not aligned for values type {:?}",
112                D::DECIMAL_TYPE
113            );
114            DecimalArray::try_new_handle(values, metadata.values_type(), *decimal_dtype, validity)
115        })
116    }
117
118    fn with_children(array: &mut Self::Array, children: Vec<ArrayRef>) -> VortexResult<()> {
119        vortex_ensure!(
120            children.len() <= 1,
121            "DecimalArray expects 0 or 1 child (validity), got {}",
122            children.len()
123        );
124
125        if children.is_empty() {
126            array.validity = Validity::from(array.dtype.nullability());
127        } else {
128            array.validity = Validity::Array(
129                children
130                    .into_iter()
131                    .next()
132                    .vortex_expect("children length already validated"),
133            );
134        }
135        Ok(())
136    }
137
138    fn execute(array: &Self::Array, _ctx: &mut ExecutionCtx) -> VortexResult<ArrayRef> {
139        Ok(array.to_array())
140    }
141
142    fn reduce_parent(
143        array: &Self::Array,
144        parent: &ArrayRef,
145        child_idx: usize,
146    ) -> VortexResult<Option<ArrayRef>> {
147        RULES.evaluate(array, parent, child_idx)
148    }
149
150    fn execute_parent(
151        array: &Self::Array,
152        parent: &ArrayRef,
153        child_idx: usize,
154        ctx: &mut ExecutionCtx,
155    ) -> VortexResult<Option<ArrayRef>> {
156        PARENT_KERNELS.execute(array, parent, child_idx, ctx)
157    }
158}
159
160#[derive(Debug)]
161pub struct DecimalVTable;
162
163impl DecimalVTable {
164    pub const ID: ArrayId = ArrayId::new_ref("vortex.decimal");
165}
166
167#[cfg(test)]
168mod tests {
169    use vortex_buffer::ByteBufferMut;
170    use vortex_buffer::buffer;
171    use vortex_dtype::DecimalDType;
172
173    use crate::ArrayContext;
174    use crate::IntoArray;
175    use crate::LEGACY_SESSION;
176    use crate::arrays::DecimalArray;
177    use crate::arrays::DecimalVTable;
178    use crate::serde::ArrayParts;
179    use crate::serde::SerializeOptions;
180    use crate::validity::Validity;
181
182    #[test]
183    fn test_array_serde() {
184        let array = DecimalArray::new(
185            buffer![100i128, 200i128, 300i128, 400i128, 500i128],
186            DecimalDType::new(10, 2),
187            Validity::NonNullable,
188        );
189        let dtype = array.dtype().clone();
190
191        let ctx = ArrayContext::empty();
192        let out = array
193            .into_array()
194            .serialize(&ctx, &SerializeOptions::default())
195            .unwrap();
196        // Concat into a single buffer
197        let mut concat = ByteBufferMut::empty();
198        for buf in out {
199            concat.extend_from_slice(buf.as_ref());
200        }
201
202        let concat = concat.freeze();
203
204        let parts = ArrayParts::try_from(concat).unwrap();
205        let decoded = parts.decode(&dtype, 5, &ctx, &LEGACY_SESSION).unwrap();
206        assert!(decoded.is::<DecimalVTable>());
207    }
208}