Skip to main content

search_core/cost/
wide.rs

1//! The exact cost-by-cost product [`WideMul`] and its implementations.
2
3use super::Decimal;
4#[cfg(feature = "float")]
5use super::NonNegF64;
6
7/// The product of two costs, in a type wide enough to hold it.
8///
9/// [`Cost`](crate::Cost) can only scale a cost by a small integer. Some searches need to
10/// compare ratios of costs, `a / b` against `c / d`, which they do without division by
11/// comparing the cross products `a · d` and `c · b`. This trait gives those products exactly:
12/// for the integer types and [`Decimal`] the product never overflows and never rounds, so
13/// `a.wide_mul(d) < c.wide_mul(b)` holds exactly when `a · d < c · b`.
14///
15/// The ratios such searches compare are often differences over costs, as in
16/// `(x - y) / z`, and [`Cost`](crate::Cost) has no subtraction. [`WideMul::abs_diff`] gives
17/// the exact difference, which never leaves the type's range.
18///
19/// It is a separate trait rather than a part of [`Cost`](crate::Cost), so that cost types
20/// without a product keep working with every algorithm that does not need one.
21///
22/// | Cost | `Wide` | Exact |
23/// |---|---|---|
24/// | `u8`, `u16`, `u32`, `u64` | the next wider unsigned integer | yes |
25/// | `usize` | `u128` | yes |
26/// | `u128` | `(u128, u128)`, the high and low halves of the 256-bit product | yes |
27/// | [`Decimal<K>`] | `u128`, the product of the raw values (scale `10^(2K)`) | yes |
28/// | `NonNegF64` (feature `float`) | `NonNegF64` | rounded like `f64` multiplication |
29///
30/// # Examples
31///
32/// Comparing `3 / 4` with `5 / 7` in `u64` without division or overflow:
33///
34/// ```
35/// use search_core::WideMul;
36///
37/// /// Returns `true` if `a / b < c / d`, for positive `b` and `d`.
38/// fn ratio_less<T: WideMul>(a: T, b: T, c: T, d: T) -> bool {
39///     a.wide_mul(d) < c.wide_mul(b)
40/// }
41///
42/// assert!(!ratio_less(3_u64, 4, 5, 7));
43/// assert!(ratio_less(u64::MAX - 1, u64::MAX, 1, 1));
44/// ```
45pub trait WideMul: Copy {
46    /// The type of the product, ordered like the numbers it holds.
47    type Wide: Copy + Ord;
48
49    /// Multiplies two costs into [`WideMul::Wide`].
50    #[must_use]
51    fn wide_mul(self, other: Self) -> Self::Wide;
52
53    /// The distance `|self - other|`, exact for the integers and [`Decimal`].
54    #[must_use]
55    fn abs_diff(self, other: Self) -> Self;
56}
57
58/// Implements [`WideMul`] for unsigned integers that widen losslessly into `$wide`.
59macro_rules! widening {
60    ($($ty:ty => $wide:ty),*) => {
61        $(
62            impl WideMul for $ty {
63                type Wide = $wide;
64
65                fn wide_mul(self, other: Self) -> $wide {
66                    <$wide>::from(self) * <$wide>::from(other)
67                }
68
69                fn abs_diff(self, other: Self) -> Self {
70                    <$ty>::abs_diff(self, other)
71                }
72            }
73        )*
74    };
75}
76
77widening!(u8 => u16, u16 => u32, u32 => u64, u64 => u128);
78
79impl WideMul for usize {
80    type Wide = u128;
81
82    fn wide_mul(self, other: Self) -> u128 {
83        // `usize` is at most 64 bits on every target Rust supports, so this never fails.
84        let widen = |x: usize| u128::from(u64::try_from(x).expect("usize fits in u64"));
85        widen(self) * widen(other)
86    }
87
88    fn abs_diff(self, other: Self) -> Self {
89        usize::abs_diff(self, other)
90    }
91}
92
93impl WideMul for u128 {
94    /// `(high, low)`: the product is `high · 2^128 + low`. Tuples compare lexicographically,
95    /// which is the numeric order here.
96    type Wide = (u128, u128);
97
98    fn wide_mul(self, other: Self) -> (u128, u128) {
99        mul_u128(self, other)
100    }
101
102    fn abs_diff(self, other: Self) -> Self {
103        u128::abs_diff(self, other)
104    }
105}
106
107/// The full 256-bit product of `a` and `b` as `(high, low)` 128-bit halves.
108///
109/// Schoolbook multiplication on 64-bit limbs: each limb product fits in `u128`, and the
110/// middle sum is split so that no intermediate addition overflows.
111fn mul_u128(a: u128, b: u128) -> (u128, u128) {
112    const LOW: u128 = u64::MAX as u128;
113
114    let (a_hi, a_lo) = (a >> 64, a & LOW);
115    let (b_hi, b_lo) = (b >> 64, b & LOW);
116
117    let lo_lo = a_lo * b_lo;
118    let hi_lo = a_hi * b_lo;
119    let lo_hi = a_lo * b_hi;
120    let hi_hi = a_hi * b_hi;
121
122    // Bits 64..192, as three numbers below 2^64 each, summed: below 3 · 2^64.
123    let middle = (lo_lo >> 64) + (hi_lo & LOW) + (lo_hi & LOW);
124    let low = (middle << 64) | (lo_lo & LOW);
125    let high = hi_hi + (hi_lo >> 64) + (lo_hi >> 64) + (middle >> 64);
126
127    (high, low)
128}
129
130impl<const K: u32> WideMul for Decimal<K> {
131    /// The product of the raw values, at scale `10^(2K)`.
132    type Wide = u128;
133
134    fn wide_mul(self, other: Self) -> u128 {
135        self.raw().wide_mul(other.raw())
136    }
137
138    fn abs_diff(self, other: Self) -> Self {
139        Self::from_raw(self.raw().abs_diff(other.raw()))
140    }
141}
142
143#[cfg(feature = "float")]
144impl WideMul for NonNegF64 {
145    type Wide = Self;
146
147    /// The `f64` product, with `0 · ∞ = 0` instead of NaN.
148    fn wide_mul(self, other: Self) -> Self {
149        if self.get() == 0.0 || other.get() == 0.0 {
150            return Self::new(0.0).expect("zero is a valid cost");
151        }
152
153        Self::new(self.get() * other.get()).expect("a product of non-negative non-NaN values")
154    }
155
156    /// The `f64` distance, with `∞ - ∞ = 0` instead of NaN.
157    fn abs_diff(self, other: Self) -> Self {
158        if self == other {
159            return Self::new(0.0).expect("zero is a valid cost");
160        }
161
162        Self::new((self.get() - other.get()).abs()).expect("a distance of unequal values")
163    }
164}
165
166#[cfg(test)]
167mod tests {
168    //! Unit and property tests for [`WideMul`].
169
170    use super::{Decimal, WideMul, mul_u128};
171    use proptest::prelude::*;
172
173    /// The largest products of each type are exact.
174    #[test]
175    fn extremes_are_exact() {
176        assert_eq!(u8::MAX.wide_mul(u8::MAX), 65_025);
177        assert_eq!(
178            u64::MAX.wide_mul(u64::MAX),
179            u128::from(u64::MAX) * u128::from(u64::MAX)
180        );
181        assert_eq!(u128::MAX.wide_mul(u128::MAX), (u128::MAX - 1, 1));
182        assert_eq!(u128::MAX.wide_mul(0), (0, 0));
183        assert_eq!(usize::MAX.wide_mul(2), 2 * u128::from(u64::MAX));
184    }
185
186    /// Distances are symmetric and exact at the extremes.
187    #[test]
188    fn abs_diff_is_exact() {
189        assert_eq!(WideMul::abs_diff(3_u8, 250), 247);
190        assert_eq!(WideMul::abs_diff(u128::MAX, 0), u128::MAX);
191        let (a, b) = (Decimal::<1>::from_raw(5), Decimal::<1>::from_raw(12));
192        assert_eq!(WideMul::abs_diff(a, b), Decimal::from_raw(7));
193    }
194
195    /// [`Decimal`] multiplies its raw values.
196    #[test]
197    fn decimal_multiplies_raw_values() {
198        let a = Decimal::<2>::from_raw(150);
199        let b = Decimal::<2>::from_raw(u64::MAX);
200        assert_eq!(a.wide_mul(b), 150 * u128::from(u64::MAX));
201    }
202
203    /// Zero times infinity is zero, and products round like `f64`.
204    #[cfg(feature = "float")]
205    #[test]
206    fn float_products() {
207        use crate::NonNegF64;
208
209        let inf = NonNegF64::new(f64::INFINITY).unwrap();
210        let zero = NonNegF64::new(0.0).unwrap();
211        let half = NonNegF64::new(0.5).unwrap();
212        assert_eq!(inf.wide_mul(zero), zero);
213        assert_eq!(half.wide_mul(half).get(), 0.25);
214        assert_eq!(inf.wide_mul(half), inf);
215        assert_eq!(WideMul::abs_diff(inf, inf), zero);
216        assert_eq!(WideMul::abs_diff(half, inf), inf);
217    }
218
219    proptest! {
220        /// The 256-bit product splits back into the 128-bit operands' product when it fits,
221        /// and agrees with a product of the 64-bit halves computed independently.
222        #[test]
223        fn u128_matches_limb_reference(a: u128, b: u128) {
224            let (high, low) = mul_u128(a, b);
225            prop_assert_eq!(low, a.wrapping_mul(b));
226            if let Some(exact) = a.checked_mul(b) {
227                prop_assert_eq!((high, low), (0, exact));
228            }
229
230            // a · b = (a / k) · b · k + (a mod k) · b, with k = 2: compare via the shifted
231            // product, which halves `a` and so cannot be the same computation.
232            let (h2, l2) = mul_u128(a >> 1, b);
233            let doubled = ((h2 << 1) | (l2 >> 127), l2 << 1);
234            let odd = if a & 1 == 1 { b } else { 0 };
235            let (sum_low, carry) = doubled.1.overflowing_add(odd);
236            prop_assert_eq!((high, low), (doubled.0 + u128::from(carry), sum_low));
237        }
238
239        /// The widening products agree with the independent 256-bit limb product.
240        #[test]
241        fn widening_matches_limb_product(a: u64, b: u64, c: u32, d: u32, e: u16, f: u16) {
242            prop_assert_eq!(mul_u128(a.into(), b.into()), (0, a.wide_mul(b)));
243            prop_assert_eq!(mul_u128(c.into(), d.into()), (0, c.wide_mul(d).into()));
244            prop_assert_eq!(mul_u128(e.into(), f.into()), (0, e.wide_mul(f).into()));
245        }
246    }
247}