Skip to main content

native_solver/solver/
chips.rs

1//! Exact chip amounts for tree construction. Pots, stacks, and bet sizes are
2//! integers in units of `1 / CHIP_SCALE` input chips, so all-in detection,
3//! raise eligibility, and bet deduplication are exact comparisons and the
4//! tree's shape does not depend on the scale of the inputs. Payoffs are
5//! converted back to `f64` input chips only at terminals.
6
7use std::fmt;
8use std::ops::{Add, AddAssign, Sub, SubAssign};
9
10/// Internal units per input chip (amounts are quantized to 0.001 chips).
11pub const CHIP_SCALE: i64 = 1000;
12
13/// Largest unit count accepted from `f64` input: every value up to 2^53 is
14/// exact in `f64`, so the conversion back for payoffs is lossless.
15const MAX_UNITS: f64 = 9_007_199_254_740_992.0;
16
17/// An exact chip amount, stored as a whole number of `1 / CHIP_SCALE` chips.
18///
19/// Integer amounts make all-in detection, raise eligibility, and bet
20/// deduplication exact, and keep the tree's shape independent of the scale of
21/// the inputs. Build one with [`Chips::whole`] or [`Chips::from_f64`].
22///
23/// # Examples
24///
25/// ```
26/// use native_solver::Chips;
27///
28/// assert_eq!(Chips::from_f64(2.5), Some(Chips::whole(2) + Chips::from_f64(0.5).unwrap()));
29/// assert_eq!(Chips::from_f64(0.0001), None); // finer than 1/1000 of a chip
30/// assert_eq!(Chips::whole(3).to_string(), "3");
31/// ```
32#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
33pub struct Chips(pub(crate) i64);
34
35impl Chips {
36    /// No chips.
37    pub const ZERO: Chips = Chips(0);
38
39    /// A whole number of input chips.
40    ///
41    /// # Panics
42    /// Panics if the amount is larger than [`Chips::from_f64`] accepts
43    /// (2^53 internal units, about 9 × 10^12 chips), in every build mode.
44    pub const fn whole(chips: i64) -> Chips {
45        match chips.checked_mul(CHIP_SCALE) {
46            Some(units) if units.unsigned_abs() <= 1 << 53 => Chips(units),
47            _ => panic!("Chips::whole: amount out of range"),
48        }
49    }
50
51    /// An amount in internal units of `1 / CHIP_SCALE` input chips, so
52    /// `Chips::from_units(CHIP_SCALE)` is one chip.
53    pub const fn from_units(units: i64) -> Chips {
54        Chips(units)
55    }
56
57    /// The amount in internal units of `1 / CHIP_SCALE` input chips.
58    pub const fn units(self) -> i64 {
59        self.0
60    }
61
62    /// Converts an amount of chips, if it is a whole number of `1 / CHIP_SCALE` units.
63    ///
64    /// Only `f64` representation error is tolerated. Returns `None` for non-finite,
65    /// out-of-range, or finer-grained amounts rather than silently solving a
66    /// different game than the caller described.
67    pub fn from_f64(amount: f64) -> Option<Chips> {
68        let scaled = amount * CHIP_SCALE as f64;
69        if !scaled.is_finite() || scaled.abs() > MAX_UNITS {
70            return None;
71        }
72        let units = scaled.round();
73        let error = (units / CHIP_SCALE as f64 - amount).abs();
74        (error <= 1e-9 || error <= 4.0 * f64::EPSILON * amount.abs()).then_some(Chips(units as i64))
75    }
76
77    /// The amount in input chips.
78    pub fn to_f64(self) -> f64 {
79        self.0 as f64 / CHIP_SCALE as f64
80    }
81
82    /// `fraction` of this amount, rounded half-to-even to a whole unit.
83    ///
84    /// Non-finite or negative results become zero or negative amounts.
85    pub fn fraction(self, fraction: f64) -> Chips {
86        // `as` saturates out-of-range values and maps NaN to 0.
87        Chips((self.0 as f64 * fraction).round_ties_even() as i64)
88    }
89}
90
91impl Add for Chips {
92    type Output = Chips;
93    fn add(self, rhs: Chips) -> Chips {
94        Chips(self.0 + rhs.0)
95    }
96}
97
98impl AddAssign for Chips {
99    fn add_assign(&mut self, rhs: Chips) {
100        self.0 += rhs.0;
101    }
102}
103
104impl Sub for Chips {
105    type Output = Chips;
106    fn sub(self, rhs: Chips) -> Chips {
107        Chips(self.0 - rhs.0)
108    }
109}
110
111impl SubAssign for Chips {
112    fn sub_assign(&mut self, rhs: Chips) {
113        self.0 -= rhs.0;
114    }
115}
116
117/// Decimal input chips with at most three fractional digits and no trailing
118/// zeros (`1.815`, `0.5`, `100`), so distinct amounts never print alike.
119impl fmt::Display for Chips {
120    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121        let sign = if self.0 < 0 { "-" } else { "" };
122        let units = self.0.unsigned_abs();
123        let scale = CHIP_SCALE as u64;
124        let (whole, frac) = (units / scale, units % scale);
125        if frac == 0 {
126            return write!(f, "{sign}{whole}");
127        }
128        let digits = format!("{frac:03}");
129        write!(f, "{sign}{whole}.{}", digits.trim_end_matches('0'))
130    }
131}
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136
137    #[test]
138    fn whole_and_units_round_trip_within_the_exact_range() {
139        assert_eq!(Chips::whole(7).units(), 7 * CHIP_SCALE);
140        assert_eq!(Chips::from_units(CHIP_SCALE), Chips::whole(1));
141        let largest = (1i64 << 53) / CHIP_SCALE;
142        assert_eq!(Chips::whole(largest).units(), largest * CHIP_SCALE);
143        assert_eq!(Chips::whole(-largest).units(), -largest * CHIP_SCALE);
144    }
145
146    #[test]
147    #[should_panic(expected = "Chips::whole: amount out of range")]
148    fn whole_rejects_amounts_beyond_the_exact_range() {
149        let _ = Chips::whole(i64::MAX / CHIP_SCALE);
150    }
151
152    #[test]
153    fn from_f64_accepts_thousandths_and_rejects_finer_amounts() {
154        assert_eq!(Chips::from_f64(5.5), Some(Chips(5500)));
155        assert_eq!(Chips::from_f64(0.001), Some(Chips(1)));
156        assert_eq!(Chips::from_f64(0.1 + 0.2), Some(Chips(300)));
157        assert_eq!(Chips::from_f64(1e9), Some(Chips::whole(1_000_000_000)));
158        assert_eq!(
159            Chips::from_f64(123_456_789.123),
160            Some(Chips(123_456_789_123))
161        );
162        assert_eq!(Chips::from_f64(0.0005), None);
163        assert_eq!(Chips::from_f64(1e-6), None);
164        assert_eq!(Chips::from_f64(1_000_000.000_1), None);
165        assert_eq!(Chips::from_f64(f64::NAN), None);
166        assert_eq!(Chips::from_f64(f64::INFINITY), None);
167        assert_eq!(Chips::from_f64(f64::MAX), None);
168    }
169
170    #[test]
171    fn display_is_exact_and_trims_trailing_zeros() {
172        assert_eq!(Chips(1815).to_string(), "1.815");
173        assert_eq!(Chips(500).to_string(), "0.5");
174        assert_eq!(Chips(1).to_string(), "0.001");
175        assert_eq!(Chips::whole(100).to_string(), "100");
176        assert_eq!(Chips(-2050).to_string(), "-2.05");
177        assert_ne!(Chips(1814).to_string(), Chips(1815).to_string());
178    }
179
180    #[test]
181    fn fraction_rounds_half_to_even() {
182        assert_eq!(Chips(5500).fraction(0.33), Chips(1815));
183        assert_eq!(Chips(5).fraction(0.5), Chips(2));
184        assert_eq!(Chips(7).fraction(0.5), Chips(4));
185        assert_eq!(Chips(100).fraction(f64::NAN), Chips::ZERO);
186    }
187}