Skip to main content

search_core/cost/
decimal.rs

1//! The fixed-point decimal cost [`Decimal`].
2
3use core::fmt;
4use core::ops::Add;
5
6use super::Cost;
7
8mod parse;
9
10pub use parse::ParseDecimalError;
11
12/// A non-negative fixed-point decimal cost with `K` decimal places.
13///
14/// Stores an integer number of units of `10^-K` in a `u64`, so `Decimal::<2>` counts
15/// hundredths. Arithmetic is exact integer arithmetic: sums never round and are independent
16/// of the summation order, which floats cannot promise. The scale is part of the type, so
17/// costs of different scales cannot be mixed by accident.
18///
19/// `K` ranges from `0` to `19`; a larger `K` is rejected at compile time as soon as a
20/// constructor, [`Decimal::SCALE`] or formatting is used. The largest representable cost is
21/// `u64::MAX / 10^K` whole units plus the fraction; `+` overflows like `u64` (see the
22/// [`Cost`] contract).
23///
24/// ```compile_fail
25/// // 10^20 does not fit into u64.
26/// let _ = search_core::Decimal::<20>::from_raw(1);
27/// ```
28///
29/// [`Default`] is zero and, being derived, skips that check; it is harmless because every
30/// operation that needs the scale performs it.
31///
32/// [`Display`](fmt::Display) and [`Debug`](fmt::Debug) both print the decimal value with
33/// exactly `K` fraction digits; [`FromStr`](core::str::FromStr) parses it back exactly,
34/// rejecting text that would round (see [`ParseDecimalError`]).
35///
36/// # Examples
37///
38/// ```
39/// use search_core::{Cost, Decimal};
40///
41/// type Cents = Decimal<2>;
42///
43/// let step = Cents::from_raw(125); // 1.25
44/// let bonus = Cents::from_int(2).unwrap();
45///
46/// assert_eq!(step + bonus, Cents::from_raw(325));
47/// assert_eq!((step + bonus).to_string(), "3.25");
48/// assert!(Cents::ZERO < step);
49/// ```
50#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
51pub struct Decimal<const K: u32>(u64);
52
53impl<const K: u32> Decimal<K> {
54    /// The number of raw units in one whole unit: `10^K`.
55    ///
56    /// Referencing it with `K > 19` is a compile-time error, because `10^20` exceeds `u64`.
57    pub const SCALE: u64 = {
58        assert!(K <= 19, "Decimal supports at most 19 decimal places");
59        10_u64.pow(K)
60    };
61
62    /// Creates a cost from its raw number of `10^-K` units.
63    #[must_use]
64    pub const fn from_raw(raw: u64) -> Self {
65        let _ = Self::SCALE;
66        Self(raw)
67    }
68
69    /// Creates the cost of `whole` full units, or `None` if `whole * 10^K` overflows `u64`.
70    #[must_use]
71    pub const fn from_int(whole: u64) -> Option<Self> {
72        match whole.checked_mul(Self::SCALE) {
73            Some(raw) => Some(Self(raw)),
74            None => None,
75        }
76    }
77
78    /// The raw number of `10^-K` units.
79    #[must_use]
80    pub const fn raw(self) -> u64 {
81        self.0
82    }
83}
84
85impl<const K: u32> Add for Decimal<K> {
86    type Output = Self;
87
88    fn add(self, other: Self) -> Self {
89        Self(self.0 + other.0)
90    }
91}
92
93impl<const K: u32> Cost for Decimal<K> {
94    const ZERO: Self = Self::from_raw(0);
95
96    fn saturating_add(self, other: Self) -> Self {
97        Self(self.0.saturating_add(other.0))
98    }
99
100    fn saturating_times(self, factor: u32) -> Self {
101        Self(self.0.saturating_mul(u64::from(factor)))
102    }
103}
104
105impl<const K: u32> fmt::Display for Decimal<K> {
106    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
107        let whole = self.0 / Self::SCALE;
108        if K == 0 {
109            return write!(f, "{whole}");
110        }
111
112        let fraction = self.0 % Self::SCALE;
113        let digits = K as usize;
114
115        write!(f, "{whole}.{fraction:0digits$}")
116    }
117}
118
119impl<const K: u32> fmt::Debug for Decimal<K> {
120    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121        fmt::Display::fmt(self, f)
122    }
123}
124
125#[cfg(test)]
126mod tests {
127    //! Unit and property tests for [`Decimal`].
128
129    extern crate std;
130
131    use std::string::ToString;
132
133    use super::{Cost, Decimal};
134    use proptest::prelude::*;
135
136    /// Formatting pads the fraction to exactly `K` digits.
137    #[test]
138    fn display_pads_fraction() {
139        assert_eq!(Decimal::<2>::from_raw(5).to_string(), "0.05");
140        assert_eq!(Decimal::<3>::from_raw(12_000).to_string(), "12.000");
141        assert_eq!(format_debug(Decimal::<1>::from_raw(15)), "1.5");
142    }
143
144    /// `K = 0` prints a plain integer without a decimal point.
145    #[test]
146    fn display_without_fraction() {
147        assert_eq!(Decimal::<0>::from_raw(42).to_string(), "42");
148        assert_eq!(Decimal::<0>::SCALE, 1);
149    }
150
151    /// The largest scale prints all 19 fraction digits of `u64::MAX`.
152    #[test]
153    fn display_largest_scale() {
154        assert_eq!(
155            Decimal::<19>::from_raw(u64::MAX).to_string(),
156            "1.8446744073709551615"
157        );
158        assert_eq!(Decimal::<19>::SCALE, 10_000_000_000_000_000_000);
159    }
160
161    /// `from_int` multiplies by the scale and rejects overflow.
162    #[test]
163    fn from_int_checks_overflow() {
164        assert_eq!(Decimal::<3>::from_int(7).map(Decimal::raw), Some(7_000));
165        assert_eq!(
166            Decimal::<19>::from_int(1).map(Decimal::raw),
167            Some(Decimal::<19>::SCALE)
168        );
169        assert_eq!(Decimal::<19>::from_int(2), None);
170    }
171
172    /// The saturating operations clamp at `u64::MAX` raw units.
173    #[test]
174    fn saturating_operations_clamp() {
175        let max = Decimal::<2>::from_raw(u64::MAX);
176        assert_eq!(max.saturating_add(Decimal::from_raw(1)), max);
177        assert_eq!(max.saturating_times(2), max);
178        assert_eq!(max.saturating_times(0), Decimal::ZERO);
179    }
180
181    /// Formats a value with [`Debug`](core::fmt::Debug).
182    fn format_debug(value: Decimal<1>) -> std::string::String {
183        std::format!("{value:?}")
184    }
185
186    proptest! {
187        /// Order and addition agree with the raw `u64` values.
188        #[test]
189        fn matches_raw_arithmetic(a in 0..u64::MAX / 2, b in 0..u64::MAX / 2) {
190            let (x, y) = (Decimal::<4>::from_raw(a), Decimal::<4>::from_raw(b));
191            prop_assert_eq!((x + y).raw(), a + b);
192            prop_assert_eq!(x.cmp(&y), a.cmp(&b));
193        }
194
195        /// Formatting round-trips: whole part and padded fraction reproduce the raw value.
196        #[test]
197        fn display_round_trips(raw: u64) {
198            let text = Decimal::<6>::from_raw(raw).to_string();
199            let (whole, fraction) = text.split_once('.').expect("K > 0 prints a point");
200            prop_assert_eq!(fraction.len(), 6);
201            let parsed = whole.parse::<u64>().unwrap() * 1_000_000 + fraction.parse::<u64>().unwrap();
202            prop_assert_eq!(parsed, raw);
203        }
204    }
205}