/
bignums.rs
2761 lines (2556 loc) · 76.4 KB
/
bignums.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! This module powers the arbitrarly precise fractions of SFLK by providing
//! an implementation of "big fractions" (fractions of big integers) that
//! relies on an implementation of big integers (arbitrarly big integers).
//!
//! There is 3 layers of abstraction here:
//! - The `big_uint` submodule is the "low level" part of `bignums`, it provides
//! an implementation of unsigned big integers and it contains the hardest part
//! of the math implemented here (addition, subtraction, multiplication,
//! euclidian division, etc.).
//! - The `big_sint` submodule is built on top of `big_uint` and extends the
//! big integers by adding a sign to it.
//! - The `big_frac` submodule is built on top of `big_sint` and provides
//! fractions of big integers.
//!
//! This module is meant to be almost a stand-alone implementation of
//! big fractions, and it is to remain pure and free of all SFLK-related concerns.
//!
//! TODO: There is stuff to optimize here and there.
//!
//! TODO: Make bigint types that use `u64` or `i64` when the value fits
//! and converts it to big int when needed. This will spare a lot of allocations,
//! and it will speed up operations on small numbers.
//!
//! TODO: Get a full coverage with the unit tests.
/// A conversion from a big number into a primitive integer type have failed due
/// to the value being ouside the representable range of values supported by the
/// primitive integer type.
#[derive(Debug)]
pub(crate) struct DoesNotFitInPrimitive;
/// When converting a string to a number, the base in which the string is expected
/// to be written is given, and this error is returned in the event that a character
/// is not a digit in that base (for example, `f` is a digit in base 16 but not in
/// base 10, and `@` is not a digit in any base).
#[derive(Debug)]
// The fields ARE used when their values are printed by `unwrap`, but for some reason
// (see [https://github.com/rust-lang/rust/issues/88900]) the compiler says they are not.
#[allow(unused)]
pub(crate) struct CharIsNoDigitInBase {
character: char,
base: u64,
}
/// Provide an implementation of unsigned big integers.
pub(crate) mod big_uint {
use super::DoesNotFitInPrimitive;
use std::{
cmp::Ordering,
ops::{Add, AddAssign, Mul, MulAssign, Sub, SubAssign},
};
/// The type of one digit. The base used for the representation of the digits is `BASE`,
/// which should be the number of values that the `Digit` type can represent.
///
/// It does not have to be `u8` (although some tests may rely on that),
/// this is an arbitrary decision, and an uneducated guess at that.
///
/// TODO: Benchmark heavy math hapenning with different types for `Digit`.
/// I heard Python uses digits that fit closely in 32-bits or something,
/// maybe a `u32` could be more appropriate.
///
/// TODO: Make `BigUint` be generic over the type used for digitis, and over the `BASE` value.
type Digit = u8;
/// The base should be of type `u64` (as a lot of computations are done with `u64`s)
/// and is the number of values that the `Digit` type can represent.
const BASE: u64 = Digit::MAX as u64 + 1;
/// Unsigned big integer. Actually a list of digits in base `BASE`
/// represented with the integer type `Digit`.
#[derive(Clone, Debug)]
pub(crate) struct BigUint {
/// The most significants digits are at the back.
/// There shall not be insignificant leading zeros.
/// The value zero is represented by an empty list of digits.
///
/// Respecting these rules ensures that each unsigned integer value can be
/// represented by one unique representation, code is simpler in some places.
///
/// For example, in base 10, the number 1234 would be stored as `vec![4, 3, 2, 1]`.
digits: Vec<Digit>,
}
impl BigUint {
pub(crate) fn zero() -> BigUint {
BigUint { digits: Vec::new() }
}
pub(crate) fn is_zero(&self) -> bool {
self.digits.is_empty()
}
pub(crate) fn one() -> BigUint {
BigUint { digits: vec![1] }
}
pub(crate) fn is_one(&self) -> bool {
self.digits == [1]
}
/// Removes the insignificant leading zeros that may have been added
/// by initialisation or for convinience.
///
/// A lot of methods expect the absence of insignificant leading zeros,
/// and all the methods shall not allow `self` or a returned `BigUint`
/// to contain insignificant leading zeros.
fn remove_illegal_leading_zeros(&mut self) {
while self.digits.last().copied() == Some(0) {
self.digits.pop();
}
}
/// Interpret the given list of digits as a sequence of digits that make up a number
/// which is the value of the `BigUint` that is returned. The given digits are
/// interpreted as the most significant digits being at the back
/// (i.e. it is written "backwards", "from right to left").
///
/// For example, in base 10, giving `digits` = `vec![4, 3, 2, 1]` would construct
/// a `BigUint` that represents the value 1234.
/// Note: The base is not 10.
fn from_digits_with_most_significant_at_the_back(digits: Vec<Digit>) -> BigUint {
// The `digits` vector is already in the expected orientation for `BigUint`.
let mut big_uint = BigUint { digits };
big_uint.remove_illegal_leading_zeros();
big_uint
}
/// Iterate over the digits, beginning with the most significant digits
/// (i.e. iterating "from the left").
///
/// For example, in base 10, with `self` being the number 123456,
/// the iterator would give (in order): 1, 2, 3, 4, 5, 6, and stop.
fn iter_digits_from_most_significant(&self) -> impl Iterator<Item = Digit> + '_ {
self.digits.iter().rev().copied()
}
}
/// Locat trait used to tag a few primitive integer types that can be converted
/// to `BigUint`. Bounding to this local trait is allowed by the orphan rule,
/// unlike bounding directly to `Into<u64>`.
pub(crate) trait LocalIntoU64: Into<u64> {}
macro_rules! impl_local_into_u64 {
($($primitive_type:ty),*) => {
$(
impl LocalIntoU64 for $primitive_type {}
)*
}
}
impl_local_into_u64!(u8, u16, u32, u64);
impl<T: LocalIntoU64> From<T> for BigUint {
fn from(value: T) -> BigUint {
let mut value: u64 = value.into();
let mut digits: Vec<Digit> = Vec::new();
// Extract the digits in base `BASE` from `value`,
// with the most significants digits at the back
// (same layout in BigUint so faster conversion).
while value > 0 {
digits.push((value % BASE) as Digit);
value = value as u64 / BASE;
}
BigUint::from_digits_with_most_significant_at_the_back(digits)
}
}
/// Both the primpitive types and the `TryFrom` trait are not local to this crate,
/// thus the orphan rule forbids a nice `impl` block that generalizes all the convenrsions,
/// and a local trait to tag the primitive types won't work here somehow.
/// However, one by one, it works. Well then, how about one by one but all at once.
macro_rules! impl_try_from_big_uint {
($($primitive_type:ty),*) => {
$(
impl TryFrom<&BigUint> for $primitive_type {
type Error = DoesNotFitInPrimitive;
fn try_from(
value: &BigUint
) -> Result<$primitive_type, DoesNotFitInPrimitive> {
let mut acc = 0 as $primitive_type;
for digit in value.iter_digits_from_most_significant() {
acc = acc.checked_mul(BASE as $primitive_type)
.ok_or(DoesNotFitInPrimitive)?;
acc += digit as $primitive_type;
}
Ok(acc)
}
}
)*
}
}
impl_try_from_big_uint!(u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize);
impl Eq for BigUint {}
impl PartialEq for BigUint {
fn eq(&self, rhs: &Self) -> bool {
self.digits == rhs.digits
}
}
impl Ord for BigUint {
fn cmp(&self, rhs: &BigUint) -> Ordering {
// First, look if one inetger has more digits than the `rhs`
// in which case that would be the bigger one.
match self.digits.len().cmp(&rhs.digits.len()) {
ord @ (Ordering::Less | Ordering::Greater) => return ord,
Ordering::Equal => (),
}
// Both integers have the same number of digits.
// Now, compare the digits, one to one.
// `zip` works since both iterators will stop at the same time.
//
// We start from the most significant digits because the only digit to digit
// difference that matters is the most significant one.
//
// For example, in the comparison `11811211 > 11611911`, the only
// digit to digit comparison that matters is 8 > 6 that that is because
// this is the most significant digit to digit comparison.
for (digit_self, digit_rhs) in self
.iter_digits_from_most_significant()
.zip(rhs.iter_digits_from_most_significant())
{
match digit_self.cmp(&digit_rhs) {
Ordering::Greater => return Ordering::Greater,
Ordering::Less => return Ordering::Less,
Ordering::Equal => (),
}
}
// There is no difference in the digits of the numbers.
Ordering::Equal
}
}
impl PartialOrd for BigUint {
fn partial_cmp(&self, rhs: &BigUint) -> Option<Ordering> {
Some(self.cmp(rhs))
}
}
impl AddAssign<&BigUint> for BigUint {
fn add_assign(&mut self, rhs: &BigUint) {
// When a digit to digit addition produces a result too big to fit
// in the one digit being iterated over, this `carry` gets what
// remains from the digit to digit sum to carry to the next iteration.
let mut carry = 0;
// Iterating beginning from the least significant digits.
for i in 0.. {
if i >= self.digits.len() && i >= rhs.digits.len() && carry == 0 {
// There is no digit left nor a carry to add to `self`.
break;
}
// Make sure there is a digit in `self` at index `i` to add something to.
if i >= self.digits.len() {
// ADDING LEADING ZERO
// Unused leading zeros must be removed before returning.
self.digits.push(0);
}
let self_digit = self.digits[i] as u64;
let rhs_digit = rhs.digits.get(i).copied().unwrap_or(0) as u64;
// Perform one step of the addition, adding digit to digit and
// handling the carry.
let digit_sum = self_digit + rhs_digit + carry;
self.digits[i] = (digit_sum % BASE) as Digit;
let digit_sum_remians_devided_by_base = digit_sum / BASE;
// The next iteration will be over one digit "to the left" (more significant),
// thus this `carry` will be worth more (times `BASE` more) than during
// this step, so is had to be divided by `BASE` to conserve value.
carry = digit_sum_remians_devided_by_base;
assert!(carry == 0 || carry == 1);
}
self.remove_illegal_leading_zeros();
}
}
impl AddAssign<BigUint> for BigUint {
fn add_assign(&mut self, rhs: BigUint) {
*self += &rhs;
}
}
impl Add<&BigUint> for BigUint {
type Output = BigUint;
fn add(mut self, rhs: &BigUint) -> BigUint {
self += rhs;
self
}
}
impl Add<BigUint> for BigUint {
type Output = BigUint;
fn add(mut self, rhs: BigUint) -> BigUint {
self += &rhs;
self
}
}
impl Add<&BigUint> for &BigUint {
type Output = BigUint;
fn add(self, rhs: &BigUint) -> BigUint {
let mut res = self.clone();
res += rhs;
res
}
}
impl Add<BigUint> for &BigUint {
type Output = BigUint;
fn add(self, mut rhs: BigUint) -> BigUint {
// `+` is commutative.
rhs += self;
rhs
}
}
impl SubAssign<&BigUint> for BigUint {
fn sub_assign(&mut self, rhs: &BigUint) {
// When a digit from `self` is too small to starnd the subtraction with
// the digit from `rhs`, this `carry` helps by "moving" some value from
// the digit from `self` that will be covered in the next iteration.
let mut carry = 0;
// Iterating beginning from the least significant digits.
for i in 0.. {
if i >= rhs.digits.len() && carry == 0 {
// There is no digit left nor any carry to subtract from `self`.
break;
}
if i >= self.digits.len() {
// If we get to iterate past the most significant digit of `self`
// while still having digitis or carries to subtract, then it means
// that `self` was strictly bigger than `rhs`.
panic!("subtracting a BigUint from a smaller BigUint");
}
let mut value_from_which_to_subtract = self.digits[i] as u64;
let rhs_digit = rhs.digits.get(i).copied().unwrap_or(0) as u64;
// Perform one step of the subtraction, subtracting digit to digit and
// handling the carry.
let value_to_subtract = rhs_digit + carry;
carry = 0;
if value_from_which_to_subtract < value_to_subtract {
// The digit from `self` to subtract to is not high enough,
// so we "move" some value from the one digit of `self` "to the left"
// (more significant) to add to the current one. The carry will carry
// this information to the next iteration so that value is concerved.
let value_moved_from_next_iteration = BASE;
value_from_which_to_subtract += value_moved_from_next_iteration;
// The next iteration will be over one digit "to the left" (more significant),
// thus this `carry` will be worth more (times `BASE` more) than during
// this step, so is has to be divided by `BASE` to conserve value.
carry = value_moved_from_next_iteration / BASE;
}
assert!(carry == 0 || carry == 1);
let digit_subtraction = value_from_which_to_subtract - value_to_subtract;
assert!(
digit_subtraction < BASE,
"`digit_subtraction` is expected to fit in a digit"
);
self.digits[i] = digit_subtraction as Digit;
}
// Despite never explicitly adding insignificant leading zeros,
// something like `x - x` would make all the digits to become zero,
// and some other cases would make some of the leading digits to become zero,
// so these potential leading zeros must be taken care of.
self.remove_illegal_leading_zeros();
}
}
impl SubAssign<BigUint> for BigUint {
fn sub_assign(&mut self, rhs: BigUint) {
*self -= &rhs;
}
}
impl Sub<&BigUint> for BigUint {
type Output = BigUint;
fn sub(mut self, rhs: &BigUint) -> BigUint {
self -= rhs;
self
}
}
impl Sub<BigUint> for BigUint {
type Output = BigUint;
fn sub(mut self, rhs: BigUint) -> BigUint {
self -= &rhs;
self
}
}
impl Sub<&BigUint> for &BigUint {
type Output = BigUint;
fn sub(self, rhs: &BigUint) -> BigUint {
let mut res = self.clone();
res -= rhs;
res
}
}
impl Sub<BigUint> for &BigUint {
type Output = BigUint;
fn sub(self, rhs: BigUint) -> BigUint {
let mut res = self.clone();
res -= rhs;
res
}
}
impl Mul<&BigUint> for &BigUint {
type Output = BigUint;
fn mul(self, rhs: &BigUint) -> BigUint {
// See [https://en.wikipedia.org/wiki/Multiplication_algorithm#Long_multiplication]
// for more explanations on the algorithm used here.
// It does not quite works in the same order we (at least in France) do it on paper
// (doing number by digit multiplications, and then doing the sum of all the
// intermediary results). Instead, it does digit by digit multiplications for all
// the pairs of digits in the input, in an order that is similar to directly adding
// the "current intermediary result (that is still not complete)" on the final result,
// with a carry for the addition. Whatever, it works (and is more efficient than
// would be storing all the intermediary results to add them later, or even just store
// one intermediary result).
//
// Note: Doing a multiplication on paper might help to understand.
let mut res_digits =
Vec::from_iter(std::iter::repeat(0).take(self.digits.len() + rhs.digits.len()));
for i_rhs in 0..rhs.digits.len() {
let mut carry = 0;
for i_self in 0..self.digits.len() {
let self_digit = self.digits[i_self] as u64;
let rhs_digit = rhs.digits[i_rhs] as u64;
let i_res = i_self + i_rhs;
let target_digit_before = res_digits[i_res] as u64;
// Perform one step of the multiplication, multiplying digit to digit,
// adding it to the result and handling the carry for the ongoing
// addition.
let input_digit_product = self_digit * rhs_digit;
let digit_sum = target_digit_before + input_digit_product + carry;
res_digits[i_res] = (digit_sum % BASE) as Digit;
let digit_sum_remians_devided_by_base = digit_sum / BASE;
// The next iteration will be over one digit "to the left" (more significant)
// regarding the ongoing addition to the result,
// thus this `carry` will be worth more (times `BASE` more) than during
// this step, so is had to be divided by `BASE` to conserve value.
carry = digit_sum_remians_devided_by_base;
}
// If any `carry` remains after all the digits to add, it must still be
// counted in the result so as to not lose any value.
// There is nothing in `res_digits` at this index yet, so there is
// no need to add the `carry` to what was there before (which would be 0 anyway).
res_digits[self.digits.len() + i_rhs] = carry as Digit;
}
// This conversion will take care of the potential remaining
// insignificant leading zeros.
BigUint::from_digits_with_most_significant_at_the_back(res_digits)
}
}
impl Mul<BigUint> for &BigUint {
type Output = BigUint;
fn mul(self, rhs: BigUint) -> BigUint {
self * &rhs
}
}
impl Mul<&BigUint> for BigUint {
type Output = BigUint;
fn mul(mut self, rhs: &BigUint) -> BigUint {
self = &self * rhs;
self
}
}
impl Mul<BigUint> for BigUint {
type Output = BigUint;
fn mul(mut self, rhs: BigUint) -> BigUint {
self = &self * &rhs;
self
}
}
impl MulAssign<BigUint> for BigUint {
fn mul_assign(&mut self, rhs: BigUint) {
*self = &*self * &rhs;
}
}
impl MulAssign<&BigUint> for BigUint {
fn mul_assign(&mut self, rhs: &BigUint) {
*self = &*self * rhs;
}
}
impl BigUint {
/// Performs the euclidian division `self / rhs`,
/// returns `(quotient, remainder)`.
#[must_use]
pub(crate) fn div_euclidian(&self, rhs: &BigUint) -> (BigUint, BigUint) {
// Classic long division algorithm.
// Surprisingly, it is pretty hard to find a readable and complete implementation
// or pseudocode of this algorithm on the Internet (or I haven't searched good enough),
// so this is a custom version. It works (for what it's worth).
//
// Note: Doing a division on paper will probably help to understand.
assert_ne!(rhs, &BigUint::zero(), "dividing a BigUint by zero");
let mut quotient_digits = Vec::from_iter(std::iter::repeat(0).take(self.digits.len()));
let mut current = BigUint::zero();
for i in 1..=self.digits.len() {
// Append "to the right" of the result of the last subtraction
// (or to 0 for the first iteration) the next most significant digit of `self`
// that have not yet been considered.
current.digits.insert(0, self.digits[self.digits.len() - i]);
// Might be an insignificant leading zero that causes problems
// in a subtraction later.
current.remove_illegal_leading_zeros();
// Now must happen a subtraction between `current` (the bigger number
// in the subtraction) and the biggets possible multiple of `rhs`.
// To find this biggest multiple (let it be `factor * rhs`),
// `factor` is searched for (in a fast way), then the subtraction
// happens and the result becomes the next `current`.
// `current - factor * rhs = next_current`.
// `factor` is supposed to be smaller than `BASE` and is the next
// digit to be appended "to the right" of the `quotient`.
let factor = if ¤t < rhs {
// The case when `factor == 0` seem to be a special case for the
// following algorithm that searches `factor`.
0
} else {
// That bigest multiple of `rhs` that is strictly smaller than `current`
// is searched for in the "same order" that a binary search is done
// (see [https://en.wikipedia.org/wiki/Binary_search_algorithm] or something).
//
// `factor` is supposed to be between 0 and `BASE` (excluded), so only this
// range is scanned. A failed attemp can tell us if ths `factor` we search is
// smaller or bigger, so we can cut in half the range to scan each try.
//
// For example, if `BASE` is 256 and the `factor` we search is 100, the values
// that will be tested are (in order):
// tested `factor`: 128, 64, 96, 112, 104, 100
// `BASE / power_of_two`: 64, 32, 16, 8, 4, 2 ...
let mut power_of_two = 2;
let mut factor = BASE / power_of_two;
let mut factor_times_rhs = BigUint::from(factor) * rhs;
loop {
power_of_two *= 2;
if current >= factor_times_rhs {
// We have `0 <= current - factor * rhs`, now we check if
// this `factor` is the biggest possible that has this property.
let subtraction_result = ¤t - factor_times_rhs;
if &subtraction_result < rhs {
// This is the `factor` we search (as we have
// `0 <= current - factor * rhs < rhs`, both increasing or
// decreasing `factor` would make this invalid)!
// Also, the subtrcation result is the next `current`.
current = subtraction_result;
break factor;
} else {
// The `factor` we search is bigger.
factor += BASE / power_of_two;
}
} else {
// The `factor` we search is smaller
// (since `current < factor * rhs` and we want
// `0 <= current - factor * rhs`).
factor -= BASE / power_of_two;
}
factor_times_rhs = BigUint::from(factor) * rhs;
}
};
// Append `factor` as a digit "to the right" of the `quotient`
// (its new least significant digit).
assert!(factor < BASE);
let i_quotient = quotient_digits.len() - i;
quotient_digits[i_quotient] = factor as Digit;
}
let remainder = current;
// This conversion will take care of the potential remaining
// insignificant leading zeros.
let quotient = BigUint::from_digits_with_most_significant_at_the_back(quotient_digits);
(quotient, remainder)
}
}
#[cfg(test)]
mod tests {
use super::*;
impl BigUint {
fn has_illegal_leading_zeros(&self) -> bool {
self.digits.last().copied() == Some(0)
}
}
/// A few integer values to iterate over in tests.
fn some_values() -> impl Iterator<Item = u64> {
let values: Vec<u64> = vec![
0,
1,
8,
17,
42,
69,
100000000,
123456789,
0x123456789ABCDEF,
BASE - 1,
BASE,
BASE + 1,
u16::MAX as u64 - 123,
u16::MAX as u64 - 1,
u16::MAX as u64,
u16::MAX as u64 + 1,
u16::MAX as u64 + 123,
u32::MAX as u64 - 123,
u32::MAX as u64 - 1,
u32::MAX as u64,
u32::MAX as u64 + 1,
u32::MAX as u64 + 123,
u64::MAX - 123,
u64::MAX - 1,
u64::MAX,
];
values.into_iter()
}
#[test]
fn no_leading_zeros_from_digits() {
let digits_without_leading_zeros: Vec<Digit> = vec![0x69, 0x42, 0xCA, 0xCA];
let digits_with_leading_zeros: Vec<Digit> = {
let mut vec = digits_without_leading_zeros.clone();
vec.append(&mut vec![0x00, 0x00, 0x00]);
vec
};
let bu =
BigUint::from_digits_with_most_significant_at_the_back(digits_with_leading_zeros);
assert_eq!(
bu.digits, digits_without_leading_zeros,
"illegal leading zeros in BigUint when constructed from a digit vec"
);
}
#[test]
fn no_leading_zeros_from_primitive() {
for value in some_values() {
let bu = BigUint::from(value);
assert!(
!bu.has_illegal_leading_zeros(),
"illegal leading zeros in BigUint when constructed from a primitive"
);
}
}
#[test]
fn preserve_value() {
for value in some_values() {
let value_before = value;
let bu = BigUint::from(value_before);
let value_after = u64::try_from(&bu).unwrap();
assert_eq!(
value_before, value_after,
"converting to and then from a BigUint does not preserve the value"
);
}
}
#[test]
fn too_big_to_fit() {
let too_big_for_u32 = u32::MAX as u64 + 1;
let does_not_fit = u32::try_from(&BigUint::from(too_big_for_u32));
assert!(
matches!(does_not_fit, Err(DoesNotFitInPrimitive)),
"converting to u32 a BigUint that represents a value \
too big to fit in a u32 must fail"
);
}
#[test]
fn eq_with_itself() {
for value in some_values() {
let bu = BigUint::from(value);
assert_eq!(bu, bu, "BigUint is not equal with itself");
}
}
#[test]
fn eq() {
for value_a in some_values() {
let bu_a = BigUint::from(value_a);
for value_b in some_values() {
let bu_b = BigUint::from(value_b);
assert_eq!(
value_a.eq(&value_b),
bu_a.eq(&bu_b),
"BigUint equality test behaves differently from Rust's"
);
}
}
}
#[test]
fn ord() {
for value_a in some_values() {
let bu_a = BigUint::from(value_a);
for value_b in some_values() {
let bu_b = BigUint::from(value_b);
assert_eq!(
value_a.cmp(&value_b),
bu_a.cmp(&bu_b),
"BigUint comparison behaves differently from Rust's"
);
}
}
}
#[test]
fn eq_consistent_with_ord() {
for value_a in some_values() {
let bu_a = BigUint::from(value_a);
for value_b in some_values() {
let bu_b = BigUint::from(value_b);
assert_eq!(
bu_a.eq(&bu_b),
bu_a.cmp(&bu_b) == Ordering::Equal,
"BigUint comparison (cmp) behaves differently BigUint equality test (eq)"
);
}
}
}
#[test]
fn add() {
for value_a in some_values() {
let bu_a = BigUint::from(value_a);
for value_b in some_values() {
let bu_b = BigUint::from(value_b);
let big_sum_a_b = {
let mut tmp = bu_a.clone();
tmp += &bu_b;
tmp
};
assert!(
!big_sum_a_b.has_illegal_leading_zeros(),
"illegal leading zeros in BigUint resulting from addition"
);
// Check against Rust's result, if available.
if let Some(sum_a_b) = value_a.checked_add(value_b) {
let sum_a_b_after = u64::try_from(&big_sum_a_b).expect(
"the checked addition passed, thus this was expected to pass too",
);
assert_eq!(
sum_a_b, sum_a_b_after,
"BigUint addition behaves differently from Rusts's"
);
}
// Check consistency accross all the `impl` blocks related to the addition.
assert_eq!(
big_sum_a_b,
{
let mut tmp = bu_a.clone();
tmp += bu_b.clone();
tmp
},
"one of the `impl`s is missbehaving"
);
assert_eq!(
big_sum_a_b,
&bu_a + &bu_b,
"one of the `impl`s is missbehaving"
);
assert_eq!(
big_sum_a_b,
&bu_a + bu_b.clone(),
"one of the `impl`s is missbehaving"
);
assert_eq!(
big_sum_a_b,
bu_a.clone() + &bu_b,
"one of the `impl`s is missbehaving"
);
assert_eq!(
big_sum_a_b,
bu_a.clone() + bu_b.clone(),
"one of the `impl`s is missbehaving"
);
}
}
}
#[test]
fn sub() {
for value_a in some_values() {
let bu_a = BigUint::from(value_a);
for value_b in some_values() {
// If Rust can't do the subtraction, neither can we.
if let Some(subtraction_a_b) = value_a.checked_sub(value_b) {
let bu_b = BigUint::from(value_b);
let big_subtration_a_b = {
let mut tmp = bu_a.clone();
tmp -= &bu_b;
tmp
};
assert!(
!big_subtration_a_b.has_illegal_leading_zeros(),
"illegal leading zeros in BigUint resulting from subtraction"
);
// Check against Rust's result.
let subtraction_a_b_after = u64::try_from(&big_subtration_a_b).unwrap();
assert_eq!(
subtraction_a_b, subtraction_a_b_after,
"BigUint subctarction behaves differently from Rusts's"
);
// Check consistency accross all the `impl` blocks related
// to the subtraction.
assert_eq!(
big_subtration_a_b,
{
let mut tmp = bu_a.clone();
tmp -= bu_b.clone();
tmp
},
"one of the `impl`s is missbehaving"
);
assert_eq!(
big_subtration_a_b,
&bu_a - &bu_b,
"one of the `impl`s is missbehaving"
);
assert_eq!(
big_subtration_a_b,
&bu_a - bu_b.clone(),
"one of the `impl`s is missbehaving"
);
assert_eq!(
big_subtration_a_b,
bu_a.clone() - &bu_b,
"one of the `impl`s is missbehaving"
);
assert_eq!(
big_subtration_a_b,
bu_a.clone() - bu_b.clone(),
"one of the `impl`s is missbehaving"
);
}
}
}
}
#[test]
#[should_panic]
fn sub_small_minus_big() {
// 8 - 42 = -34 which require a sign (not available with `BigUint`),
// so this should not work and is expected to panic.
let _does_not_work = BigUint::from(8u64) - BigUint::from(42u64);
}
#[test]
fn mul() {
for value_a in some_values() {
let bu_a = BigUint::from(value_a);
for value_b in some_values() {
let bu_b = BigUint::from(value_b);
let big_product_a_b = &bu_a * &bu_b;
assert!(
!big_product_a_b.has_illegal_leading_zeros(),
"illegal leading zeros in BigUint resulting from multiplication"
);
// Check against Rust's result, if available.
if let Some(product_a_b) = value_a.checked_mul(value_b) {
let product_a_b_after = u64::try_from(&big_product_a_b).expect(
"the checked multiplication passed, \
thus this was expected to pass too",
);
assert_eq!(
product_a_b, product_a_b_after,
"BigUint multiplication behaves differently from Rusts's"
);
}
// Check consistency accross all the `impl` blocks related
// to the multiplication.
assert_eq!(
big_product_a_b,
&bu_a * bu_b.clone(),
"one of the `impl`s is missbehaving"
);
assert_eq!(
big_product_a_b,
bu_a.clone() * &bu_b,
"one of the `impl`s is missbehaving"
);
assert_eq!(
big_product_a_b,
bu_a.clone() * bu_b.clone(),
"one of the `impl`s is missbehaving"
);
assert_eq!(
big_product_a_b,
{
let mut tmp = bu_a.clone();
tmp *= &bu_b;
tmp
},
"one of the `impl`s is missbehaving"
);
assert_eq!(
big_product_a_b,
{
let mut tmp = bu_a.clone();
tmp *= bu_b.clone();
tmp
},
"one of the `impl`s is missbehaving"
);
}
}
}
#[test]
fn div_euclidian() {
for value_a in some_values() {
let bu_a = BigUint::from(value_a);
for value_b in some_values() {
// If Rust can't do the division (because `value_b` is zero), neither can we.
if let Some(quotient_a_b) = value_a.checked_div(value_b) {
let remainder_a_b = value_a % value_b;
let bu_b = BigUint::from(value_b);
let (big_quotient_a_b, big_remainder_a_b) = bu_a.div_euclidian(&bu_b);
assert!(
!big_quotient_a_b.has_illegal_leading_zeros(),
"illegal leading zeros in BigUint resulting from \
euclidian division (quotient)"
);
assert!(
!big_remainder_a_b.has_illegal_leading_zeros(),
"illegal leading zeros in BigUint resulting from \
euclidian division (remainder)"
);
// Check against Rust's result.
let quotient_a_b_after = u64::try_from(&big_quotient_a_b).unwrap();
assert_eq!(
quotient_a_b, quotient_a_b_after,
"BigUint euclidian behaves differently from Rusts's for the quotient"
);
let remainder_a_b_after = u64::try_from(&big_remainder_a_b).unwrap();
assert_eq!(
remainder_a_b, remainder_a_b_after,
"BigUint euclidian behaves differently from Rusts's for the remainder"
);
}
}
}
}
#[test]
#[should_panic]
fn div_by_zero() {
let _does_not_work = BigUint::from(69u64).div_euclidian(&BigUint::zero());
}
}
pub(crate) mod string_conversion {
use super::super::CharIsNoDigitInBase;
use super::BigUint;
/// Returns the number value of a character that represent a digit in the given base.
/// For example, in base 10, `'8'` maps to `8`, and in base 16, `'f'` maps to `15`.
fn char_to_number_in_base(c: char, base: u64) -> Result<u64, CharIsNoDigitInBase> {
assert!(base >= 1);
assert!(
base <= 10 + 26,
"base {base} is too high to be supported by digits and letters"
);
if c.is_ascii_digit() {
let value = c as u64 - '0' as u64;
if value < base {
Ok(value)
} else {
Err(CharIsNoDigitInBase { character: c, base })
}
} else if c.is_ascii_alphabetic() {
let value = 10 + c as u64 - if c.is_uppercase() { 'A' } else { 'a' } as u64;
if value < base {