You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@arrow.apache.org by "liukun4515 (via GitHub)" <gi...@apache.org> on 2023/04/14 08:43:19 UTC

[GitHub] [arrow-rs] liukun4515 opened a new pull request, #4088: optimize cast for same decimal type and same scale

liukun4515 opened a new pull request, #4088:
URL: https://github.com/apache/arrow-rs/pull/4088

   # Which issue does this PR close?
   
   <!--
   We generally require a GitHub issue to be filed for all bug fixes and enhancements and this helps us generate change logs for our releases. You can link an issue to this PR using the GitHub syntax. For example `Closes #123` indicates that this PR will close issue #123.
   -->
   
   Closes #.
   
   we are optimizing the TPCH query, and find some decimal cast is heavy such TPCH-1.
   
   
   
   In the Sum Agg, the sum decimal type is (precision+10, scale). The scale is not changed, we don't need to visit the converted function with the same decimal128 or decimal256
   
   
   
   # Rationale for this change
    
   <!--
   Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed.
   Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes.
   -->
   
   add two micro benchmark, and get the result:
   
   ```
   cast decimal128 to decimal128 512 with same scale
                           time:   [213.91 ns 214.46 ns 215.11 ns]
                           change: [-96.673% -96.654% -96.628%] (p = 0.00 < 0.05)
                           Performance has improved.
   Found 10 outliers among 100 measurements (10.00%)
     3 (3.00%) high mild
     7 (7.00%) high severe
   
   cast decimal256 to decimal256 512 with same scale
                           time:   [212.81 ns 213.51 ns 214.28 ns]
                           change: [-98.529% -98.524% -98.519%] (p = 0.00 < 0.05)
                           Performance has improved.
   ```
   
   # What changes are included in this PR?
   
   <!--
   There is no need to duplicate the description in the issue here but it is sometimes worth providing a summary of the individual changes in this PR.
   -->
   
   # Are there any user-facing changes?
   
   
   <!--
   If there are user-facing changes then we may require documentation to be updated before approving the PR.
   -->
   
   <!---
   If there are any breaking changes to public APIs, please add the `breaking change` label.
   -->
   


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] viirya commented on a diff in pull request #4088: optimize cast for same decimal type and same scale

Posted by "viirya (via GitHub)" <gi...@apache.org>.
viirya commented on code in PR #4088:
URL: https://github.com/apache/arrow-rs/pull/4088#discussion_r1169132139


##########
arrow-cast/src/cast.rs:
##########
@@ -2081,66 +2081,166 @@ impl DecimalCast for i256 {
     }
 }
 
-fn cast_decimal_to_decimal<I, O>(
-    array: &PrimitiveArray<I>,
-    input_scale: i8,
+fn cast_decimal_to_decimal_error<I, O>(
     output_precision: u8,
     output_scale: i8,
-    cast_options: &CastOptions,
-) -> Result<ArrayRef, ArrowError>
+) -> impl Fn(<I as ArrowPrimitiveType>::Native) -> ArrowError
 where
     I: DecimalType,
     O: DecimalType,
     I::Native: DecimalCast + ArrowNativeTypeOp,
     O::Native: DecimalCast + ArrowNativeTypeOp,
 {
-    let error = |x| {
+    move |x: I::Native| {
         ArrowError::CastError(format!(
             "Cannot cast to {}({}, {}). Overflowing on {:?}",
             O::PREFIX,
             output_precision,
             output_scale,
             x
         ))
-    };
+    }
+}
 
-    let array: PrimitiveArray<O> = if input_scale > output_scale {
-        let div = I::Native::from_decimal(10_i128)
-            .unwrap()
-            .pow_checked((input_scale - output_scale) as u32)?;
+fn convert_to_smaller_equal_scale_decimal<I, O>(
+    array: &PrimitiveArray<I>,
+    input_scale: i8,
+    output_precision: u8,
+    output_scale: i8,
+    cast_options: &CastOptions,
+) -> Result<PrimitiveArray<O>, ArrowError>
+where
+    I: DecimalType,
+    O: DecimalType,
+    I::Native: DecimalCast + ArrowNativeTypeOp,
+    O::Native: DecimalCast + ArrowNativeTypeOp,
+{
+    let error = cast_decimal_to_decimal_error::<I, O>(output_precision, output_scale);
+    let div = I::Native::from_decimal(10_i128)
+        .unwrap()
+        .pow_checked((input_scale - output_scale) as u32)?;
 
-        let half = div.div_wrapping(I::Native::from_usize(2).unwrap());
-        let half_neg = half.neg_wrapping();
+    let half = div.div_wrapping(I::Native::from_usize(2).unwrap());
+    let half_neg = half.neg_wrapping();
 
-        let f = |x: I::Native| {
-            // div is >= 10 and so this cannot overflow
-            let d = x.div_wrapping(div);
-            let r = x.mod_wrapping(div);
+    let f = |x: I::Native| {
+        // div is >= 10 and so this cannot overflow
+        let d = x.div_wrapping(div);
+        let r = x.mod_wrapping(div);
 
-            // Round result
-            let adjusted = match x >= I::Native::ZERO {
-                true if r >= half => d.add_wrapping(I::Native::ONE),
-                false if r <= half_neg => d.sub_wrapping(I::Native::ONE),
-                _ => d,
-            };
-            O::Native::from_decimal(adjusted)
+        // Round result
+        let adjusted = match x >= I::Native::ZERO {
+            true if r >= half => d.add_wrapping(I::Native::ONE),
+            false if r <= half_neg => d.sub_wrapping(I::Native::ONE),
+            _ => d,
         };
+        O::Native::from_decimal(adjusted)
+    };
 
-        match cast_options.safe {
-            true => array.unary_opt(f),
-            false => array.try_unary(|x| f(x).ok_or_else(|| error(x)))?,
-        }
-    } else {
-        let mul = O::Native::from_decimal(10_i128)
-            .unwrap()
-            .pow_checked((output_scale - input_scale) as u32)?;
+    Ok(match cast_options.safe {
+        true => array.unary_opt(f),
+        false => array.try_unary(|x| f(x).ok_or_else(|| error(x)))?,
+    })
+}
 
-        let f = |x| O::Native::from_decimal(x).and_then(|x| x.mul_checked(mul).ok());
+fn convert_to_bigger_scale_decimal<I, O>(
+    array: &PrimitiveArray<I>,
+    input_scale: i8,
+    output_precision: u8,
+    output_scale: i8,
+    cast_options: &CastOptions,
+) -> Result<PrimitiveArray<O>, ArrowError>
+where
+    I: DecimalType,
+    O: DecimalType,
+    I::Native: DecimalCast + ArrowNativeTypeOp,
+    O::Native: DecimalCast + ArrowNativeTypeOp,
+{
+    let error = cast_decimal_to_decimal_error::<I, O>(output_precision, output_scale);
+    let mul = O::Native::from_decimal(10_i128)
+        .unwrap()
+        .pow_checked((output_scale - input_scale) as u32)?;
 
-        match cast_options.safe {
-            true => array.unary_opt(f),
-            false => array.try_unary(|x| f(x).ok_or_else(|| error(x)))?,
+    let f = |x| O::Native::from_decimal(x).and_then(|x| x.mul_checked(mul).ok());
+
+    Ok(match cast_options.safe {
+        true => array.unary_opt(f),
+        false => array.try_unary(|x| f(x).ok_or_else(|| error(x)))?,
+    })
+}
+
+// Only support one type of decimal cast operations
+fn cast_decimal_to_decimal_same_type<T>(
+    array: &PrimitiveArray<T>,
+    input_scale: i8,
+    output_precision: u8,
+    output_scale: i8,
+    cast_options: &CastOptions,
+) -> Result<ArrayRef, ArrowError>
+where
+    T: DecimalType,
+    T::Native: DecimalCast + ArrowNativeTypeOp,
+{
+    let array: PrimitiveArray<T> = match input_scale.cmp(&output_scale) {
+        Ordering::Equal => {
+            // the scale doesn't change, the native value don't need to be changed
+            array.clone()
         }
+        Ordering::Greater => convert_to_smaller_equal_scale_decimal::<T, T>(
+            array,
+            input_scale,
+            output_precision,
+            output_scale,
+            cast_options,
+        )?,
+        Ordering::Less => {
+            // input_scale < output_scale
+            convert_to_bigger_scale_decimal::<T, T>(
+                array,
+                input_scale,
+                output_precision,
+                output_scale,
+                cast_options,
+            )?
+        }
+    };
+
+    Ok(Arc::new(array.with_precision_and_scale(
+        output_precision,
+        output_scale,
+    )?))
+}
+
+// Support two different types of decimal cast operations
+fn cast_decimal_to_decimal<I, O>(
+    array: &PrimitiveArray<I>,
+    input_scale: i8,
+    output_precision: u8,
+    output_scale: i8,
+    cast_options: &CastOptions,
+) -> Result<ArrayRef, ArrowError>
+where
+    I: DecimalType,
+    O: DecimalType,
+    I::Native: DecimalCast + ArrowNativeTypeOp,
+    O::Native: DecimalCast + ArrowNativeTypeOp,
+{
+    let array: PrimitiveArray<O> = if input_scale > output_scale {
+        convert_to_smaller_equal_scale_decimal::<I, O>(

Review Comment:
   ```suggestion
           convert_to_smaller_scale_decimal::<I, O>(
   ```



##########
arrow-cast/src/cast.rs:
##########
@@ -2081,66 +2081,166 @@ impl DecimalCast for i256 {
     }
 }
 
-fn cast_decimal_to_decimal<I, O>(
-    array: &PrimitiveArray<I>,
-    input_scale: i8,
+fn cast_decimal_to_decimal_error<I, O>(
     output_precision: u8,
     output_scale: i8,
-    cast_options: &CastOptions,
-) -> Result<ArrayRef, ArrowError>
+) -> impl Fn(<I as ArrowPrimitiveType>::Native) -> ArrowError
 where
     I: DecimalType,
     O: DecimalType,
     I::Native: DecimalCast + ArrowNativeTypeOp,
     O::Native: DecimalCast + ArrowNativeTypeOp,
 {
-    let error = |x| {
+    move |x: I::Native| {
         ArrowError::CastError(format!(
             "Cannot cast to {}({}, {}). Overflowing on {:?}",
             O::PREFIX,
             output_precision,
             output_scale,
             x
         ))
-    };
+    }
+}
 
-    let array: PrimitiveArray<O> = if input_scale > output_scale {
-        let div = I::Native::from_decimal(10_i128)
-            .unwrap()
-            .pow_checked((input_scale - output_scale) as u32)?;
+fn convert_to_smaller_equal_scale_decimal<I, O>(
+    array: &PrimitiveArray<I>,
+    input_scale: i8,
+    output_precision: u8,
+    output_scale: i8,
+    cast_options: &CastOptions,
+) -> Result<PrimitiveArray<O>, ArrowError>
+where
+    I: DecimalType,
+    O: DecimalType,
+    I::Native: DecimalCast + ArrowNativeTypeOp,
+    O::Native: DecimalCast + ArrowNativeTypeOp,
+{
+    let error = cast_decimal_to_decimal_error::<I, O>(output_precision, output_scale);
+    let div = I::Native::from_decimal(10_i128)
+        .unwrap()
+        .pow_checked((input_scale - output_scale) as u32)?;
 
-        let half = div.div_wrapping(I::Native::from_usize(2).unwrap());
-        let half_neg = half.neg_wrapping();
+    let half = div.div_wrapping(I::Native::from_usize(2).unwrap());
+    let half_neg = half.neg_wrapping();
 
-        let f = |x: I::Native| {
-            // div is >= 10 and so this cannot overflow
-            let d = x.div_wrapping(div);
-            let r = x.mod_wrapping(div);
+    let f = |x: I::Native| {
+        // div is >= 10 and so this cannot overflow
+        let d = x.div_wrapping(div);
+        let r = x.mod_wrapping(div);
 
-            // Round result
-            let adjusted = match x >= I::Native::ZERO {
-                true if r >= half => d.add_wrapping(I::Native::ONE),
-                false if r <= half_neg => d.sub_wrapping(I::Native::ONE),
-                _ => d,
-            };
-            O::Native::from_decimal(adjusted)
+        // Round result
+        let adjusted = match x >= I::Native::ZERO {
+            true if r >= half => d.add_wrapping(I::Native::ONE),
+            false if r <= half_neg => d.sub_wrapping(I::Native::ONE),
+            _ => d,
         };
+        O::Native::from_decimal(adjusted)
+    };
 
-        match cast_options.safe {
-            true => array.unary_opt(f),
-            false => array.try_unary(|x| f(x).ok_or_else(|| error(x)))?,
-        }
-    } else {
-        let mul = O::Native::from_decimal(10_i128)
-            .unwrap()
-            .pow_checked((output_scale - input_scale) as u32)?;
+    Ok(match cast_options.safe {
+        true => array.unary_opt(f),
+        false => array.try_unary(|x| f(x).ok_or_else(|| error(x)))?,
+    })
+}
 
-        let f = |x| O::Native::from_decimal(x).and_then(|x| x.mul_checked(mul).ok());
+fn convert_to_bigger_scale_decimal<I, O>(
+    array: &PrimitiveArray<I>,
+    input_scale: i8,
+    output_precision: u8,
+    output_scale: i8,
+    cast_options: &CastOptions,
+) -> Result<PrimitiveArray<O>, ArrowError>
+where
+    I: DecimalType,
+    O: DecimalType,
+    I::Native: DecimalCast + ArrowNativeTypeOp,
+    O::Native: DecimalCast + ArrowNativeTypeOp,
+{
+    let error = cast_decimal_to_decimal_error::<I, O>(output_precision, output_scale);
+    let mul = O::Native::from_decimal(10_i128)
+        .unwrap()
+        .pow_checked((output_scale - input_scale) as u32)?;
 
-        match cast_options.safe {
-            true => array.unary_opt(f),
-            false => array.try_unary(|x| f(x).ok_or_else(|| error(x)))?,
+    let f = |x| O::Native::from_decimal(x).and_then(|x| x.mul_checked(mul).ok());
+
+    Ok(match cast_options.safe {
+        true => array.unary_opt(f),
+        false => array.try_unary(|x| f(x).ok_or_else(|| error(x)))?,
+    })
+}
+
+// Only support one type of decimal cast operations
+fn cast_decimal_to_decimal_same_type<T>(
+    array: &PrimitiveArray<T>,
+    input_scale: i8,
+    output_precision: u8,
+    output_scale: i8,
+    cast_options: &CastOptions,
+) -> Result<ArrayRef, ArrowError>
+where
+    T: DecimalType,
+    T::Native: DecimalCast + ArrowNativeTypeOp,
+{
+    let array: PrimitiveArray<T> = match input_scale.cmp(&output_scale) {
+        Ordering::Equal => {
+            // the scale doesn't change, the native value don't need to be changed
+            array.clone()
         }
+        Ordering::Greater => convert_to_smaller_equal_scale_decimal::<T, T>(
+            array,
+            input_scale,
+            output_precision,
+            output_scale,
+            cast_options,
+        )?,
+        Ordering::Less => {
+            // input_scale < output_scale
+            convert_to_bigger_scale_decimal::<T, T>(
+                array,
+                input_scale,
+                output_precision,
+                output_scale,
+                cast_options,
+            )?
+        }
+    };
+
+    Ok(Arc::new(array.with_precision_and_scale(
+        output_precision,
+        output_scale,
+    )?))
+}
+
+// Support two different types of decimal cast operations
+fn cast_decimal_to_decimal<I, O>(
+    array: &PrimitiveArray<I>,
+    input_scale: i8,
+    output_precision: u8,
+    output_scale: i8,
+    cast_options: &CastOptions,
+) -> Result<ArrayRef, ArrowError>
+where
+    I: DecimalType,
+    O: DecimalType,
+    I::Native: DecimalCast + ArrowNativeTypeOp,
+    O::Native: DecimalCast + ArrowNativeTypeOp,
+{
+    let array: PrimitiveArray<O> = if input_scale > output_scale {
+        convert_to_smaller_equal_scale_decimal::<I, O>(
+            array,
+            input_scale,
+            output_precision,
+            output_scale,
+            cast_options,
+        )?
+    } else {
+        convert_to_bigger_scale_decimal::<I, O>(

Review Comment:
   ```suggestion
           convert_to_bigger_or_equal_scale_decimal::<I, O>(
   ```



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] liukun4515 commented on a diff in pull request #4088: optimize cast for same decimal type and same scale

Posted by "liukun4515 (via GitHub)" <gi...@apache.org>.
liukun4515 commented on code in PR #4088:
URL: https://github.com/apache/arrow-rs/pull/4088#discussion_r1167543788


##########
arrow-cast/src/cast.rs:
##########
@@ -2081,29 +2081,102 @@ impl DecimalCast for i256 {
     }
 }
 
-fn cast_decimal_to_decimal<I, O>(
-    array: &PrimitiveArray<I>,
-    input_scale: i8,
+fn cast_decimal_to_decimal_error<O>(
     output_precision: u8,
     output_scale: i8,
-    cast_options: &CastOptions,
-) -> Result<ArrayRef, ArrowError>
+) -> impl Fn(<O as ArrowPrimitiveType>::Native) -> ArrowError
 where
-    I: DecimalType,
     O: DecimalType,
-    I::Native: DecimalCast + ArrowNativeTypeOp,
     O::Native: DecimalCast + ArrowNativeTypeOp,
 {
-    let error = |x| {
+    move |x: O::Native| {
         ArrowError::CastError(format!(
             "Cannot cast to {}({}, {}). Overflowing on {:?}",
             O::PREFIX,
             output_precision,
             output_scale,
             x
         ))
+    }
+}
+
+fn cast_decimal_to_decimal_same_type<T>(

Review Comment:
   Not same args, 
   `cast_decimal_to_decimal_same_type` just accept the one type of decimal of `T`.



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] viirya commented on a diff in pull request #4088: optimize cast for same decimal type and same scale

Posted by "viirya (via GitHub)" <gi...@apache.org>.
viirya commented on code in PR #4088:
URL: https://github.com/apache/arrow-rs/pull/4088#discussion_r1167053564


##########
arrow-cast/src/cast.rs:
##########
@@ -2081,29 +2081,102 @@ impl DecimalCast for i256 {
     }
 }
 
-fn cast_decimal_to_decimal<I, O>(
-    array: &PrimitiveArray<I>,
-    input_scale: i8,
+fn cast_decimal_to_decimal_error<O>(
     output_precision: u8,
     output_scale: i8,
-    cast_options: &CastOptions,
-) -> Result<ArrayRef, ArrowError>
+) -> impl Fn(<O as ArrowPrimitiveType>::Native) -> ArrowError
 where
-    I: DecimalType,
     O: DecimalType,
-    I::Native: DecimalCast + ArrowNativeTypeOp,
     O::Native: DecimalCast + ArrowNativeTypeOp,
 {
-    let error = |x| {
+    move |x: O::Native| {
         ArrowError::CastError(format!(
             "Cannot cast to {}({}, {}). Overflowing on {:?}",
             O::PREFIX,
             output_precision,
             output_scale,
             x
         ))
+    }
+}
+
+fn cast_decimal_to_decimal_same_type<T>(
+    array: &PrimitiveArray<T>,
+    input_scale: i8,
+    output_precision: u8,
+    output_scale: i8,
+    cast_options: &CastOptions,
+) -> Result<ArrayRef, ArrowError>
+where
+    T: DecimalType,
+    T::Native: DecimalCast + ArrowNativeTypeOp,
+{
+    let error = cast_decimal_to_decimal_error::<T>(output_precision, output_scale);
+
+    let array: PrimitiveArray<T> = if input_scale == output_scale {
+        // the scale doesn't change, the native value don't need to be changed
+        array.clone()
+    } else if input_scale > output_scale {
+        let div = T::Native::from_decimal(10_i128)
+            .unwrap()
+            .pow_checked((input_scale - output_scale) as u32)?;
+
+        let half = div.div_wrapping(T::Native::from_usize(2).unwrap());
+        let half_neg = half.neg_wrapping();
+
+        let f = |x: T::Native| {
+            // div is >= 10 and so this cannot overflow
+            let d = x.div_wrapping(div);
+            let r = x.mod_wrapping(div);
+
+            // Round result
+            let adjusted = match x >= T::Native::ZERO {
+                true if r >= half => d.add_wrapping(T::Native::ONE),
+                false if r <= half_neg => d.sub_wrapping(T::Native::ONE),
+                _ => d,
+            };
+            Some(adjusted)
+        };
+
+        match cast_options.safe {
+            true => array.unary_opt(f),
+            false => array.try_unary(|x| f(x).ok_or_else(|| error(x)))?,

Review Comment:
   `f(x)` cannot be `None` now.



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] liukun4515 commented on a diff in pull request #4088: optimize cast for same decimal type and same scale

Posted by "liukun4515 (via GitHub)" <gi...@apache.org>.
liukun4515 commented on code in PR #4088:
URL: https://github.com/apache/arrow-rs/pull/4088#discussion_r1167447570


##########
arrow-cast/src/cast.rs:
##########
@@ -2081,29 +2081,102 @@ impl DecimalCast for i256 {
     }
 }
 
-fn cast_decimal_to_decimal<I, O>(
-    array: &PrimitiveArray<I>,
-    input_scale: i8,
+fn cast_decimal_to_decimal_error<O>(
     output_precision: u8,
     output_scale: i8,
-    cast_options: &CastOptions,
-) -> Result<ArrayRef, ArrowError>
+) -> impl Fn(<O as ArrowPrimitiveType>::Native) -> ArrowError
 where
-    I: DecimalType,
     O: DecimalType,
-    I::Native: DecimalCast + ArrowNativeTypeOp,
     O::Native: DecimalCast + ArrowNativeTypeOp,
 {
-    let error = |x| {
+    move |x: O::Native| {
         ArrowError::CastError(format!(
             "Cannot cast to {}({}, {}). Overflowing on {:?}",
             O::PREFIX,
             output_precision,
             output_scale,
             x
         ))
+    }
+}
+
+fn cast_decimal_to_decimal_same_type<T>(
+    array: &PrimitiveArray<T>,
+    input_scale: i8,
+    output_precision: u8,
+    output_scale: i8,
+    cast_options: &CastOptions,
+) -> Result<ArrayRef, ArrowError>
+where
+    T: DecimalType,
+    T::Native: DecimalCast + ArrowNativeTypeOp,
+{
+    let error = cast_decimal_to_decimal_error::<T>(output_precision, output_scale);
+
+    let array: PrimitiveArray<T> = if input_scale == output_scale {
+        // the scale doesn't change, the native value don't need to be changed
+        array.clone()
+    } else if input_scale > output_scale {
+        let div = T::Native::from_decimal(10_i128)
+            .unwrap()
+            .pow_checked((input_scale - output_scale) as u32)?;
+
+        let half = div.div_wrapping(T::Native::from_usize(2).unwrap());
+        let half_neg = half.neg_wrapping();
+
+        let f = |x: T::Native| {
+            // div is >= 10 and so this cannot overflow
+            let d = x.div_wrapping(div);
+            let r = x.mod_wrapping(div);
+
+            // Round result
+            let adjusted = match x >= T::Native::ZERO {
+                true if r >= half => d.add_wrapping(T::Native::ONE),
+                false if r <= half_neg => d.sub_wrapping(T::Native::ONE),
+                _ => d,
+            };
+            Some(adjusted)
+        };
+
+        match cast_options.safe {
+            true => array.unary_opt(f),
+            false => array.try_unary(|x| f(x).ok_or_else(|| error(x)))?,

Review Comment:
   Sorry, I didn't get your point.
   The result of `f(x)` must be Some(...) 



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] liukun4515 commented on a diff in pull request #4088: optimize cast for same decimal type and same scale

Posted by "liukun4515 (via GitHub)" <gi...@apache.org>.
liukun4515 commented on code in PR #4088:
URL: https://github.com/apache/arrow-rs/pull/4088#discussion_r1167472594


##########
arrow-cast/src/cast.rs:
##########
@@ -2081,29 +2081,102 @@ impl DecimalCast for i256 {
     }
 }
 
-fn cast_decimal_to_decimal<I, O>(
-    array: &PrimitiveArray<I>,
-    input_scale: i8,
+fn cast_decimal_to_decimal_error<O>(
     output_precision: u8,
     output_scale: i8,
-    cast_options: &CastOptions,
-) -> Result<ArrayRef, ArrowError>
+) -> impl Fn(<O as ArrowPrimitiveType>::Native) -> ArrowError
 where
-    I: DecimalType,
     O: DecimalType,
-    I::Native: DecimalCast + ArrowNativeTypeOp,
     O::Native: DecimalCast + ArrowNativeTypeOp,
 {
-    let error = |x| {
+    move |x: O::Native| {
         ArrowError::CastError(format!(
             "Cannot cast to {}({}, {}). Overflowing on {:?}",
             O::PREFIX,
             output_precision,
             output_scale,
             x
         ))
+    }
+}
+
+fn cast_decimal_to_decimal_same_type<T>(
+    array: &PrimitiveArray<T>,
+    input_scale: i8,
+    output_precision: u8,
+    output_scale: i8,
+    cast_options: &CastOptions,
+) -> Result<ArrayRef, ArrowError>
+where
+    T: DecimalType,
+    T::Native: DecimalCast + ArrowNativeTypeOp,
+{
+    let error = cast_decimal_to_decimal_error::<T>(output_precision, output_scale);
+
+    let array: PrimitiveArray<T> = if input_scale == output_scale {
+        // the scale doesn't change, the native value don't need to be changed
+        array.clone()
+    } else if input_scale > output_scale {

Review Comment:
   I will add two method:
   1. convert to bigger scale decimal 
   2. convert to smaller scale decimal 
   to reduce the effort of maintenance.



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] alamb commented on a diff in pull request #4088: optimize cast for same decimal type and same scale

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #4088:
URL: https://github.com/apache/arrow-rs/pull/4088#discussion_r1167159839


##########
arrow-cast/src/cast.rs:
##########
@@ -2081,29 +2081,102 @@ impl DecimalCast for i256 {
     }
 }
 
-fn cast_decimal_to_decimal<I, O>(
-    array: &PrimitiveArray<I>,
-    input_scale: i8,
+fn cast_decimal_to_decimal_error<O>(
     output_precision: u8,
     output_scale: i8,
-    cast_options: &CastOptions,
-) -> Result<ArrayRef, ArrowError>
+) -> impl Fn(<O as ArrowPrimitiveType>::Native) -> ArrowError
 where
-    I: DecimalType,
     O: DecimalType,
-    I::Native: DecimalCast + ArrowNativeTypeOp,
     O::Native: DecimalCast + ArrowNativeTypeOp,
 {
-    let error = |x| {
+    move |x: O::Native| {
         ArrowError::CastError(format!(
             "Cannot cast to {}({}, {}). Overflowing on {:?}",
             O::PREFIX,
             output_precision,
             output_scale,
             x
         ))
+    }
+}
+
+fn cast_decimal_to_decimal_same_type<T>(

Review Comment:
   Could you please add some comments here about what the difference between `cast_decimal_to_decimal_same_type` and `cast_decimal_to_decimal` are, especially given their arguments appear to be the the same. 
   



##########
arrow-cast/src/cast.rs:
##########
@@ -2081,29 +2081,102 @@ impl DecimalCast for i256 {
     }
 }
 
-fn cast_decimal_to_decimal<I, O>(
-    array: &PrimitiveArray<I>,
-    input_scale: i8,
+fn cast_decimal_to_decimal_error<O>(
     output_precision: u8,
     output_scale: i8,
-    cast_options: &CastOptions,
-) -> Result<ArrayRef, ArrowError>
+) -> impl Fn(<O as ArrowPrimitiveType>::Native) -> ArrowError
 where
-    I: DecimalType,
     O: DecimalType,
-    I::Native: DecimalCast + ArrowNativeTypeOp,
     O::Native: DecimalCast + ArrowNativeTypeOp,
 {
-    let error = |x| {
+    move |x: O::Native| {
         ArrowError::CastError(format!(
             "Cannot cast to {}({}, {}). Overflowing on {:?}",
             O::PREFIX,
             output_precision,
             output_scale,
             x
         ))
+    }
+}
+
+fn cast_decimal_to_decimal_same_type<T>(
+    array: &PrimitiveArray<T>,
+    input_scale: i8,
+    output_precision: u8,
+    output_scale: i8,
+    cast_options: &CastOptions,
+) -> Result<ArrayRef, ArrowError>
+where
+    T: DecimalType,
+    T::Native: DecimalCast + ArrowNativeTypeOp,
+{
+    let error = cast_decimal_to_decimal_error::<T>(output_precision, output_scale);
+
+    let array: PrimitiveArray<T> = if input_scale == output_scale {
+        // the scale doesn't change, the native value don't need to be changed
+        array.clone()
+    } else if input_scale > output_scale {

Review Comment:
   this code and below looks very similar to what is in `cast_decimal_to_decimal`
   
   Is there any way they can be combined to reduce the maintenance burden longer term?



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] liukun4515 commented on a diff in pull request #4088: optimize cast for same decimal type and same scale

Posted by "liukun4515 (via GitHub)" <gi...@apache.org>.
liukun4515 commented on code in PR #4088:
URL: https://github.com/apache/arrow-rs/pull/4088#discussion_r1169498040


##########
arrow-cast/src/cast.rs:
##########
@@ -2081,66 +2081,166 @@ impl DecimalCast for i256 {
     }
 }
 
-fn cast_decimal_to_decimal<I, O>(
-    array: &PrimitiveArray<I>,
-    input_scale: i8,
+fn cast_decimal_to_decimal_error<I, O>(
     output_precision: u8,
     output_scale: i8,
-    cast_options: &CastOptions,
-) -> Result<ArrayRef, ArrowError>
+) -> impl Fn(<I as ArrowPrimitiveType>::Native) -> ArrowError
 where
     I: DecimalType,
     O: DecimalType,
     I::Native: DecimalCast + ArrowNativeTypeOp,
     O::Native: DecimalCast + ArrowNativeTypeOp,
 {
-    let error = |x| {
+    move |x: I::Native| {
         ArrowError::CastError(format!(
             "Cannot cast to {}({}, {}). Overflowing on {:?}",
             O::PREFIX,
             output_precision,
             output_scale,
             x
         ))
-    };
+    }
+}
 
-    let array: PrimitiveArray<O> = if input_scale > output_scale {
-        let div = I::Native::from_decimal(10_i128)
-            .unwrap()
-            .pow_checked((input_scale - output_scale) as u32)?;
+fn convert_to_smaller_equal_scale_decimal<I, O>(
+    array: &PrimitiveArray<I>,
+    input_scale: i8,
+    output_precision: u8,
+    output_scale: i8,
+    cast_options: &CastOptions,
+) -> Result<PrimitiveArray<O>, ArrowError>
+where
+    I: DecimalType,
+    O: DecimalType,
+    I::Native: DecimalCast + ArrowNativeTypeOp,
+    O::Native: DecimalCast + ArrowNativeTypeOp,
+{
+    let error = cast_decimal_to_decimal_error::<I, O>(output_precision, output_scale);
+    let div = I::Native::from_decimal(10_i128)
+        .unwrap()
+        .pow_checked((input_scale - output_scale) as u32)?;
 
-        let half = div.div_wrapping(I::Native::from_usize(2).unwrap());
-        let half_neg = half.neg_wrapping();
+    let half = div.div_wrapping(I::Native::from_usize(2).unwrap());
+    let half_neg = half.neg_wrapping();
 
-        let f = |x: I::Native| {
-            // div is >= 10 and so this cannot overflow
-            let d = x.div_wrapping(div);
-            let r = x.mod_wrapping(div);
+    let f = |x: I::Native| {
+        // div is >= 10 and so this cannot overflow
+        let d = x.div_wrapping(div);
+        let r = x.mod_wrapping(div);
 
-            // Round result
-            let adjusted = match x >= I::Native::ZERO {
-                true if r >= half => d.add_wrapping(I::Native::ONE),
-                false if r <= half_neg => d.sub_wrapping(I::Native::ONE),
-                _ => d,
-            };
-            O::Native::from_decimal(adjusted)
+        // Round result
+        let adjusted = match x >= I::Native::ZERO {
+            true if r >= half => d.add_wrapping(I::Native::ONE),
+            false if r <= half_neg => d.sub_wrapping(I::Native::ONE),
+            _ => d,
         };
+        O::Native::from_decimal(adjusted)
+    };
 
-        match cast_options.safe {
-            true => array.unary_opt(f),
-            false => array.try_unary(|x| f(x).ok_or_else(|| error(x)))?,
-        }
-    } else {
-        let mul = O::Native::from_decimal(10_i128)
-            .unwrap()
-            .pow_checked((output_scale - input_scale) as u32)?;
+    Ok(match cast_options.safe {
+        true => array.unary_opt(f),
+        false => array.try_unary(|x| f(x).ok_or_else(|| error(x)))?,
+    })
+}
 
-        let f = |x| O::Native::from_decimal(x).and_then(|x| x.mul_checked(mul).ok());
+fn convert_to_bigger_scale_decimal<I, O>(
+    array: &PrimitiveArray<I>,
+    input_scale: i8,
+    output_precision: u8,
+    output_scale: i8,
+    cast_options: &CastOptions,
+) -> Result<PrimitiveArray<O>, ArrowError>
+where
+    I: DecimalType,
+    O: DecimalType,
+    I::Native: DecimalCast + ArrowNativeTypeOp,
+    O::Native: DecimalCast + ArrowNativeTypeOp,
+{
+    let error = cast_decimal_to_decimal_error::<I, O>(output_precision, output_scale);
+    let mul = O::Native::from_decimal(10_i128)
+        .unwrap()
+        .pow_checked((output_scale - input_scale) as u32)?;
 
-        match cast_options.safe {
-            true => array.unary_opt(f),
-            false => array.try_unary(|x| f(x).ok_or_else(|| error(x)))?,
+    let f = |x| O::Native::from_decimal(x).and_then(|x| x.mul_checked(mul).ok());
+
+    Ok(match cast_options.safe {
+        true => array.unary_opt(f),
+        false => array.try_unary(|x| f(x).ok_or_else(|| error(x)))?,
+    })
+}
+
+// Only support one type of decimal cast operations
+fn cast_decimal_to_decimal_same_type<T>(
+    array: &PrimitiveArray<T>,
+    input_scale: i8,
+    output_precision: u8,
+    output_scale: i8,
+    cast_options: &CastOptions,
+) -> Result<ArrayRef, ArrowError>
+where
+    T: DecimalType,
+    T::Native: DecimalCast + ArrowNativeTypeOp,
+{
+    let array: PrimitiveArray<T> = match input_scale.cmp(&output_scale) {
+        Ordering::Equal => {
+            // the scale doesn't change, the native value don't need to be changed
+            array.clone()
         }
+        Ordering::Greater => convert_to_smaller_equal_scale_decimal::<T, T>(

Review Comment:
   `convert_to_smaller_equal_scale_decimal` can do the casting for different input and output decimal type with smaller or equal scale.
   
   But it is not efficient for same input and output type with the same scale.



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] viirya commented on a diff in pull request #4088: optimize cast for same decimal type and same scale

Posted by "viirya (via GitHub)" <gi...@apache.org>.
viirya commented on code in PR #4088:
URL: https://github.com/apache/arrow-rs/pull/4088#discussion_r1167581858


##########
arrow-cast/src/cast.rs:
##########
@@ -2081,29 +2081,102 @@ impl DecimalCast for i256 {
     }
 }
 
-fn cast_decimal_to_decimal<I, O>(
-    array: &PrimitiveArray<I>,
-    input_scale: i8,
+fn cast_decimal_to_decimal_error<O>(
     output_precision: u8,
     output_scale: i8,
-    cast_options: &CastOptions,
-) -> Result<ArrayRef, ArrowError>
+) -> impl Fn(<O as ArrowPrimitiveType>::Native) -> ArrowError
 where
-    I: DecimalType,
     O: DecimalType,
-    I::Native: DecimalCast + ArrowNativeTypeOp,
     O::Native: DecimalCast + ArrowNativeTypeOp,
 {
-    let error = |x| {
+    move |x: O::Native| {
         ArrowError::CastError(format!(
             "Cannot cast to {}({}, {}). Overflowing on {:?}",
             O::PREFIX,
             output_precision,
             output_scale,
             x
         ))
+    }
+}
+
+fn cast_decimal_to_decimal_same_type<T>(
+    array: &PrimitiveArray<T>,
+    input_scale: i8,
+    output_precision: u8,
+    output_scale: i8,
+    cast_options: &CastOptions,
+) -> Result<ArrayRef, ArrowError>
+where
+    T: DecimalType,
+    T::Native: DecimalCast + ArrowNativeTypeOp,
+{
+    let error = cast_decimal_to_decimal_error::<T>(output_precision, output_scale);
+
+    let array: PrimitiveArray<T> = if input_scale == output_scale {
+        // the scale doesn't change, the native value don't need to be changed
+        array.clone()
+    } else if input_scale > output_scale {
+        let div = T::Native::from_decimal(10_i128)
+            .unwrap()
+            .pow_checked((input_scale - output_scale) as u32)?;
+
+        let half = div.div_wrapping(T::Native::from_usize(2).unwrap());
+        let half_neg = half.neg_wrapping();
+
+        let f = |x: T::Native| {
+            // div is >= 10 and so this cannot overflow
+            let d = x.div_wrapping(div);
+            let r = x.mod_wrapping(div);
+
+            // Round result
+            let adjusted = match x >= T::Native::ZERO {
+                true if r >= half => d.add_wrapping(T::Native::ONE),
+                false if r <= half_neg => d.sub_wrapping(T::Native::ONE),
+                _ => d,
+            };
+            Some(adjusted)
+        };
+
+        match cast_options.safe {
+            true => array.unary_opt(f),
+            false => array.try_unary(|x| f(x).ok_or_else(|| error(x)))?,

Review Comment:
   Your `f(x)` always returns `Some`. So you don't need `try_unary` (because you never get a error).



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] viirya commented on a diff in pull request #4088: optimize cast for same decimal type and same scale

Posted by "viirya (via GitHub)" <gi...@apache.org>.
viirya commented on code in PR #4088:
URL: https://github.com/apache/arrow-rs/pull/4088#discussion_r1169130723


##########
arrow-cast/src/cast.rs:
##########
@@ -2081,66 +2081,166 @@ impl DecimalCast for i256 {
     }
 }
 
-fn cast_decimal_to_decimal<I, O>(
-    array: &PrimitiveArray<I>,
-    input_scale: i8,
+fn cast_decimal_to_decimal_error<I, O>(
     output_precision: u8,
     output_scale: i8,
-    cast_options: &CastOptions,
-) -> Result<ArrayRef, ArrowError>
+) -> impl Fn(<I as ArrowPrimitiveType>::Native) -> ArrowError
 where
     I: DecimalType,
     O: DecimalType,
     I::Native: DecimalCast + ArrowNativeTypeOp,
     O::Native: DecimalCast + ArrowNativeTypeOp,
 {
-    let error = |x| {
+    move |x: I::Native| {
         ArrowError::CastError(format!(
             "Cannot cast to {}({}, {}). Overflowing on {:?}",
             O::PREFIX,
             output_precision,
             output_scale,
             x
         ))
-    };
+    }
+}
 
-    let array: PrimitiveArray<O> = if input_scale > output_scale {
-        let div = I::Native::from_decimal(10_i128)
-            .unwrap()
-            .pow_checked((input_scale - output_scale) as u32)?;
+fn convert_to_smaller_equal_scale_decimal<I, O>(
+    array: &PrimitiveArray<I>,
+    input_scale: i8,
+    output_precision: u8,
+    output_scale: i8,
+    cast_options: &CastOptions,
+) -> Result<PrimitiveArray<O>, ArrowError>
+where
+    I: DecimalType,
+    O: DecimalType,
+    I::Native: DecimalCast + ArrowNativeTypeOp,
+    O::Native: DecimalCast + ArrowNativeTypeOp,
+{
+    let error = cast_decimal_to_decimal_error::<I, O>(output_precision, output_scale);
+    let div = I::Native::from_decimal(10_i128)
+        .unwrap()
+        .pow_checked((input_scale - output_scale) as u32)?;
 
-        let half = div.div_wrapping(I::Native::from_usize(2).unwrap());
-        let half_neg = half.neg_wrapping();
+    let half = div.div_wrapping(I::Native::from_usize(2).unwrap());
+    let half_neg = half.neg_wrapping();
 
-        let f = |x: I::Native| {
-            // div is >= 10 and so this cannot overflow
-            let d = x.div_wrapping(div);
-            let r = x.mod_wrapping(div);
+    let f = |x: I::Native| {
+        // div is >= 10 and so this cannot overflow
+        let d = x.div_wrapping(div);
+        let r = x.mod_wrapping(div);
 
-            // Round result
-            let adjusted = match x >= I::Native::ZERO {
-                true if r >= half => d.add_wrapping(I::Native::ONE),
-                false if r <= half_neg => d.sub_wrapping(I::Native::ONE),
-                _ => d,
-            };
-            O::Native::from_decimal(adjusted)
+        // Round result
+        let adjusted = match x >= I::Native::ZERO {
+            true if r >= half => d.add_wrapping(I::Native::ONE),
+            false if r <= half_neg => d.sub_wrapping(I::Native::ONE),
+            _ => d,
         };
+        O::Native::from_decimal(adjusted)
+    };
 
-        match cast_options.safe {
-            true => array.unary_opt(f),
-            false => array.try_unary(|x| f(x).ok_or_else(|| error(x)))?,
-        }
-    } else {
-        let mul = O::Native::from_decimal(10_i128)
-            .unwrap()
-            .pow_checked((output_scale - input_scale) as u32)?;
+    Ok(match cast_options.safe {
+        true => array.unary_opt(f),
+        false => array.try_unary(|x| f(x).ok_or_else(|| error(x)))?,
+    })
+}
 
-        let f = |x| O::Native::from_decimal(x).and_then(|x| x.mul_checked(mul).ok());
+fn convert_to_bigger_scale_decimal<I, O>(
+    array: &PrimitiveArray<I>,
+    input_scale: i8,
+    output_precision: u8,
+    output_scale: i8,
+    cast_options: &CastOptions,
+) -> Result<PrimitiveArray<O>, ArrowError>
+where
+    I: DecimalType,
+    O: DecimalType,
+    I::Native: DecimalCast + ArrowNativeTypeOp,
+    O::Native: DecimalCast + ArrowNativeTypeOp,
+{
+    let error = cast_decimal_to_decimal_error::<I, O>(output_precision, output_scale);
+    let mul = O::Native::from_decimal(10_i128)
+        .unwrap()
+        .pow_checked((output_scale - input_scale) as u32)?;
 
-        match cast_options.safe {
-            true => array.unary_opt(f),
-            false => array.try_unary(|x| f(x).ok_or_else(|| error(x)))?,
+    let f = |x| O::Native::from_decimal(x).and_then(|x| x.mul_checked(mul).ok());
+
+    Ok(match cast_options.safe {
+        true => array.unary_opt(f),
+        false => array.try_unary(|x| f(x).ok_or_else(|| error(x)))?,
+    })
+}
+
+// Only support one type of decimal cast operations
+fn cast_decimal_to_decimal_same_type<T>(
+    array: &PrimitiveArray<T>,
+    input_scale: i8,
+    output_precision: u8,
+    output_scale: i8,
+    cast_options: &CastOptions,
+) -> Result<ArrayRef, ArrowError>
+where
+    T: DecimalType,
+    T::Native: DecimalCast + ArrowNativeTypeOp,
+{
+    let array: PrimitiveArray<T> = match input_scale.cmp(&output_scale) {
+        Ordering::Equal => {
+            // the scale doesn't change, the native value don't need to be changed
+            array.clone()
         }
+        Ordering::Greater => convert_to_smaller_equal_scale_decimal::<T, T>(

Review Comment:
   Equal scale is handled by above branch. Why this is `convert_to_smaller_equal_scale_decimal`?



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] alamb commented on a diff in pull request #4088: optimize cast for same decimal type and same scale

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #4088:
URL: https://github.com/apache/arrow-rs/pull/4088#discussion_r1167834759


##########
arrow-cast/src/cast.rs:
##########
@@ -2081,29 +2081,102 @@ impl DecimalCast for i256 {
     }
 }
 
-fn cast_decimal_to_decimal<I, O>(
-    array: &PrimitiveArray<I>,
-    input_scale: i8,
+fn cast_decimal_to_decimal_error<O>(
     output_precision: u8,
     output_scale: i8,
-    cast_options: &CastOptions,
-) -> Result<ArrayRef, ArrowError>
+) -> impl Fn(<O as ArrowPrimitiveType>::Native) -> ArrowError
 where
-    I: DecimalType,
     O: DecimalType,
-    I::Native: DecimalCast + ArrowNativeTypeOp,
     O::Native: DecimalCast + ArrowNativeTypeOp,
 {
-    let error = |x| {
+    move |x: O::Native| {
         ArrowError::CastError(format!(
             "Cannot cast to {}({}, {}). Overflowing on {:?}",
             O::PREFIX,
             output_precision,
             output_scale,
             x
         ))
+    }
+}
+
+fn cast_decimal_to_decimal_same_type<T>(

Review Comment:
   got it -- thank you --I think your most recent PR makes this different much more clear



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] viirya commented on a diff in pull request #4088: optimize cast for same decimal type and same scale

Posted by "viirya (via GitHub)" <gi...@apache.org>.
viirya commented on code in PR #4088:
URL: https://github.com/apache/arrow-rs/pull/4088#discussion_r1167054727


##########
arrow-cast/src/cast.rs:
##########
@@ -2081,29 +2081,102 @@ impl DecimalCast for i256 {
     }
 }
 
-fn cast_decimal_to_decimal<I, O>(
-    array: &PrimitiveArray<I>,
-    input_scale: i8,
+fn cast_decimal_to_decimal_error<O>(
     output_precision: u8,
     output_scale: i8,
-    cast_options: &CastOptions,
-) -> Result<ArrayRef, ArrowError>
+) -> impl Fn(<O as ArrowPrimitiveType>::Native) -> ArrowError
 where
-    I: DecimalType,
     O: DecimalType,
-    I::Native: DecimalCast + ArrowNativeTypeOp,
     O::Native: DecimalCast + ArrowNativeTypeOp,
 {
-    let error = |x| {
+    move |x: O::Native| {
         ArrowError::CastError(format!(
             "Cannot cast to {}({}, {}). Overflowing on {:?}",
             O::PREFIX,
             output_precision,
             output_scale,
             x
         ))
+    }
+}
+
+fn cast_decimal_to_decimal_same_type<T>(
+    array: &PrimitiveArray<T>,
+    input_scale: i8,
+    output_precision: u8,
+    output_scale: i8,
+    cast_options: &CastOptions,
+) -> Result<ArrayRef, ArrowError>
+where
+    T: DecimalType,
+    T::Native: DecimalCast + ArrowNativeTypeOp,
+{
+    let error = cast_decimal_to_decimal_error::<T>(output_precision, output_scale);
+
+    let array: PrimitiveArray<T> = if input_scale == output_scale {
+        // the scale doesn't change, the native value don't need to be changed
+        array.clone()
+    } else if input_scale > output_scale {
+        let div = T::Native::from_decimal(10_i128)
+            .unwrap()
+            .pow_checked((input_scale - output_scale) as u32)?;
+
+        let half = div.div_wrapping(T::Native::from_usize(2).unwrap());
+        let half_neg = half.neg_wrapping();
+
+        let f = |x: T::Native| {
+            // div is >= 10 and so this cannot overflow
+            let d = x.div_wrapping(div);
+            let r = x.mod_wrapping(div);
+
+            // Round result
+            let adjusted = match x >= T::Native::ZERO {
+                true if r >= half => d.add_wrapping(T::Native::ONE),
+                false if r <= half_neg => d.sub_wrapping(T::Native::ONE),
+                _ => d,
+            };
+            Some(adjusted)
+        };
+
+        match cast_options.safe {
+            true => array.unary_opt(f),
+            false => array.try_unary(|x| f(x).ok_or_else(|| error(x)))?,
+        }
+    } else {
+        // input_scale > output_scale

Review Comment:
   ```suggestion
           // input_scale < output_scale
   ```



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] liukun4515 commented on a diff in pull request #4088: optimize cast for same decimal type and same scale

Posted by "liukun4515 (via GitHub)" <gi...@apache.org>.
liukun4515 commented on code in PR #4088:
URL: https://github.com/apache/arrow-rs/pull/4088#discussion_r1169501781


##########
arrow-cast/src/cast.rs:
##########
@@ -2081,66 +2081,166 @@ impl DecimalCast for i256 {
     }
 }
 
-fn cast_decimal_to_decimal<I, O>(
-    array: &PrimitiveArray<I>,
-    input_scale: i8,
+fn cast_decimal_to_decimal_error<I, O>(
     output_precision: u8,
     output_scale: i8,
-    cast_options: &CastOptions,
-) -> Result<ArrayRef, ArrowError>
+) -> impl Fn(<I as ArrowPrimitiveType>::Native) -> ArrowError
 where
     I: DecimalType,
     O: DecimalType,
     I::Native: DecimalCast + ArrowNativeTypeOp,
     O::Native: DecimalCast + ArrowNativeTypeOp,
 {
-    let error = |x| {
+    move |x: I::Native| {
         ArrowError::CastError(format!(
             "Cannot cast to {}({}, {}). Overflowing on {:?}",
             O::PREFIX,
             output_precision,
             output_scale,
             x
         ))
-    };
+    }
+}
 
-    let array: PrimitiveArray<O> = if input_scale > output_scale {
-        let div = I::Native::from_decimal(10_i128)
-            .unwrap()
-            .pow_checked((input_scale - output_scale) as u32)?;
+fn convert_to_smaller_equal_scale_decimal<I, O>(
+    array: &PrimitiveArray<I>,
+    input_scale: i8,
+    output_precision: u8,
+    output_scale: i8,
+    cast_options: &CastOptions,
+) -> Result<PrimitiveArray<O>, ArrowError>
+where
+    I: DecimalType,
+    O: DecimalType,
+    I::Native: DecimalCast + ArrowNativeTypeOp,
+    O::Native: DecimalCast + ArrowNativeTypeOp,
+{
+    let error = cast_decimal_to_decimal_error::<I, O>(output_precision, output_scale);
+    let div = I::Native::from_decimal(10_i128)
+        .unwrap()
+        .pow_checked((input_scale - output_scale) as u32)?;
 
-        let half = div.div_wrapping(I::Native::from_usize(2).unwrap());
-        let half_neg = half.neg_wrapping();
+    let half = div.div_wrapping(I::Native::from_usize(2).unwrap());
+    let half_neg = half.neg_wrapping();
 
-        let f = |x: I::Native| {
-            // div is >= 10 and so this cannot overflow
-            let d = x.div_wrapping(div);
-            let r = x.mod_wrapping(div);
+    let f = |x: I::Native| {
+        // div is >= 10 and so this cannot overflow
+        let d = x.div_wrapping(div);
+        let r = x.mod_wrapping(div);
 
-            // Round result
-            let adjusted = match x >= I::Native::ZERO {
-                true if r >= half => d.add_wrapping(I::Native::ONE),
-                false if r <= half_neg => d.sub_wrapping(I::Native::ONE),
-                _ => d,
-            };
-            O::Native::from_decimal(adjusted)
+        // Round result
+        let adjusted = match x >= I::Native::ZERO {
+            true if r >= half => d.add_wrapping(I::Native::ONE),
+            false if r <= half_neg => d.sub_wrapping(I::Native::ONE),
+            _ => d,
         };
+        O::Native::from_decimal(adjusted)
+    };
 
-        match cast_options.safe {
-            true => array.unary_opt(f),
-            false => array.try_unary(|x| f(x).ok_or_else(|| error(x)))?,
-        }
-    } else {
-        let mul = O::Native::from_decimal(10_i128)
-            .unwrap()
-            .pow_checked((output_scale - input_scale) as u32)?;
+    Ok(match cast_options.safe {
+        true => array.unary_opt(f),
+        false => array.try_unary(|x| f(x).ok_or_else(|| error(x)))?,
+    })
+}
 
-        let f = |x| O::Native::from_decimal(x).and_then(|x| x.mul_checked(mul).ok());
+fn convert_to_bigger_scale_decimal<I, O>(
+    array: &PrimitiveArray<I>,
+    input_scale: i8,
+    output_precision: u8,
+    output_scale: i8,
+    cast_options: &CastOptions,
+) -> Result<PrimitiveArray<O>, ArrowError>
+where
+    I: DecimalType,
+    O: DecimalType,
+    I::Native: DecimalCast + ArrowNativeTypeOp,
+    O::Native: DecimalCast + ArrowNativeTypeOp,
+{
+    let error = cast_decimal_to_decimal_error::<I, O>(output_precision, output_scale);
+    let mul = O::Native::from_decimal(10_i128)
+        .unwrap()
+        .pow_checked((output_scale - input_scale) as u32)?;
 
-        match cast_options.safe {
-            true => array.unary_opt(f),
-            false => array.try_unary(|x| f(x).ok_or_else(|| error(x)))?,
+    let f = |x| O::Native::from_decimal(x).and_then(|x| x.mul_checked(mul).ok());
+
+    Ok(match cast_options.safe {
+        true => array.unary_opt(f),
+        false => array.try_unary(|x| f(x).ok_or_else(|| error(x)))?,
+    })
+}
+
+// Only support one type of decimal cast operations
+fn cast_decimal_to_decimal_same_type<T>(
+    array: &PrimitiveArray<T>,
+    input_scale: i8,
+    output_precision: u8,
+    output_scale: i8,
+    cast_options: &CastOptions,
+) -> Result<ArrayRef, ArrowError>
+where
+    T: DecimalType,
+    T::Native: DecimalCast + ArrowNativeTypeOp,
+{
+    let array: PrimitiveArray<T> = match input_scale.cmp(&output_scale) {
+        Ordering::Equal => {
+            // the scale doesn't change, the native value don't need to be changed
+            array.clone()
         }
+        Ordering::Greater => convert_to_smaller_equal_scale_decimal::<T, T>(

Review Comment:
   the name of function is not right.
   And I will change the name to `convert_to_smaller_scale_decimal`



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] liukun4515 commented on a diff in pull request #4088: optimize cast for same decimal type and same scale

Posted by "liukun4515 (via GitHub)" <gi...@apache.org>.
liukun4515 commented on code in PR #4088:
URL: https://github.com/apache/arrow-rs/pull/4088#discussion_r1169502213


##########
arrow-cast/src/cast.rs:
##########
@@ -2081,66 +2081,166 @@ impl DecimalCast for i256 {
     }
 }
 
-fn cast_decimal_to_decimal<I, O>(
-    array: &PrimitiveArray<I>,
-    input_scale: i8,
+fn cast_decimal_to_decimal_error<I, O>(
     output_precision: u8,
     output_scale: i8,
-    cast_options: &CastOptions,
-) -> Result<ArrayRef, ArrowError>
+) -> impl Fn(<I as ArrowPrimitiveType>::Native) -> ArrowError
 where
     I: DecimalType,
     O: DecimalType,
     I::Native: DecimalCast + ArrowNativeTypeOp,
     O::Native: DecimalCast + ArrowNativeTypeOp,
 {
-    let error = |x| {
+    move |x: I::Native| {
         ArrowError::CastError(format!(
             "Cannot cast to {}({}, {}). Overflowing on {:?}",
             O::PREFIX,
             output_precision,
             output_scale,
             x
         ))
-    };
+    }
+}
 
-    let array: PrimitiveArray<O> = if input_scale > output_scale {
-        let div = I::Native::from_decimal(10_i128)
-            .unwrap()
-            .pow_checked((input_scale - output_scale) as u32)?;
+fn convert_to_smaller_equal_scale_decimal<I, O>(
+    array: &PrimitiveArray<I>,
+    input_scale: i8,
+    output_precision: u8,
+    output_scale: i8,
+    cast_options: &CastOptions,
+) -> Result<PrimitiveArray<O>, ArrowError>
+where
+    I: DecimalType,
+    O: DecimalType,
+    I::Native: DecimalCast + ArrowNativeTypeOp,
+    O::Native: DecimalCast + ArrowNativeTypeOp,
+{
+    let error = cast_decimal_to_decimal_error::<I, O>(output_precision, output_scale);
+    let div = I::Native::from_decimal(10_i128)
+        .unwrap()
+        .pow_checked((input_scale - output_scale) as u32)?;
 
-        let half = div.div_wrapping(I::Native::from_usize(2).unwrap());
-        let half_neg = half.neg_wrapping();
+    let half = div.div_wrapping(I::Native::from_usize(2).unwrap());
+    let half_neg = half.neg_wrapping();
 
-        let f = |x: I::Native| {
-            // div is >= 10 and so this cannot overflow
-            let d = x.div_wrapping(div);
-            let r = x.mod_wrapping(div);
+    let f = |x: I::Native| {
+        // div is >= 10 and so this cannot overflow
+        let d = x.div_wrapping(div);
+        let r = x.mod_wrapping(div);
 
-            // Round result
-            let adjusted = match x >= I::Native::ZERO {
-                true if r >= half => d.add_wrapping(I::Native::ONE),
-                false if r <= half_neg => d.sub_wrapping(I::Native::ONE),
-                _ => d,
-            };
-            O::Native::from_decimal(adjusted)
+        // Round result
+        let adjusted = match x >= I::Native::ZERO {
+            true if r >= half => d.add_wrapping(I::Native::ONE),
+            false if r <= half_neg => d.sub_wrapping(I::Native::ONE),
+            _ => d,
         };
+        O::Native::from_decimal(adjusted)
+    };
 
-        match cast_options.safe {
-            true => array.unary_opt(f),
-            false => array.try_unary(|x| f(x).ok_or_else(|| error(x)))?,
-        }
-    } else {
-        let mul = O::Native::from_decimal(10_i128)
-            .unwrap()
-            .pow_checked((output_scale - input_scale) as u32)?;
+    Ok(match cast_options.safe {
+        true => array.unary_opt(f),
+        false => array.try_unary(|x| f(x).ok_or_else(|| error(x)))?,
+    })
+}
 
-        let f = |x| O::Native::from_decimal(x).and_then(|x| x.mul_checked(mul).ok());
+fn convert_to_bigger_scale_decimal<I, O>(
+    array: &PrimitiveArray<I>,
+    input_scale: i8,
+    output_precision: u8,
+    output_scale: i8,
+    cast_options: &CastOptions,
+) -> Result<PrimitiveArray<O>, ArrowError>
+where
+    I: DecimalType,
+    O: DecimalType,
+    I::Native: DecimalCast + ArrowNativeTypeOp,
+    O::Native: DecimalCast + ArrowNativeTypeOp,
+{
+    let error = cast_decimal_to_decimal_error::<I, O>(output_precision, output_scale);
+    let mul = O::Native::from_decimal(10_i128)
+        .unwrap()
+        .pow_checked((output_scale - input_scale) as u32)?;
 
-        match cast_options.safe {
-            true => array.unary_opt(f),
-            false => array.try_unary(|x| f(x).ok_or_else(|| error(x)))?,
+    let f = |x| O::Native::from_decimal(x).and_then(|x| x.mul_checked(mul).ok());
+
+    Ok(match cast_options.safe {
+        true => array.unary_opt(f),
+        false => array.try_unary(|x| f(x).ok_or_else(|| error(x)))?,
+    })
+}
+
+// Only support one type of decimal cast operations
+fn cast_decimal_to_decimal_same_type<T>(
+    array: &PrimitiveArray<T>,
+    input_scale: i8,
+    output_precision: u8,
+    output_scale: i8,
+    cast_options: &CastOptions,
+) -> Result<ArrayRef, ArrowError>
+where
+    T: DecimalType,
+    T::Native: DecimalCast + ArrowNativeTypeOp,
+{
+    let array: PrimitiveArray<T> = match input_scale.cmp(&output_scale) {
+        Ordering::Equal => {
+            // the scale doesn't change, the native value don't need to be changed
+            array.clone()
         }
+        Ordering::Greater => convert_to_smaller_equal_scale_decimal::<T, T>(
+            array,
+            input_scale,
+            output_precision,
+            output_scale,
+            cast_options,
+        )?,
+        Ordering::Less => {
+            // input_scale < output_scale
+            convert_to_bigger_scale_decimal::<T, T>(
+                array,
+                input_scale,
+                output_precision,
+                output_scale,
+                cast_options,
+            )?
+        }
+    };
+
+    Ok(Arc::new(array.with_precision_and_scale(
+        output_precision,
+        output_scale,
+    )?))
+}
+
+// Support two different types of decimal cast operations
+fn cast_decimal_to_decimal<I, O>(
+    array: &PrimitiveArray<I>,
+    input_scale: i8,
+    output_precision: u8,
+    output_scale: i8,
+    cast_options: &CastOptions,
+) -> Result<ArrayRef, ArrowError>
+where
+    I: DecimalType,
+    O: DecimalType,
+    I::Native: DecimalCast + ArrowNativeTypeOp,
+    O::Native: DecimalCast + ArrowNativeTypeOp,
+{
+    let array: PrimitiveArray<O> = if input_scale > output_scale {
+        convert_to_smaller_equal_scale_decimal::<I, O>(
+            array,
+            input_scale,
+            output_precision,
+            output_scale,
+            cast_options,
+        )?
+    } else {
+        convert_to_bigger_scale_decimal::<I, O>(

Review Comment:
   changed in the new commit.
   Thanks for your review @viirya 



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] liukun4515 commented on a diff in pull request #4088: optimize cast for same decimal type and same scale

Posted by "liukun4515 (via GitHub)" <gi...@apache.org>.
liukun4515 commented on code in PR #4088:
URL: https://github.com/apache/arrow-rs/pull/4088#discussion_r1168468151


##########
arrow-cast/src/cast.rs:
##########
@@ -2081,29 +2081,102 @@ impl DecimalCast for i256 {
     }
 }
 
-fn cast_decimal_to_decimal<I, O>(
-    array: &PrimitiveArray<I>,
-    input_scale: i8,
+fn cast_decimal_to_decimal_error<O>(
     output_precision: u8,
     output_scale: i8,
-    cast_options: &CastOptions,
-) -> Result<ArrayRef, ArrowError>
+) -> impl Fn(<O as ArrowPrimitiveType>::Native) -> ArrowError
 where
-    I: DecimalType,
     O: DecimalType,
-    I::Native: DecimalCast + ArrowNativeTypeOp,
     O::Native: DecimalCast + ArrowNativeTypeOp,
 {
-    let error = |x| {
+    move |x: O::Native| {
         ArrowError::CastError(format!(
             "Cannot cast to {}({}, {}). Overflowing on {:?}",
             O::PREFIX,
             output_precision,
             output_scale,
             x
         ))
+    }
+}
+
+fn cast_decimal_to_decimal_same_type<T>(
+    array: &PrimitiveArray<T>,
+    input_scale: i8,
+    output_precision: u8,
+    output_scale: i8,
+    cast_options: &CastOptions,
+) -> Result<ArrayRef, ArrowError>
+where
+    T: DecimalType,
+    T::Native: DecimalCast + ArrowNativeTypeOp,
+{
+    let error = cast_decimal_to_decimal_error::<T>(output_precision, output_scale);
+
+    let array: PrimitiveArray<T> = if input_scale == output_scale {
+        // the scale doesn't change, the native value don't need to be changed
+        array.clone()
+    } else if input_scale > output_scale {
+        let div = T::Native::from_decimal(10_i128)
+            .unwrap()
+            .pow_checked((input_scale - output_scale) as u32)?;
+
+        let half = div.div_wrapping(T::Native::from_usize(2).unwrap());
+        let half_neg = half.neg_wrapping();
+
+        let f = |x: T::Native| {
+            // div is >= 10 and so this cannot overflow
+            let d = x.div_wrapping(div);
+            let r = x.mod_wrapping(div);
+
+            // Round result
+            let adjusted = match x >= T::Native::ZERO {
+                true if r >= half => d.add_wrapping(T::Native::ONE),
+                false if r <= half_neg => d.sub_wrapping(T::Native::ONE),
+                _ => d,
+            };
+            Some(adjusted)
+        };
+
+        match cast_options.safe {
+            true => array.unary_opt(f),
+            false => array.try_unary(|x| f(x).ok_or_else(|| error(x)))?,

Review Comment:
   > Your `f(x)` always returns `Some`. So you don't need `try_unary` (because you never get a error).
   
   thanks for your explanation
   
   I have refactor the code according to the comments to combine the same logic.



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] liukun4515 merged pull request #4088: optimize cast for same decimal type and same scale

Posted by "liukun4515 (via GitHub)" <gi...@apache.org>.
liukun4515 merged PR #4088:
URL: https://github.com/apache/arrow-rs/pull/4088


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org