Skip to main content

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