Skip to content

Commit

Permalink
Use saturating_abs() to protect against overflow
Browse files Browse the repository at this point in the history
  • Loading branch information
rafal-ch committed Sep 23, 2024
1 parent 5c0f1fd commit 056ba1e
Show file tree
Hide file tree
Showing 2 changed files with 2 additions and 26 deletions.
21 changes: 0 additions & 21 deletions crates/fuel-gas-price-algorithm/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,24 +18,3 @@ pub(crate) fn cumulative_percentage_change(
// `f64` over `u64::MAX` are cast to `u64::MAX`
approx.ceil() as u64
}

pub(crate) fn safe_signed_abs(n: i128) -> i128 {
let n = if n == i128::MIN {
n.saturating_add(1)
} else {
n
};
debug_assert!(n != i128::MIN);
n.abs()
}

#[cfg(test)]
mod tests {
use crate::utils::safe_signed_abs;

#[test]
fn safe_signed_abs_does_not_overflow_on_min_value() {
let abs = safe_signed_abs(i128::MIN);
assert_eq!(abs, i128::MAX);
}
}
7 changes: 2 additions & 5 deletions crates/fuel-gas-price-algorithm/src/v1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,7 @@ use std::{
ops::Div,
};

use crate::utils::{
cumulative_percentage_change,
safe_signed_abs,
};
use crate::utils::cumulative_percentage_change;

#[cfg(test)]
mod tests;
Expand Down Expand Up @@ -334,7 +331,7 @@ impl AlgorithmUpdaterV1 {
.saturating_mul(upcast_percent)
.saturating_div(100)
.into();
let clamped_change = safe_signed_abs(pd_change).min(max_change);
let clamped_change = pd_change.saturating_abs().min(max_change);
pd_change.signum().saturating_mul(clamped_change)
}

Expand Down

0 comments on commit 056ba1e

Please sign in to comment.