1use crate::cast::*;
6use crate::parse::{DecimalParseError, parse_decimal_checked};
7
8pub trait DecimalCast: Sized {
11 fn to_i32(self) -> Option<i32>;
13
14 fn to_i64(self) -> Option<i64>;
16
17 fn to_i128(self) -> Option<i128>;
19
20 fn to_i256(self) -> Option<i256>;
22
23 fn from_decimal<T: DecimalCast>(n: T) -> Option<Self>;
25
26 fn from_f64(n: f64) -> Option<Self>;
28
29 fn mul_checked_opt(self, rhs: Self) -> Option<Self>
34 where
35 Self: ArrowNativeTypeOp,
36 {
37 self.mul_checked(rhs).ok()
38 }
39}
40
41impl DecimalCast for i32 {
42 fn to_i32(self) -> Option<i32> {
43 Some(self)
44 }
45
46 fn to_i64(self) -> Option<i64> {
47 Some(self as i64)
48 }
49
50 fn to_i128(self) -> Option<i128> {
51 Some(self as i128)
52 }
53
54 fn to_i256(self) -> Option<i256> {
55 Some(i256::from_i128(self as i128))
56 }
57
58 fn from_decimal<T: DecimalCast>(n: T) -> Option<Self> {
59 n.to_i32()
60 }
61
62 fn from_f64(n: f64) -> Option<Self> {
63 n.to_i32()
64 }
65
66 #[inline]
67 fn mul_checked_opt(self, rhs: Self) -> Option<Self> {
68 self.checked_mul(rhs)
69 }
70}
71
72impl DecimalCast for i64 {
73 fn to_i32(self) -> Option<i32> {
74 i32::try_from(self).ok()
75 }
76
77 fn to_i64(self) -> Option<i64> {
78 Some(self)
79 }
80
81 fn to_i128(self) -> Option<i128> {
82 Some(self as i128)
83 }
84
85 fn to_i256(self) -> Option<i256> {
86 Some(i256::from_i128(self as i128))
87 }
88
89 fn from_decimal<T: DecimalCast>(n: T) -> Option<Self> {
90 n.to_i64()
91 }
92
93 fn from_f64(n: f64) -> Option<Self> {
94 num_traits::ToPrimitive::to_i64(&n)
97 }
98
99 #[inline]
100 fn mul_checked_opt(self, rhs: Self) -> Option<Self> {
101 self.checked_mul(rhs)
102 }
103}
104
105impl DecimalCast for i128 {
106 fn to_i32(self) -> Option<i32> {
107 i32::try_from(self).ok()
108 }
109
110 fn to_i64(self) -> Option<i64> {
111 i64::try_from(self).ok()
112 }
113
114 fn to_i128(self) -> Option<i128> {
115 Some(self)
116 }
117
118 fn to_i256(self) -> Option<i256> {
119 Some(i256::from_i128(self))
120 }
121
122 fn from_decimal<T: DecimalCast>(n: T) -> Option<Self> {
123 n.to_i128()
124 }
125
126 fn from_f64(n: f64) -> Option<Self> {
127 n.to_i128()
128 }
129
130 #[inline]
131 fn mul_checked_opt(self, rhs: Self) -> Option<Self> {
132 self.checked_mul(rhs)
133 }
134}
135
136impl DecimalCast for i256 {
137 fn to_i32(self) -> Option<i32> {
138 self.to_i128().map(|x| i32::try_from(x).ok())?
139 }
140
141 fn to_i64(self) -> Option<i64> {
142 self.to_i128().map(|x| i64::try_from(x).ok())?
143 }
144
145 fn to_i128(self) -> Option<i128> {
146 self.to_i128()
147 }
148
149 fn to_i256(self) -> Option<i256> {
150 Some(self)
151 }
152
153 fn from_decimal<T: DecimalCast>(n: T) -> Option<Self> {
154 n.to_i256()
155 }
156
157 fn from_f64(n: f64) -> Option<Self> {
158 i256::from_f64(n)
159 }
160
161 #[inline]
162 fn mul_checked_opt(self, rhs: Self) -> Option<Self> {
163 self.checked_mul(rhs)
164 }
165}
166
167#[expect(clippy::type_complexity)]
179fn make_upscaler<I: DecimalType, O: DecimalType>(
180 input_precision: u8,
181 input_scale: i8,
182 output_precision: u8,
183 output_scale: i8,
184) -> Option<(
185 impl Fn(I::Native) -> Option<O::Native>,
186 Option<impl Fn(I::Native) -> O::Native>,
187)>
188where
189 I::Native: DecimalCast + ArrowNativeTypeOp,
190 O::Native: DecimalCast + ArrowNativeTypeOp,
191{
192 let delta_scale = output_scale as i16 - input_scale as i16;
193
194 let max = O::MAX_FOR_EACH_PRECISION.get(delta_scale as usize)?;
199 let mul = max.add_wrapping(O::Native::ONE);
200 let f_fallible = move |x| O::Native::from_decimal(x)?.mul_checked_opt(mul);
201
202 let is_infallible_cast = (input_precision as i16) + delta_scale <= (output_precision as i16);
209 let f_infallible = is_infallible_cast
210 .then_some(move |x| O::Native::from_decimal(x).unwrap().mul_wrapping(mul));
211 Some((f_fallible, f_infallible))
212}
213
214#[expect(clippy::type_complexity)]
228fn make_downscaler<I: DecimalType, O: DecimalType>(
229 input_precision: u8,
230 input_scale: i8,
231 output_precision: u8,
232 output_scale: i8,
233) -> Option<(
234 impl Fn(I::Native) -> Option<O::Native>,
235 Option<impl Fn(I::Native) -> O::Native>,
236)>
237where
238 I::Native: DecimalCast + ArrowNativeTypeOp,
239 O::Native: DecimalCast + ArrowNativeTypeOp,
240{
241 let delta_scale = input_scale as i16 - output_scale as i16;
242
243 let max = I::MAX_FOR_EACH_PRECISION.get(delta_scale as usize)?;
250
251 let div = max.add_wrapping(I::Native::ONE);
252 let half = div.div_wrapping(I::Native::ONE.add_wrapping(I::Native::ONE));
253 let half_neg = half.neg_wrapping();
254
255 let f_fallible = move |x: I::Native| {
256 let (d, r) = x.div_rem_wrapping(div);
258
259 let adjusted = if x >= I::Native::ZERO {
262 std::hint::select_unpredictable(r >= half, d.add_wrapping(I::Native::ONE), d)
263 } else {
264 std::hint::select_unpredictable(r <= half_neg, d.sub_wrapping(I::Native::ONE), d)
265 };
266 O::Native::from_decimal(adjusted)
267 };
268
269 let is_infallible_cast = (input_precision as i16) - delta_scale < (output_precision as i16);
280 let f_infallible = is_infallible_cast.then_some(move |x| f_fallible(x).unwrap());
281 Some((f_fallible, f_infallible))
282}
283
284fn apply_rescaler<I: DecimalType, O: DecimalType>(
288 value: I::Native,
289 output_precision: u8,
290 f: impl Fn(I::Native) -> Option<O::Native>,
291 f_infallible: Option<impl Fn(I::Native) -> O::Native>,
292) -> Option<O::Native>
293where
294 I::Native: DecimalCast,
295 O::Native: DecimalCast,
296{
297 if let Some(f_infallible) = f_infallible {
298 Some(f_infallible(value))
299 } else {
300 f(value).filter(|v| O::is_valid_decimal_precision(*v, output_precision))
301 }
302}
303
304pub fn rescale_decimal<I: DecimalType, O: DecimalType>(
320 value: I::Native,
321 input_precision: u8,
322 input_scale: i8,
323 output_precision: u8,
324 output_scale: i8,
325) -> Option<O::Native>
326where
327 I::Native: DecimalCast + ArrowNativeTypeOp,
328 O::Native: DecimalCast + ArrowNativeTypeOp,
329{
330 validate_decimal_precision_and_scale::<I>(input_precision, input_scale).ok()?;
331 validate_decimal_precision_and_scale::<O>(output_precision, output_scale).ok()?;
332
333 if input_scale <= output_scale {
334 if let Some((f, f_infallible)) =
335 make_upscaler::<I, O>(input_precision, input_scale, output_precision, output_scale)
336 {
337 apply_rescaler::<I, O>(value, output_precision, f, f_infallible)
338 } else {
339 (value == I::Native::ZERO).then_some(O::Native::ZERO)
341 }
342 } else {
343 let Some((f, f_infallible)) =
344 make_downscaler::<I, O>(input_precision, input_scale, output_precision, output_scale)
345 else {
346 return Some(O::Native::ZERO);
348 };
349 apply_rescaler::<I, O>(value, output_precision, f, f_infallible)
350 }
351}
352
353fn cast_decimal_to_decimal_error<I, O>(
354 output_precision: u8,
355 output_scale: i8,
356) -> impl Fn(<I as ArrowPrimitiveType>::Native) -> ArrowError
357where
358 I: DecimalType,
359 O: DecimalType,
360 I::Native: DecimalCast + ArrowNativeTypeOp,
361 O::Native: DecimalCast + ArrowNativeTypeOp,
362{
363 move |x: I::Native| {
364 ArrowError::CastError(format!(
365 "Cannot cast to {}({}, {}). Overflowing on {:?}",
366 O::PREFIX,
367 output_precision,
368 output_scale,
369 x
370 ))
371 }
372}
373
374fn apply_decimal_cast<I: DecimalType, O: DecimalType>(
375 array: &PrimitiveArray<I>,
376 output_precision: u8,
377 output_scale: i8,
378 f_fallible: impl Fn(I::Native) -> Option<O::Native>,
379 f_infallible: Option<impl Fn(I::Native) -> O::Native>,
380 cast_options: &CastOptions,
381) -> Result<PrimitiveArray<O>, ArrowError>
382where
383 I::Native: DecimalCast + ArrowNativeTypeOp,
384 O::Native: DecimalCast + ArrowNativeTypeOp,
385{
386 let array = if let Some(f_infallible) = f_infallible {
387 array.unary(f_infallible)
388 } else if cast_options.safe {
389 array.unary_opt(|x| {
390 f_fallible(x).filter(|v| O::is_valid_decimal_precision(*v, output_precision))
391 })
392 } else {
393 let error = cast_decimal_to_decimal_error::<I, O>(output_precision, output_scale);
394 array.try_unary(|x| {
395 let v = f_fallible(x).ok_or_else(|| error(x))?;
396 O::validate_decimal_precision(v, output_precision, output_scale).map(|()| v)
397 })?
398 };
399 Ok(array)
400}
401
402fn convert_to_smaller_scale_decimal<I, O>(
403 array: &PrimitiveArray<I>,
404 input_precision: u8,
405 input_scale: i8,
406 output_precision: u8,
407 output_scale: i8,
408 cast_options: &CastOptions,
409) -> Result<PrimitiveArray<O>, ArrowError>
410where
411 I: DecimalType,
412 O: DecimalType,
413 I::Native: DecimalCast + ArrowNativeTypeOp,
414 O::Native: DecimalCast + ArrowNativeTypeOp,
415{
416 if let Some((f_fallible, f_infallible)) =
417 make_downscaler::<I, O>(input_precision, input_scale, output_precision, output_scale)
418 {
419 apply_decimal_cast(
420 array,
421 output_precision,
422 output_scale,
423 f_fallible,
424 f_infallible,
425 cast_options,
426 )
427 } else {
428 let zeros = vec![O::Native::ZERO; array.len()];
430 Ok(PrimitiveArray::new(zeros.into(), array.nulls().cloned()))
431 }
432}
433
434fn convert_to_bigger_or_equal_scale_decimal<I, O>(
435 array: &PrimitiveArray<I>,
436 input_precision: u8,
437 input_scale: i8,
438 output_precision: u8,
439 output_scale: i8,
440 cast_options: &CastOptions,
441) -> Result<PrimitiveArray<O>, ArrowError>
442where
443 I: DecimalType,
444 O: DecimalType,
445 I::Native: DecimalCast + ArrowNativeTypeOp,
446 O::Native: DecimalCast + ArrowNativeTypeOp,
447{
448 if let Some((f, f_infallible)) =
449 make_upscaler::<I, O>(input_precision, input_scale, output_precision, output_scale)
450 {
451 apply_decimal_cast(
452 array,
453 output_precision,
454 output_scale,
455 f,
456 f_infallible,
457 cast_options,
458 )
459 } else {
460 let f_fallible = move |x| (x == I::Native::ZERO).then_some(O::Native::ZERO);
463 apply_decimal_cast(
464 array,
465 output_precision,
466 output_scale,
467 f_fallible,
468 None::<fn(I::Native) -> O::Native>,
469 cast_options,
470 )
471 }
472}
473
474pub(crate) fn cast_decimal_to_decimal_same_type<T>(
476 array: &PrimitiveArray<T>,
477 input_precision: u8,
478 input_scale: i8,
479 output_precision: u8,
480 output_scale: i8,
481 cast_options: &CastOptions,
482) -> Result<ArrayRef, ArrowError>
483where
484 T: DecimalType,
485 T::Native: DecimalCast + ArrowNativeTypeOp,
486{
487 let array: PrimitiveArray<T> =
488 if input_scale == output_scale && input_precision <= output_precision {
489 array.clone()
490 } else if input_scale <= output_scale {
491 convert_to_bigger_or_equal_scale_decimal::<T, T>(
492 array,
493 input_precision,
494 input_scale,
495 output_precision,
496 output_scale,
497 cast_options,
498 )?
499 } else {
500 convert_to_smaller_scale_decimal::<T, T>(
502 array,
503 input_precision,
504 input_scale,
505 output_precision,
506 output_scale,
507 cast_options,
508 )?
509 };
510
511 Ok(Arc::new(array.with_precision_and_scale(
512 output_precision,
513 output_scale,
514 )?))
515}
516
517pub(crate) fn cast_decimal_to_decimal<I, O>(
519 array: &PrimitiveArray<I>,
520 input_precision: u8,
521 input_scale: i8,
522 output_precision: u8,
523 output_scale: i8,
524 cast_options: &CastOptions,
525) -> Result<ArrayRef, ArrowError>
526where
527 I: DecimalType,
528 O: DecimalType,
529 I::Native: DecimalCast + ArrowNativeTypeOp,
530 O::Native: DecimalCast + ArrowNativeTypeOp,
531{
532 let array: PrimitiveArray<O> = if input_scale > output_scale {
533 convert_to_smaller_scale_decimal::<I, O>(
534 array,
535 input_precision,
536 input_scale,
537 output_precision,
538 output_scale,
539 cast_options,
540 )?
541 } else {
542 convert_to_bigger_or_equal_scale_decimal::<I, O>(
543 array,
544 input_precision,
545 input_scale,
546 output_precision,
547 output_scale,
548 cast_options,
549 )?
550 };
551
552 Ok(Arc::new(array.with_precision_and_scale(
553 output_precision,
554 output_scale,
555 )?))
556}
557
558#[deprecated(
567 since = "60.0.0",
568 note = "Use `arrow_cast::parse::parse_decimal` instead"
569)]
570pub fn parse_string_to_decimal_native<T: DecimalType>(
571 value_str: &str,
572 scale: usize,
573) -> Result<T::Native, ArrowError> {
574 let overflow = || {
575 ArrowError::InvalidArgumentError(format!(
576 "Cannot convert {value_str} to {}: Overflow",
577 T::PREFIX
578 ))
579 };
580 let scale = i8::try_from(scale).map_err(|_| overflow())?;
581 parse_decimal_checked::<T>(value_str, T::MAX_PRECISION, scale).map_err(|e| match e {
582 DecimalParseError::InvalidFormat => {
583 ArrowError::InvalidArgumentError(format!("Invalid decimal format: {value_str:?}"))
584 }
585 DecimalParseError::Overflow => overflow(),
586 })
587}
588
589pub(crate) fn generic_string_to_decimal_cast<'a, T, S>(
590 from: &'a S,
591 precision: u8,
592 scale: i8,
593 cast_options: &CastOptions,
594) -> Result<PrimitiveArray<T>, ArrowError>
595where
596 T: DecimalType,
597 &'a S: StringArrayType<'a>,
598{
599 if cast_options.safe {
600 let iter = from
601 .iter()
602 .map(|v| parse_decimal_checked::<T>(v?, precision, scale).ok());
603 Ok(unsafe {
609 PrimitiveArray::<T>::from_trusted_len_iter(iter)
610 .with_precision_and_scale(precision, scale)?
611 })
612 } else {
613 let mut builder = PrimitiveBuilder::<T>::with_capacity(from.len());
614 for v in from.iter() {
615 match v {
616 Some(v) => {
617 let v = parse_decimal_checked::<T>(v, precision, scale).map_err(|e| {
618 let reason = match e {
619 DecimalParseError::InvalidFormat => "invalid decimal format",
620 DecimalParseError::Overflow => "value does not fit",
621 };
622 ArrowError::CastError(format!(
623 "Cannot cast string '{v}' to value of {}({precision}, {scale}) type: {reason}",
624 T::PREFIX,
625 ))
626 })?;
627 builder.append_value(v);
628 }
629 None => builder.append_null(),
630 }
631 }
632 builder.finish().with_precision_and_scale(precision, scale)
633 }
634}
635
636pub(crate) fn string_to_decimal_cast<T: DecimalType, Offset: OffsetSizeTrait>(
637 from: &GenericStringArray<Offset>,
638 precision: u8,
639 scale: i8,
640 cast_options: &CastOptions,
641) -> Result<PrimitiveArray<T>, ArrowError> {
642 generic_string_to_decimal_cast::<T, GenericStringArray<Offset>>(
643 from,
644 precision,
645 scale,
646 cast_options,
647 )
648}
649
650pub(crate) fn string_view_to_decimal_cast<T: DecimalType>(
651 from: &StringViewArray,
652 precision: u8,
653 scale: i8,
654 cast_options: &CastOptions,
655) -> Result<PrimitiveArray<T>, ArrowError> {
656 generic_string_to_decimal_cast::<T, StringViewArray>(from, precision, scale, cast_options)
657}
658
659pub(crate) fn cast_string_to_decimal<T: DecimalType, Offset: OffsetSizeTrait>(
661 from: &dyn Array,
662 precision: u8,
663 scale: i8,
664 cast_options: &CastOptions,
665) -> Result<ArrayRef, ArrowError> {
666 validate_decimal_precision_and_scale::<T>(precision, scale)?;
667
668 let result = match from.data_type() {
669 DataType::Utf8View => string_view_to_decimal_cast::<T>(
670 from.as_any().downcast_ref::<StringViewArray>().unwrap(),
671 precision,
672 scale,
673 cast_options,
674 )?,
675 DataType::Utf8 | DataType::LargeUtf8 => string_to_decimal_cast::<T, Offset>(
676 from.as_any()
677 .downcast_ref::<GenericStringArray<Offset>>()
678 .unwrap(),
679 precision,
680 scale,
681 cast_options,
682 )?,
683 _ => unreachable!(
684 "cast_to_decimal only calls cast_string_to_decimal for Utf8, LargeUtf8, or Utf8View"
685 ),
686 };
687
688 Ok(Arc::new(result))
689}
690
691pub(crate) fn cast_floating_point_to_decimal<T: ArrowPrimitiveType, D>(
692 array: &PrimitiveArray<T>,
693 precision: u8,
694 scale: i8,
695 cast_options: &CastOptions,
696) -> Result<ArrayRef, ArrowError>
697where
698 <T as ArrowPrimitiveType>::Native: AsPrimitive<f64>,
699 D: DecimalType + ArrowPrimitiveType,
700 <D as ArrowPrimitiveType>::Native: DecimalCast,
701{
702 validate_decimal_precision_and_scale::<D>(precision, scale)?;
703 let mul = 10_f64.powi(scale as i32);
704
705 if cast_options.safe {
706 array
707 .unary_opt::<_, D>(|v| float_to_decimal_checked::<D>(v.as_(), mul, precision).ok())
708 .with_precision_and_scale(precision, scale)
709 .map(|a| Arc::new(a) as ArrayRef)
710 } else {
711 array
712 .try_unary::<_, D, _>(|v| {
713 float_to_decimal_checked::<D>(v.as_(), mul, precision)
714 .map_err(|e| e.into_arrow_error(v, precision, scale))
715 })?
716 .with_precision_and_scale(precision, scale)
717 .map(|a| Arc::new(a) as ArrayRef)
718 }
719}
720
721#[inline]
736pub fn float_to_decimal<D>(input: f64, precision: u8, scale: i8) -> Result<D::Native, ArrowError>
737where
738 D: DecimalType,
739 D::Native: DecimalCast,
740{
741 validate_decimal_precision_and_scale::<D>(precision, scale)?;
742 float_to_decimal_checked::<D>(input, 10_f64.powi(scale as i32), precision)
743 .map_err(|e| e.into_arrow_error(input, precision, scale))
744}
745
746pub fn float_to_decimal_opt<D>(input: f64, precision: u8, scale: i8) -> Option<D::Native>
757where
758 D: DecimalType,
759 D::Native: DecimalCast,
760{
761 validate_decimal_precision_and_scale::<D>(precision, scale).ok()?;
762 float_to_decimal_checked::<D>(input, 10_f64.powi(scale as i32), precision).ok()
763}
764
765enum FloatToDecimalError<D: DecimalType> {
767 NativeOverflow,
768 PrecisionOverflow(D::Native),
769}
770
771impl<D: DecimalType> FloatToDecimalError<D> {
772 fn into_arrow_error(self, input: impl std::fmt::Debug, precision: u8, scale: i8) -> ArrowError {
773 match self {
774 Self::NativeOverflow => ArrowError::CastError(format!(
775 "Cannot cast to {}({}, {}). Overflowing on {:?}",
776 D::PREFIX,
777 precision,
778 scale,
779 input
780 )),
781 Self::PrecisionOverflow(value) => {
782 D::validate_decimal_precision(value, precision, scale).unwrap_err()
783 }
784 }
785 }
786}
787
788#[inline]
790fn float_to_decimal_checked<D>(
791 input: f64,
792 mul: f64,
793 precision: u8,
794) -> Result<D::Native, FloatToDecimalError<D>>
795where
796 D: DecimalType,
797 D::Native: DecimalCast,
798{
799 let value =
800 D::Native::from_f64((mul * input).round()).ok_or(FloatToDecimalError::NativeOverflow)?;
801 if D::is_valid_decimal_precision(value, precision) {
802 Ok(value)
803 } else {
804 Err(FloatToDecimalError::PrecisionOverflow(value))
805 }
806}
807
808#[deprecated(since = "60.0.0", note = "Use `float_to_decimal` instead")]
812#[inline(always)]
813pub fn single_float_to_decimal<D>(input: f64, mul: f64) -> Option<D::Native>
814where
815 D: DecimalType + ArrowPrimitiveType,
816 <D as ArrowPrimitiveType>::Native: DecimalCast,
817{
818 D::Native::from_f64((mul * input).round())
819}
820
821pub(crate) fn cast_decimal_to_integer<D, T>(
822 array: &dyn Array,
823 scale: i8,
824 cast_options: &CastOptions,
825) -> Result<ArrayRef, ArrowError>
826where
827 T: ArrowPrimitiveType,
828 <T as ArrowPrimitiveType>::Native: NumCast,
829 D: DecimalType + ArrowPrimitiveType,
830 <D as ArrowPrimitiveType>::Native: ToPrimitive,
831{
832 let array = array.as_primitive::<D>();
833
834 let div: D::Native = D::Native::usize_as(10)
836 .pow_checked(scale.unsigned_abs() as u32)
837 .map_err(|_| {
838 ArrowError::CastError(format!(
839 "Cannot cast to {:?}. The scale {} causes overflow.",
840 D::PREFIX,
841 scale,
842 ))
843 })?;
844
845 let mut value_builder = PrimitiveBuilder::<T>::with_capacity(array.len());
846
847 if scale < 0 {
848 match cast_options.safe {
849 true => {
850 for i in 0..array.len() {
851 if array.is_null(i) {
852 value_builder.append_null();
853 } else {
854 let v = array
855 .value(i)
856 .mul_checked(div)
857 .ok()
858 .and_then(<T::Native as NumCast>::from::<D::Native>);
859 value_builder.append_option(v);
860 }
861 }
862 }
863 false => {
864 for i in 0..array.len() {
865 if array.is_null(i) {
866 value_builder.append_null();
867 } else {
868 let v = array.value(i).mul_checked(div)?;
869
870 let value =
871 <T::Native as NumCast>::from::<D::Native>(v).ok_or_else(|| {
872 ArrowError::CastError(format!(
873 "value of {:?} is out of range {}",
874 v,
875 T::DATA_TYPE
876 ))
877 })?;
878
879 value_builder.append_value(value);
880 }
881 }
882 }
883 }
884 } else {
885 match cast_options.safe {
886 true => {
887 for i in 0..array.len() {
888 if array.is_null(i) {
889 value_builder.append_null();
890 } else {
891 let v = array.value(i).div_wrapping(div);
892 let v = <T::Native as NumCast>::from(v);
893 value_builder.append_option(v);
894 }
895 }
896 }
897 false => {
898 for i in 0..array.len() {
899 if array.is_null(i) {
900 value_builder.append_null();
901 } else {
902 let v = array.value(i).div_wrapping(div);
903
904 let value =
905 <T::Native as NumCast>::from::<D::Native>(v).ok_or_else(|| {
906 ArrowError::CastError(format!(
907 "value of {:?} is out of range {}",
908 v,
909 T::DATA_TYPE
910 ))
911 })?;
912
913 value_builder.append_value(value);
914 }
915 }
916 }
917 }
918 }
919 Ok(Arc::new(value_builder.finish()))
920}
921
922pub(crate) fn cast_decimal_to_float<D: DecimalType, T: ArrowPrimitiveType, F>(
928 array: &dyn Array,
929 op: F,
930) -> Result<ArrayRef, ArrowError>
931where
932 F: Fn(D::Native) -> T::Native,
933{
934 let array = array.as_primitive::<D>();
935 let array = array.unary::<_, T>(op);
936 Ok(Arc::new(array))
937}
938
939fn integer_to_decimal_native<I, M>(value: I) -> Option<M>
947where
948 I: Into<i128>,
949 M: DecimalCast,
950{
951 M::from_decimal(value.into())
952}
953
954fn integers_fit_digits<T>(array: &PrimitiveArray<T>, digits: u32) -> bool
960where
961 T: ArrowPrimitiveType,
962 T::Native: ArrowNativeTypeOp,
963{
964 let Ok(bound) = T::Native::usize_as(10).pow_checked(digits) else {
965 return true;
968 };
969 let hi = bound.sub_wrapping(T::Native::ONE);
970 let lo = T::Native::ZERO.sub_checked(hi).unwrap_or(T::Native::ZERO);
972
973 array
977 .values()
978 .chunks(64)
979 .all(|chunk| chunk.iter().fold(true, |ok, &v| ok & (v >= lo) & (v <= hi)))
980}
981
982fn cast_integer_to_decimal<
983 T: ArrowPrimitiveType,
984 D: DecimalType + ArrowPrimitiveType<Native = M>,
985 M,
986>(
987 array: &PrimitiveArray<T>,
988 precision: u8,
989 scale: i8,
990 cast_options: &CastOptions,
991) -> Result<ArrayRef, ArrowError>
992where
993 <T as ArrowPrimitiveType>::Native: ArrowNativeTypeOp + Into<i128>,
994 M: ArrowNativeTypeOp + DecimalCast,
995{
996 let overflow = |v: T::Native| {
997 ArrowError::CastError(format!(
998 "Cannot cast to {}({precision}, {scale}). Overflowing on {v:?}",
999 D::PREFIX,
1000 ))
1001 };
1002
1003 validate_decimal_precision_and_scale::<D>(precision, scale)?;
1006
1007 let digits = (precision as i32 - scale as i32) as u32;
1018 let all_fit = integers_fit_digits(array, digits);
1019
1020 let array = if scale < 0 {
1021 let scale_factor = T::Native::usize_as(10)
1028 .pow_checked(scale.unsigned_abs() as u32)
1029 .ok();
1030
1031 match (scale_factor, cast_options.safe) {
1032 (Some(scale_factor), _) if all_fit => array.unary::<_, D>(|v| {
1033 integer_to_decimal_native::<_, M>(v.div_wrapping(scale_factor))
1034 .expect("value fits the decimal")
1035 }),
1036 (Some(scale_factor), true) => array.unary_opt::<_, D>(|v| {
1037 let v = integer_to_decimal_native::<_, M>(v.div_wrapping(scale_factor))?;
1038 (D::is_valid_decimal_precision(v, precision)).then_some(v)
1039 }),
1040 (Some(scale_factor), false) => array.try_unary::<_, D, _>(|v| {
1041 let v = integer_to_decimal_native::<_, M>(v.div_wrapping(scale_factor))
1042 .ok_or_else(|| overflow(v))?;
1043 D::validate_decimal_precision(v, precision, scale).map(|()| v)
1044 })?,
1045 (None, _) => array.unary::<_, D>(|_| M::ZERO),
1050 }
1051 } else {
1052 let scale_factor = M::usize_as(10)
1053 .pow_checked(scale.unsigned_abs() as u32)
1054 .map_err(|_| {
1055 ArrowError::CastError(format!(
1056 "Cannot cast to {:?}({}, {}). The scale causes overflow.",
1057 D::PREFIX,
1058 precision,
1059 scale,
1060 ))
1061 })?;
1062
1063 if all_fit {
1064 array.unary::<_, D>(|v| {
1065 integer_to_decimal_native::<_, M>(v)
1066 .expect("value fits the decimal")
1067 .mul_wrapping(scale_factor)
1068 })
1069 } else if cast_options.safe {
1070 array.unary_opt::<_, D>(|v| {
1071 let v = integer_to_decimal_native::<_, M>(v)
1072 .and_then(|v| v.mul_checked_opt(scale_factor))?;
1073 (D::is_valid_decimal_precision(v, precision)).then_some(v)
1074 })
1075 } else {
1076 array.try_unary::<_, D, _>(|v| {
1077 let v = integer_to_decimal_native::<_, M>(v)
1078 .ok_or_else(|| overflow(v))
1079 .and_then(|v| v.mul_checked(scale_factor))?;
1080 D::validate_decimal_precision(v, precision, scale).map(|()| v)
1081 })?
1082 }
1083 };
1084
1085 Ok(Arc::new(array.with_precision_and_scale(precision, scale)?))
1086}
1087
1088pub(crate) fn cast_from_decimal<D, F>(
1089 array: &dyn Array,
1090 scale: &i8,
1091 from_type: &DataType,
1092 to_type: &DataType,
1093 as_float: F,
1094 cast_options: &CastOptions,
1095) -> Result<ArrayRef, ArrowError>
1096where
1097 D: DecimalType + ArrowPrimitiveType,
1098 <D as ArrowPrimitiveType>::Native: ToPrimitive,
1099 F: Fn(D::Native) -> f64,
1100{
1101 use DataType::*;
1102 match to_type {
1104 UInt8 => cast_decimal_to_integer::<D, UInt8Type>(array, *scale, cast_options),
1105 UInt16 => cast_decimal_to_integer::<D, UInt16Type>(array, *scale, cast_options),
1106 UInt32 => cast_decimal_to_integer::<D, UInt32Type>(array, *scale, cast_options),
1107 UInt64 => cast_decimal_to_integer::<D, UInt64Type>(array, *scale, cast_options),
1108 Int8 => cast_decimal_to_integer::<D, Int8Type>(array, *scale, cast_options),
1109 Int16 => cast_decimal_to_integer::<D, Int16Type>(array, *scale, cast_options),
1110 Int32 => cast_decimal_to_integer::<D, Int32Type>(array, *scale, cast_options),
1111 Int64 => cast_decimal_to_integer::<D, Int64Type>(array, *scale, cast_options),
1112 Float16 => cast_decimal_to_float::<D, Float16Type, _>(array, |x| {
1113 half::f16::from_f64(single_decimal_to_float_lossy::<D, F>(
1114 &as_float,
1115 x,
1116 <i32 as From<i8>>::from(*scale),
1117 ))
1118 }),
1119 Float32 => cast_decimal_to_f32::<D, F>(array, &as_float, *scale),
1120 Float64 => cast_decimal_to_f64::<D, F>(array, &as_float, *scale),
1121 Utf8View => value_to_string_view(array, cast_options),
1122 Utf8 => value_to_string::<i32>(array, cast_options),
1123 LargeUtf8 => value_to_string::<i64>(array, cast_options),
1124 Null => Ok(new_null_array(to_type, array.len())),
1125 _ => Err(ArrowError::InvalidArgumentError(format!(
1126 "Casting from {from_type} to {to_type} not supported"
1127 ))),
1128 }
1129}
1130
1131pub(crate) fn cast_to_decimal<D, M>(
1132 array: &dyn Array,
1133 precision: &u8,
1134 scale: &i8,
1135 from_type: &DataType,
1136 to_type: &DataType,
1137 cast_options: &CastOptions,
1138) -> Result<ArrayRef, ArrowError>
1139where
1140 D: DecimalType + ArrowPrimitiveType<Native = M>,
1141 M: ArrowNativeTypeOp + DecimalCast,
1142{
1143 use DataType::*;
1144 match from_type {
1146 UInt8 => cast_integer_to_decimal::<_, D, M>(
1147 array.as_primitive::<UInt8Type>(),
1148 *precision,
1149 *scale,
1150 cast_options,
1151 ),
1152 UInt16 => cast_integer_to_decimal::<_, D, _>(
1153 array.as_primitive::<UInt16Type>(),
1154 *precision,
1155 *scale,
1156 cast_options,
1157 ),
1158 UInt32 => cast_integer_to_decimal::<_, D, _>(
1159 array.as_primitive::<UInt32Type>(),
1160 *precision,
1161 *scale,
1162 cast_options,
1163 ),
1164 UInt64 => cast_integer_to_decimal::<_, D, _>(
1165 array.as_primitive::<UInt64Type>(),
1166 *precision,
1167 *scale,
1168 cast_options,
1169 ),
1170 Int8 => cast_integer_to_decimal::<_, D, _>(
1171 array.as_primitive::<Int8Type>(),
1172 *precision,
1173 *scale,
1174 cast_options,
1175 ),
1176 Int16 => cast_integer_to_decimal::<_, D, _>(
1177 array.as_primitive::<Int16Type>(),
1178 *precision,
1179 *scale,
1180 cast_options,
1181 ),
1182 Int32 => cast_integer_to_decimal::<_, D, _>(
1183 array.as_primitive::<Int32Type>(),
1184 *precision,
1185 *scale,
1186 cast_options,
1187 ),
1188 Int64 => cast_integer_to_decimal::<_, D, _>(
1189 array.as_primitive::<Int64Type>(),
1190 *precision,
1191 *scale,
1192 cast_options,
1193 ),
1194 Float16 => cast_floating_point_to_decimal::<_, D>(
1195 array.as_primitive::<Float16Type>(),
1196 *precision,
1197 *scale,
1198 cast_options,
1199 ),
1200 Float32 => cast_floating_point_to_decimal::<_, D>(
1201 array.as_primitive::<Float32Type>(),
1202 *precision,
1203 *scale,
1204 cast_options,
1205 ),
1206 Float64 => cast_floating_point_to_decimal::<_, D>(
1207 array.as_primitive::<Float64Type>(),
1208 *precision,
1209 *scale,
1210 cast_options,
1211 ),
1212 Utf8View | Utf8 => {
1213 cast_string_to_decimal::<D, i32>(array, *precision, *scale, cast_options)
1214 }
1215 LargeUtf8 => cast_string_to_decimal::<D, i64>(array, *precision, *scale, cast_options),
1216 Null => Ok(new_null_array(to_type, array.len())),
1217 _ => Err(ArrowError::InvalidArgumentError(format!(
1218 "Casting from {from_type} to {to_type} not supported"
1219 ))),
1220 }
1221}
1222
1223#[cfg(test)]
1224mod tests {
1225 use super::*;
1226
1227 #[test]
1228 fn test_float_to_decimal() {
1229 fn check<D: DecimalType>()
1230 where
1231 D::Native: DecimalCast,
1232 {
1233 for (input, scale, expected) in [
1234 (12.345, 2, 1235),
1235 (-12.345, 2, -1235),
1236 (999.99, 2, 99999),
1237 (-999.99, 2, -99999),
1238 (99999.25, 0, 99999),
1239 (999992.5, -1, 99999),
1240 (0.0, 2, 0),
1241 ] {
1242 assert_eq!(
1243 float_to_decimal_opt::<D>(input, 5, scale),
1244 float_to_decimal::<D>(input, 5, scale).ok(),
1245 );
1246 assert_eq!(
1247 float_to_decimal::<D>(input, 5, scale)
1248 .unwrap()
1249 .to_i128()
1250 .unwrap(),
1251 expected,
1252 );
1253 }
1254 for (input, scale) in [
1255 (12345.678, 2),
1256 (-12345.678, 2),
1257 (999.9975, 2),
1258 (-999.9975, 2),
1259 (99999.75, 0),
1260 (-99999.75, 0),
1261 (999997.5, -1),
1262 (-999997.5, -1),
1263 (f64::NAN, 0),
1264 (f64::INFINITY, 0),
1265 (f64::NEG_INFINITY, 0),
1266 (f64::MAX, 0),
1267 ] {
1268 assert!(float_to_decimal::<D>(input, 5, scale).is_err());
1269 assert!(float_to_decimal_opt::<D>(input, 5, scale).is_none());
1270 }
1271 for (precision, scale) in [(0, 0), (D::MAX_PRECISION + 1, 0), (5, 6)] {
1272 assert!(float_to_decimal::<D>(0.0, precision, scale).is_err());
1273 assert!(float_to_decimal_opt::<D>(0.0, precision, scale).is_none());
1274 }
1275 }
1276 check::<Decimal32Type>();
1277 check::<Decimal64Type>();
1278 check::<Decimal128Type>();
1279 check::<Decimal256Type>();
1280 }
1281
1282 #[test]
1283 #[expect(deprecated)]
1284 fn test_single_float_to_decimal_preserves_native_range() {
1285 for (input, expected) in [
1288 (1_000_000_000.0, 1_000_000_000),
1289 (-1_000_000_000.0, -1_000_000_000),
1290 (999_999_999.75, 1_000_000_000),
1291 (-999_999_999.75, -1_000_000_000),
1292 ] {
1293 assert_eq!(
1294 single_float_to_decimal::<Decimal32Type>(input, 1.0),
1295 Some(expected)
1296 );
1297 assert!(float_to_decimal::<Decimal32Type>(input, 9, 0).is_err());
1298 }
1299 assert_eq!(
1300 single_float_to_decimal::<Decimal32Type>(999_999_999.0, 1.0),
1301 Some(999_999_999),
1302 );
1303 assert_eq!(
1304 single_float_to_decimal::<Decimal32Type>(12.345, 100.0),
1305 Some(1235)
1306 );
1307 assert_eq!(
1308 single_float_to_decimal::<Decimal32Type>(f64::MAX, 1.0),
1309 None
1310 );
1311 }
1312
1313 #[test]
1314 #[expect(deprecated)]
1315 fn test_parse_string_to_decimal_native() {
1316 assert_eq!(
1317 parse_string_to_decimal_native::<Decimal128Type>("123.456", 2).unwrap(),
1318 12346
1319 );
1320 assert_eq!(
1323 parse_string_to_decimal_native::<Decimal128Type>(&"9".repeat(38), 0).unwrap(),
1324 10_i128.pow(38) - 1
1325 );
1326 assert!(
1327 parse_string_to_decimal_native::<Decimal128Type>(&i128::MAX.to_string(), 0).is_err()
1328 );
1329 assert_eq!(
1330 parse_string_to_decimal_native::<Decimal128Type>("abc", 2)
1331 .unwrap_err()
1332 .to_string(),
1333 "Invalid argument error: Invalid decimal format: \"abc\""
1334 );
1335 assert_eq!(
1336 parse_string_to_decimal_native::<Decimal32Type>("1", 10)
1337 .unwrap_err()
1338 .to_string(),
1339 "Invalid argument error: Cannot convert 1 to Decimal32: Overflow"
1340 );
1341 }
1342
1343 #[test]
1344 fn test_rescale_decimal_upscale_within_precision() {
1345 let result = rescale_decimal::<Decimal128Type, Decimal128Type>(
1346 12_345_i128, 5,
1348 2,
1349 8,
1350 5,
1351 );
1352 assert_eq!(result, Some(12_345_000_i128));
1353 }
1354
1355 #[test]
1356 fn test_rescale_decimal_downscale_rounds_half_away_from_zero() {
1357 let positive = rescale_decimal::<Decimal128Type, Decimal128Type>(
1358 1_050_i128, 5, 3, 5, 1,
1360 );
1361 assert_eq!(positive, Some(11_i128)); let negative = rescale_decimal::<Decimal128Type, Decimal128Type>(
1364 -1_050_i128, 5,
1366 3,
1367 5,
1368 1,
1369 );
1370 assert_eq!(negative, Some(-11_i128)); }
1372
1373 #[test]
1374 fn test_rescale_decimal_downscale_large_delta_returns_zero() {
1375 let result = rescale_decimal::<Decimal32Type, Decimal32Type>(12_345_i32, 9, 9, 9, 4);
1376 assert_eq!(result, Some(0_i32));
1377 }
1378
1379 #[test]
1380 fn test_rescale_decimal_upscale_overflow_returns_none() {
1381 let result = rescale_decimal::<Decimal32Type, Decimal32Type>(9_999_i32, 4, 0, 5, 2);
1382 assert_eq!(result, None);
1383 }
1384
1385 #[test]
1386 fn test_rescale_decimal256_extreme_scales() {
1387 assert_eq!(
1388 rescale_decimal::<Decimal256Type, Decimal256Type>(i256::ONE, 76, -76, 76, 0),
1389 None
1390 );
1391 assert_eq!(
1392 rescale_decimal::<Decimal256Type, Decimal256Type>(i256::ZERO, 76, -76, 76, 0),
1393 Some(i256::ZERO)
1394 );
1395 assert_eq!(
1396 rescale_decimal::<Decimal256Type, Decimal256Type>(i256::ONE, 76, i8::MIN, 76, 76),
1397 None
1398 );
1399 assert_eq!(
1400 rescale_decimal::<Decimal256Type, Decimal256Type>(i256::ONE, 76, 76, 76, i8::MIN),
1401 Some(i256::ZERO)
1402 );
1403 }
1404
1405 #[test]
1406 fn test_rescale_decimal_invalid_input_precision_scale_returns_none() {
1407 let result = rescale_decimal::<Decimal128Type, Decimal128Type>(123_i128, 39, 39, 38, 38);
1408 assert_eq!(result, None);
1409 }
1410
1411 #[test]
1412 fn test_rescale_decimal_invalid_output_precision_scale_returns_none() {
1413 let result = rescale_decimal::<Decimal128Type, Decimal128Type>(123_i128, 38, 38, 39, 39);
1414 assert_eq!(result, None);
1415 }
1416
1417 #[test]
1418 fn test_rescale_decimal_upscale_large_delta() {
1419 let zero = rescale_decimal::<Decimal128Type, Decimal128Type>(0_i128, 5, -2, 38, 38);
1421 assert_eq!(zero, Some(0_i128));
1422
1423 let non_zero = rescale_decimal::<Decimal128Type, Decimal128Type>(1_i128, 5, -2, 38, 38);
1424 assert_eq!(non_zero, None);
1425
1426 let negative = rescale_decimal::<Decimal128Type, Decimal128Type>(-1_i128, 5, -2, 38, 38);
1427 assert_eq!(negative, None);
1428
1429 let zero_d32 = rescale_decimal::<Decimal32Type, Decimal32Type>(0_i32, 3, -10, 9, 9);
1431 assert_eq!(zero_d32, Some(0_i32));
1432
1433 let non_zero_d32 = rescale_decimal::<Decimal32Type, Decimal32Type>(1_i32, 3, -10, 9, 9);
1434 assert_eq!(non_zero_d32, None);
1435 }
1436}