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

fix(sub): error instead of panic when subtraction yields NaN #1186

Merged
merged 5 commits into from
Dec 11, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions changelog.d/2893.fix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix a panic in float subtraction that produces NaN values.
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# result: can't subtract type float from float

large = to_float!("1.7976931348623157e+308")
inf_float = large + large
inf_float - inf_float
20 changes: 14 additions & 6 deletions src/compiler/value/arithmetic.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
#![deny(clippy::arithmetic_side_effects)]

use std::ops::{Add, Mul, Rem, Sub};

use bytes::{BufMut, Bytes, BytesMut};
use std::ops::{Add, Mul, Rem};

use crate::compiler::{
value::{Kind, VrlValueConvert},
ExpressionError,
};
use crate::value::{ObjectMap, Value};
use bytes::{BufMut, Bytes, BytesMut};

use super::ValueError;

Expand Down Expand Up @@ -60,6 +59,15 @@ pub trait VrlValueArithmetic: Sized {
fn eq_lossy(&self, rhs: &Self) -> bool;
}

fn safe_sub(lhv: f64, rhv: f64) -> Option<Value> {
let result = lhv - rhv;
if result.is_nan() {
None
} else {
Some(Value::from_f64_or_zero(result))
}
}

impl VrlValueArithmetic for Value {
/// Similar to [`std::ops::Mul`], but fallible (e.g. `TryMul`).
fn try_mul(self, rhs: Self) -> Result<Self, ValueError> {
Expand Down Expand Up @@ -155,9 +163,9 @@ impl VrlValueArithmetic for Value {
let rhv = rhs.try_into_i64().map_err(|_| err())?;
i64::wrapping_sub(lhv, rhv).into()
}
Value::Float(lhv) => {
let rhv = rhs.try_into_f64().map_err(|_| err())?;
lhv.sub(rhv).into()
Value::Float(lhs) => {
let rhs = rhs.try_into_f64().map_err(|_| err())?;
safe_sub(*lhs, rhs).ok_or_else(err)?
}
_ => return Err(err()),
};
Expand Down
Loading