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, AddAssign, Mul, MulAssign};
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///
68/// `+` and `*` also take references (`&a + &b`), and `+=` and `*=` take
69/// `&BigUint`; `a += &b` reuses `a`'s limbs.
70#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
71pub struct BigUint(Vec<u32>);
72
73impl BigUint {
74    /// The limbs, least significant first; empty for zero.
75    #[must_use]
76    pub fn limbs(&self) -> &[u32] {
77        &self.0
78    }
79
80    /// Drops the most significant zero limbs.
81    fn trimmed(mut self) -> Self {
82        while self.0.last() == Some(&0) {
83            self.0.pop();
84        }
85
86        self
87    }
88
89    /// `self - other` for `self >= other`.
90    fn minus(&self, other: &Self) -> Self {
91        let mut out = self.clone();
92        out.subtract(other, false);
93        out
94    }
95
96    /// In place, `self - other` (`reversed == false`, needs `self >= other`)
97    /// or `other - self` (`reversed == true`, needs `other >= self`).
98    fn subtract(&mut self, other: &Self, reversed: bool) {
99        if self.0.len() < other.0.len() {
100            self.0.resize(other.0.len(), 0);
101        }
102
103        let mut borrow = 0_i64;
104        for (i, slot) in self.0.iter_mut().enumerate() {
105            let theirs = i64::from(other.0.get(i).copied().unwrap_or(0));
106            let ours = i64::from(*slot);
107            let (minuend, subtrahend) = if reversed {
108                (theirs, ours)
109            } else {
110                (ours, theirs)
111            };
112            let mut v = minuend - subtrahend - borrow;
113            borrow = 0;
114            if v < 0 {
115                v += 1 << 32;
116                borrow = 1;
117            }
118
119            *slot = u32::try_from(v).expect("a limb after borrowing");
120        }
121
122        debug_assert_eq!(borrow, 0, "the subtrahend exceeds the minuend");
123        self.trim();
124    }
125
126    /// Drops the most significant zero limbs, in place.
127    fn trim(&mut self) {
128        while self.0.last() == Some(&0) {
129            self.0.pop();
130        }
131    }
132
133    /// The product of two limb slices.
134    fn product(a: &[u32], b: &[u32]) -> Self {
135        let mut out = alloc::vec![0_u32; a.len() + b.len()];
136        for (i, &x) in a.iter().enumerate() {
137            let mut carry = 0_u64;
138            for (j, &y) in b.iter().enumerate() {
139                let t = u64::from(x) * u64::from(y) + u64::from(out[i + j]) + carry;
140                out[i + j] = u32::try_from(t & u64::from(u32::MAX)).expect("masked");
141                carry = t >> 32;
142            }
143
144            out[i + b.len()] = u32::try_from(carry).expect("below 2^32");
145        }
146
147        Self(out).trimmed()
148    }
149}
150
151impl From<u128> for BigUint {
152    fn from(mut value: u128) -> Self {
153        let mut limbs = Vec::new();
154        while value > 0 {
155            limbs.push(u32::try_from(value & u128::from(u32::MAX)).expect("masked"));
156            value >>= 32;
157        }
158
159        Self(limbs)
160    }
161}
162
163impl AddAssign<&BigUint> for BigUint {
164    /// Adds in place, reusing this value's limbs.
165    fn add_assign(&mut self, other: &BigUint) {
166        if self.0.len() < other.0.len() {
167            self.0.resize(other.0.len(), 0);
168        }
169
170        let mut carry = 0_u64;
171        for (i, slot) in self.0.iter_mut().enumerate() {
172            let s = u64::from(*slot) + u64::from(other.0.get(i).copied().unwrap_or(0)) + carry;
173            *slot = u32::try_from(s & u64::from(u32::MAX)).expect("masked");
174            carry = s >> 32;
175            if carry == 0 && i + 1 >= other.0.len() {
176                return;
177            }
178        }
179
180        if carry > 0 {
181            self.0.push(u32::try_from(carry).expect("a carry bit"));
182        }
183    }
184}
185
186impl AddAssign for BigUint {
187    fn add_assign(&mut self, other: Self) {
188        *self += &other;
189    }
190}
191
192impl Add for BigUint {
193    type Output = Self;
194
195    fn add(mut self, other: Self) -> Self {
196        self += &other;
197        self
198    }
199}
200
201impl Add<&BigUint> for BigUint {
202    type Output = Self;
203
204    fn add(mut self, other: &BigUint) -> Self {
205        self += other;
206        self
207    }
208}
209
210impl Add for &BigUint {
211    type Output = BigUint;
212
213    fn add(self, other: Self) -> BigUint {
214        // Copy the longer operand, so the sum rarely grows the buffer.
215        let (long, short) = if self.0.len() >= other.0.len() {
216            (self, other)
217        } else {
218            (other, self)
219        };
220        long.clone() + short
221    }
222}
223
224impl MulAssign<&BigUint> for BigUint {
225    fn mul_assign(&mut self, other: &BigUint) {
226        *self = BigUint::product(&self.0, &other.0);
227    }
228}
229
230impl MulAssign for BigUint {
231    fn mul_assign(&mut self, other: Self) {
232        *self *= &other;
233    }
234}
235
236impl Mul for BigUint {
237    type Output = Self;
238
239    fn mul(self, other: Self) -> Self {
240        Self::product(&self.0, &other.0)
241    }
242}
243
244impl Mul<&BigUint> for BigUint {
245    type Output = Self;
246
247    fn mul(self, other: &BigUint) -> Self {
248        Self::product(&self.0, &other.0)
249    }
250}
251
252impl Mul for &BigUint {
253    type Output = BigUint;
254
255    fn mul(self, other: Self) -> BigUint {
256        BigUint::product(&self.0, &other.0)
257    }
258}
259
260impl PartialOrd for BigUint {
261    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
262        Some(self.cmp(other))
263    }
264}
265
266impl Ord for BigUint {
267    fn cmp(&self, other: &Self) -> Ordering {
268        self.0
269            .len()
270            .cmp(&other.0.len())
271            .then_with(|| self.0.iter().rev().cmp(other.0.iter().rev()))
272    }
273}
274
275impl ExactNumber for BigUint {
276    fn zero() -> Self {
277        Self(Vec::new())
278    }
279
280    fn one() -> Self {
281        Self(alloc::vec![1])
282    }
283
284    fn abs_diff(&self, other: &Self) -> Self {
285        if self >= other {
286            self.minus(other)
287        } else {
288            other.minus(self)
289        }
290    }
291}
292
293/// Implements [`ExactArith`] for unsigned integers that widen into `u128`.
294macro_rules! exact_unsigned {
295    ($($ty:ty),*) => {
296        $(
297            impl ExactArith for $ty {
298                type Exact = BigUint;
299
300                fn exact(self) -> BigUint {
301                    BigUint::from(u128::from(self))
302                }
303            }
304        )*
305    };
306}
307
308exact_unsigned!(u8, u16, u32, u64, u128);
309
310impl ExactArith for usize {
311    type Exact = BigUint;
312
313    fn exact(self) -> BigUint {
314        // `usize` is at most 64 bits on every target Rust supports.
315        BigUint::from(u128::from(u64::try_from(self).expect("usize fits in u64")))
316    }
317}
318
319impl<const K: u32> ExactArith for Decimal<K> {
320    /// The raw value, at scale `10^K`.
321    type Exact = BigUint;
322
323    fn exact(self) -> BigUint {
324        BigUint::from(u128::from(self.raw()))
325    }
326}
327
328#[cfg(feature = "float")]
329impl ExactNumber for NonNegF64 {
330    fn zero() -> Self {
331        Self::new(0.0).expect("zero is a valid cost")
332    }
333
334    fn one() -> Self {
335        Self::new(1.0).expect("one is a valid cost")
336    }
337
338    fn abs_diff(&self, other: &Self) -> Self {
339        crate::WideMul::abs_diff(*self, *other)
340    }
341}
342
343#[cfg(feature = "float")]
344impl ExactArith for NonNegF64 {
345    /// Itself: `f64` sums and products round.
346    type Exact = Self;
347
348    fn exact(self) -> Self {
349        self
350    }
351}
352
353#[cfg(test)]
354mod tests {
355    //! Unit and property tests for [`BigUint`].
356
357    use proptest::prelude::*;
358
359    use super::{BigUint, ExactArith, ExactNumber};
360
361    /// The value of a big integer as `u128`, for values that fit.
362    fn value(b: &BigUint) -> u128 {
363        b.limbs()
364            .iter()
365            .rev()
366            .fold(0, |v, &l| (v << 32) | u128::from(l))
367    }
368
369    /// Zero has no limbs and is the identity.
370    #[test]
371    fn zero() {
372        assert_eq!(BigUint::zero().limbs(), &[] as &[u32]);
373        assert_eq!(BigUint::zero() + 5_u64.exact(), 5_u64.exact());
374        assert_eq!(BigUint::zero() * 5_u64.exact(), BigUint::zero());
375        assert_eq!(BigUint::one() * 5_u64.exact(), 5_u64.exact());
376    }
377
378    proptest! {
379        /// Sums, products and distances match `u128` where it does not
380        /// overflow, and order matches.
381        #[test]
382        fn matches_u128(a: u64, b: u64, c: u32) {
383            let (x, y, z) = (a.exact(), b.exact(), c.exact());
384            prop_assert_eq!(value(&(x.clone() + y.clone())), u128::from(a) + u128::from(b));
385            prop_assert_eq!(value(&(x.clone() * y.clone())), u128::from(a) * u128::from(b));
386            prop_assert_eq!(value(&x.abs_diff(&y)), u128::from(a.abs_diff(b)));
387            prop_assert_eq!(x.cmp(&y), a.cmp(&b));
388            // Beyond 128 bits: (a · b) · c compared with a · (b · c).
389            prop_assert_eq!((x.clone() * y.clone()) * z.clone(), x * (y * z));
390        }
391
392        /// The by-reference and in-place operations equal the owned ones,
393        /// on values of up to eight limbs.
394        #[test]
395        fn by_reference_matches_owned(
396            a in proptest::collection::vec(any::<u32>(), 0..8),
397            b in proptest::collection::vec(any::<u32>(), 0..8),
398        ) {
399            let (x, y) = (BigUint(a).trimmed(), BigUint(b).trimmed());
400            let sum = x.clone() + y.clone();
401            let product = x.clone() * y.clone();
402
403            prop_assert_eq!(&x + &y, sum.clone());
404            prop_assert_eq!(x.clone() + &y, sum.clone());
405            prop_assert_eq!(&x * &y, product.clone());
406            prop_assert_eq!(x.clone() * &y, product.clone());
407
408            let mut z = x.clone();
409            z += &y;
410            prop_assert_eq!(&z, &sum);
411            z = x.clone();
412            z += y.clone();
413            prop_assert_eq!(&z, &sum);
414            z = x.clone();
415            z *= &y;
416            prop_assert_eq!(&z, &product);
417            z = x.clone();
418            z *= y.clone();
419            prop_assert_eq!(&z, &product);
420
421            // Sums carry into a new limb and stay trimmed; distances undo sums.
422            prop_assert_ne!(sum.limbs().last(), Some(&0));
423            prop_assert_eq!(sum.abs_diff(&y), x.clone());
424            prop_assert_eq!(y.abs_diff(&sum), x);
425        }
426    }
427}