Skip to main content

search_core/cost/exact/
signed.rs

1//! The signed exact integer [`BigInt`], for differences of exact cost
2//! expressions that may go negative.
3
4use core::cmp::Ordering;
5use core::ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign};
6
7use super::{BigUint, ExactNumber};
8
9/// An arbitrary-precision signed integer: a sign and a [`BigUint`] magnitude.
10///
11/// Costs are never negative, but expressions over them can be: a parametric weight
12/// `den · c₁ - num · c₂` (Dinkelbach's method for ratio objectives), a reduced cost, or the
13/// difference of two path sums. `BigInt` holds such values exactly; `+`, `-` and `*` never
14/// overflow or round.
15///
16/// Zero has a single representation, so it is never negative and `-0 == 0`.
17///
18/// Every operator also takes references (`&a + &b`), and `+=`, `-=` and `*=` take
19/// `&BigInt`. In a hot loop, `sum += &weight` reuses `sum`'s limbs instead of cloning
20/// both operands.
21///
22/// # Examples
23///
24/// ```
25/// use search_core::{BigInt, ExactArith};
26///
27/// // den · c₁ - num · c₂ for one edge, with 128-bit ratio terms and 64-bit costs.
28/// let weight = |den: u128, c1: u64, num: u128, c2: u64| {
29///     BigInt::from(den.exact() * c1.exact()) - BigInt::from(num.exact() * c2.exact())
30/// };
31///
32/// let w = weight(u128::MAX, 2, u128::MAX, 3);
33/// assert!(w.is_negative());
34/// assert_eq!(w + weight(u128::MAX, 1, 0, 0), BigInt::from(0_u128));
35/// assert!(BigInt::from(-5_i128) < BigInt::from(3_i128));
36/// ```
37#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
38pub struct BigInt {
39    /// `true` for values below zero. Never `true` for zero.
40    negative: bool,
41    /// The absolute value.
42    magnitude: BigUint,
43}
44
45impl BigInt {
46    /// Builds `±magnitude`, keeping zero non-negative.
47    fn from_parts(negative: bool, magnitude: BigUint) -> Self {
48        let negative = negative && !magnitude.limbs().is_empty();
49
50        Self {
51            negative,
52            magnitude,
53        }
54    }
55
56    /// Adds `±magnitude` in place, reusing this value's limbs.
57    fn add_signed(&mut self, negative: bool, magnitude: &BigUint) {
58        if self.negative == negative {
59            self.magnitude += magnitude;
60            return;
61        }
62
63        // Opposite signs: the larger magnitude keeps its sign.
64        if self.magnitude >= *magnitude {
65            self.magnitude.subtract(magnitude, false);
66        } else {
67            self.magnitude.subtract(magnitude, true);
68            self.negative = negative;
69        }
70
71        self.negative = self.negative && !self.magnitude.limbs().is_empty();
72    }
73
74    /// `true` if the value is below zero.
75    #[must_use]
76    pub fn is_negative(&self) -> bool {
77        self.negative
78    }
79
80    /// The absolute value.
81    #[must_use]
82    pub fn magnitude(&self) -> &BigUint {
83        &self.magnitude
84    }
85}
86
87impl From<BigUint> for BigInt {
88    fn from(magnitude: BigUint) -> Self {
89        Self::from_parts(false, magnitude)
90    }
91}
92
93impl From<u128> for BigInt {
94    fn from(value: u128) -> Self {
95        Self::from(BigUint::from(value))
96    }
97}
98
99impl From<i128> for BigInt {
100    fn from(value: i128) -> Self {
101        Self::from_parts(value < 0, BigUint::from(value.unsigned_abs()))
102    }
103}
104
105impl Neg for BigInt {
106    type Output = Self;
107
108    fn neg(self) -> Self {
109        Self::from_parts(!self.negative, self.magnitude)
110    }
111}
112
113impl Neg for &BigInt {
114    type Output = BigInt;
115
116    fn neg(self) -> BigInt {
117        -self.clone()
118    }
119}
120
121impl AddAssign<&BigInt> for BigInt {
122    /// Adds in place, reusing this value's limbs.
123    fn add_assign(&mut self, other: &BigInt) {
124        self.add_signed(other.negative, &other.magnitude);
125    }
126}
127
128impl AddAssign for BigInt {
129    fn add_assign(&mut self, other: Self) {
130        *self += &other;
131    }
132}
133
134impl SubAssign<&BigInt> for BigInt {
135    /// Subtracts in place, reusing this value's limbs.
136    fn sub_assign(&mut self, other: &BigInt) {
137        let negative = !other.negative && !other.magnitude.limbs().is_empty();
138        self.add_signed(negative, &other.magnitude);
139    }
140}
141
142impl SubAssign for BigInt {
143    fn sub_assign(&mut self, other: Self) {
144        *self -= &other;
145    }
146}
147
148impl Add for BigInt {
149    type Output = Self;
150
151    fn add(mut self, other: Self) -> Self {
152        self += &other;
153        self
154    }
155}
156
157impl Add<&BigInt> for BigInt {
158    type Output = Self;
159
160    fn add(mut self, other: &BigInt) -> Self {
161        self += other;
162        self
163    }
164}
165
166impl Add for &BigInt {
167    type Output = BigInt;
168
169    fn add(self, other: Self) -> BigInt {
170        self.clone() + other
171    }
172}
173
174impl Sub for BigInt {
175    type Output = Self;
176
177    fn sub(mut self, other: Self) -> Self {
178        self -= &other;
179        self
180    }
181}
182
183impl Sub<&BigInt> for BigInt {
184    type Output = Self;
185
186    fn sub(mut self, other: &BigInt) -> Self {
187        self -= other;
188        self
189    }
190}
191
192impl Sub for &BigInt {
193    type Output = BigInt;
194
195    fn sub(self, other: Self) -> BigInt {
196        self.clone() - other
197    }
198}
199
200impl Mul for &BigInt {
201    type Output = BigInt;
202
203    fn mul(self, other: Self) -> BigInt {
204        BigInt::from_parts(
205            self.negative != other.negative,
206            &self.magnitude * &other.magnitude,
207        )
208    }
209}
210
211impl Mul for BigInt {
212    type Output = Self;
213
214    fn mul(self, other: Self) -> Self {
215        &self * &other
216    }
217}
218
219impl Mul<&BigInt> for BigInt {
220    type Output = Self;
221
222    fn mul(self, other: &BigInt) -> Self {
223        &self * other
224    }
225}
226
227impl MulAssign<&BigInt> for BigInt {
228    fn mul_assign(&mut self, other: &BigInt) {
229        *self = &*self * other;
230    }
231}
232
233impl MulAssign for BigInt {
234    fn mul_assign(&mut self, other: Self) {
235        *self *= &other;
236    }
237}
238
239impl PartialOrd for BigInt {
240    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
241        Some(self.cmp(other))
242    }
243}
244
245impl Ord for BigInt {
246    fn cmp(&self, other: &Self) -> Ordering {
247        match (self.negative, other.negative) {
248            (false, true) => Ordering::Greater,
249            (true, false) => Ordering::Less,
250            (false, false) => self.magnitude.cmp(&other.magnitude),
251            (true, true) => other.magnitude.cmp(&self.magnitude),
252        }
253    }
254}
255
256impl ExactNumber for BigInt {
257    fn zero() -> Self {
258        Self::from(BigUint::zero())
259    }
260
261    fn one() -> Self {
262        Self::from(BigUint::one())
263    }
264
265    fn abs_diff(&self, other: &Self) -> Self {
266        let difference = self - other;
267
268        Self::from(difference.magnitude)
269    }
270}
271
272#[cfg(test)]
273mod tests {
274    //! Unit and property tests for [`BigInt`], against `i128` arithmetic.
275
276    use proptest::prelude::*;
277
278    use super::{BigInt, BigUint, ExactNumber};
279
280    /// The value of a big integer as `i128`, for values that fit.
281    fn value(b: &BigInt) -> i128 {
282        let magnitude = b
283            .magnitude()
284            .limbs()
285            .iter()
286            .rev()
287            .fold(0_i128, |v, &l| (v << 32) | i128::from(l));
288
289        if b.is_negative() {
290            -magnitude
291        } else {
292            magnitude
293        }
294    }
295
296    /// Zero is never negative, however it is reached.
297    #[test]
298    fn zero_is_not_negative() {
299        let five = BigInt::from(5_i128);
300
301        assert!(!(five.clone() - five.clone()).is_negative());
302        assert!(!(-BigInt::zero()).is_negative());
303        assert!(!(BigInt::from(-5_i128) * BigInt::zero()).is_negative());
304        assert_eq!(-BigInt::zero(), BigInt::zero());
305    }
306
307    /// Values beyond `i128` stay exact.
308    #[test]
309    fn exceeds_i128() {
310        let max = BigInt::from(i128::MAX);
311        let min = BigInt::from(i128::MIN);
312
313        assert_eq!(max.clone() - min.clone() - max.clone(), -min.clone());
314        assert!(min.clone() * max.clone() < min);
315        assert_eq!(
316            BigInt::from(i128::MIN).magnitude(),
317            &BigUint::from(1_u128 << 127)
318        );
319    }
320
321    proptest! {
322        /// `+`, `-` and `*` agree with `i128` on 64-bit inputs.
323        #[test]
324        fn matches_i128(a: i64, b: i64) {
325            let (x, y) = (BigInt::from(i128::from(a)), BigInt::from(i128::from(b)));
326            let (a, b) = (i128::from(a), i128::from(b));
327
328            prop_assert_eq!(value(&(x.clone() + y.clone())), a + b);
329            prop_assert_eq!(value(&(x.clone() - y.clone())), a - b);
330            prop_assert_eq!(value(&(x.clone() * y.clone())), a * b);
331            prop_assert_eq!(value(&x.abs_diff(&y)), (a - b).abs());
332            prop_assert_eq!(value(&-x.clone()), -a);
333        }
334
335        /// The by-reference and in-place operations equal the owned ones,
336        /// beyond `i128` too.
337        #[test]
338        fn by_reference_matches_owned(a: i128, b: i128, sa: bool, sb: bool) {
339            // Square into up to 254 bits, then sign.
340            let sign = |v: BigInt, negative: bool| if negative { -v } else { v };
341            let x = sign(BigInt::from(a) * BigInt::from(a), sa) + BigInt::from(b);
342            let y = sign(BigInt::from(b) * BigInt::from(b), sb) - BigInt::from(a);
343            let sum = x.clone() + y.clone();
344            let difference = x.clone() - y.clone();
345            let product = x.clone() * y.clone();
346
347            prop_assert_eq!(&x + &y, sum.clone());
348            prop_assert_eq!(x.clone() + &y, sum.clone());
349            prop_assert_eq!(&x - &y, difference.clone());
350            prop_assert_eq!(x.clone() - &y, difference.clone());
351            prop_assert_eq!(&x * &y, product.clone());
352            prop_assert_eq!(x.clone() * &y, product.clone());
353            prop_assert_eq!(-&x, -x.clone());
354
355            let mut z = x.clone();
356            z += &y;
357            prop_assert_eq!(&z, &sum);
358            z = x.clone();
359            z += y.clone();
360            prop_assert_eq!(&z, &sum);
361            z = x.clone();
362            z -= &y;
363            prop_assert_eq!(&z, &difference);
364            z = x.clone();
365            z -= y.clone();
366            prop_assert_eq!(&z, &difference);
367            z = x.clone();
368            z *= &y;
369            prop_assert_eq!(&z, &product);
370            z = x.clone();
371            z *= y.clone();
372            prop_assert_eq!(&z, &product);
373
374            // Sums and differences round-trip, and x - x is a non-negative zero.
375            prop_assert_eq!(&sum - &y, x.clone());
376            prop_assert_eq!(&difference + &y, x.clone());
377            let mut zero = x.clone();
378            zero -= &x;
379            prop_assert!(!zero.is_negative());
380            prop_assert_eq!(zero, BigInt::zero());
381        }
382
383        /// The order agrees with `i128`.
384        #[test]
385        fn order_matches_i128(a: i128, b: i128) {
386            prop_assert_eq!(BigInt::from(a).cmp(&BigInt::from(b)), a.cmp(&b));
387        }
388    }
389}