You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@arrow.apache.org by GitBox <gi...@apache.org> on 2022/11/05 00:54:51 UTC

[GitHub] [arrow-rs] viirya opened a new pull request, #3021: Check overflow while casting floating point value to decimal128

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

   # 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 #3020.
   
   # 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.
   -->
   
   # 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 pull request #3021: Check overflow while casting floating point value to decimal128

Posted by GitBox <gi...@apache.org>.
viirya commented on PR #3021:
URL: https://github.com/apache/arrow-rs/pull/3021#issuecomment-1304743611

   Thanks @tustvold 


-- 
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] tustvold merged pull request #3021: Check overflow while casting floating point value to decimal128

Posted by GitBox <gi...@apache.org>.
tustvold merged PR #3021:
URL: https://github.com/apache/arrow-rs/pull/3021


-- 
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] tustvold commented on a diff in pull request #3021: Check overflow while casting floating point value to decimal128

Posted by GitBox <gi...@apache.org>.
tustvold commented on code in PR #3021:
URL: https://github.com/apache/arrow-rs/pull/3021#discussion_r1014764363


##########
arrow-cast/src/cast.rs:
##########
@@ -344,16 +344,50 @@ fn cast_floating_point_to_decimal128<T: ArrowPrimitiveType>(
     array: &PrimitiveArray<T>,
     precision: u8,
     scale: u8,
+    cast_options: &CastOptions,
 ) -> Result<ArrayRef, ArrowError>
 where
     <T as ArrowPrimitiveType>::Native: AsPrimitive<f64>,
 {
     let mul = 10_f64.powi(scale as i32);
 
-    array
-        .unary::<_, Decimal128Type>(|v| (v.as_() * mul).round() as i128)
-        .with_precision_and_scale(precision, scale)
-        .map(|a| Arc::new(a) as ArrayRef)
+    if cast_options.safe {
+        let iter = array.iter().map(|v| {
+            v.and_then(|v| {
+                let mul_v = (mul * v.as_()).round();
+                if mul_v == f64::INFINITY || mul_v == f64::NEG_INFINITY {
+                    None
+                } else {
+                    Some(mul_v as i128)
+                }

Review Comment:
   ```suggestion
                   (mul * v.as_()).round().to_i128()
   ```



-- 
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] tustvold commented on a diff in pull request #3021: Check overflow while casting floating point value to decimal128

Posted by GitBox <gi...@apache.org>.
tustvold commented on code in PR #3021:
URL: https://github.com/apache/arrow-rs/pull/3021#discussion_r1014555110


##########
arrow-cast/src/cast.rs:
##########
@@ -6110,4 +6158,24 @@ mod tests {
         );
         assert!(casted_array.is_err());
     }
+
+    #[test]
+    fn test_cast_floating_point_to_decimal128_overflow() {
+        let array = Float64Array::from(vec![100e10]);
+        let array = Arc::new(array) as ArrayRef;
+        let casted_array = cast_with_options(
+            &array,
+            &DataType::Decimal128(38, 30),
+            &CastOptions { safe: true },
+        );
+        assert!(casted_array.is_ok());
+        assert!(casted_array.unwrap().is_null(0));
+
+        let casted_array = cast_with_options(
+            &array,
+            &DataType::Decimal128(38, 30),
+            &CastOptions { safe: false },
+        );
+        assert!(casted_array.is_err());

Review Comment:
   Typically we do something like 
   
   ```
   let err = operation.unwrap_err().to_string();
   assert!(err.contains("EXPECTED), "{}", err)
   ```
   To avoid false positives



-- 
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 #3021: Check overflow while casting floating point value to decimal128

Posted by GitBox <gi...@apache.org>.
viirya commented on code in PR #3021:
URL: https://github.com/apache/arrow-rs/pull/3021#discussion_r1014569664


##########
arrow-cast/src/cast.rs:
##########
@@ -344,16 +348,58 @@ fn cast_floating_point_to_decimal128<T: ArrowPrimitiveType>(
     array: &PrimitiveArray<T>,
     precision: u8,
     scale: u8,
+    cast_options: &CastOptions,
 ) -> Result<ArrayRef, ArrowError>
 where
     <T as ArrowPrimitiveType>::Native: AsPrimitive<f64>,
 {
     let mul = 10_f64.powi(scale as i32);
 
-    array
-        .unary::<_, Decimal128Type>(|v| (v.as_() * mul).round() as i128)
-        .with_precision_and_scale(precision, scale)
-        .map(|a| Arc::new(a) as ArrayRef)
+    if cast_options.safe {
+        let iter = array.iter().map(|v| {
+            v.and_then(|v| {
+                let mul_v = (mul * v.as_()).round() as i128;

Review Comment:
   If we don't need to validate against precision, the multiplication of f64 itself won't overflow.



-- 
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] tustvold commented on a diff in pull request #3021: Check overflow while casting floating point value to decimal128

Posted by GitBox <gi...@apache.org>.
tustvold commented on code in PR #3021:
URL: https://github.com/apache/arrow-rs/pull/3021#discussion_r1014751245


##########
arrow-cast/src/cast.rs:
##########
@@ -344,16 +344,61 @@ fn cast_floating_point_to_decimal128<T: ArrowPrimitiveType>(
     array: &PrimitiveArray<T>,
     precision: u8,
     scale: u8,
+    cast_options: &CastOptions,
 ) -> Result<ArrayRef, ArrowError>
 where
     <T as ArrowPrimitiveType>::Native: AsPrimitive<f64>,
 {
     let mul = 10_f64.powi(scale as i32);
 
-    array
-        .unary::<_, Decimal128Type>(|v| (v.as_() * mul).round() as i128)
-        .with_precision_and_scale(precision, scale)
-        .map(|a| Arc::new(a) as ArrayRef)
+    if cast_options.safe {
+        let iter = array.iter().map(|v| {
+            v.and_then(|v| {
+                let mul_v = (mul * v.as_()).round();
+                if mul_v == f64::INFINITY || mul_v == f64::NEG_INFINITY {
+                    None
+                } else {
+                    Some(mul_v as i128)
+                }
+            })
+        });
+        let casted_array =
+            unsafe { PrimitiveArray::<Decimal128Type>::from_trusted_len_iter(iter) };
+        casted_array
+            .with_precision_and_scale(precision, scale)
+            .map(|a| Arc::new(a) as ArrayRef)
+    } else {
+        array
+            .try_unary::<_, Decimal128Type, _>(|v| {
+                mul.mul_checked(v.as_()).and_then(|value| {
+                    let mul_v = value.round();
+                    if mul_v == f64::INFINITY || mul_v == f64::NEG_INFINITY {
+                        Err(ArrowError::CastError(format!(
+                            "Cannot cast to {}({}, {}). Overflowing on {:?}",
+                            Decimal128Type::PREFIX,
+                            precision,
+                            scale,
+                            v
+                        )))
+                    } else {
+                        let integer = mul_v as i128;
+                        if integer == i128::MAX || integer == i128::MIN {

Review Comment:
   Can we use TryInto here, or some other fallible conversion instead of as, I think this will be faster and also avoid a false positive on i128::MAX?



-- 
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 #3021: Check overflow while casting floating point value to decimal128

Posted by GitBox <gi...@apache.org>.
viirya commented on code in PR #3021:
URL: https://github.com/apache/arrow-rs/pull/3021#discussion_r1014729434


##########
arrow-cast/src/cast.rs:
##########
@@ -344,16 +344,50 @@ fn cast_floating_point_to_decimal128<T: ArrowPrimitiveType>(
     array: &PrimitiveArray<T>,
     precision: u8,
     scale: u8,
+    cast_options: &CastOptions,
 ) -> Result<ArrayRef, ArrowError>
 where
     <T as ArrowPrimitiveType>::Native: AsPrimitive<f64>,
 {
     let mul = 10_f64.powi(scale as i32);
 
-    array
-        .unary::<_, Decimal128Type>(|v| (v.as_() * mul).round() as i128)
-        .with_precision_and_scale(precision, scale)
-        .map(|a| Arc::new(a) as ArrayRef)
+    if cast_options.safe {
+        let iter = array.iter().map(|v| {
+            v.and_then(|v| {
+                let mul_v = (mul * v.as_()).round();
+                if mul_v == f64::INFINITY || mul_v == f64::NEG_INFINITY {
+                    None
+                } else {
+                    Some(mul_v as i128)
+                }
+            })
+        });
+        let casted_array =
+            unsafe { PrimitiveArray::<Decimal128Type>::from_trusted_len_iter(iter) };
+        casted_array
+            .with_precision_and_scale(precision, scale)
+            .map(|a| Arc::new(a) as ArrayRef)
+    } else {
+        array
+            .try_unary::<_, Decimal128Type, _>(|v| {
+                mul.mul_checked(v.as_()).and_then(|value| {
+                    let mul_v = value.round();
+                    if mul_v == f64::INFINITY || mul_v == f64::NEG_INFINITY {
+                        Err(ArrowError::CastError(format!(
+                            "Cannot cast to {}({}, {}). Overflowing on {:?}",
+                            Decimal128Type::PREFIX,
+                            precision,
+                            scale,
+                            v
+                        )))
+                    } else {
+                        Ok(mul_v as i128)

Review Comment:
   Converting a floating value larger than i128::MAX to i128 will get i128::MAX.



-- 
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] tustvold commented on a diff in pull request #3021: Check overflow while casting floating point value to decimal128

Posted by GitBox <gi...@apache.org>.
tustvold commented on code in PR #3021:
URL: https://github.com/apache/arrow-rs/pull/3021#discussion_r1014751245


##########
arrow-cast/src/cast.rs:
##########
@@ -344,16 +344,61 @@ fn cast_floating_point_to_decimal128<T: ArrowPrimitiveType>(
     array: &PrimitiveArray<T>,
     precision: u8,
     scale: u8,
+    cast_options: &CastOptions,
 ) -> Result<ArrayRef, ArrowError>
 where
     <T as ArrowPrimitiveType>::Native: AsPrimitive<f64>,
 {
     let mul = 10_f64.powi(scale as i32);
 
-    array
-        .unary::<_, Decimal128Type>(|v| (v.as_() * mul).round() as i128)
-        .with_precision_and_scale(precision, scale)
-        .map(|a| Arc::new(a) as ArrayRef)
+    if cast_options.safe {
+        let iter = array.iter().map(|v| {
+            v.and_then(|v| {
+                let mul_v = (mul * v.as_()).round();
+                if mul_v == f64::INFINITY || mul_v == f64::NEG_INFINITY {
+                    None
+                } else {
+                    Some(mul_v as i128)
+                }
+            })
+        });
+        let casted_array =
+            unsafe { PrimitiveArray::<Decimal128Type>::from_trusted_len_iter(iter) };
+        casted_array
+            .with_precision_and_scale(precision, scale)
+            .map(|a| Arc::new(a) as ArrayRef)
+    } else {
+        array
+            .try_unary::<_, Decimal128Type, _>(|v| {
+                mul.mul_checked(v.as_()).and_then(|value| {
+                    let mul_v = value.round();
+                    if mul_v == f64::INFINITY || mul_v == f64::NEG_INFINITY {
+                        Err(ArrowError::CastError(format!(
+                            "Cannot cast to {}({}, {}). Overflowing on {:?}",
+                            Decimal128Type::PREFIX,
+                            precision,
+                            scale,
+                            v
+                        )))
+                    } else {
+                        let integer = mul_v as i128;
+                        if integer == i128::MAX || integer == i128::MIN {

Review Comment:
   Can we use TryInto here, I think this will be faster and also avoid a false positive on i128::MAX?



-- 
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 #3021: Check overflow while casting floating point value to decimal128

Posted by GitBox <gi...@apache.org>.
viirya commented on code in PR #3021:
URL: https://github.com/apache/arrow-rs/pull/3021#discussion_r1014756011


##########
arrow-cast/src/cast.rs:
##########
@@ -344,16 +344,50 @@ fn cast_floating_point_to_decimal128<T: ArrowPrimitiveType>(
     array: &PrimitiveArray<T>,
     precision: u8,
     scale: u8,
+    cast_options: &CastOptions,
 ) -> Result<ArrayRef, ArrowError>
 where
     <T as ArrowPrimitiveType>::Native: AsPrimitive<f64>,
 {
     let mul = 10_f64.powi(scale as i32);
 
-    array
-        .unary::<_, Decimal128Type>(|v| (v.as_() * mul).round() as i128)
-        .with_precision_and_scale(precision, scale)
-        .map(|a| Arc::new(a) as ArrayRef)
+    if cast_options.safe {
+        let iter = array.iter().map(|v| {
+            v.and_then(|v| {
+                let mul_v = (mul * v.as_()).round();
+                if mul_v == f64::INFINITY || mul_v == f64::NEG_INFINITY {
+                    None
+                } else {
+                    Some(mul_v as i128)
+                }
+            })
+        });
+        let casted_array =
+            unsafe { PrimitiveArray::<Decimal128Type>::from_trusted_len_iter(iter) };
+        casted_array
+            .with_precision_and_scale(precision, scale)
+            .map(|a| Arc::new(a) as ArrayRef)
+    } else {
+        array
+            .try_unary::<_, Decimal128Type, _>(|v| {
+                mul.mul_checked(v.as_()).and_then(|value| {
+                    let mul_v = value.round();
+                    let integer: i128 = mul_v.to_i128().ok_or_else(|| {

Review Comment:
   It covers f64::INFINITY, f64::MAX, etc. cases.



-- 
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] tustvold commented on a diff in pull request #3021: Check overflow while casting floating point value to decimal128

Posted by GitBox <gi...@apache.org>.
tustvold commented on code in PR #3021:
URL: https://github.com/apache/arrow-rs/pull/3021#discussion_r1014728749


##########
arrow-cast/src/cast.rs:
##########
@@ -344,16 +344,50 @@ fn cast_floating_point_to_decimal128<T: ArrowPrimitiveType>(
     array: &PrimitiveArray<T>,
     precision: u8,
     scale: u8,
+    cast_options: &CastOptions,
 ) -> Result<ArrayRef, ArrowError>
 where
     <T as ArrowPrimitiveType>::Native: AsPrimitive<f64>,
 {
     let mul = 10_f64.powi(scale as i32);
 
-    array
-        .unary::<_, Decimal128Type>(|v| (v.as_() * mul).round() as i128)
-        .with_precision_and_scale(precision, scale)
-        .map(|a| Arc::new(a) as ArrayRef)
+    if cast_options.safe {
+        let iter = array.iter().map(|v| {
+            v.and_then(|v| {
+                let mul_v = (mul * v.as_()).round();
+                if mul_v == f64::INFINITY || mul_v == f64::NEG_INFINITY {
+                    None
+                } else {
+                    Some(mul_v as i128)
+                }
+            })
+        });
+        let casted_array =
+            unsafe { PrimitiveArray::<Decimal128Type>::from_trusted_len_iter(iter) };
+        casted_array
+            .with_precision_and_scale(precision, scale)
+            .map(|a| Arc::new(a) as ArrayRef)
+    } else {
+        array
+            .try_unary::<_, Decimal128Type, _>(|v| {
+                mul.mul_checked(v.as_()).and_then(|value| {
+                    let mul_v = value.round();
+                    if mul_v == f64::INFINITY || mul_v == f64::NEG_INFINITY {
+                        Err(ArrowError::CastError(format!(
+                            "Cannot cast to {}({}, {}). Overflowing on {:?}",
+                            Decimal128Type::PREFIX,
+                            precision,
+                            scale,
+                            v
+                        )))
+                    } else {
+                        Ok(mul_v as i128)

Review Comment:
   I'm still confused as to how this can't overflow?
   
   If the float value was i128::MAX any scale greater than 1 would result in this conversion overflowing?



-- 
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 #3021: Check overflow while casting floating point value to decimal128

Posted by GitBox <gi...@apache.org>.
viirya commented on code in PR #3021:
URL: https://github.com/apache/arrow-rs/pull/3021#discussion_r1014754383


##########
arrow-cast/src/cast.rs:
##########
@@ -344,16 +344,61 @@ fn cast_floating_point_to_decimal128<T: ArrowPrimitiveType>(
     array: &PrimitiveArray<T>,
     precision: u8,
     scale: u8,
+    cast_options: &CastOptions,
 ) -> Result<ArrayRef, ArrowError>
 where
     <T as ArrowPrimitiveType>::Native: AsPrimitive<f64>,
 {
     let mul = 10_f64.powi(scale as i32);
 
-    array
-        .unary::<_, Decimal128Type>(|v| (v.as_() * mul).round() as i128)
-        .with_precision_and_scale(precision, scale)
-        .map(|a| Arc::new(a) as ArrayRef)
+    if cast_options.safe {
+        let iter = array.iter().map(|v| {
+            v.and_then(|v| {
+                let mul_v = (mul * v.as_()).round();
+                if mul_v == f64::INFINITY || mul_v == f64::NEG_INFINITY {
+                    None
+                } else {
+                    Some(mul_v as i128)
+                }
+            })
+        });
+        let casted_array =
+            unsafe { PrimitiveArray::<Decimal128Type>::from_trusted_len_iter(iter) };
+        casted_array
+            .with_precision_and_scale(precision, scale)
+            .map(|a| Arc::new(a) as ArrayRef)
+    } else {
+        array
+            .try_unary::<_, Decimal128Type, _>(|v| {
+                mul.mul_checked(v.as_()).and_then(|value| {
+                    let mul_v = value.round();
+                    if mul_v == f64::INFINITY || mul_v == f64::NEG_INFINITY {
+                        Err(ArrowError::CastError(format!(
+                            "Cannot cast to {}({}, {}). Overflowing on {:?}",
+                            Decimal128Type::PREFIX,
+                            precision,
+                            scale,
+                            v
+                        )))
+                    } else {
+                        let integer = mul_v as i128;
+                        if integer == i128::MAX || integer == i128::MIN {

Review Comment:
   Do you think we need to implement `From<f64>` for i128?
   ```
   error[E0277]: the trait bound `i128: From<f64>` is not satisfied
   ```



-- 
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] ursabot commented on pull request #3021: Check overflow while casting floating point value to decimal128

Posted by GitBox <gi...@apache.org>.
ursabot commented on PR #3021:
URL: https://github.com/apache/arrow-rs/pull/3021#issuecomment-1304725230

   Benchmark runs are scheduled for baseline = 4f525fe1daa1058dfa90b3cd72cb6cc957f2ea7a and contender = 108e7d276a83bfd9c3144005e0a000e8331fdfaa. 108e7d276a83bfd9c3144005e0a000e8331fdfaa is a master commit associated with this PR. Results will be available as each benchmark for each run completes.
   Conbench compare runs links:
   [Skipped :warning: Benchmarking of arrow-rs-commits is not supported on ec2-t3-xlarge-us-east-2] [ec2-t3-xlarge-us-east-2](https://conbench.ursa.dev/compare/runs/f4f2052f92114df2bcb0221ee01de2c3...85be5072883f4839a23b83ac026732fe/)
   [Skipped :warning: Benchmarking of arrow-rs-commits is not supported on test-mac-arm] [test-mac-arm](https://conbench.ursa.dev/compare/runs/3d63b1ba462e46349e9997a03e321b9d...e9516bfcec06442e95054fcb2788b99b/)
   [Skipped :warning: Benchmarking of arrow-rs-commits is not supported on ursa-i9-9960x] [ursa-i9-9960x](https://conbench.ursa.dev/compare/runs/d17af09da8f646ba9e3abd1630a70464...b22ea179df5d4c28963d2975bb7df07b/)
   [Skipped :warning: Benchmarking of arrow-rs-commits is not supported on ursa-thinkcentre-m75q] [ursa-thinkcentre-m75q](https://conbench.ursa.dev/compare/runs/bb9ae7c9dcbd41fc969b2a1728c66443...060427eff1c346c3a95a3e116b59b886/)
   Buildkite builds:
   Supported benchmarks:
   ec2-t3-xlarge-us-east-2: Supported benchmark langs: Python, R. Runs only benchmarks with cloud = True
   test-mac-arm: Supported benchmark langs: C++, Python, R
   ursa-i9-9960x: Supported benchmark langs: Python, R, JavaScript
   ursa-thinkcentre-m75q: Supported benchmark langs: C++, Java
   


-- 
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] tustvold commented on a diff in pull request #3021: Check overflow while casting floating point value to decimal128

Posted by GitBox <gi...@apache.org>.
tustvold commented on code in PR #3021:
URL: https://github.com/apache/arrow-rs/pull/3021#discussion_r1014554917


##########
arrow-cast/src/cast.rs:
##########
@@ -344,16 +348,58 @@ fn cast_floating_point_to_decimal128<T: ArrowPrimitiveType>(
     array: &PrimitiveArray<T>,
     precision: u8,
     scale: u8,
+    cast_options: &CastOptions,
 ) -> Result<ArrayRef, ArrowError>
 where
     <T as ArrowPrimitiveType>::Native: AsPrimitive<f64>,
 {
     let mul = 10_f64.powi(scale as i32);
 
-    array
-        .unary::<_, Decimal128Type>(|v| (v.as_() * mul).round() as i128)
-        .with_precision_and_scale(precision, scale)
-        .map(|a| Arc::new(a) as ArrayRef)
+    if cast_options.safe {
+        let iter = array.iter().map(|v| {
+            v.and_then(|v| {
+                let mul_v = (mul * v.as_()).round() as i128;
+                if precision <= DECIMAL128_MAX_PRECISION
+                    && (mul_v > MAX_DECIMAL_FOR_EACH_PRECISION[precision as usize - 1]
+                        || mul_v < MIN_DECIMAL_FOR_EACH_PRECISION[precision as usize - 1])

Review Comment:
   I don't think we need to validate precision, as we don't in other places. This is explicitly an opt-in, we only need to error if the underlying value is truncated/overflows - i.e. data loss has occurred.



-- 
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] tustvold commented on a diff in pull request #3021: Check overflow while casting floating point value to decimal128

Posted by GitBox <gi...@apache.org>.
tustvold commented on code in PR #3021:
URL: https://github.com/apache/arrow-rs/pull/3021#discussion_r1014554847


##########
arrow-cast/src/cast.rs:
##########
@@ -344,16 +348,58 @@ fn cast_floating_point_to_decimal128<T: ArrowPrimitiveType>(
     array: &PrimitiveArray<T>,
     precision: u8,
     scale: u8,
+    cast_options: &CastOptions,
 ) -> Result<ArrayRef, ArrowError>
 where
     <T as ArrowPrimitiveType>::Native: AsPrimitive<f64>,
 {
     let mul = 10_f64.powi(scale as i32);
 
-    array
-        .unary::<_, Decimal128Type>(|v| (v.as_() * mul).round() as i128)
-        .with_precision_and_scale(precision, scale)
-        .map(|a| Arc::new(a) as ArrayRef)
+    if cast_options.safe {
+        let iter = array.iter().map(|v| {
+            v.and_then(|v| {
+                let mul_v = (mul * v.as_()).round() as i128;

Review Comment:
   Can this overflow?



-- 
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 #3021: Check overflow while casting floating point value to decimal128

Posted by GitBox <gi...@apache.org>.
viirya commented on code in PR #3021:
URL: https://github.com/apache/arrow-rs/pull/3021#discussion_r1014570319


##########
arrow-cast/src/cast.rs:
##########
@@ -344,16 +348,58 @@ fn cast_floating_point_to_decimal128<T: ArrowPrimitiveType>(
     array: &PrimitiveArray<T>,
     precision: u8,
     scale: u8,
+    cast_options: &CastOptions,
 ) -> Result<ArrayRef, ArrowError>
 where
     <T as ArrowPrimitiveType>::Native: AsPrimitive<f64>,
 {
     let mul = 10_f64.powi(scale as i32);
 
-    array
-        .unary::<_, Decimal128Type>(|v| (v.as_() * mul).round() as i128)
-        .with_precision_and_scale(precision, scale)
-        .map(|a| Arc::new(a) as ArrayRef)
+    if cast_options.safe {
+        let iter = array.iter().map(|v| {
+            v.and_then(|v| {
+                let mul_v = (mul * v.as_()).round() as i128;

Review Comment:
   The only case that might be "overflow" here is an infinity value. After converting to `i128`, it is `i128::MAX` that is over the range of decimal 128.



-- 
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] tustvold commented on a diff in pull request #3021: Check overflow while casting floating point value to decimal128

Posted by GitBox <gi...@apache.org>.
tustvold commented on code in PR #3021:
URL: https://github.com/apache/arrow-rs/pull/3021#discussion_r1014755155


##########
arrow-cast/src/cast.rs:
##########
@@ -344,16 +344,61 @@ fn cast_floating_point_to_decimal128<T: ArrowPrimitiveType>(
     array: &PrimitiveArray<T>,
     precision: u8,
     scale: u8,
+    cast_options: &CastOptions,
 ) -> Result<ArrayRef, ArrowError>
 where
     <T as ArrowPrimitiveType>::Native: AsPrimitive<f64>,
 {
     let mul = 10_f64.powi(scale as i32);
 
-    array
-        .unary::<_, Decimal128Type>(|v| (v.as_() * mul).round() as i128)
-        .with_precision_and_scale(precision, scale)
-        .map(|a| Arc::new(a) as ArrayRef)
+    if cast_options.safe {
+        let iter = array.iter().map(|v| {
+            v.and_then(|v| {
+                let mul_v = (mul * v.as_()).round();
+                if mul_v == f64::INFINITY || mul_v == f64::NEG_INFINITY {
+                    None
+                } else {
+                    Some(mul_v as i128)
+                }
+            })
+        });
+        let casted_array =
+            unsafe { PrimitiveArray::<Decimal128Type>::from_trusted_len_iter(iter) };
+        casted_array
+            .with_precision_and_scale(precision, scale)
+            .map(|a| Arc::new(a) as ArrayRef)
+    } else {
+        array
+            .try_unary::<_, Decimal128Type, _>(|v| {
+                mul.mul_checked(v.as_()).and_then(|value| {
+                    let mul_v = value.round();
+                    if mul_v == f64::INFINITY || mul_v == f64::NEG_INFINITY {
+                        Err(ArrowError::CastError(format!(
+                            "Cannot cast to {}({}, {}). Overflowing on {:?}",
+                            Decimal128Type::PREFIX,
+                            precision,
+                            scale,
+                            v
+                        )))
+                    } else {
+                        let integer = mul_v as i128;
+                        if integer == i128::MAX || integer == i128::MIN {

Review Comment:
   Oh... It seems support for this is unstable https://github.com/rust-lang/rust/issues/67057
   
   Perhaps we could use https://docs.rs/num/latest/num/trait.ToPrimitive.html ?
   
   This appears to be correctly checked https://docs.rs/num-traits/0.2.14/src/num_traits/cast.rs.html#310. We could also copy this 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] tustvold commented on a diff in pull request #3021: Check overflow while casting floating point value to decimal128

Posted by GitBox <gi...@apache.org>.
tustvold commented on code in PR #3021:
URL: https://github.com/apache/arrow-rs/pull/3021#discussion_r1014730326


##########
arrow-cast/src/cast.rs:
##########
@@ -344,16 +344,50 @@ fn cast_floating_point_to_decimal128<T: ArrowPrimitiveType>(
     array: &PrimitiveArray<T>,
     precision: u8,
     scale: u8,
+    cast_options: &CastOptions,
 ) -> Result<ArrayRef, ArrowError>
 where
     <T as ArrowPrimitiveType>::Native: AsPrimitive<f64>,
 {
     let mul = 10_f64.powi(scale as i32);
 
-    array
-        .unary::<_, Decimal128Type>(|v| (v.as_() * mul).round() as i128)
-        .with_precision_and_scale(precision, scale)
-        .map(|a| Arc::new(a) as ArrayRef)
+    if cast_options.safe {
+        let iter = array.iter().map(|v| {
+            v.and_then(|v| {
+                let mul_v = (mul * v.as_()).round();
+                if mul_v == f64::INFINITY || mul_v == f64::NEG_INFINITY {
+                    None
+                } else {
+                    Some(mul_v as i128)
+                }
+            })
+        });
+        let casted_array =
+            unsafe { PrimitiveArray::<Decimal128Type>::from_trusted_len_iter(iter) };
+        casted_array
+            .with_precision_and_scale(precision, scale)
+            .map(|a| Arc::new(a) as ArrayRef)
+    } else {
+        array
+            .try_unary::<_, Decimal128Type, _>(|v| {
+                mul.mul_checked(v.as_()).and_then(|value| {
+                    let mul_v = value.round();
+                    if mul_v == f64::INFINITY || mul_v == f64::NEG_INFINITY {
+                        Err(ArrowError::CastError(format!(
+                            "Cannot cast to {}({}, {}). Overflowing on {:?}",
+                            Decimal128Type::PREFIX,
+                            precision,
+                            scale,
+                            v
+                        )))
+                    } else {
+                        Ok(mul_v as i128)

Review Comment:
   I believe we also return errors for truncation when casting from say u64 to u32? I think it would a bit surprising to return an error for wrapping overflow but not saturating?



-- 
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 #3021: Check overflow while casting floating point value to decimal128

Posted by GitBox <gi...@apache.org>.
viirya commented on code in PR #3021:
URL: https://github.com/apache/arrow-rs/pull/3021#discussion_r1014729480


##########
arrow-cast/src/cast.rs:
##########
@@ -344,16 +344,50 @@ fn cast_floating_point_to_decimal128<T: ArrowPrimitiveType>(
     array: &PrimitiveArray<T>,
     precision: u8,
     scale: u8,
+    cast_options: &CastOptions,
 ) -> Result<ArrayRef, ArrowError>
 where
     <T as ArrowPrimitiveType>::Native: AsPrimitive<f64>,
 {
     let mul = 10_f64.powi(scale as i32);
 
-    array
-        .unary::<_, Decimal128Type>(|v| (v.as_() * mul).round() as i128)
-        .with_precision_and_scale(precision, scale)
-        .map(|a| Arc::new(a) as ArrayRef)
+    if cast_options.safe {
+        let iter = array.iter().map(|v| {
+            v.and_then(|v| {
+                let mul_v = (mul * v.as_()).round();
+                if mul_v == f64::INFINITY || mul_v == f64::NEG_INFINITY {
+                    None
+                } else {
+                    Some(mul_v as i128)
+                }
+            })
+        });
+        let casted_array =
+            unsafe { PrimitiveArray::<Decimal128Type>::from_trusted_len_iter(iter) };
+        casted_array
+            .with_precision_and_scale(precision, scale)
+            .map(|a| Arc::new(a) as ArrayRef)
+    } else {
+        array
+            .try_unary::<_, Decimal128Type, _>(|v| {
+                mul.mul_checked(v.as_()).and_then(|value| {
+                    let mul_v = value.round();
+                    if mul_v == f64::INFINITY || mul_v == f64::NEG_INFINITY {
+                        Err(ArrowError::CastError(format!(
+                            "Cannot cast to {}({}, {}). Overflowing on {:?}",
+                            Decimal128Type::PREFIX,
+                            precision,
+                            scale,
+                            v
+                        )))
+                    } else {
+                        Ok(mul_v as i128)

Review Comment:
   It won't overflow and won't wrapping back to smaller value.



-- 
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 #3021: Check overflow while casting floating point value to decimal128

Posted by GitBox <gi...@apache.org>.
viirya commented on code in PR #3021:
URL: https://github.com/apache/arrow-rs/pull/3021#discussion_r1014769206


##########
arrow-cast/src/cast.rs:
##########
@@ -344,16 +344,50 @@ fn cast_floating_point_to_decimal128<T: ArrowPrimitiveType>(
     array: &PrimitiveArray<T>,
     precision: u8,
     scale: u8,
+    cast_options: &CastOptions,
 ) -> Result<ArrayRef, ArrowError>
 where
     <T as ArrowPrimitiveType>::Native: AsPrimitive<f64>,
 {
     let mul = 10_f64.powi(scale as i32);
 
-    array
-        .unary::<_, Decimal128Type>(|v| (v.as_() * mul).round() as i128)
-        .with_precision_and_scale(precision, scale)
-        .map(|a| Arc::new(a) as ArrayRef)
+    if cast_options.safe {
+        let iter = array.iter().map(|v| {
+            v.and_then(|v| {
+                let mul_v = (mul * v.as_()).round();
+                if mul_v == f64::INFINITY || mul_v == f64::NEG_INFINITY {
+                    None
+                } else {
+                    Some(mul_v as i128)
+                }

Review Comment:
   oops, forgot this.



-- 
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