search_core/cost/
exact.rs1use 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
16pub trait ExactNumber: Clone + Ord + Add<Output = Self> + Mul<Output = Self> {
23 fn zero() -> Self;
25
26 fn one() -> Self;
28
29 #[must_use]
31 fn abs_diff(&self, other: &Self) -> Self;
32}
33
34pub trait ExactArith: Cost {
57 type Exact: ExactNumber;
59
60 #[must_use]
62 fn exact(self) -> Self::Exact;
63}
64
65#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
68pub struct BigUint(Vec<u32>);
69
70impl BigUint {
71 #[must_use]
73 pub fn limbs(&self) -> &[u32] {
74 &self.0
75 }
76
77 fn trimmed(mut self) -> Self {
79 while self.0.last() == Some(&0) {
80 self.0.pop();
81 }
82
83 self
84 }
85
86 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
191macro_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 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 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 type Exact = Self;
245
246 fn exact(self) -> Self {
247 self
248 }
249}
250
251#[cfg(test)]
252mod tests {
253 use proptest::prelude::*;
256
257 use super::{BigUint, ExactArith, ExactNumber};
258
259 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 #[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 #[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 prop_assert_eq!((x.clone() * y.clone()) * z.clone(), x * (y * z));
288 }
289 }
290}