mod decimal;
#[cfg(feature = "alloc")]
mod exact;
mod ext;
#[cfg(feature = "float")]
mod float;
mod wide;
use core::ops::Add;
pub use decimal::{Decimal, ParseDecimalError};
#[cfg(feature = "alloc")]
pub use exact::{BigUint, ExactArith, ExactNumber};
pub use ext::CostExt;
#[cfg(feature = "float")]
pub use float::NonNegF64;
pub use wide::WideMul;
pub trait Cost: Copy + Ord + Add<Output = Self> {
const ZERO: Self;
#[must_use]
fn saturating_add(self, other: Self) -> Self;
#[must_use]
fn saturating_times(self, factor: u32) -> Self;
}
macro_rules! unsigned_cost {
($($ty:ty),*) => {
$(
impl Cost for $ty {
const ZERO: Self = 0;
fn saturating_add(self, other: Self) -> Self {
<$ty>::saturating_add(self, other)
}
fn saturating_times(self, factor: u32) -> Self {
self.saturating_mul(<$ty>::from(factor))
}
}
)*
};
}
unsigned_cost!(u32, u64, u128);
macro_rules! narrow_unsigned_cost {
($($ty:ty),*) => {
$(
impl Cost for $ty {
const ZERO: Self = 0;
fn saturating_add(self, other: Self) -> Self {
<$ty>::saturating_add(self, other)
}
fn saturating_times(self, factor: u32) -> Self {
match <$ty>::try_from(factor) {
Ok(factor) => self.saturating_mul(factor),
Err(_) if self == 0 => 0,
Err(_) => <$ty>::MAX,
}
}
}
)*
};
}
narrow_unsigned_cost!(u8, u16, usize);
#[cfg(test)]
mod tests {
use super::Cost;
use proptest::prelude::*;
#[test]
fn saturating_add_saturates() {
assert_eq!(Cost::saturating_add(u8::MAX, 1), u8::MAX);
assert_eq!(Cost::saturating_add(3_u32, 4), 7);
}
#[test]
fn narrow_times_saturates_on_wide_factor() {
assert_eq!(2_u8.saturating_times(300), u8::MAX);
assert_eq!(0_u8.saturating_times(300), 0);
assert_eq!(7_u16.saturating_times(3), 21);
assert_eq!(0_u16.saturating_times(u32::MAX), 0);
}
#[test]
fn wide_times_is_exact() {
assert_eq!(5_u64.saturating_times(u32::MAX), 5 * u64::from(u32::MAX));
assert_eq!(u32::MAX.saturating_times(2), u32::MAX);
assert_eq!(9_u128.saturating_times(0), 0);
}
#[test]
fn zero_is_minimum() {
assert_eq!(<u8 as Cost>::ZERO, u8::MIN);
assert_eq!(<usize as Cost>::ZERO, usize::MIN);
}
proptest! {
#[test]
fn u16_times_matches_clamped_product(cost: u16, factor: u32) {
let exact = u64::from(cost) * u64::from(factor);
let expected = u16::try_from(exact).unwrap_or(u16::MAX);
prop_assert_eq!(cost.saturating_times(factor), expected);
}
#[test]
fn u32_add_matches_clamped_sum(a: u32, b: u32) {
let exact = u64::from(a) + u64::from(b);
let expected = u32::try_from(exact).unwrap_or(u32::MAX);
prop_assert_eq!(Cost::saturating_add(a, b), expected);
}
}
}