Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Check overflow while casting floating point value to decimal128 #3021

Merged
merged 7 commits into from
Nov 6, 2022
Merged
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 78 additions & 4 deletions arrow-cast/src/cast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
viirya marked this conversation as resolved.
Show resolved Hide resolved
})
});
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 {
Copy link
Contributor

@tustvold tustvold Nov 6, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you think we need to implement From<f64> for i128?

error[E0277]: the trait bound `i128: From<f64>` is not satisfied

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh... It seems support for this is unstable rust-lang/rust#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

Err(ArrowError::CastError(format!(
"Cannot cast to {}({}, {}). Overflowing on {:?}",
Decimal128Type::PREFIX,
precision,
scale,
v
)))
} else {
Ok(mul_v as i128)
}
}
})
})
.and_then(|a| a.with_precision_and_scale(precision, scale))
.map(|a| Arc::new(a) as ArrayRef)
}
}

fn cast_floating_point_to_decimal256<T: ArrowPrimitiveType>(
Expand Down Expand Up @@ -588,11 +633,13 @@ pub fn cast_with_options(
as_primitive_array::<Float32Type>(array),
*precision,
*scale,
cast_options,
),
Float64 => cast_floating_point_to_decimal128(
as_primitive_array::<Float64Type>(array),
*precision,
*scale,
cast_options,
),
Null => Ok(new_null_array(to_type, array.len())),
_ => Err(ArrowError::CastError(format!(
Expand Down Expand Up @@ -6110,4 +6157,31 @@ mod tests {
);
assert!(casted_array.is_err());
}

#[test]
fn test_cast_floating_point_to_decimal128_overflow() {
let array = Float64Array::from(vec![f64::MAX]);
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 },
);
let err = casted_array.unwrap_err().to_string();
let expected_error = "Cast error: Cannot cast to Decimal128(38, 30)";
assert!(
err.contains(expected_error),
"did not find expected error '{}' in actual error '{}'",
expected_error,
err
);
}
}