vortex_array/builders/
decimal.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::any::Any;
5
6use vortex_buffer::BufferMut;
7use vortex_dtype::BigCast;
8use vortex_dtype::DType;
9use vortex_dtype::DecimalDType;
10use vortex_dtype::NativeDecimalType;
11use vortex_dtype::Nullability;
12use vortex_dtype::match_each_decimal_value;
13use vortex_dtype::match_each_decimal_value_type;
14use vortex_error::VortexExpect;
15use vortex_error::VortexResult;
16use vortex_error::vortex_ensure;
17use vortex_error::vortex_err;
18use vortex_error::vortex_panic;
19use vortex_mask::Mask;
20use vortex_scalar::DecimalValue;
21use vortex_scalar::Scalar;
22use vortex_scalar::i256;
23
24use crate::Array;
25use crate::ArrayRef;
26use crate::IntoArray;
27use crate::ToCanonical;
28use crate::arrays::DecimalArray;
29use crate::builders::ArrayBuilder;
30use crate::builders::DEFAULT_BUILDER_CAPACITY;
31use crate::builders::LazyBitBufferBuilder;
32use crate::canonical::Canonical;
33
34/// The builder for building a [`DecimalArray`].
35///
36/// The output will be a new [`DecimalArray`] holding values of `T`. Any value that is a valid
37/// [decimal type][NativeDecimalType] can be appended to the builder and it will be immediately
38/// coerced into the target type.
39pub struct DecimalBuilder {
40    dtype: DType,
41    values: DecimalBuffer,
42    nulls: LazyBitBufferBuilder,
43}
44
45/// Wrapper around the typed builder.
46///
47/// We want to be able to downcast a `Box<dyn ArrayBuilder>` to a [`DecimalBuilder`] and we
48/// generally don't have enough type information to get the `T` at the call site, so we instead use
49/// this to hold values and can push values into the correct buffer type generically.
50enum DecimalBuffer {
51    I8(BufferMut<i8>),
52    I16(BufferMut<i16>),
53    I32(BufferMut<i32>),
54    I64(BufferMut<i64>),
55    I128(BufferMut<i128>),
56    I256(BufferMut<i256>),
57}
58
59macro_rules! delegate_fn {
60    ($self:expr, | $tname:ident, $buffer:ident | $body:block) => {{
61        #[allow(unused)]
62        match $self {
63            DecimalBuffer::I8(buffer) => {
64                type $tname = i8;
65                let $buffer = buffer;
66                $body
67            }
68            DecimalBuffer::I16(buffer) => {
69                type $tname = i16;
70                let $buffer = buffer;
71                $body
72            }
73            DecimalBuffer::I32(buffer) => {
74                type $tname = i32;
75                let $buffer = buffer;
76                $body
77            }
78            DecimalBuffer::I64(buffer) => {
79                type $tname = i64;
80                let $buffer = buffer;
81                $body
82            }
83            DecimalBuffer::I128(buffer) => {
84                type $tname = i128;
85                let $buffer = buffer;
86                $body
87            }
88            DecimalBuffer::I256(buffer) => {
89                type $tname = i256;
90                let $buffer = buffer;
91                $body
92            }
93        }
94    }};
95}
96
97impl DecimalBuilder {
98    /// Creates a new `DecimalBuilder` with a capacity of [`DEFAULT_BUILDER_CAPACITY`].
99    pub fn new<T: NativeDecimalType>(decimal: DecimalDType, nullability: Nullability) -> Self {
100        Self::with_capacity::<T>(DEFAULT_BUILDER_CAPACITY, decimal, nullability)
101    }
102
103    /// Creates a new `DecimalBuilder` with the given `capacity`.
104    pub fn with_capacity<T: NativeDecimalType>(
105        capacity: usize,
106        decimal: DecimalDType,
107        nullability: Nullability,
108    ) -> Self {
109        Self {
110            dtype: DType::Decimal(decimal, nullability),
111            values: match_each_decimal_value_type!(T::DECIMAL_TYPE, |D| {
112                DecimalBuffer::from(BufferMut::<D>::with_capacity(capacity))
113            }),
114            nulls: LazyBitBufferBuilder::new(capacity),
115        }
116    }
117
118    /// Appends a decimal `value` to the builder.
119    pub fn append_value<V: NativeDecimalType>(&mut self, value: V) {
120        self.values.push(value);
121        self.nulls.append_non_null();
122    }
123
124    /// Finishes the builder directly into a [`DecimalArray`].
125    pub fn finish_into_decimal(&mut self) -> DecimalArray {
126        let validity = self.nulls.finish_with_nullability(self.dtype.nullability());
127
128        let decimal_dtype = *self.decimal_dtype();
129
130        delegate_fn!(std::mem::take(&mut self.values), |T, values| {
131            DecimalArray::new::<T>(values.freeze(), decimal_dtype, validity)
132        })
133    }
134
135    /// The [`DecimalDType`] of this builder.
136    pub fn decimal_dtype(&self) -> &DecimalDType {
137        let DType::Decimal(decimal_dtype, _) = &self.dtype else {
138            vortex_panic!("`DecimalBuilder` somehow had dtype {}", self.dtype);
139        };
140
141        decimal_dtype
142    }
143}
144
145impl ArrayBuilder for DecimalBuilder {
146    fn as_any(&self) -> &dyn Any {
147        self
148    }
149
150    fn as_any_mut(&mut self) -> &mut dyn Any {
151        self
152    }
153
154    fn dtype(&self) -> &DType {
155        &self.dtype
156    }
157
158    fn len(&self) -> usize {
159        self.values.len()
160    }
161
162    fn append_zeros(&mut self, n: usize) {
163        self.values.push_n(0, n);
164        self.nulls.append_n_non_nulls(n);
165    }
166
167    unsafe fn append_nulls_unchecked(&mut self, n: usize) {
168        self.values.push_n(0, n);
169        self.nulls.append_n_nulls(n);
170    }
171
172    fn append_scalar(&mut self, scalar: &Scalar) -> VortexResult<()> {
173        vortex_ensure!(
174            scalar.dtype() == self.dtype(),
175            "DecimalBuilder expected scalar with dtype {:?}, got {:?}",
176            self.dtype(),
177            scalar.dtype()
178        );
179
180        match scalar.as_decimal().decimal_value() {
181            None => self.append_null(),
182            Some(v) => match_each_decimal_value!(v, |dec_val| {
183                self.append_value(dec_val);
184            }),
185        }
186
187        Ok(())
188    }
189
190    unsafe fn extend_from_array_unchecked(&mut self, array: &dyn Array) {
191        let decimal_array = array.to_decimal();
192
193        match_each_decimal_value_type!(decimal_array.values_type(), |D| {
194            // Extends the values buffer from another buffer of type D where D can be coerced to the
195            // builder type.
196            self.values
197                .extend(decimal_array.buffer::<D>().iter().copied());
198        });
199
200        self.nulls
201            .append_validity_mask(decimal_array.validity_mask());
202    }
203
204    fn reserve_exact(&mut self, additional: usize) {
205        self.values.reserve(additional);
206        self.nulls.reserve_exact(additional);
207    }
208
209    unsafe fn set_validity_unchecked(&mut self, validity: Mask) {
210        self.nulls = LazyBitBufferBuilder::new(validity.len());
211        self.nulls.append_validity_mask(validity);
212    }
213
214    fn finish(&mut self) -> ArrayRef {
215        self.finish_into_decimal().into_array()
216    }
217
218    fn finish_into_canonical(&mut self) -> Canonical {
219        Canonical::Decimal(self.finish_into_decimal())
220    }
221}
222
223impl DecimalBuffer {
224    fn push<V: NativeDecimalType>(&mut self, value: V) {
225        delegate_fn!(self, |T, buffer| {
226            buffer.push(
227                <T as BigCast>::from(value)
228                    .ok_or_else(|| {
229                        vortex_err!(
230                            "decimal conversion failure {:?}, type: {:?} to {:?}",
231                            value,
232                            V::DECIMAL_TYPE,
233                            T::DECIMAL_TYPE,
234                        )
235                    })
236                    .vortex_expect("operation should succeed in builder"),
237            )
238        });
239    }
240
241    fn push_n<V: NativeDecimalType>(&mut self, value: V, n: usize) {
242        delegate_fn!(self, |T, buffer| {
243            buffer.push_n(
244                <T as BigCast>::from(value).vortex_expect("decimal conversion failure"),
245                n,
246            )
247        });
248    }
249
250    fn reserve(&mut self, additional: usize) {
251        delegate_fn!(self, |T, buffer| { buffer.reserve(additional) })
252    }
253
254    fn len(&self) -> usize {
255        delegate_fn!(self, |T, buffer| { buffer.len() })
256    }
257
258    pub fn extend<I, V: NativeDecimalType>(&mut self, iter: I)
259    where
260        I: Iterator<Item = V>,
261    {
262        delegate_fn!(self, |T, buffer| {
263            buffer.extend(
264                iter.map(|x| <T as BigCast>::from(x).vortex_expect("decimal conversion failure")),
265            )
266        })
267    }
268}
269
270macro_rules! impl_from_buffer {
271    ($T:ty, $variant:ident) => {
272        impl From<BufferMut<$T>> for DecimalBuffer {
273            fn from(buffer: BufferMut<$T>) -> Self {
274                Self::$variant(buffer)
275            }
276        }
277    };
278}
279
280impl_from_buffer!(i8, I8);
281impl_from_buffer!(i16, I16);
282impl_from_buffer!(i32, I32);
283impl_from_buffer!(i64, I64);
284impl_from_buffer!(i128, I128);
285impl_from_buffer!(i256, I256);
286
287impl Default for DecimalBuffer {
288    fn default() -> Self {
289        Self::I8(BufferMut::<i8>::empty())
290    }
291}
292
293#[cfg(test)]
294mod tests {
295    use vortex_dtype::DecimalDType;
296
297    use crate::arrays::DecimalArray;
298    use crate::assert_arrays_eq;
299    use crate::builders::ArrayBuilder;
300    use crate::builders::DecimalBuilder;
301
302    #[test]
303    fn test_mixed_extend() {
304        let values = 42i8;
305
306        let mut i8s = DecimalBuilder::new::<i8>(DecimalDType::new(2, 1), false.into());
307        for v in 0..values {
308            i8s.append_value(v);
309        }
310        let i8s = i8s.finish();
311
312        let mut i128s = DecimalBuilder::new::<i128>(DecimalDType::new(2, 1), false.into());
313        i128s.extend_from_array(&i8s);
314        let i128s = i128s.finish();
315
316        for i in 0..i8s.len() {
317            assert_eq!(i8s.scalar_at(i), i128s.scalar_at(i));
318        }
319    }
320
321    #[test]
322    fn test_append_scalar() {
323        use vortex_scalar::Scalar;
324
325        // Simply test that the builder accepts its own finish output via scalar.
326        let mut builder = DecimalBuilder::new::<i64>(DecimalDType::new(10, 2), true.into());
327        builder.append_value(1234i64);
328        builder.append_value(5678i64);
329        builder.append_null();
330
331        let array = builder.finish();
332        let expected = DecimalArray::from_option_iter(
333            [Some(1234i64), Some(5678), None],
334            DecimalDType::new(10, 2),
335        );
336        assert_arrays_eq!(&array, &expected);
337
338        // Test by taking a scalar from the array and appending it to a new builder.
339        let mut builder2 = DecimalBuilder::new::<i64>(DecimalDType::new(10, 2), true.into());
340        for i in 0..array.len() {
341            let scalar = array.scalar_at(i);
342            builder2.append_scalar(&scalar).unwrap();
343        }
344
345        let array2 = builder2.finish();
346        assert_arrays_eq!(&array2, &array);
347
348        // Test wrong dtype error.
349        let mut builder = DecimalBuilder::new::<i64>(DecimalDType::new(10, 2), false.into());
350        let wrong_scalar = Scalar::from(true);
351        assert!(builder.append_scalar(&wrong_scalar).is_err());
352    }
353}