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, Mul, Neg, Sub};
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/// # Examples
19///
20/// ```
21/// use search_core::{BigInt, ExactArith};
22///
23/// // den · c₁ - num · c₂ for one edge, with 128-bit ratio terms and 64-bit costs.
24/// let weight = |den: u128, c1: u64, num: u128, c2: u64| {
25///     BigInt::from(den.exact() * c1.exact()) - BigInt::from(num.exact() * c2.exact())
26/// };
27///
28/// let w = weight(u128::MAX, 2, u128::MAX, 3);
29/// assert!(w.is_negative());
30/// assert_eq!(w + weight(u128::MAX, 1, 0, 0), BigInt::from(0_u128));
31/// assert!(BigInt::from(-5_i128) < BigInt::from(3_i128));
32/// ```
33#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
34pub struct BigInt {
35    /// `true` for values below zero. Never `true` for zero.
36    negative: bool,
37    /// The absolute value.
38    magnitude: BigUint,
39}
40
41impl BigInt {
42    /// Builds `±magnitude`, keeping zero non-negative.
43    fn from_parts(negative: bool, magnitude: BigUint) -> Self {
44        let negative = negative && !magnitude.limbs().is_empty();
45
46        Self {
47            negative,
48            magnitude,
49        }
50    }
51
52    /// `true` if the value is below zero.
53    #[must_use]
54    pub fn is_negative(&self) -> bool {
55        self.negative
56    }
57
58    /// The absolute value.
59    #[must_use]
60    pub fn magnitude(&self) -> &BigUint {
61        &self.magnitude
62    }
63}
64
65impl From<BigUint> for BigInt {
66    fn from(magnitude: BigUint) -> Self {
67        Self::from_parts(false, magnitude)
68    }
69}
70
71impl From<u128> for BigInt {
72    fn from(value: u128) -> Self {
73        Self::from(BigUint::from(value))
74    }
75}
76
77impl From<i128> for BigInt {
78    fn from(value: i128) -> Self {
79        Self::from_parts(value < 0, BigUint::from(value.unsigned_abs()))
80    }
81}
82
83impl Neg for BigInt {
84    type Output = Self;
85
86    fn neg(self) -> Self {
87        Self::from_parts(!self.negative, self.magnitude)
88    }
89}
90
91impl Add for BigInt {
92    type Output = Self;
93
94    fn add(self, other: Self) -> Self {
95        if self.negative == other.negative {
96            return Self::from_parts(self.negative, self.magnitude + other.magnitude);
97        }
98
99        // Opposite signs: the larger magnitude keeps its sign.
100        if self.magnitude >= other.magnitude {
101            Self::from_parts(self.negative, self.magnitude.minus(&other.magnitude))
102        } else {
103            Self::from_parts(other.negative, other.magnitude.minus(&self.magnitude))
104        }
105    }
106}
107
108impl Sub for BigInt {
109    type Output = Self;
110
111    fn sub(self, other: Self) -> Self {
112        self + -other
113    }
114}
115
116impl Mul for BigInt {
117    type Output = Self;
118
119    fn mul(self, other: Self) -> Self {
120        Self::from_parts(
121            self.negative != other.negative,
122            self.magnitude * other.magnitude,
123        )
124    }
125}
126
127impl PartialOrd for BigInt {
128    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
129        Some(self.cmp(other))
130    }
131}
132
133impl Ord for BigInt {
134    fn cmp(&self, other: &Self) -> Ordering {
135        match (self.negative, other.negative) {
136            (false, true) => Ordering::Greater,
137            (true, false) => Ordering::Less,
138            (false, false) => self.magnitude.cmp(&other.magnitude),
139            (true, true) => other.magnitude.cmp(&self.magnitude),
140        }
141    }
142}
143
144impl ExactNumber for BigInt {
145    fn zero() -> Self {
146        Self::from(BigUint::zero())
147    }
148
149    fn one() -> Self {
150        Self::from(BigUint::one())
151    }
152
153    fn abs_diff(&self, other: &Self) -> Self {
154        let difference = self.clone() - other.clone();
155
156        Self::from(difference.magnitude)
157    }
158}
159
160#[cfg(test)]
161mod tests {
162    //! Unit and property tests for [`BigInt`], against `i128` arithmetic.
163
164    use proptest::prelude::*;
165
166    use super::{BigInt, BigUint, ExactNumber};
167
168    /// The value of a big integer as `i128`, for values that fit.
169    fn value(b: &BigInt) -> i128 {
170        let magnitude = b
171            .magnitude()
172            .limbs()
173            .iter()
174            .rev()
175            .fold(0_i128, |v, &l| (v << 32) | i128::from(l));
176
177        if b.is_negative() {
178            -magnitude
179        } else {
180            magnitude
181        }
182    }
183
184    /// Zero is never negative, however it is reached.
185    #[test]
186    fn zero_is_not_negative() {
187        let five = BigInt::from(5_i128);
188
189        assert!(!(five.clone() - five.clone()).is_negative());
190        assert!(!(-BigInt::zero()).is_negative());
191        assert!(!(BigInt::from(-5_i128) * BigInt::zero()).is_negative());
192        assert_eq!(-BigInt::zero(), BigInt::zero());
193    }
194
195    /// Values beyond `i128` stay exact.
196    #[test]
197    fn exceeds_i128() {
198        let max = BigInt::from(i128::MAX);
199        let min = BigInt::from(i128::MIN);
200
201        assert_eq!(max.clone() - min.clone() - max.clone(), -min.clone());
202        assert!(min.clone() * max.clone() < min);
203        assert_eq!(
204            BigInt::from(i128::MIN).magnitude(),
205            &BigUint::from(1_u128 << 127)
206        );
207    }
208
209    proptest! {
210        /// `+`, `-` and `*` agree with `i128` on 64-bit inputs.
211        #[test]
212        fn matches_i128(a: i64, b: i64) {
213            let (x, y) = (BigInt::from(i128::from(a)), BigInt::from(i128::from(b)));
214            let (a, b) = (i128::from(a), i128::from(b));
215
216            prop_assert_eq!(value(&(x.clone() + y.clone())), a + b);
217            prop_assert_eq!(value(&(x.clone() - y.clone())), a - b);
218            prop_assert_eq!(value(&(x.clone() * y.clone())), a * b);
219            prop_assert_eq!(value(&x.abs_diff(&y)), (a - b).abs());
220            prop_assert_eq!(value(&-x.clone()), -a);
221        }
222
223        /// The order agrees with `i128`.
224        #[test]
225        fn order_matches_i128(a: i128, b: i128) {
226            prop_assert_eq!(BigInt::from(a).cmp(&BigInt::from(b)), a.cmp(&b));
227        }
228    }
229}