Skip to content

Commit

Permalink
fix(sub): error instead of panic when subtraction yields NaN (#1186)
Browse files Browse the repository at this point in the history
* fix(sub): panic when diffing inf floats

* cargo fmt

* clippy fix

* clippy fix

* changelog
  • Loading branch information
pront authored Dec 11, 2024
1 parent 62ac471 commit f1b7c8c
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 6 deletions.
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

0 comments on commit f1b7c8c

Please sign in to comment.