1use 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
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)]
71pub struct BigUint(Vec<u32>);
72
73impl BigUint {
74 #[must_use]
76 pub fn limbs(&self) -> &[u32] {
77 &self.0
78 }
79
80 fn trimmed(mut self) -> Self {
82 while self.0.last() == Some(&0) {
83 self.0.pop();
84 }
85
86 self
87 }
88
89 fn minus(&self, other: &Self) -> Self {
91 let mut out = self.clone();
92 out.subtract(other, false);
93 out
94 }
95
96 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 fn trim(&mut self) {
128 while self.0.last() == Some(&0) {
129 self.0.pop();
130 }
131 }
132
133 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 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 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
293macro_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 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 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 type Exact = Self;
347
348 fn exact(self) -> Self {
349 self
350 }
351}
352
353#[cfg(test)]
354mod tests {
355 use proptest::prelude::*;
358
359 use super::{BigUint, ExactArith, ExactNumber};
360
361 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 #[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 #[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 prop_assert_eq!((x.clone() * y.clone()) * z.clone(), x * (y * z));
390 }
391
392 #[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 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}