1use 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 #[slot(0)]
50 pub validity_child: Option<ArrayRef>,
51}
52
53#[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
108pub struct DecimalDataParts {
110 pub decimal_dtype: DecimalDType,
112 pub values: BufferHandle,
114 pub values_type: DecimalType,
123 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 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 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 pub fn len(&self) -> usize {
213 self.values.len() / self.values_type().byte_width()
214 }
215
216 pub fn is_empty(&self) -> bool {
218 self.len() == 0
219 }
220
221 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 pub fn values_type(&self) -> DecimalType {
239 self.decimal_dtype.canonical_values_type()
240 }
241
242 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
270impl Array<Decimal> {
273 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 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 unsafe { Self::new_unchecked_handle(values, T::DECIMAL_TYPE, decimal_dtype, validity) }
310 }
311
312 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 #[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 unsafe {
346 Self::new_unchecked_handle(values, values_type, decimal_dtype, Validity::NonNullable)
347 }
348 }
349
350 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 unsafe { Self::new_unchecked_handle(values, values_type, decimal_dtype, validity) }
374 }
375
376 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 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 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 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 unsafe { Array::from_parts_unchecked(parts) }
470 }
471
472 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 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 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 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}