Skip to main content

vortex_array/arrays/decimal/
array.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::fmt::Display;
5use std::fmt::Formatter;
6
7use smallvec::smallvec;
8use vortex_buffer::Alignment;
9use vortex_buffer::BitBufferMut;
10use vortex_buffer::Buffer;
11use vortex_error::VortexExpect;
12use vortex_error::VortexResult;
13use vortex_error::vortex_ensure;
14use vortex_error::vortex_ensure_eq;
15use vortex_error::vortex_panic;
16
17use crate::ArrayRef;
18use crate::ArraySlots;
19use crate::ExecutionCtx;
20use crate::IntoArray;
21use crate::array::Array;
22use crate::array::ArrayParts;
23use crate::array::TypedArrayRef;
24use crate::array::child_to_validity;
25use crate::array::validity_to_child;
26use crate::array_slots;
27use crate::arrays::Decimal;
28use crate::arrays::DecimalArray;
29use crate::arrays::PrimitiveArray;
30use crate::arrays::decimal::cast_value_in_precision;
31use crate::arrays::decimal::check_precision;
32use crate::arrays::decimal::precision_bounds;
33use crate::arrays::primitive::PrimitiveArrayExt;
34use crate::buffer::BufferHandle;
35use crate::dtype::DType;
36use crate::dtype::DecimalDType;
37use crate::dtype::DecimalType;
38use crate::dtype::IntegerPType;
39use crate::dtype::NativeDecimalType;
40use crate::dtype::Nullability;
41use crate::match_each_decimal_value_type;
42use crate::match_each_unsigned_integer_ptype;
43use crate::patches::Patches;
44use crate::validity::Validity;
45
46#[array_slots(Decimal)]
47pub struct DecimalSlots {
48    /// The validity bitmap indicating which elements are non-null.
49    #[slot(0)]
50    pub validity_child: Option<ArrayRef>,
51}
52
53/// The decimal dtype and values buffer of a [`DecimalArray`].
54///
55/// A valid row stores a signed integer whose logical value is `integer / 10^scale`. The
56/// precision determines the integer type through [`DecimalDType::canonical_values_type`].
57///
58/// | Precision | Integer type |
59/// |-----------|--------------|
60/// | 1 to 2    | `i8`         |
61/// | 3 to 4    | `i16`        |
62/// | 5 to 9    | `i32`        |
63/// | 10 to 18  | `i64`        |
64/// | 19 to 38  | `i128`       |
65/// | 39 to 76  | `i256`       |
66///
67/// The `vortex.decimal` wire format records the stored width separately. The reader uses
68/// [`DecimalDataParts`] to convert a different width to a canonical leaf or to a
69/// [`Widen`](crate::arrays::Widen) over a lower-precision leaf.
70///
71/// # Examples
72///
73/// ```
74/// use vortex_array::VortexSessionExecute;
75/// use vortex_array::arrays::DecimalArray;
76/// use vortex_array::dtype::DecimalDType;
77/// use vortex_array::validity::Validity;
78/// use vortex_buffer::buffer;
79/// use vortex_session::VortexSession;
80///
81/// let decimal_dtype = DecimalDType::new(5, 2);
82/// let values = buffer![12345i32, 67890i32, -12300i32];
83/// let mut ctx = VortexSession::empty().create_execution_ctx();
84/// let array = DecimalArray::try_new(values, decimal_dtype, Validity::NonNullable, &mut ctx)?;
85///
86/// assert_eq!(array.precision(), 5);
87/// assert_eq!(array.scale(), 2);
88/// assert_eq!(array.len(), 3);
89/// # Ok::<(), vortex_error::VortexError>(())
90/// ```
91#[derive(Clone, Debug)]
92pub struct DecimalData {
93    pub(super) decimal_dtype: DecimalDType,
94    pub(super) values: BufferHandle,
95}
96
97impl Display for DecimalData {
98    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
99        write!(
100            f,
101            "decimal_dtype: {}, values_type: {}",
102            self.decimal_dtype,
103            self.values_type()
104        )
105    }
106}
107
108/// Decimal storage and validity, as returned by [`DecimalArray::into_data_parts`].
109pub struct DecimalDataParts {
110    /// The precision and scale of the values.
111    pub decimal_dtype: DecimalDType,
112    /// Unscaled integers of type `values_type` in host or device memory.
113    pub values: BufferHandle,
114    /// Actual storage type, retained to interpret input before canonical conversion.
115    ///
116    /// Legacy `vortex.decimal` nodes can use a different width from
117    /// [`DecimalDType::canonical_values_type`]. Comparing the widths identifies noncanonical
118    /// storage, not the age of the data. Current [`WidenPlugin`] writes store noncanonical widths
119    /// too.
120    ///
121    /// [`WidenPlugin`]: crate::arrays::widen::WidenPlugin
122    pub values_type: DecimalType,
123    /// The validity of the values, which also gives the nullability of the array.
124    pub validity: Validity,
125}
126
127pub trait DecimalArrayExt: TypedArrayRef<Decimal> {
128    fn decimal_dtype(&self) -> DecimalDType {
129        match self.dtype() {
130            DType::Decimal(decimal_dtype, _) => *decimal_dtype,
131            _ => unreachable!("DecimalArrayExt requires a decimal dtype"),
132        }
133    }
134
135    fn nullability(&self) -> Nullability {
136        match self.dtype() {
137            DType::Decimal(_, nullability) => *nullability,
138            _ => unreachable!("DecimalArrayExt requires a decimal dtype"),
139        }
140    }
141
142    fn validity(&self) -> Validity {
143        child_to_validity(self.validity_child(), self.nullability())
144    }
145
146    fn values_type(&self) -> DecimalType {
147        DecimalData::values_type(self)
148    }
149
150    fn precision(&self) -> u8 {
151        self.decimal_dtype().precision()
152    }
153
154    fn scale(&self) -> i8 {
155        self.decimal_dtype().scale()
156    }
157
158    fn buffer_handle(&self) -> &BufferHandle {
159        &self.values
160    }
161
162    fn buffer<T: NativeDecimalType>(&self) -> Buffer<T> {
163        DecimalData::buffer::<T>(self)
164    }
165}
166impl<T: TypedArrayRef<Decimal>> DecimalArrayExt for T {}
167
168impl DecimalData {
169    /// Build the slots vector for this array.
170    fn make_slots(validity: &Validity, len: usize) -> ArraySlots {
171        smallvec![validity_to_child(validity, len)]
172    }
173
174    pub(super) fn validate_width(
175        values_type: DecimalType,
176        decimal_dtype: DecimalDType,
177    ) -> VortexResult<()> {
178        let canonical = decimal_dtype.canonical_values_type();
179        vortex_ensure_eq!(
180            values_type,
181            canonical,
182            "{decimal_dtype} requires {canonical} values, got {values_type}",
183        );
184
185        Ok(())
186    }
187
188    /// Validates the layout of a decimal values buffer.
189    ///
190    /// Checks byte length and alignment for `values_type`. Does not read values or check validity.
191    pub(crate) fn validate(buffer: &BufferHandle, values_type: DecimalType) -> VortexResult<()> {
192        let byte_width = values_type.byte_width();
193        vortex_ensure!(
194            buffer.len().is_multiple_of(byte_width),
195            "decimal buffer size {} is not divisible by element width {}",
196            buffer.len(),
197            byte_width,
198        );
199        match_each_decimal_value_type!(values_type, |D| {
200            vortex_ensure!(
201                buffer.is_aligned_to(Alignment::of::<D>()),
202                "decimal buffer alignment {:?} is invalid for values type {:?}",
203                buffer.alignment(),
204                D::DECIMAL_TYPE,
205            );
206            Ok::<(), vortex_error::VortexError>(())
207        })?;
208        Ok(())
209    }
210
211    /// Returns the length of this array.
212    pub fn len(&self) -> usize {
213        self.values.len() / self.values_type().byte_width()
214    }
215
216    /// Returns `true` if this array is empty.
217    pub fn is_empty(&self) -> bool {
218        self.len() == 0
219    }
220
221    /// Returns the host or device buffer that stores the unscaled integers.
222    pub fn buffer_handle(&self) -> &BufferHandle {
223        &self.values
224    }
225
226    pub fn buffer<T: NativeDecimalType>(&self) -> Buffer<T> {
227        if self.values_type() != T::DECIMAL_TYPE {
228            vortex_panic!(
229                "Cannot extract Buffer<{:?}> for DecimalArray with values_type {:?}",
230                T::DECIMAL_TYPE,
231                self.values_type(),
232            );
233        }
234        Buffer::<T>::from_byte_buffer(self.values.as_host().clone())
235    }
236
237    /// Returns the integer type of the values, which is the canonical type for the precision.
238    pub fn values_type(&self) -> DecimalType {
239        self.decimal_dtype.canonical_values_type()
240    }
241
242    /// Returns the decimal type information.
243    pub fn decimal_dtype(&self) -> DecimalDType {
244        self.decimal_dtype
245    }
246
247    pub fn precision(&self) -> u8 {
248        self.decimal_dtype.precision()
249    }
250
251    pub fn scale(&self) -> i8 {
252        self.decimal_dtype.scale()
253    }
254}
255
256impl Array<Decimal> {
257    pub fn into_data_parts(self) -> DecimalDataParts {
258        let validity = DecimalArrayExt::validity(&self);
259        let decimal_dtype = DecimalArrayExt::decimal_dtype(&self);
260        let data = self.into_data();
261        DecimalDataParts {
262            decimal_dtype,
263            values: data.values,
264            values_type: decimal_dtype.canonical_values_type(),
265            validity,
266        }
267    }
268}
269
270// Keep array construction in the non-generic handle constructors so downstream crates do not
271// compile the decimal vtable for each typed constructor.
272impl Array<Decimal> {
273    /// Creates a decimal array from a buffer of the canonical type for `decimal_dtype`.
274    ///
275    /// # Panics
276    ///
277    /// Panics if [`Self::try_new`] rejects the buffer or validity.
278    pub fn new<T: NativeDecimalType>(
279        buffer: Buffer<T>,
280        decimal_dtype: DecimalDType,
281        validity: Validity,
282        ctx: &mut ExecutionCtx,
283    ) -> Self {
284        Self::try_new(buffer, decimal_dtype, validity, ctx)
285            .vortex_expect("DecimalArray construction failed")
286    }
287
288    /// Creates a decimal array without checking its values or validity.
289    ///
290    /// A valid row outside the declared precision can yield incorrect results in later operations,
291    /// including comparisons that use the declared range.
292    ///
293    /// # Panics
294    ///
295    /// Panics if `T` differs from the canonical type for `decimal_dtype`.
296    ///
297    /// # Safety
298    ///
299    /// An array-backed validity must contain one non-nullable boolean per value.
300    pub unsafe fn new_unchecked<T: NativeDecimalType>(
301        buffer: Buffer<T>,
302        decimal_dtype: DecimalDType,
303        validity: Validity,
304    ) -> Self {
305        let values = BufferHandle::new_host(buffer.into_byte_buffer());
306
307        // SAFETY: The typed buffer supplies the required length and alignment. The caller
308        // guarantees the validity matches it.
309        unsafe { Self::new_unchecked_handle(values, T::DECIMAL_TYPE, decimal_dtype, validity) }
310    }
311
312    /// Creates a decimal array, reusing the typed buffer. When every validity buffer is on the
313    /// host, checks that each valid row fits the precision. Null slots may hold any value.
314    ///
315    /// # Errors
316    ///
317    /// Returns an error if [`Self::try_new_handle`] rejects the width, validity or values.
318    pub fn try_new<T: NativeDecimalType>(
319        buffer: Buffer<T>,
320        decimal_dtype: DecimalDType,
321        validity: Validity,
322        ctx: &mut ExecutionCtx,
323    ) -> VortexResult<Self> {
324        let values = BufferHandle::new_host(buffer.into_byte_buffer());
325        Self::try_new_handle(values, T::DECIMAL_TYPE, decimal_dtype, validity, ctx)
326    }
327
328    /// Collects values into a buffer of the canonical type for `decimal_dtype`.
329    ///
330    /// # Panics
331    ///
332    /// Panics if any value falls outside the declared precision.
333    #[expect(
334        clippy::same_name_method,
335        reason = "intentionally named from_iter like Iterator::from_iter"
336    )]
337    pub fn from_iter<T: NativeDecimalType, I: IntoIterator<Item = T>>(
338        iter: I,
339        decimal_dtype: DecimalDType,
340    ) -> Self {
341        let values_type = decimal_dtype.canonical_values_type();
342        let values = collect_decimal_values(iter.into_iter(), decimal_dtype);
343
344        // SAFETY: Collection produced an aligned buffer at the canonical width, checking each value.
345        unsafe {
346            Self::new_unchecked_handle(values, values_type, decimal_dtype, Validity::NonNullable)
347        }
348    }
349
350    /// Collects optional values into a nullable array of the canonical type for `decimal_dtype`.
351    /// Null slots contain zero.
352    ///
353    /// # Panics
354    ///
355    /// Panics if any present value falls outside the declared precision.
356    pub fn from_option_iter<T: NativeDecimalType, I: IntoIterator<Item = Option<T>>>(
357        iter: I,
358        decimal_dtype: DecimalDType,
359    ) -> Self {
360        let iter = iter.into_iter();
361        let mut validity = BitBufferMut::with_capacity(iter.size_hint().0);
362        let values_type = decimal_dtype.canonical_values_type();
363        let values = collect_decimal_values(
364            iter.map(|value| {
365                validity.append(value.is_some());
366                value.unwrap_or_default()
367            }),
368            decimal_dtype,
369        );
370        let validity = Validity::from(validity.freeze());
371
372        // SAFETY: Collection produced one validity bit for each value in the typed, canonical buffer.
373        unsafe { Self::new_unchecked_handle(values, values_type, decimal_dtype, validity) }
374    }
375
376    /// Creates a decimal array from a host or device buffer.
377    ///
378    /// # Panics
379    ///
380    /// Panics on any error from [`Self::try_new_handle`].
381    pub fn new_handle(
382        values: BufferHandle,
383        values_type: DecimalType,
384        decimal_dtype: DecimalDType,
385        validity: Validity,
386        ctx: &mut ExecutionCtx,
387    ) -> Self {
388        Self::try_new_handle(values, values_type, decimal_dtype, validity, ctx)
389            .vortex_expect("DecimalArray construction failed")
390    }
391
392    /// Creates a decimal array from a host or device buffer.
393    ///
394    /// If the values and every buffer of the validity are host-resident, checks each valid
395    /// value against the declared precision. Null slots may hold any value. If either input
396    /// contains a device buffer, checks only the layout and leaves the buffers in place.
397    ///
398    /// # Errors
399    ///
400    /// Returns an error if the layout is invalid, host validity execution fails, or a valid
401    /// host row exceeds the declared precision. The precision error names the first such row.
402    pub fn try_new_handle(
403        values: BufferHandle,
404        values_type: DecimalType,
405        decimal_dtype: DecimalDType,
406        validity: Validity,
407        ctx: &mut ExecutionCtx,
408    ) -> VortexResult<Self> {
409        let array =
410            Self::try_new_handle_from_trusted_values(values, values_type, decimal_dtype, validity)?;
411        let validity = array.validity()?;
412        if array.buffer_handle().is_on_host() && validity.as_array().is_none_or(ArrayRef::is_host) {
413            let mask = validity.execute_mask(array.len(), ctx)?;
414            match_each_decimal_value_type!(values_type, |T| {
415                check_precision(array.buffer::<T>().as_slice(), &mask, decimal_dtype)
416            })?;
417        }
418        Ok(array)
419    }
420
421    /// Reconstructs stored decimal values after checking their layout.
422    ///
423    /// Use this when reading a file that declares its precision, or when a kernel preserves
424    /// or has already checked the valid values. The values buffer and validity remain in place.
425    /// If the declared precision is wrong, later operations may return incorrect results or a
426    /// precision error. Use [`Self::try_new_handle`] to check host values.
427    ///
428    /// # Errors
429    ///
430    /// Returns an error if the width differs from the canonical width of `decimal_dtype`, the
431    /// buffer has invalid alignment or byte length, or the validity has the wrong length or dtype.
432    pub fn try_new_handle_from_trusted_values(
433        values: BufferHandle,
434        values_type: DecimalType,
435        decimal_dtype: DecimalDType,
436        validity: Validity,
437    ) -> VortexResult<Self> {
438        DecimalData::validate_width(values_type, decimal_dtype)?;
439        let parts = Self::decimal_parts(values, decimal_dtype, validity);
440
441        Array::try_from_parts(parts)
442    }
443
444    /// Creates a decimal array without checking its buffer layout, validity or values.
445    ///
446    /// Valid rows must fit the declared precision for correct results. Trusted file values
447    /// can exceed that precision without affecting memory safety.
448    ///
449    /// # Panics
450    ///
451    /// Panics if `values_type` differs from the canonical type for `decimal_dtype`.
452    ///
453    /// # Safety
454    ///
455    /// The buffer must be aligned for `values_type` and contain a whole number of values. An
456    /// array-backed validity must contain one non-nullable boolean per value. A malformed layout
457    /// can panic when the array is read.
458    pub unsafe fn new_unchecked_handle(
459        values: BufferHandle,
460        values_type: DecimalType,
461        decimal_dtype: DecimalDType,
462        validity: Validity,
463    ) -> Self {
464        DecimalData::validate_width(values_type, decimal_dtype)
465            .unwrap_or_else(|error| vortex_panic!(error));
466        let parts = Self::decimal_parts(values, decimal_dtype, validity);
467
468        // SAFETY: The width matches the dtype, and the caller guarantees the layout and validity.
469        unsafe { Array::from_parts_unchecked(parts) }
470    }
471
472    /// Assembles the parts of a leaf whose buffer holds values of the canonical type for
473    /// `decimal_dtype`. [`Array::try_from_parts`] checks the buffer layout and validity before
474    /// exposing the array. A caller that skips validation must establish them.
475    pub(super) fn decimal_parts(
476        values: BufferHandle,
477        decimal_dtype: DecimalDType,
478        validity: Validity,
479    ) -> ArrayParts<Decimal> {
480        let dtype = DType::Decimal(decimal_dtype, validity.nullability());
481        let len = values.len() / decimal_dtype.canonical_values_type().byte_width();
482        let slots = DecimalData::make_slots(&validity, len);
483        let data = DecimalData {
484            decimal_dtype,
485            values,
486        };
487
488        ArrayParts::new(Decimal, dtype, len, data, slots)
489    }
490
491    /// Replaces the values and validity at the patch indices.
492    pub fn patch(self, patches: &Patches, ctx: &mut ExecutionCtx) -> VortexResult<Self> {
493        vortex_ensure!(
494            self.dtype().eq_ignore_nullability(patches.values().dtype()),
495            "Decimal patch values have dtype {}, expected {}",
496            patches.values().dtype(),
497            self.dtype(),
498        );
499        let patch_indices = patches.indices().clone().execute::<PrimitiveArray>(ctx)?;
500        let patch_values = patches.values().clone().execute::<DecimalArray>(ctx)?;
501        let decimal_dtype = self.decimal_dtype();
502
503        let validity = self.validity()?.patch(
504            self.len(),
505            patches.offset(),
506            &patch_indices.clone().into_array(),
507            &patch_values.validity()?,
508            ctx,
509        )?;
510        // Patch indices are non-negative, so signed and unsigned indices can share a kernel.
511        let indices = patch_indices.reinterpret_cast(patch_indices.ptype().to_unsigned());
512        match_each_unsigned_integer_ptype!(indices.ptype(), |I| {
513            match_each_decimal_value_type!(decimal_dtype.canonical_values_type(), |T| {
514                self.patch_typed(
515                    indices.as_slice::<I>(),
516                    patches.offset(),
517                    &patch_values.buffer::<T>(),
518                    validity,
519                )
520            })
521        })
522    }
523
524    fn patch_typed<I: IntegerPType, T: NativeDecimalType>(
525        self,
526        indices: &[I],
527        offset: usize,
528        patch_values: &[T],
529        validity: Validity,
530    ) -> VortexResult<Self> {
531        let decimal_dtype = self.decimal_dtype();
532        let bytes = self.into_data().values.unwrap_host();
533        let mut values = Buffer::<T>::from_byte_buffer(bytes).into_mut();
534        for (index, value) in itertools::zip_eq(indices, patch_values) {
535            values[index.as_() - offset] = *value;
536        }
537
538        // Each row gets its value and validity from the same decimal input.
539        Self::try_new_handle_from_trusted_values(
540            BufferHandle::new_host(values.freeze().into_byte_buffer()),
541            T::DECIMAL_TYPE,
542            decimal_dtype,
543            validity,
544        )
545    }
546}
547
548fn collect_decimal_values<T: NativeDecimalType>(
549    iter: impl Iterator<Item = T>,
550    decimal_dtype: DecimalDType,
551) -> BufferHandle {
552    match_each_decimal_value_type!(decimal_dtype.canonical_values_type(), |D| {
553        let bounds = precision_bounds::<D>(decimal_dtype);
554        let values = Buffer::<D>::from_iter(
555            iter.map(|value| cast_value_in_precision(value, decimal_dtype, &bounds)),
556        );
557
558        BufferHandle::new_host(values.into_byte_buffer())
559    })
560}