Skip to content

Commit

Permalink
Extract safe_signed_abs() function
Browse files Browse the repository at this point in the history
  • Loading branch information
rafal-ch committed Sep 23, 2024
1 parent eaa2616 commit 5c0f1fd
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 8 deletions.
21 changes: 21 additions & 0 deletions crates/fuel-gas-price-algorithm/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,24 @@ 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);
}
}
13 changes: 5 additions & 8 deletions crates/fuel-gas-price-algorithm/src/v1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ use std::{
ops::Div,
};

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

#[cfg(test)]
mod tests;
Expand Down Expand Up @@ -325,19 +328,13 @@ impl AlgorithmUpdaterV1 {

fn da_change(&self, p: i128, d: i128) -> i128 {
let pd_change = p.saturating_add(d);
let pd_change = if pd_change == i128::MIN {
pd_change + 1
} else {
pd_change
};
let upcast_percent = self.max_da_gas_price_change_percent.into();
let max_change = self
.new_scaled_da_gas_price
.saturating_mul(upcast_percent)
.saturating_div(100)
.into();
debug_assert!(pd_change != i128::MIN);
let clamped_change = pd_change.abs().min(max_change);
let clamped_change = safe_signed_abs(pd_change).min(max_change);
pd_change.signum().saturating_mul(clamped_change)
}

Expand Down

0 comments on commit 5c0f1fd

Please sign in to comment.