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
4//! The [`Decimal`] vtable and the plugin that owns its wire form.
5//!
6//! The vtable does not serialize or deserialize. [`DecimalPlugin`] reads and writes the
7//! `vortex.decimal` wire form, including legacy nodes.
8
9mod kernel;
10mod operations;
11
12mod plugin;
13pub use plugin::DecimalPlugin;
14
15mod validity;
16
17use std::hash::Hash;
18use std::hash::Hasher;
19
20use vortex_error::VortexResult;
21use vortex_error::vortex_bail;
22use vortex_error::vortex_ensure_eq;
23use vortex_session::VortexSession;
24use vortex_session::registry::CachedId;
25
26use crate::ArrayParts;
27use crate::ArrayRef;
28use crate::EqMode;
29use crate::ExecutionCtx;
30use crate::ExecutionResult;
31use crate::array::Array;
32use crate::array::ArrayId;
33use crate::array::ArrayView;
34use crate::array::VTable;
35use crate::arrays::decimal::DecimalData;
36use crate::arrays::decimal::array::DecimalSlots;
37use crate::arrays::decimal::compute::rules::RULES;
38use crate::arrays::fixed_width::vtable as fixed_width;
39use crate::buffer::BufferHandle;
40use crate::builders::ArrayBuilder;
41use crate::builders::DecimalBuilder;
42use crate::dtype::DType;
43use crate::hash::ArrayEq;
44use crate::hash::ArrayHash;
45use crate::serde::ArrayChildren;
46
47/// A [`Decimal`]-encoded Vortex array.
48pub type DecimalArray = Array<Decimal>;
49
50pub(crate) fn initialize(session: &VortexSession) {
51    kernel::initialize(session);
52}
53
54impl ArrayHash for DecimalData {
55    fn array_hash<H: Hasher>(&self, state: &mut H, accuracy: EqMode) {
56        self.values.array_hash(state, accuracy);
57        std::mem::discriminant(&self.values_type).hash(state);
58    }
59}
60
61impl ArrayEq for DecimalData {
62    fn array_eq(&self, other: &Self, accuracy: EqMode) -> bool {
63        self.values.array_eq(&other.values, accuracy) && self.values_type == other.values_type
64    }
65}
66
67impl VTable for Decimal {
68    type TypedArrayData = DecimalData;
69
70    type OperationsVTable = Self;
71    type ValidityVTable = Self;
72
73    fn id(&self) -> ArrayId {
74        static ID: CachedId = CachedId::new("vortex.decimal");
75        *ID
76    }
77
78    fn nbuffers(_array: ArrayView<'_, Self>) -> usize {
79        1
80    }
81
82    fn buffer(array: ArrayView<'_, Self>, idx: usize) -> BufferHandle {
83        fixed_width::buffer("DecimalArray", &array.values, idx)
84    }
85
86    fn buffer_name(_array: ArrayView<'_, Self>, idx: usize) -> Option<String> {
87        fixed_width::buffer_name(idx)
88    }
89
90    fn with_buffers(
91        &self,
92        array: ArrayView<'_, Self>,
93        buffers: &[BufferHandle],
94    ) -> VortexResult<ArrayParts<Self>> {
95        let mut data = array.data().clone();
96        data.values = fixed_width::single_buffer(buffers)?;
97        Ok(ArrayParts::new(
98            self.clone(),
99            array.dtype().clone(),
100            array.len(),
101            data,
102            array.slots().iter().cloned().collect(),
103        ))
104    }
105
106    fn serialize(
107        _array: ArrayView<'_, Self>,
108        _session: &VortexSession,
109    ) -> VortexResult<Option<Vec<u8>>> {
110        Ok(None)
111    }
112
113    fn validate(
114        &self,
115        data: &DecimalData,
116        dtype: &DType,
117        len: usize,
118        slots: &[Option<ArrayRef>],
119    ) -> VortexResult<()> {
120        let DType::Decimal(_, nullability) = dtype else {
121            vortex_bail!("Expected decimal dtype, got {dtype:?}");
122        };
123        vortex_ensure_eq!(
124            data.len(),
125            len,
126            "DecimalArray length does not match outer length",
127        );
128        let validity =
129            crate::array::child_to_validity(slots[DecimalSlots::VALIDITY].as_ref(), *nullability);
130        if let Some(validity_len) = validity.maybe_len() {
131            vortex_ensure_eq!(
132                validity_len,
133                len,
134                "DecimalArray validity len does not match outer length",
135            );
136        }
137
138        Ok(())
139    }
140
141    fn deserialize(
142        &self,
143        _dtype: &DType,
144        _len: usize,
145        _metadata: &[u8],
146        _buffers: &[BufferHandle],
147        _children: &dyn ArrayChildren,
148        _session: &VortexSession,
149    ) -> VortexResult<ArrayParts<Self>> {
150        vortex_bail!("Decimal deserialization requires DecimalPlugin")
151    }
152
153    fn slot_name(_array: ArrayView<'_, Self>, idx: usize) -> String {
154        DecimalSlots::NAMES[idx].to_string()
155    }
156
157    fn execute(array: Array<Self>, _ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
158        Ok(ExecutionResult::done(array))
159    }
160
161    fn append_to_builder(
162        array: ArrayView<'_, Self>,
163        builder: &mut dyn ArrayBuilder,
164        ctx: &mut ExecutionCtx,
165    ) -> VortexResult<()> {
166        let Some(builder) = builder.as_any_mut().downcast_mut::<DecimalBuilder>() else {
167            vortex_bail!("append_to_builder for Decimal requires a DecimalBuilder");
168        };
169        builder.append_decimal_array(&array.into_owned(), ctx)
170    }
171
172    fn reduce_parent(
173        array: ArrayView<'_, Self>,
174        parent: &ArrayRef,
175        child_idx: usize,
176    ) -> VortexResult<Option<ArrayRef>> {
177        RULES.evaluate(array, parent, child_idx)
178    }
179}
180
181/// The vtable of [`DecimalArray`].
182///
183/// This vtable does not serialize or deserialize. A session **must** register [`DecimalPlugin`]
184/// in its place to read or write decimal arrays.
185#[derive(Clone, Debug)]
186pub struct Decimal;