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