tustvold commented on code in PR #3040:
URL: https://github.com/apache/arrow-rs/pull/3040#discussion_r1016054603


##########
arrow-cast/src/cast.rs:
##########
@@ -433,34 +434,52 @@ fn cast_reinterpret_arrays<
     ))
 }
 
-// cast the decimal array to integer array
-macro_rules! cast_decimal_to_integer {
-    ($ARRAY:expr, $SCALE : ident, $VALUE_BUILDER: ident, $NATIVE_TYPE : ident, 
$DATA_TYPE : expr) => {{
-        let array = $ARRAY.as_any().downcast_ref::<Decimal128Array>().unwrap();
-        let mut value_builder = $VALUE_BUILDER::with_capacity(array.len());
-        let div: i128 = 10_i128.pow(*$SCALE as u32);
-        let min_bound = ($NATIVE_TYPE::MIN) as i128;
-        let max_bound = ($NATIVE_TYPE::MAX) as i128;
-        for i in 0..array.len() {
-            if array.is_null(i) {
-                value_builder.append_null();
+fn cast_decimal_to_integer<D, T>(
+    array: &ArrayRef,
+    base: D::Native,
+    scale: u8,
+    max_bound: D::Native,
+    min_bound: D::Native,
+) -> Result<ArrayRef, ArrowError>
+where
+    T: ArrowPrimitiveType,
+    <T as ArrowPrimitiveType>::Native: NumCast,
+    D: DecimalType + ArrowPrimitiveType,
+    <D as ArrowPrimitiveType>::Native: ArrowNativeTypeOp + ToPrimitive,
+{
+    let array = array.as_any().downcast_ref::<PrimitiveArray<D>>().unwrap();
+
+    let div: D::Native = base.pow_checked(scale as u32).map_err(|_| {
+        ArrowError::CastError(format!(
+            "Cannot cast to {:?}. The scale {} causes overflow.",
+            D::PREFIX,
+            scale,
+        ))
+    })?;
+
+    let mut value_builder = PrimitiveBuilder::<T>::with_capacity(array.len());
+    for i in 0..array.len() {
+        if array.is_null(i) {
+            value_builder.append_null();
+        } else {
+            let v = array.value(i).div_checked(div)?;
+
+            // check the overflow
+            // For example: Decimal(128,10,0) as i8

Review Comment:
   Can we just use `append_option(NumCast::from(v))` and eliminate the bounds 
checks from this code?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to