1use std::ops::RangeInclusive;
5
6use vortex_buffer::Buffer;
7use vortex_buffer::BufferMut;
8use vortex_compute::lane_kernels::IndexedSourceExt;
9use vortex_error::VortexExpect;
10use vortex_error::VortexResult;
11use vortex_error::vortex_bail;
12use vortex_error::vortex_ensure_eq;
13use vortex_error::vortex_panic;
14use vortex_mask::AllOr;
15use vortex_mask::Mask;
16
17pub use crate::aggregate_fn::fns::min_max::valid_range;
18use crate::arrays::DecimalArray;
19use crate::arrays::decimal::DecimalArrayExt;
20use crate::arrays::decimal::DecimalData;
21use crate::buffer::BufferHandle;
22use crate::dtype::BigCast;
23use crate::dtype::DecimalDType;
24use crate::dtype::NativeDecimalType;
25use crate::match_each_decimal_value_type;
26
27pub(crate) fn widened_buffer<W: NativeDecimalType>(array: &DecimalData) -> Buffer<W> {
30 if array.values_type() == W::DECIMAL_TYPE {
31 return array.buffer::<W>();
32 }
33 match_each_decimal_value_type!(array.values_type(), |T| {
34 if const { (T::DECIMAL_TYPE as u8) < (W::DECIMAL_TYPE as u8) } {
37 widen_values::<T, W>(&array.buffer::<T>())
38 } else {
39 unreachable!(
40 "{} is not narrower than {}",
41 T::DECIMAL_TYPE,
42 W::DECIMAL_TYPE
43 )
44 }
45 })
46}
47
48pub fn converted_buffer<W: NativeDecimalType>(
55 array: &DecimalArray,
56 validity: &Mask,
57) -> VortexResult<Buffer<W>> {
58 if array.values_type() <= W::DECIMAL_TYPE {
60 return Ok(widened_buffer(array));
61 }
62 match_each_decimal_value_type!(array.values_type(), |T| {
63 if const { (T::DECIMAL_TYPE as u8) > (W::DECIMAL_TYPE as u8) } {
66 let src = array.buffer::<T>();
67 match validity {
68 Mask::AllTrue(_) => {
69 let any_overflow = src.iter().fold(false, |acc, v| acc | W::from(*v).is_none());
72 if any_overflow {
73 let (i, v) = src
74 .iter()
75 .enumerate()
76 .find(|&(_, v)| W::from(*v).is_none())
77 .vortex_expect("overflow scan found an overflowing value");
78 vortex_bail!(
79 "decimal value {v} at index {i} does not fit {}",
80 W::DECIMAL_TYPE
81 );
82 }
83 }
84 Mask::AllFalse(_) => return Ok(Buffer::zeroed(src.len())),
85 Mask::Values(values) => {
86 let any_overflow = src.iter().fold(false, |acc, v| acc | W::from(*v).is_none());
87 if any_overflow {
88 for (i, v) in src.iter().enumerate() {
89 if values.value(i) && W::from(*v).is_none() {
90 vortex_bail!(
91 "decimal value {v} at index {i} does not fit {}",
92 W::DECIMAL_TYPE
93 );
94 }
95 }
96 }
97 }
98 }
99 Ok(src
102 .iter()
103 .map(|v| W::from(*v).unwrap_or_default())
104 .collect())
105 } else {
106 unreachable!("{} is not wider than {}", T::DECIMAL_TYPE, W::DECIMAL_TYPE)
107 }
108 })
109}
110
111pub fn copy_to_canonical_width<F: NativeDecimalType>(
130 values: &[F],
131 validity: &Mask,
132 target: DecimalDType,
133) -> VortexResult<BufferHandle> {
134 vortex_ensure_eq!(validity.len(), values.len());
135
136 let canonical_type = target.canonical_values_type();
137 if F::DECIMAL_TYPE == canonical_type {
138 return Ok(BufferHandle::new_host(
139 Buffer::<F>::copy_from(values).into_byte_buffer(),
140 ));
141 }
142
143 let copy = match_each_decimal_value_type!(canonical_type, |W| {
144 if const { (F::DECIMAL_TYPE as u8) <= (W::DECIMAL_TYPE as u8) } {
145 widen_values::<F, W>(values).into_byte_buffer()
146 } else {
147 check_precision(values, validity, target)?;
148 narrow_checked_values::<F, W>(values, validity).into_byte_buffer()
149 }
150 });
151
152 Ok(BufferHandle::new_host(copy))
153}
154
155fn widen_values<F: NativeDecimalType, W: NativeDecimalType>(values: &[F]) -> Buffer<W> {
158 assert!(
162 (F::DECIMAL_TYPE as u8) <= (W::DECIMAL_TYPE as u8),
163 "widen_values requires a target at least as wide as the source, got {} into {}",
164 F::DECIMAL_TYPE,
165 W::DECIMAL_TYPE
166 );
167
168 Buffer::from_trusted_len_iter(
175 values
176 .iter()
177 .map(|&value| <W as BigCast>::from(value).unwrap_or_default()),
178 )
179}
180
181fn narrow_checked_values<F: NativeDecimalType, W: NativeDecimalType>(
183 values: &[F],
184 validity: &Mask,
185) -> Buffer<W> {
186 let len = values.len();
187 let valid_bits = match validity.bit_buffer() {
188 AllOr::All => None,
189 AllOr::None => return Buffer::zeroed(len),
190 AllOr::Some(valid_bits) => Some(valid_bits),
191 };
192
193 let narrow = |value: F| <W as BigCast>::from(value).unwrap_or_default();
196
197 let mut buffer = BufferMut::<W>::with_capacity(len);
198 let out = &mut buffer.spare_capacity_mut()[..len];
199 match valid_bits {
200 None => values.map_into(out, narrow),
201 Some(valid_bits) => values.map_masked_into(valid_bits, out, narrow),
202 }
203
204 unsafe { buffer.set_len(len) };
206
207 buffer.freeze()
208}
209
210pub fn check_precision<T: NativeDecimalType>(
221 values: &[T],
222 validity: &Mask,
223 decimal_dtype: DecimalDType,
224) -> VortexResult<()> {
225 vortex_ensure_eq!(validity.len(), values.len());
226
227 if decimal_dtype.precision() > T::MAX_PRECISION || matches!(validity, Mask::AllFalse(_)) {
229 return Ok(());
230 }
231 let bounds = precision_bounds::<T>(decimal_dtype);
232 let any_outside = values.iter().fold(false, |outside, value| {
235 outside | (value < bounds.start()) | (value > bounds.end())
236 });
237 if any_outside && let Some(row) = first_outside_precision(values, validity, decimal_dtype) {
238 vortex_bail!(
239 "decimal value at row {row} must be within the precision of {decimal_dtype}, got {}",
240 values[row]
241 );
242 }
243 Ok(())
244}
245
246pub(crate) fn first_outside_precision<T: NativeDecimalType>(
251 values: &[T],
252 validity: &Mask,
253 decimal_dtype: DecimalDType,
254) -> Option<usize> {
255 debug_assert_eq!(validity.len(), values.len());
256 if decimal_dtype.precision() > T::MAX_PRECISION {
257 return None;
258 }
259 let bounds = precision_bounds::<T>(decimal_dtype);
260 match validity.bit_buffer() {
261 AllOr::All => values.iter().position(|value| !bounds.contains(value)),
262 AllOr::None => None,
263 AllOr::Some(bits) => bits
264 .set_indices()
265 .find(|&row| !bounds.contains(&values[row])),
266 }
267}
268
269pub(crate) fn precision_bounds<T: NativeDecimalType>(
271 decimal_dtype: DecimalDType,
272) -> RangeInclusive<T> {
273 let precision = usize::from(decimal_dtype.precision());
274 T::MIN_BY_PRECISION[precision]..=T::MAX_BY_PRECISION[precision]
275}
276
277pub(crate) fn cast_value_in_precision<F: NativeDecimalType, T: NativeDecimalType>(
279 value: F,
280 decimal_dtype: DecimalDType,
281 bounds: &RangeInclusive<T>,
282) -> T {
283 <T as BigCast>::from(value)
284 .filter(|v| bounds.contains(v))
285 .unwrap_or_else(|| {
286 vortex_panic!("decimal value {value} exceeds the precision of {decimal_dtype}")
287 })
288}
289
290#[cfg(test)]
291mod tests {
292 use rstest::rstest;
293 use vortex_buffer::Buffer;
294 use vortex_error::VortexExpect;
295 use vortex_error::VortexResult;
296 use vortex_mask::Mask;
297
298 use super::check_precision;
299 use super::converted_buffer;
300 use super::copy_to_canonical_width;
301 use super::valid_range;
302 use super::widen_values;
303 use crate::arrays::DecimalArray;
304 use crate::dtype::BigCast;
305 use crate::dtype::DecimalDType;
306 use crate::dtype::DecimalType;
307 use crate::dtype::NativeDecimalType;
308 use crate::dtype::ToI256;
309 use crate::dtype::i256;
310 use crate::match_each_decimal_value_type;
311
312 fn copy_as_i256<F: NativeDecimalType>(
315 values: &[F],
316 validity: &Mask,
317 target: DecimalDType,
318 ) -> VortexResult<Vec<i256>> {
319 let copy = copy_to_canonical_width(values, validity, target)?;
320 let width = target.canonical_values_type();
321 assert_eq!(copy.len(), values.len() * width.byte_width());
322
323 Ok(match_each_decimal_value_type!(width, |W| {
324 Buffer::<W>::from_byte_buffer(copy.unwrap_host())
325 .iter()
326 .map(|value| value.to_i256().vortex_expect("decimal values fit i256"))
327 .collect()
328 }))
329 }
330
331 fn ten_to_the(precision: u8) -> i256 {
333 i256::from_i128(10)
334 .checked_pow(precision.into())
335 .vortex_expect("10^76 fits i256")
336 }
337
338 fn to_native<T: NativeDecimalType>(values: &[i256]) -> Vec<T> {
340 values
341 .iter()
342 .map(|&value| <T as BigCast>::from(value).vortex_expect("test value fits the type"))
343 .collect()
344 }
345
346 #[rstest]
347 #[case::all_valid(vec![5, -3, 7], vec![true, true, true], Some((-3, 7)))]
348 #[case::partly_valid(vec![5, -3, 7], vec![true, true, false], Some((-3, 5)))]
349 #[case::all_null(vec![5, -3, 7], vec![false, false, false], None)]
350 #[case::empty(vec![], vec![], None)]
351 #[case::one_valid(vec![5, -3, 7], vec![false, true, false], Some((-3, -3)))]
352 #[case::outside_i8_precision(vec![-100, 100], vec![true, true], Some((-100, 100)))]
353 fn test_valid_range(
354 #[case] values: Vec<i8>,
355 #[case] validity: Vec<bool>,
356 #[case] expected: Option<(i8, i8)>,
357 #[values(
358 DecimalType::I8,
359 DecimalType::I16,
360 DecimalType::I32,
361 DecimalType::I64,
362 DecimalType::I128,
363 DecimalType::I256
364 )]
365 storage: DecimalType,
366 ) -> VortexResult<()> {
367 let validity = Mask::from_iter(validity);
368 match_each_decimal_value_type!(storage, |T| {
369 let values: Vec<T> = values
370 .iter()
371 .map(|&value| {
372 <T as BigCast>::from(value).vortex_expect("i8 values fit every decimal type")
373 })
374 .collect();
375 let expected = expected.map(|(min, max)| {
376 (
377 <T as BigCast>::from(min).vortex_expect("i8 values fit every decimal type"),
378 <T as BigCast>::from(max).vortex_expect("i8 values fit every decimal type"),
379 )
380 });
381 assert_eq!(valid_range(&values, &validity), expected);
382 });
383
384 Ok(())
385 }
386
387 #[rstest]
388 fn test_valid_range_ignores_null_extremes(
389 #[values(
390 DecimalType::I8,
391 DecimalType::I16,
392 DecimalType::I32,
393 DecimalType::I64,
394 DecimalType::I128,
395 DecimalType::I256
396 )]
397 storage: DecimalType,
398 ) -> VortexResult<()> {
399 let validity = Mask::from_iter([false, true, true, false]);
400 match_each_decimal_value_type!(storage, |T| {
401 let min = <T as BigCast>::from(-3i8).vortex_expect("-3 fits every decimal type");
402 let max = <T as BigCast>::from(7i8).vortex_expect("7 fits every decimal type");
403 assert_eq!(
404 valid_range(&[T::MIN, min, max, T::MAX], &validity),
405 Some((min, max))
406 );
407 assert_eq!(
408 valid_range(&[T::MIN, T::MAX], &Mask::AllTrue(2)),
409 Some((T::MIN, T::MAX))
410 );
411 });
412
413 Ok(())
414 }
415
416 #[test]
417 #[should_panic(expected = "valid_range requires one validity bit per value")]
418 fn test_valid_range_rejects_mismatched_mask() {
419 valid_range(&[1i8, 2], &Mask::AllTrue(3));
420 }
421
422 #[rstest]
424 fn converted_buffer_every_storage_pair(
425 #[values(2, 4, 9, 18, 38, 76)] precision: u8,
426 #[values(
427 DecimalType::I8,
428 DecimalType::I16,
429 DecimalType::I32,
430 DecimalType::I64,
431 DecimalType::I128,
432 DecimalType::I256
433 )]
434 target: DecimalType,
435 ) -> VortexResult<()> {
436 let values = [1i8, -2, 3];
437 let array = DecimalArray::from_iter(values, DecimalDType::new(precision, 0));
438
439 match_each_decimal_value_type!(target, |W| {
440 let converted = converted_buffer::<W>(&array, &Mask::new_true(values.len()))?;
441 let expected = values.map(|value| {
442 <W as BigCast>::from(value).vortex_expect("small values fit every decimal type")
443 });
444 assert_eq!(converted.as_slice(), expected.as_slice());
445 });
446 Ok(())
447 }
448
449 #[rstest]
450 #[case::i8_to_i16(DecimalType::I8, 3)]
451 #[case::i16_to_i32(DecimalType::I16, 5)]
452 #[case::i32_to_i64(DecimalType::I32, 10)]
453 #[case::i64_to_i128(DecimalType::I64, 19)]
454 #[case::i128_to_i256(DecimalType::I128, 39)]
455 #[case::i8_to_i256(DecimalType::I8, 76)]
456 #[case::i64_same_width(DecimalType::I64, 18)]
457 fn test_copy_to_canonical_width_widens(
458 #[case] source: DecimalType,
459 #[case] target_precision: u8,
460 ) -> VortexResult<()> {
461 let target = DecimalDType::new(target_precision, 2);
462 match_each_decimal_value_type!(source, |F| {
463 let limit = ten_to_the(F::MAX_PRECISION) - i256::ONE;
465 let expected = [-limit, i256::ZERO, limit];
466 let values = to_native::<F>(&expected);
467 assert_eq!(copy_as_i256(&values, &Mask::new_true(3), target)?, expected);
468 });
469 Ok(())
470 }
471
472 #[rstest]
474 #[case::i8_to_i16(DecimalType::I8, DecimalType::I16)]
475 #[case::i8_to_i32(DecimalType::I8, DecimalType::I32)]
476 #[case::i8_to_i64(DecimalType::I8, DecimalType::I64)]
477 #[case::i8_to_i128(DecimalType::I8, DecimalType::I128)]
478 #[case::i8_to_i256(DecimalType::I8, DecimalType::I256)]
479 #[case::i16_to_i32(DecimalType::I16, DecimalType::I32)]
480 #[case::i16_to_i64(DecimalType::I16, DecimalType::I64)]
481 #[case::i16_to_i128(DecimalType::I16, DecimalType::I128)]
482 #[case::i16_to_i256(DecimalType::I16, DecimalType::I256)]
483 #[case::i32_to_i64(DecimalType::I32, DecimalType::I64)]
484 #[case::i32_to_i128(DecimalType::I32, DecimalType::I128)]
485 #[case::i32_to_i256(DecimalType::I32, DecimalType::I256)]
486 #[case::i64_to_i128(DecimalType::I64, DecimalType::I128)]
487 #[case::i64_to_i256(DecimalType::I64, DecimalType::I256)]
488 #[case::i128_to_i256(DecimalType::I128, DecimalType::I256)]
489 fn test_widen_values_sign_extends(#[case] source: DecimalType, #[case] target: DecimalType) {
490 match_each_decimal_value_type!(source, |F| {
491 let small = |value: i8| {
492 <F as BigCast>::from(value).vortex_expect("small values fit every decimal type")
493 };
494 let pattern = [F::MIN, small(-1), small(0), small(1), F::MAX];
495 let values: Vec<F> = pattern.into_iter().cycle().take(130).collect();
496
497 match_each_decimal_value_type!(target, |W| {
498 let expected: Vec<W> = values
499 .iter()
500 .map(|&value| {
501 <W as BigCast>::from(value)
502 .vortex_expect("W is at least as wide as F, so every value fits")
503 })
504 .collect();
505 assert_eq!(
506 widen_values::<F, W>(&values).as_slice(),
507 expected.as_slice()
508 );
509 });
510 });
511 }
512
513 #[test]
514 #[should_panic(expected = "widen_values requires a target at least as wide as the source")]
515 fn test_widen_values_rejects_narrower_target() {
516 widen_values::<i64, i32>(&[1, 2, 3]);
517 }
518
519 #[rstest]
521 #[case::i16_to_i8(DecimalType::I16, 2)]
522 #[case::i32_to_i16(DecimalType::I32, 4)]
523 #[case::i64_to_i32(DecimalType::I64, 9)]
524 #[case::i128_to_i64(DecimalType::I128, 18)]
525 #[case::i256_to_i128(DecimalType::I256, 38)]
526 #[case::i256_to_i8(DecimalType::I256, 1)]
527 fn test_copy_to_canonical_width_narrowing_boundaries(
528 #[case] source: DecimalType,
529 #[case] target_precision: u8,
530 ) -> VortexResult<()> {
531 let target = DecimalDType::new(target_precision, 0);
532 let limit = ten_to_the(target_precision);
533 let inside = [-(limit - i256::ONE), limit - i256::ONE];
534 let outside = [-limit, limit];
535
536 match_each_decimal_value_type!(source, |F| {
537 let values = to_native::<F>(&inside);
538 assert_eq!(copy_as_i256(&values, &Mask::new_true(2), target)?, inside);
539
540 for value in to_native::<F>(&outside) {
541 assert!(copy_to_canonical_width(&[value], &Mask::new_true(1), target).is_err());
542 }
543 });
544 Ok(())
545 }
546
547 #[test]
548 fn test_copy_to_canonical_width_zeros_null_slots() -> VortexResult<()> {
549 let values = [12_345i128, 10i128.pow(30), -99_999, 100_000];
552 let validity = Mask::from_iter([true, false, true, false]);
553
554 let copy = copy_as_i256(&values, &validity, DecimalDType::new(5, 2))?;
555 assert_eq!(copy, [12_345, 0, -99_999, 0].map(i256::from_i128));
556 Ok(())
557 }
558
559 #[test]
560 fn test_copy_to_canonical_width_error_names_row() {
561 let values = [1i64, 1_000_000, 1_000, 5_000];
563 let validity = Mask::from_iter([true, false, true, true]);
564
565 let error = copy_to_canonical_width(&values, &validity, DecimalDType::new(3, 0))
566 .expect_err("row 2 is outside the precision")
567 .to_string();
568 assert!(error.contains("row 2"), "{error}");
569 assert!(error.contains("got 1000"), "{error}");
570 assert!(error.contains("decimal(3,0)"), "{error}");
571 }
572
573 #[test]
574 fn test_copy_to_canonical_width_all_null() -> VortexResult<()> {
575 let values = [10i128.pow(30), i128::MIN, 7];
576 let copy = copy_as_i256(&values, &Mask::new_false(3), DecimalDType::new(5, 2))?;
577 assert_eq!(copy, [i256::ZERO; 3]);
578 Ok(())
579 }
580
581 #[rstest]
583 fn test_copy_to_canonical_width_length_mismatch(#[values(4, 18)] target_precision: u8) {
584 let target = DecimalDType::new(target_precision, 0);
585 let result = copy_to_canonical_width(&[1i32, 2, 3], &Mask::new_true(2), target);
586 assert!(result.is_err());
587 }
588
589 #[rstest]
591 #[case::i8(DecimalType::I8, 2)]
592 #[case::i16(DecimalType::I16, 4)]
593 #[case::i32(DecimalType::I32, 9)]
594 #[case::i64(DecimalType::I64, 18)]
595 #[case::i128(DecimalType::I128, 38)]
596 #[case::i256(DecimalType::I256, 76)]
597 #[case::i128_below_max_precision(DecimalType::I128, 5)]
598 fn test_check_precision_boundaries(
599 #[case] values_type: DecimalType,
600 #[case] precision: u8,
601 ) -> VortexResult<()> {
602 let decimal_dtype = DecimalDType::new(precision, 0);
603 let limit = ten_to_the(precision);
604 let inside = [-(limit - i256::ONE), limit - i256::ONE];
605 let outside = [-limit, limit];
606
607 match_each_decimal_value_type!(values_type, |T| {
608 check_precision(&to_native::<T>(&inside), &Mask::new_true(2), decimal_dtype)?;
609
610 for value in to_native::<T>(&outside) {
611 assert!(check_precision(&[value], &Mask::new_true(1), decimal_dtype).is_err());
612 }
613 });
614 Ok(())
615 }
616
617 #[test]
619 fn test_check_precision_above_max_precision_of_values_type() -> VortexResult<()> {
620 let all_valid = Mask::new_true(2);
621 check_precision(&[i8::MIN, i8::MAX], &all_valid, DecimalDType::new(3, 0))?;
622 check_precision(&[i64::MIN, i64::MAX], &all_valid, DecimalDType::new(19, 0))?;
623 Ok(())
624 }
625
626 #[test]
627 fn test_check_precision_ignores_null_slots() -> VortexResult<()> {
628 let values = [5i32, 1_000_000_000, -7];
629 let validity = Mask::from_iter([true, false, true]);
630 let decimal_dtype = DecimalDType::new(4, 0);
631
632 check_precision(&values, &validity, decimal_dtype)?;
633 check_precision(&values, &Mask::new_false(3), decimal_dtype)?;
634 Ok(())
635 }
636}