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    /// Appends `n` copies of `value` as non-null entries, directly writing into the buffer.
124    pub fn append_n_values<V: NativeDecimalType>(&mut self, value: V, n: usize) {
125        self.values.push_n(value, n);
126        self.nulls.append_n_non_nulls(n);
127    }
128
129    /// Finishes the builder directly into a [`DecimalArray`].
130    pub fn finish_into_decimal(&mut self) -> DecimalArray {
131        let validity = self.nulls.finish_with_nullability(self.dtype.nullability());
132
133        let decimal_dtype = *self.decimal_dtype();
134
135        delegate_fn!(std::mem::take(&mut self.values), |T, values| {
136            DecimalArray::new::<T>(values.freeze(), decimal_dtype, validity)
137        })
138    }
139
140    /// The [`DecimalDType`] of this builder.
141    pub fn decimal_dtype(&self) -> &DecimalDType {
142        let DType::Decimal(decimal_dtype, _) = &self.dtype else {
143            vortex_panic!("`DecimalBuilder` somehow had dtype {}", self.dtype);
144        };
145
146        decimal_dtype
147    }
148}
149
150impl ArrayBuilder for DecimalBuilder {
151    fn as_any(&self) -> &dyn Any {
152        self
153    }
154
155    fn as_any_mut(&mut self) -> &mut dyn Any {
156        self
157    }
158
159    fn dtype(&self) -> &DType {
160        &self.dtype
161    }
162
163    fn len(&self) -> usize {
164        self.values.len()
165    }
166
167    fn append_zeros(&mut self, n: usize) {
168        self.values.push_n(0, n);
169        self.nulls.append_n_non_nulls(n);
170    }
171
172    unsafe fn append_nulls_unchecked(&mut self, n: usize) {
173        self.values.push_n(0, n);
174        self.nulls.append_n_nulls(n);
175    }
176
177    fn append_scalar(&mut self, scalar: &Scalar) -> VortexResult<()> {
178        vortex_ensure!(
179            scalar.dtype() == self.dtype(),
180            "DecimalBuilder expected scalar with dtype {}, got {}",
181            self.dtype(),
182            scalar.dtype()
183        );
184
185        match scalar.as_decimal().decimal_value() {
186            None => self.append_null(),
187            Some(v) => match_each_decimal_value!(v, |dec_val| {
188                self.append_value(dec_val);
189            }),
190        }
191
192        Ok(())
193    }
194
195    unsafe fn extend_from_array_unchecked(&mut self, array: &ArrayRef) {
196        let decimal_array = array.to_decimal();
197
198        match_each_decimal_value_type!(decimal_array.values_type(), |D| {
199            // Extends the values buffer from another buffer of type D where D can be coerced to the
200            // builder type.
201            self.values
202                .extend(decimal_array.buffer::<D>().iter().copied());
203        });
204
205        self.nulls
206            .append_validity_mask(decimal_array.validity_mask().vortex_expect("validity_mask"));
207    }
208
209    fn reserve_exact(&mut self, additional: usize) {
210        self.values.reserve(additional);
211        self.nulls.reserve_exact(additional);
212    }
213
214    unsafe fn set_validity_unchecked(&mut self, validity: Mask) {
215        self.nulls = LazyBitBufferBuilder::new(validity.len());
216        self.nulls.append_validity_mask(validity);
217    }
218
219    fn finish(&mut self) -> ArrayRef {
220        self.finish_into_decimal().into_array()
221    }
222
223    fn finish_into_canonical(&mut self) -> Canonical {
224        Canonical::Decimal(self.finish_into_decimal())
225    }
226}
227
228impl DecimalBuffer {
229    fn push<V: NativeDecimalType>(&mut self, value: V) {
230        delegate_fn!(self, |T, buffer| {
231            buffer.push(
232                <T as BigCast>::from(value)
233                    .ok_or_else(|| {
234                        vortex_err!(
235                            "decimal conversion failure {:?}, type: {:?} to {:?}",
236                            value,
237                            V::DECIMAL_TYPE,
238                            T::DECIMAL_TYPE,
239                        )
240                    })
241                    .vortex_expect("operation should succeed in builder"),
242            )
243        });
244    }
245
246    fn push_n<V: NativeDecimalType>(&mut self, value: V, n: usize) {
247        delegate_fn!(self, |T, buffer| {
248            buffer.push_n(
249                <T as BigCast>::from(value).vortex_expect("decimal conversion failure"),
250                n,
251            )
252        });
253    }
254
255    fn reserve(&mut self, additional: usize) {
256        delegate_fn!(self, |T, buffer| { buffer.reserve(additional) })
257    }
258
259    fn len(&self) -> usize {
260        delegate_fn!(self, |T, buffer| { buffer.len() })
261    }
262
263    pub fn extend<I, V: NativeDecimalType>(&mut self, iter: I)
264    where
265        I: Iterator<Item = V>,
266    {
267        delegate_fn!(self, |T, buffer| {
268            buffer.extend(
269                iter.map(|x| <T as BigCast>::from(x).vortex_expect("decimal conversion failure")),
270            )
271        })
272    }
273}
274
275macro_rules! impl_from_buffer {
276    ($T:ty, $variant:ident) => {
277        impl From<BufferMut<$T>> for DecimalBuffer {
278            fn from(buffer: BufferMut<$T>) -> Self {
279                Self::$variant(buffer)
280            }
281        }
282    };
283}
284
285impl_from_buffer!(i8, I8);
286impl_from_buffer!(i16, I16);
287impl_from_buffer!(i32, I32);
288impl_from_buffer!(i64, I64);
289impl_from_buffer!(i128, I128);
290impl_from_buffer!(i256, I256);
291
292impl Default for DecimalBuffer {
293    fn default() -> Self {
294        Self::I8(BufferMut::<i8>::empty())
295    }
296}
297
298#[cfg(test)]
299mod tests {
300    use crate::assert_arrays_eq;
301    use crate::builders::ArrayBuilder;
302    use crate::builders::DecimalBuilder;
303    use crate::builders::decimal::DecimalArray;
304    use crate::dtype::DecimalDType;
305
306    #[test]
307    fn test_mixed_extend() {
308        let values = 42i8;
309
310        let mut i8s = DecimalBuilder::new::<i8>(DecimalDType::new(2, 1), false.into());
311        for v in 0..values {
312            i8s.append_value(v);
313        }
314        let i8s = i8s.finish();
315
316        let mut i128s = DecimalBuilder::new::<i128>(DecimalDType::new(2, 1), false.into());
317        i128s.extend_from_array(&i8s);
318        let i128s = i128s.finish();
319
320        for i in 0..i8s.len() {
321            assert_eq!(i8s.scalar_at(i).unwrap(), i128s.scalar_at(i).unwrap());
322        }
323    }
324
325    #[test]
326    fn test_append_scalar() {
327        use crate::scalar::Scalar;
328
329        // Simply test that the builder accepts its own finish output via scalar.
330        let mut builder = DecimalBuilder::new::<i64>(DecimalDType::new(10, 2), true.into());
331        builder.append_value(1234i64);
332        builder.append_value(5678i64);
333        builder.append_null();
334
335        let array = builder.finish();
336        let expected = DecimalArray::from_option_iter(
337            [Some(1234i64), Some(5678), None],
338            DecimalDType::new(10, 2),
339        );
340        assert_arrays_eq!(&array, &expected);
341
342        // Test by taking a scalar from the array and appending it to a new builder.
343        let mut builder2 = DecimalBuilder::new::<i64>(DecimalDType::new(10, 2), true.into());
344        for i in 0..array.len() {
345            let scalar = array.scalar_at(i).unwrap();
346            builder2.append_scalar(&scalar).unwrap();
347        }
348
349        let array2 = builder2.finish();
350        assert_arrays_eq!(&array2, &array);
351
352        // Test wrong dtype error.
353        let mut builder = DecimalBuilder::new::<i64>(DecimalDType::new(10, 2), false.into());
354        let wrong_scalar = Scalar::from(true);
355        assert!(builder.append_scalar(&wrong_scalar).is_err());
356    }
357}