#[cfg(feature = "float")]
use super::NonNegF64;
use super::{Cost, Decimal};
pub trait CostExt: Cost {
#[must_use]
fn saturating_sub(self, other: Self) -> Self;
#[must_use]
fn to_f64(self) -> f64;
}
macro_rules! integer_cost_ext {
($($ty:ty => $to_f64:path),*) => {
$(
impl CostExt for $ty {
fn saturating_sub(self, other: Self) -> Self {
<$ty>::saturating_sub(self, other)
}
fn to_f64(self) -> f64 {
$to_f64(self)
}
}
)*
};
}
integer_cost_ext!(
u8 => f64::from,
u16 => f64::from,
u32 => f64::from,
u64 => u64_to_f64,
u128 => u128_to_f64,
usize => usize_to_f64
);
#[expect(clippy::cast_precision_loss, reason = "only used for priorities")]
fn u64_to_f64(cost: u64) -> f64 {
cost as f64
}
#[expect(clippy::cast_precision_loss, reason = "only used for priorities")]
fn u128_to_f64(cost: u128) -> f64 {
cost as f64
}
#[expect(clippy::cast_precision_loss, reason = "only used for priorities")]
fn usize_to_f64(cost: usize) -> f64 {
cost as f64
}
impl<const K: u32> CostExt for Decimal<K> {
fn saturating_sub(self, other: Self) -> Self {
Self::from_raw(self.raw().saturating_sub(other.raw()))
}
fn to_f64(self) -> f64 {
u64_to_f64(self.raw())
}
}
#[cfg(feature = "float")]
impl CostExt for NonNegF64 {
fn saturating_sub(self, other: Self) -> Self {
Self::new((self.get() - other.get()).max(0.0)).unwrap_or(Self::ZERO)
}
fn to_f64(self) -> f64 {
self.get()
}
}
#[cfg(test)]
mod tests {
use proptest::prelude::*;
use super::{CostExt, Decimal};
#[test]
fn integers_saturate_and_convert() {
assert_eq!(CostExt::saturating_sub(2_u8, 5), 0);
assert_eq!(CostExt::saturating_sub(9_u128, 4), 5);
assert_eq!(CostExt::saturating_sub(7_usize, 7), 0);
assert!((CostExt::to_f64(3_u16) - 3.0).abs() < f64::EPSILON);
assert!((CostExt::to_f64(u64::from(u32::MAX)) - f64::from(u32::MAX)).abs() < 1.0);
}
#[test]
fn decimals_use_raw_units() {
let a = Decimal::<2>::from_raw(150);
let b = Decimal::<2>::from_raw(25);
assert_eq!(a.saturating_sub(b), Decimal::from_raw(125));
assert_eq!(b.saturating_sub(a), Decimal::from_raw(0));
assert!((a.to_f64() - 150.0).abs() < f64::EPSILON);
}
#[cfg(feature = "float")]
#[test]
fn floats_clamp_at_zero() {
use crate::{Cost, NonNegF64};
let half = NonNegF64::new(0.5).expect("non-negative");
let two = NonNegF64::new(2.0).expect("non-negative");
assert_eq!(
two.saturating_sub(half),
NonNegF64::new(1.5).expect("non-negative")
);
assert_eq!(half.saturating_sub(two), NonNegF64::ZERO);
assert_eq!(
NonNegF64::INFINITY.saturating_sub(NonNegF64::INFINITY),
NonNegF64::ZERO
);
assert_eq!(NonNegF64::INFINITY.saturating_sub(two), NonNegF64::INFINITY);
assert!((two.to_f64() - 2.0).abs() < f64::EPSILON);
}
proptest! {
#[test]
fn subtraction_inverts_addition(a in 0..u64::MAX / 2, b in 0..u64::MAX / 2) {
prop_assert_eq!(CostExt::saturating_sub(a + b, b), a);
prop_assert_eq!(CostExt::saturating_sub(b, a + b + 1), 0);
}
#[test]
fn conversion_is_monotone(a: u64, b: u64) {
if a <= b {
prop_assert!(a.to_f64() <= b.to_f64());
}
}
}
}