use std::fmt;
use std::ops::{Add, AddAssign, Sub, SubAssign};
pub const CHIP_SCALE: i64 = 1000;
const MAX_UNITS: f64 = 9_007_199_254_740_992.0;
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Chips(pub(crate) i64);
impl Chips {
pub const ZERO: Chips = Chips(0);
pub const fn whole(chips: i64) -> Chips {
match chips.checked_mul(CHIP_SCALE) {
Some(units) if units.unsigned_abs() <= 1 << 53 => Chips(units),
_ => panic!("Chips::whole: amount out of range"),
}
}
pub const fn from_units(units: i64) -> Chips {
Chips(units)
}
pub const fn units(self) -> i64 {
self.0
}
pub fn from_f64(amount: f64) -> Option<Chips> {
let scaled = amount * CHIP_SCALE as f64;
if !scaled.is_finite() || scaled.abs() > MAX_UNITS {
return None;
}
let units = scaled.round();
let error = (units / CHIP_SCALE as f64 - amount).abs();
(error <= 1e-9 || error <= 4.0 * f64::EPSILON * amount.abs()).then_some(Chips(units as i64))
}
pub fn to_f64(self) -> f64 {
self.0 as f64 / CHIP_SCALE as f64
}
pub fn fraction(self, fraction: f64) -> Chips {
Chips((self.0 as f64 * fraction).round_ties_even() as i64)
}
}
impl Add for Chips {
type Output = Chips;
fn add(self, rhs: Chips) -> Chips {
Chips(self.0 + rhs.0)
}
}
impl AddAssign for Chips {
fn add_assign(&mut self, rhs: Chips) {
self.0 += rhs.0;
}
}
impl Sub for Chips {
type Output = Chips;
fn sub(self, rhs: Chips) -> Chips {
Chips(self.0 - rhs.0)
}
}
impl SubAssign for Chips {
fn sub_assign(&mut self, rhs: Chips) {
self.0 -= rhs.0;
}
}
impl fmt::Display for Chips {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let sign = if self.0 < 0 { "-" } else { "" };
let units = self.0.unsigned_abs();
let scale = CHIP_SCALE as u64;
let (whole, frac) = (units / scale, units % scale);
if frac == 0 {
return write!(f, "{sign}{whole}");
}
let digits = format!("{frac:03}");
write!(f, "{sign}{whole}.{}", digits.trim_end_matches('0'))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn whole_and_units_round_trip_within_the_exact_range() {
assert_eq!(Chips::whole(7).units(), 7 * CHIP_SCALE);
assert_eq!(Chips::from_units(CHIP_SCALE), Chips::whole(1));
let largest = (1i64 << 53) / CHIP_SCALE;
assert_eq!(Chips::whole(largest).units(), largest * CHIP_SCALE);
assert_eq!(Chips::whole(-largest).units(), -largest * CHIP_SCALE);
}
#[test]
#[should_panic(expected = "Chips::whole: amount out of range")]
fn whole_rejects_amounts_beyond_the_exact_range() {
let _ = Chips::whole(i64::MAX / CHIP_SCALE);
}
#[test]
fn from_f64_accepts_thousandths_and_rejects_finer_amounts() {
assert_eq!(Chips::from_f64(5.5), Some(Chips(5500)));
assert_eq!(Chips::from_f64(0.001), Some(Chips(1)));
assert_eq!(Chips::from_f64(0.1 + 0.2), Some(Chips(300)));
assert_eq!(Chips::from_f64(1e9), Some(Chips::whole(1_000_000_000)));
assert_eq!(
Chips::from_f64(123_456_789.123),
Some(Chips(123_456_789_123))
);
assert_eq!(Chips::from_f64(0.0005), None);
assert_eq!(Chips::from_f64(1e-6), None);
assert_eq!(Chips::from_f64(1_000_000.000_1), None);
assert_eq!(Chips::from_f64(f64::NAN), None);
assert_eq!(Chips::from_f64(f64::INFINITY), None);
assert_eq!(Chips::from_f64(f64::MAX), None);
}
#[test]
fn display_is_exact_and_trims_trailing_zeros() {
assert_eq!(Chips(1815).to_string(), "1.815");
assert_eq!(Chips(500).to_string(), "0.5");
assert_eq!(Chips(1).to_string(), "0.001");
assert_eq!(Chips::whole(100).to_string(), "100");
assert_eq!(Chips(-2050).to_string(), "-2.05");
assert_ne!(Chips(1814).to_string(), Chips(1815).to_string());
}
#[test]
fn fraction_rounds_half_to_even() {
assert_eq!(Chips(5500).fraction(0.33), Chips(1815));
assert_eq!(Chips(5).fraction(0.5), Chips(2));
assert_eq!(Chips(7).fraction(0.5), Chips(4));
assert_eq!(Chips(100).fraction(f64::NAN), Chips::ZERO);
}
}