Skip to main content

search_core/cost/
exact.rs

1//! Exact arithmetic beyond one product: [`ExactArith`] maps a cost into an
2//! [`ExactNumber`] type where sums and products of any size are exact.
3
4use alloc::vec::Vec;
5use core::cmp::Ordering;
6use core::ops::{Add, Mul};
7
8#[cfg(feature = "float")]
9use super::NonNegF64;
10use super::{Cost, Decimal};
11
12mod signed;
13
14pub use signed::BigInt;
15
16/// A number type closed under exact `+` and `*`, with a zero, a one and a
17/// distance, for comparisons that [`WideMul`](crate::WideMul) cannot
18/// express: sums of products, products of three or more costs.
19///
20/// Implemented by [`BigUint`] and [`BigInt`] (exact) and, behind `float`, by
21/// `NonNegF64` (rounded like `f64`).
22pub trait ExactNumber: Clone + Ord + Add<Output = Self> + Mul<Output = Self> {
23    /// Zero.
24    fn zero() -> Self;
25
26    /// One.
27    fn one() -> Self;
28
29    /// `|self - other|`.
30    #[must_use]
31    fn abs_diff(&self, other: &Self) -> Self;
32}
33
34/// A cost that converts into an [`ExactNumber`] without loss.
35///
36/// An additive companion of [`Cost`] and [`WideMul`](crate::WideMul): cost
37/// types without it keep working everywhere else.
38///
39/// | Cost | `Exact` |
40/// |---|---|
41/// | `u8` to `u128`, `usize` | [`BigUint`] |
42/// | [`Decimal<K>`] | [`BigUint`] of the raw value (scale `10^K`) |
43/// | `NonNegF64` (feature `float`) | `NonNegF64` |
44///
45/// # Examples
46///
47/// ```
48/// use search_core::ExactArith;
49///
50/// // (d1 · c1 + s) · c2 against (d2 · c2 + s) · c1 without overflow.
51/// let e = |x: u64| x.exact();
52/// let left = (e(u64::MAX) * e(u64::MAX) + e(7)) * e(u64::MAX);
53/// let right = (e(1) * e(u64::MAX) + e(7)) * e(u64::MAX);
54/// assert!(left > right);
55/// ```
56pub trait ExactArith: Cost {
57    /// The exact number type.
58    type Exact: ExactNumber;
59
60    /// The cost as an exact number.
61    #[must_use]
62    fn exact(self) -> Self::Exact;
63}
64
65/// An arbitrary-precision unsigned integer: 32-bit limbs, least
66/// significant first, without most significant zero limbs.
67#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
68pub struct BigUint(Vec<u32>);
69
70impl BigUint {
71    /// The limbs, least significant first; empty for zero.
72    #[must_use]
73    pub fn limbs(&self) -> &[u32] {
74        &self.0
75    }
76
77    /// Drops the most significant zero limbs.
78    fn trimmed(mut self) -> Self {
79        while self.0.last() == Some(&0) {
80            self.0.pop();
81        }
82
83        self
84    }
85
86    /// `self - other` for `self >= other`.
87    fn minus(&self, other: &Self) -> Self {
88        let mut out = self.0.clone();
89        let mut borrow = 0_i64;
90        for (i, slot) in out.iter_mut().enumerate() {
91            let sub = i64::from(other.0.get(i).copied().unwrap_or(0)) + borrow;
92            let mut v = i64::from(*slot) - sub;
93            borrow = 0;
94            if v < 0 {
95                v += 1 << 32;
96                borrow = 1;
97            }
98
99            *slot = u32::try_from(v).expect("a limb after borrowing");
100        }
101
102        Self(out).trimmed()
103    }
104}
105
106impl From<u128> for BigUint {
107    fn from(mut value: u128) -> Self {
108        let mut limbs = Vec::new();
109        while value > 0 {
110            limbs.push(u32::try_from(value & u128::from(u32::MAX)).expect("masked"));
111            value >>= 32;
112        }
113
114        Self(limbs)
115    }
116}
117
118impl Add for BigUint {
119    type Output = Self;
120
121    fn add(self, other: Self) -> Self {
122        let n = self.0.len().max(other.0.len());
123        let mut out = Vec::with_capacity(n + 1);
124        let mut carry = 0_u64;
125        for i in 0..n {
126            let s = u64::from(self.0.get(i).copied().unwrap_or(0))
127                + u64::from(other.0.get(i).copied().unwrap_or(0))
128                + carry;
129            out.push(u32::try_from(s & u64::from(u32::MAX)).expect("masked"));
130            carry = s >> 32;
131        }
132
133        out.push(u32::try_from(carry).expect("a carry bit"));
134        Self(out).trimmed()
135    }
136}
137
138impl Mul for BigUint {
139    type Output = Self;
140
141    fn mul(self, other: Self) -> Self {
142        let mut out = alloc::vec![0_u32; self.0.len() + other.0.len()];
143        for (i, &a) in self.0.iter().enumerate() {
144            let mut carry = 0_u64;
145            for (j, &b) in other.0.iter().enumerate() {
146                let t = u64::from(a) * u64::from(b) + u64::from(out[i + j]) + carry;
147                out[i + j] = u32::try_from(t & u64::from(u32::MAX)).expect("masked");
148                carry = t >> 32;
149            }
150
151            out[i + other.0.len()] = u32::try_from(carry).expect("below 2^32");
152        }
153
154        Self(out).trimmed()
155    }
156}
157
158impl PartialOrd for BigUint {
159    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
160        Some(self.cmp(other))
161    }
162}
163
164impl Ord for BigUint {
165    fn cmp(&self, other: &Self) -> Ordering {
166        self.0
167            .len()
168            .cmp(&other.0.len())
169            .then_with(|| self.0.iter().rev().cmp(other.0.iter().rev()))
170    }
171}
172
173impl ExactNumber for BigUint {
174    fn zero() -> Self {
175        Self(Vec::new())
176    }
177
178    fn one() -> Self {
179        Self(alloc::vec![1])
180    }
181
182    fn abs_diff(&self, other: &Self) -> Self {
183        if self >= other {
184            self.minus(other)
185        } else {
186            other.minus(self)
187        }
188    }
189}
190
191/// Implements [`ExactArith`] for unsigned integers that widen into `u128`.
192macro_rules! exact_unsigned {
193    ($($ty:ty),*) => {
194        $(
195            impl ExactArith for $ty {
196                type Exact = BigUint;
197
198                fn exact(self) -> BigUint {
199                    BigUint::from(u128::from(self))
200                }
201            }
202        )*
203    };
204}
205
206exact_unsigned!(u8, u16, u32, u64, u128);
207
208impl ExactArith for usize {
209    type Exact = BigUint;
210
211    fn exact(self) -> BigUint {
212        // `usize` is at most 64 bits on every target Rust supports.
213        BigUint::from(u128::from(u64::try_from(self).expect("usize fits in u64")))
214    }
215}
216
217impl<const K: u32> ExactArith for Decimal<K> {
218    /// The raw value, at scale `10^K`.
219    type Exact = BigUint;
220
221    fn exact(self) -> BigUint {
222        BigUint::from(u128::from(self.raw()))
223    }
224}
225
226#[cfg(feature = "float")]
227impl ExactNumber for NonNegF64 {
228    fn zero() -> Self {
229        Self::new(0.0).expect("zero is a valid cost")
230    }
231
232    fn one() -> Self {
233        Self::new(1.0).expect("one is a valid cost")
234    }
235
236    fn abs_diff(&self, other: &Self) -> Self {
237        crate::WideMul::abs_diff(*self, *other)
238    }
239}
240
241#[cfg(feature = "float")]
242impl ExactArith for NonNegF64 {
243    /// Itself: `f64` sums and products round.
244    type Exact = Self;
245
246    fn exact(self) -> Self {
247        self
248    }
249}
250
251#[cfg(test)]
252mod tests {
253    //! Unit and property tests for [`BigUint`].
254
255    use proptest::prelude::*;
256
257    use super::{BigUint, ExactArith, ExactNumber};
258
259    /// The value of a big integer as `u128`, for values that fit.
260    fn value(b: &BigUint) -> u128 {
261        b.limbs()
262            .iter()
263            .rev()
264            .fold(0, |v, &l| (v << 32) | u128::from(l))
265    }
266
267    /// Zero has no limbs and is the identity.
268    #[test]
269    fn zero() {
270        assert_eq!(BigUint::zero().limbs(), &[] as &[u32]);
271        assert_eq!(BigUint::zero() + 5_u64.exact(), 5_u64.exact());
272        assert_eq!(BigUint::zero() * 5_u64.exact(), BigUint::zero());
273        assert_eq!(BigUint::one() * 5_u64.exact(), 5_u64.exact());
274    }
275
276    proptest! {
277        /// Sums, products and distances match `u128` where it does not
278        /// overflow, and order matches.
279        #[test]
280        fn matches_u128(a: u64, b: u64, c: u32) {
281            let (x, y, z) = (a.exact(), b.exact(), c.exact());
282            prop_assert_eq!(value(&(x.clone() + y.clone())), u128::from(a) + u128::from(b));
283            prop_assert_eq!(value(&(x.clone() * y.clone())), u128::from(a) * u128::from(b));
284            prop_assert_eq!(value(&x.abs_diff(&y)), u128::from(a.abs_diff(b)));
285            prop_assert_eq!(x.cmp(&y), a.cmp(&b));
286            // Beyond 128 bits: (a · b) · c compared with a · (b · c).
287            prop_assert_eq!((x.clone() * y.clone()) * z.clone(), x * (y * z));
288        }
289    }
290}