1use std::any::Any;
5use std::ops::RangeInclusive;
6
7use vortex_buffer::BufferAllocatorRef;
8use vortex_buffer::BufferMut;
9use vortex_error::VortexExpect;
10use vortex_error::VortexResult;
11use vortex_error::vortex_ensure_eq;
12use vortex_error::vortex_panic;
13
14use crate::ArrayRef;
15use crate::ExecutionCtx;
16use crate::IntoArray;
17use crate::array::ArrayView;
18use crate::arrays::Decimal;
19use crate::arrays::DecimalArray;
20use crate::arrays::decimal::cast_value_in_precision;
21use crate::arrays::decimal::precision_bounds;
22use crate::builders::ArrayBuilder;
23use crate::builders::DEFAULT_BUILDER_CAPACITY;
24use crate::builders::LazyBitBufferBuilder;
25use crate::canonical::Canonical;
26use crate::dtype::BigCast;
27use crate::dtype::DType;
28use crate::dtype::DecimalDType;
29use crate::dtype::NativeDecimalType;
30use crate::dtype::Nullability;
31use crate::dtype::i256;
32use crate::match_each_decimal_value;
33use crate::match_each_decimal_value_type;
34use crate::scalar::DecimalValue;
35use crate::scalar::Scalar;
36
37pub struct DecimalBuilder {
42 dtype: DType,
43 values: DecimalBuffer,
44 nulls: LazyBitBufferBuilder,
45}
46
47enum DecimalBuffer {
49 I8(DecimalValues<i8>),
50 I16(DecimalValues<i16>),
51 I32(DecimalValues<i32>),
52 I64(DecimalValues<i64>),
53 I128(DecimalValues<i128>),
54 I256(DecimalValues<i256>),
55}
56
57struct DecimalValues<T> {
58 buffer: BufferMut<T>,
59 bounds: RangeInclusive<T>,
60}
61
62macro_rules! delegate_fn {
63 ($self:expr, | $tname:ident, $buffer:ident | $body:block) => {{
64 #[allow(unused)]
65 match $self {
66 DecimalBuffer::I8(buffer) => {
67 type $tname = i8;
68 let $buffer = buffer;
69 $body
70 }
71 DecimalBuffer::I16(buffer) => {
72 type $tname = i16;
73 let $buffer = buffer;
74 $body
75 }
76 DecimalBuffer::I32(buffer) => {
77 type $tname = i32;
78 let $buffer = buffer;
79 $body
80 }
81 DecimalBuffer::I64(buffer) => {
82 type $tname = i64;
83 let $buffer = buffer;
84 $body
85 }
86 DecimalBuffer::I128(buffer) => {
87 type $tname = i128;
88 let $buffer = buffer;
89 $body
90 }
91 DecimalBuffer::I256(buffer) => {
92 type $tname = i256;
93 let $buffer = buffer;
94 $body
95 }
96 }
97 }};
98}
99
100impl DecimalBuilder {
101 #[deprecated(note = "use `new_in` with an explicit allocator")]
103 pub fn new(decimal: DecimalDType, nullability: Nullability) -> Self {
104 Self::new_in(decimal, nullability, BufferAllocatorRef::static_ref())
105 }
106
107 pub fn new_in(
109 decimal: DecimalDType,
110 nullability: Nullability,
111 allocator: &BufferAllocatorRef,
112 ) -> Self {
113 Self::with_capacity_in(DEFAULT_BUILDER_CAPACITY, decimal, nullability, allocator)
114 }
115
116 #[deprecated(note = "use `with_capacity_in` with an explicit allocator")]
118 pub fn with_capacity(capacity: usize, decimal: DecimalDType, nullability: Nullability) -> Self {
119 Self::with_capacity_in(
120 capacity,
121 decimal,
122 nullability,
123 BufferAllocatorRef::static_ref(),
124 )
125 }
126
127 pub fn with_capacity_in(
129 capacity: usize,
130 decimal: DecimalDType,
131 nullability: Nullability,
132 allocator: &BufferAllocatorRef,
133 ) -> Self {
134 Self {
135 dtype: DType::Decimal(decimal, nullability),
136 values: match_each_decimal_value_type!(decimal.canonical_values_type(), |D| {
137 DecimalBuffer::from(DecimalValues {
138 buffer: BufferMut::<D>::with_capacity_in(capacity, allocator.clone()),
139 bounds: precision_bounds::<D>(decimal),
140 })
141 }),
142 nulls: LazyBitBufferBuilder::new(capacity, allocator.clone()),
143 }
144 }
145
146 pub fn append_value<V: NativeDecimalType>(&mut self, value: V) {
152 let dtype = *self.decimal_dtype();
153 delegate_fn!(&mut self.values, |T, values| {
154 let value = cast_value_in_precision(value, dtype, &values.bounds);
155 values.buffer.push(value);
156 });
157 self.nulls.append_non_null();
158 }
159
160 pub fn append_n_values<V: NativeDecimalType>(&mut self, value: V, n: usize) {
166 let dtype = *self.decimal_dtype();
167 delegate_fn!(&mut self.values, |T, values| {
168 let value = cast_value_in_precision(value, dtype, &values.bounds);
169 values.buffer.push_n(value, n);
170 });
171 self.nulls.append_n_non_nulls(n);
172 }
173
174 pub(crate) fn append_decimal_array(
176 &mut self,
177 array: ArrayView<'_, Decimal>,
178 ctx: &mut ExecutionCtx,
179 ) -> VortexResult<()> {
180 vortex_ensure_eq!(array.dtype(), self.dtype());
181
182 let mask = array.validity()?.execute_mask(array.len(), ctx)?;
183 delegate_fn!(&mut self.values, |T, values| {
184 values.buffer.extend_from_slice(&array.buffer::<T>());
185 });
186 self.nulls.append_validity_mask(&mask);
187 Ok(())
188 }
189
190 pub fn finish_into_decimal(&mut self) -> DecimalArray {
192 let validity = self.nulls.finish_with_nullability(self.dtype.nullability());
193
194 let decimal_dtype = *self.decimal_dtype();
195
196 delegate_fn!(&mut self.values, |T, values| {
197 let values = values.buffer.take();
198 assert!(
199 validity.maybe_len().is_none_or(|len| len == values.len()),
200 "validity of length {:?} does not cover the {} values appended",
201 validity.maybe_len(),
202 values.len()
203 );
204
205 unsafe { DecimalArray::new_unchecked::<T>(values.freeze(), decimal_dtype, validity) }
208 })
209 }
210
211 pub fn decimal_dtype(&self) -> &DecimalDType {
213 let DType::Decimal(decimal_dtype, _) = &self.dtype else {
214 vortex_panic!("`DecimalBuilder` somehow had dtype {}", self.dtype);
215 };
216
217 decimal_dtype
218 }
219}
220
221impl ArrayBuilder for DecimalBuilder {
222 fn as_any(&self) -> &dyn Any {
223 self
224 }
225
226 fn as_any_mut(&mut self) -> &mut dyn Any {
227 self
228 }
229
230 fn dtype(&self) -> &DType {
231 &self.dtype
232 }
233
234 fn len(&self) -> usize {
235 self.values.len()
236 }
237
238 fn append_zeros(&mut self, n: usize) {
239 self.values.push_zeros(n);
240 self.nulls.append_n_non_nulls(n);
241 }
242
243 unsafe fn append_nulls_unchecked(&mut self, n: usize) {
244 self.values.push_zeros(n);
245 self.nulls.append_n_nulls(n);
246 }
247
248 fn append_scalar(&mut self, scalar: &Scalar) -> VortexResult<()> {
249 vortex_ensure_eq!(
250 scalar.dtype(),
251 self.dtype(),
252 "DecimalBuilder received a scalar with the wrong dtype"
253 );
254
255 match scalar.as_decimal().decimal_value() {
256 None => self.append_null(),
257 Some(value) => {
258 match_each_decimal_value!(value, |v| { self.values.push_scalar(v) });
259 self.nulls.append_non_null();
260 }
261 }
262
263 Ok(())
264 }
265
266 fn reserve_exact(&mut self, additional: usize) {
267 self.values.reserve(additional);
268 self.nulls.reserve_exact(additional);
269 }
270
271 fn finish(&mut self) -> ArrayRef {
272 self.finish_into_decimal().into_array()
273 }
274
275 fn finish_into_canonical(&mut self, _ctx: &mut ExecutionCtx) -> Canonical {
276 Canonical::Decimal(self.finish_into_decimal())
277 }
278}
279
280impl DecimalBuffer {
281 fn push_scalar<V: NativeDecimalType>(&mut self, value: V) {
282 delegate_fn!(self, |T, values| {
283 let value = <T as BigCast>::from(value)
284 .vortex_expect("a scalar of the builder dtype fits its canonical width");
285 values.buffer.push(value);
286 });
287 }
288
289 fn push_zeros(&mut self, n: usize) {
290 delegate_fn!(self, |T, values| { values.buffer.push_n(T::default(), n) });
291 }
292
293 fn reserve(&mut self, additional: usize) {
294 delegate_fn!(self, |T, values| { values.buffer.reserve(additional) })
295 }
296
297 fn len(&self) -> usize {
298 delegate_fn!(self, |T, values| { values.buffer.len() })
299 }
300}
301
302macro_rules! impl_from_values {
303 ($T:ty, $variant:ident) => {
304 impl From<DecimalValues<$T>> for DecimalBuffer {
305 fn from(values: DecimalValues<$T>) -> Self {
306 Self::$variant(values)
307 }
308 }
309 };
310}
311
312impl_from_values!(i8, I8);
313impl_from_values!(i16, I16);
314impl_from_values!(i32, I32);
315impl_from_values!(i64, I64);
316impl_from_values!(i128, I128);
317impl_from_values!(i256, I256);
318
319#[cfg(test)]
320mod tests {
321 use std::panic::AssertUnwindSafe;
322 use std::panic::catch_unwind;
323 use std::sync::LazyLock;
324
325 use rstest::rstest;
326 use vortex_buffer::BufferAllocatorRef;
327 use vortex_error::VortexResult;
328 use vortex_session::VortexSession;
329
330 use crate::VortexSessionExecute;
331 use crate::array::VTable;
332 use crate::arrays::Decimal;
333 use crate::assert_arrays_eq;
334 use crate::builders::ArrayBuilder;
335 use crate::builders::DecimalBuilder;
336 use crate::builders::decimal::DecimalArray;
337 use crate::dtype::DecimalDType;
338 use crate::dtype::DecimalType;
339 use crate::dtype::Nullability;
340 use crate::scalar::Scalar;
341
342 static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
343
344 #[rstest]
345 #[case::single(|builder: &mut DecimalBuilder| builder.append_value(-100i64))]
346 #[case::repeated(|builder: &mut DecimalBuilder| builder.append_n_values(100i64, 3))]
347 fn invalid_append_preserves_the_builder(#[case] append: fn(&mut DecimalBuilder)) {
348 let dtype = DecimalDType::new(2, 1);
349 let mut builder = DecimalBuilder::new_in(
350 dtype,
351 Nullability::Nullable,
352 BufferAllocatorRef::static_ref(),
353 );
354 builder.append_null();
355
356 assert!(catch_unwind(AssertUnwindSafe(|| append(&mut builder))).is_err());
357 builder.append_value(99i64);
358 assert_arrays_eq!(
359 builder.finish(),
360 DecimalArray::from_option_iter([None, Some(99i8)], dtype),
361 &mut SESSION.create_execution_ctx()
362 );
363 }
364
365 #[test]
366 fn append_values_at_canonical_width() -> VortexResult<()> {
367 let mut ctx = SESSION.create_execution_ctx();
368 let dtype = DecimalDType::new(2, 1);
369 let mut builder = DecimalBuilder::new_in(
370 dtype,
371 Nullability::Nullable,
372 BufferAllocatorRef::static_ref(),
373 );
374 builder.append_value(-42i128);
375 builder.append_n_values(99i16, 2);
376 builder.append_null();
377 let array = builder.finish_into_decimal();
378 assert_eq!(array.values_type(), DecimalType::I8);
379
380 array.append_to_builder(&mut builder, &mut ctx)?;
381 assert_arrays_eq!(
382 builder.finish(),
383 DecimalArray::from_option_iter([Some(-42i8), Some(99), Some(99), None], dtype),
384 &mut ctx
385 );
386 Ok(())
387 }
388
389 #[test]
390 fn append_array_rejects_mismatched_dtype() {
391 let mut ctx = SESSION.create_execution_ctx();
392 let array = DecimalArray::from_iter([1i8], DecimalDType::new(2, 0));
393 let mut builder = DecimalBuilder::new_in(
394 DecimalDType::new(4, 0),
395 Nullability::NonNullable,
396 BufferAllocatorRef::static_ref(),
397 );
398
399 assert!(Decimal::append_to_builder(array.as_view(), &mut builder, &mut ctx).is_err());
400 assert!(builder.is_empty());
401 }
402
403 #[test]
404 fn test_append_scalar() {
405 let mut ctx = SESSION.create_execution_ctx();
406
407 let mut builder = DecimalBuilder::new_in(
409 DecimalDType::new(10, 2),
410 true.into(),
411 BufferAllocatorRef::static_ref(),
412 );
413 builder.append_value(1234i64);
414 builder.append_value(5678i64);
415 builder.append_null();
416
417 let array = builder.finish();
418 let expected = DecimalArray::from_option_iter(
419 [Some(1234i64), Some(5678), None],
420 DecimalDType::new(10, 2),
421 );
422 assert_arrays_eq!(&array, &expected, &mut ctx);
423
424 let mut builder2 = DecimalBuilder::new_in(
426 DecimalDType::new(10, 2),
427 true.into(),
428 BufferAllocatorRef::static_ref(),
429 );
430 for i in 0..array.len() {
431 let scalar = array
432 .execute_scalar(i, &mut SESSION.create_execution_ctx())
433 .unwrap();
434 builder2.append_scalar(&scalar).unwrap();
435 }
436
437 let array2 = builder2.finish();
438 assert_arrays_eq!(&array2, &array, &mut ctx);
439
440 let mut builder = DecimalBuilder::new_in(
442 DecimalDType::new(10, 2),
443 false.into(),
444 BufferAllocatorRef::static_ref(),
445 );
446 let wrong_scalar = Scalar::from(true);
447 assert!(builder.append_scalar(&wrong_scalar).is_err());
448 }
449}