-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbigint.rs
2187 lines (1953 loc) · 82 KB
/
bigint.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
// Rust language amplification library providing multiple generic trait
// implementations, type wrappers, derive macros and other language enhancements
//
// Written in 2014 by
// Andrew Poelstra <[email protected]>
// Refactored & fixed in 2021-2024 by
// Dr. Maxim Orlovsky <[email protected]>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.
//
// You should have received a copy of the MIT License
// along with this software.
// If not, see <https://opensource.org/licenses/MIT>.
use crate::error::{DivError, ParseLengthError};
macro_rules! construct_bigint {
($name:ident, $n_words:expr) => {
/// Large integer type
///
/// The type is composed of little-endian ordered 64-bit words, which represents
/// its inner representation.
#[allow(non_camel_case_types)]
#[derive(Copy, Clone, PartialEq, Eq, Hash, Default)]
pub struct $name([u64; $n_words]);
impl $name {
#[inline]
/// Converts the object to a raw pointer
pub fn as_ptr(&self) -> *const u64 {
let &$name(ref dat) = self;
dat.as_ptr()
}
#[inline]
/// Converts the object to a mutable raw pointer
pub fn as_mut_ptr(&mut self) -> *mut u64 {
let &mut $name(ref mut dat) = self;
dat.as_mut_ptr()
}
#[inline]
/// Returns the underlying array of words constituting large integer
pub const fn as_inner(&self) -> &[u64; $n_words] { &self.0 }
#[inline]
/// Returns the underlying array of words constituting large integer
pub const fn into_inner(self) -> [u64; $n_words] { self.0 }
#[inline]
/// Constructs integer type from the underlying array of words.
pub const fn from_inner(array: [u64; $n_words]) -> Self { Self(array) }
}
impl $name {
/// Zero value
pub const ZERO: $name = $name([0u64; $n_words]);
/// Value for `1`
pub const ONE: $name = $name({
let mut one = [0u64; $n_words];
one[0] = 1u64;
one
});
/// Bit dimension
pub const BITS: u32 = $n_words * 64;
/// Length of the integer in bytes
pub const BYTES: u8 = $n_words * 8;
/// Length of the inner representation in 64-bit words
pub const INNER_LEN: u8 = $n_words;
/// Returns whether specific bit number is set to `1` or not
#[inline]
pub const fn bit(&self, index: usize) -> bool {
let &$name(ref arr) = self;
arr[index / 64] & (1 << (index % 64)) != 0
}
/// Returns lower 32 bits of the number as `u32`
#[inline]
pub const fn low_u32(&self) -> u32 {
let &$name(ref arr) = self;
(arr[0] & ::core::u32::MAX as u64) as u32
}
/// Returns lower 64 bits of the number as `u32`
#[inline]
pub const fn low_u64(&self) -> u64 {
let &$name(ref arr) = self;
arr[0] as u64
}
/// Returns the number of leading ones in the binary representation of
/// `self`.
#[inline]
pub fn leading_ones(&self) -> u32 {
for i in 0..$n_words {
let leading_ones = (!self[$n_words - i - 1]).leading_zeros();
if leading_ones != 64 {
return 64 * i as u32 + leading_ones;
}
}
64 * $n_words
}
/// Returns the number of leading zeros in the binary representation of
/// `self`.
#[inline]
pub fn leading_zeros(&self) -> u32 {
for i in 0..$n_words {
let leading_zeros = self[$n_words - i - 1].leading_zeros();
if leading_zeros != 64 {
return 64 * i as u32 + leading_zeros;
}
}
64 * $n_words
}
/// Returns the number of trailing ones in the binary representation of
/// `self`.
#[inline]
pub fn trailing_ones(&self) -> u32 {
for i in 0..$n_words {
let trailing_ones = (!self[i]).trailing_zeros();
if trailing_ones != 64 {
return 64 * i as u32 + trailing_ones;
}
}
64 * $n_words
}
/// Returns the number of trailing zeros in the binary representation of
/// `self`.
#[inline]
pub fn trailing_zeros(&self) -> u32 {
for i in 0..$n_words {
let trailing_zeros = self[i].trailing_zeros();
if trailing_zeros != 64 {
return 64 * i as u32 + trailing_zeros;
}
}
64 * $n_words
}
#[inline]
pub fn is_zero(&self) -> bool { self[..] == [0; $n_words] }
#[inline]
pub fn is_positive(&self) -> bool { !self.is_negative() && !self.is_zero() }
#[inline]
pub fn abs(self) -> $name {
if !self.is_negative() {
return self;
}
(!self).wrapping_add($name::ONE)
}
/// Creates the integer value from a byte array using big-endian
/// encoding
pub fn from_be_bytes(bytes: [u8; $n_words * 8]) -> $name {
Self::_from_be_slice(&bytes)
}
/// Creates the integer value from a byte slice using big-endian
/// encoding
pub fn from_be_slice(bytes: &[u8]) -> Result<$name, ParseLengthError> {
if bytes.len() != $n_words * 8 {
Err(ParseLengthError {
actual: bytes.len(),
expected: $n_words * 8,
})
} else {
Ok(Self::_from_be_slice(bytes))
}
}
/// Creates the integer value from a byte array using little-endian
/// encoding
pub fn from_le_bytes(bytes: [u8; $n_words * 8]) -> $name {
Self::_from_le_slice(&bytes)
}
/// Creates the integer value from a byte slice using little-endian
/// encoding
pub fn from_le_slice(bytes: &[u8]) -> Result<$name, ParseLengthError> {
if bytes.len() != $n_words * 8 {
Err(ParseLengthError {
actual: bytes.len(),
expected: $n_words * 8,
})
} else {
Ok(Self::_from_le_slice(bytes))
}
}
fn _from_be_slice(bytes: &[u8]) -> $name {
let mut slice = [0u64; $n_words];
slice
.iter_mut()
.rev()
.zip(bytes.chunks(8).into_iter().map(|s| {
let mut b = [0u8; 8];
b.copy_from_slice(s);
b
}))
.for_each(|(word, bytes)| *word = u64::from_be_bytes(bytes));
$name(slice)
}
fn _from_le_slice(bytes: &[u8]) -> $name {
let mut slice = [0u64; $n_words];
slice
.iter_mut()
.zip(bytes.chunks(8).into_iter().map(|s| {
let mut b = [0u8; 8];
b.copy_from_slice(s);
b
}))
.for_each(|(word, bytes)| *word = u64::from_le_bytes(bytes));
$name(slice)
}
/// Convert the integer into a byte array using big-endian encoding
pub fn to_be_bytes(self) -> [u8; $n_words * 8] {
let mut res = [0; $n_words * 8];
for i in 0..$n_words {
let start = i * 8;
res[start..start + 8]
.copy_from_slice(&self.0[$n_words - (i + 1)].to_be_bytes());
}
res
}
/// Convert a integer into a byte array using little-endian encoding
pub fn to_le_bytes(self) -> [u8; $n_words * 8] {
let mut res = [0; $n_words * 8];
for i in 0..$n_words {
let start = i * 8;
res[start..start + 8].copy_from_slice(&self.0[i].to_le_bytes());
}
res
}
// divmod like operation, returns (quotient, remainder)
#[inline]
fn div_rem(self, other: Self) -> Result<(Self, Self), DivError> {
// Check for division by 0
if other.is_zero() {
return Err(DivError::ZeroDiv);
}
if other.is_negative() && self == Self::MIN && other == Self::ONE.wrapping_neg() {
return Err(DivError::Overflow);
}
let mut me = self.abs();
let mut you = other.abs();
let mut ret = [0u64; $n_words];
if self.is_negative() == other.is_negative() && me < you {
return Ok(($name(ret), self));
}
let shift = me.bits_required() - you.bits_required();
you <<= shift;
for i in (0..=shift).rev() {
if me >= you {
ret[i / 64] |= 1 << (i % 64);
me -= you;
}
you >>= 1;
}
Ok((
if self.is_negative() == other.is_negative() {
Self(ret)
} else {
-Self(ret)
},
if self.is_negative() { -me } else { me },
))
}
#[inline]
fn div_rem_euclid(self, other: Self) -> Result<(Self, Self), DivError> {
self.div_rem(other).map(|(q, r)| {
(
match (r.is_negative(), other.is_positive()) {
(true, true) => q.wrapping_sub(Self::ONE),
(true, false) => q.wrapping_add(Self::ONE),
_ => q,
},
match (r.is_negative(), other.is_positive()) {
(true, true) => r.wrapping_add(other),
(true, false) => r.wrapping_sub(other),
_ => r,
},
)
})
}
}
impl From<bool> for $name {
fn from(init: bool) -> $name {
let mut ret = [0; $n_words];
if init {
ret[0] = 1;
}
$name(ret)
}
}
impl From<u8> for $name {
fn from(init: u8) -> $name {
let mut ret = [0; $n_words];
ret[0] = init as u64;
$name(ret)
}
}
impl From<u16> for $name {
fn from(init: u16) -> $name {
let mut ret = [0; $n_words];
ret[0] = init as u64;
$name(ret)
}
}
impl From<u32> for $name {
fn from(init: u32) -> $name {
let mut ret = [0; $n_words];
ret[0] = init as u64;
$name(ret)
}
}
impl From<u64> for $name {
fn from(init: u64) -> $name {
let mut ret = [0; $n_words];
ret[0] = init;
$name(ret)
}
}
impl From<u128> for $name {
fn from(init: u128) -> $name {
let mut ret = [0; $n_words * 8];
for (pos, byte) in init.to_le_bytes().iter().enumerate() {
ret[pos] = *byte;
}
$name::from_le_bytes(ret)
}
}
impl<'a> ::core::convert::TryFrom<&'a [u64]> for $name {
type Error = $crate::error::ParseLengthError;
fn try_from(data: &'a [u64]) -> Result<$name, Self::Error> {
if data.len() != $n_words {
Err($crate::error::ParseLengthError {
actual: data.len(),
expected: $n_words,
})
} else {
let mut bytes = [0u64; $n_words];
bytes.copy_from_slice(data);
Ok(Self::from_inner(bytes))
}
}
}
impl ::core::ops::Index<usize> for $name {
type Output = u64;
#[inline]
fn index(&self, index: usize) -> &u64 { &self.0[index] }
}
impl ::core::ops::Index<::core::ops::Range<usize>> for $name {
type Output = [u64];
#[inline]
fn index(&self, index: ::core::ops::Range<usize>) -> &[u64] { &self.0[index] }
}
impl ::core::ops::Index<::core::ops::RangeTo<usize>> for $name {
type Output = [u64];
#[inline]
fn index(&self, index: ::core::ops::RangeTo<usize>) -> &[u64] { &self.0[index] }
}
impl ::core::ops::Index<::core::ops::RangeFrom<usize>> for $name {
type Output = [u64];
#[inline]
fn index(&self, index: ::core::ops::RangeFrom<usize>) -> &[u64] { &self.0[index] }
}
impl ::core::ops::Index<::core::ops::RangeFull> for $name {
type Output = [u64];
#[inline]
fn index(&self, _: ::core::ops::RangeFull) -> &[u64] { &self.0[..] }
}
impl PartialOrd for $name {
#[inline]
fn partial_cmp(&self, other: &$name) -> Option<::core::cmp::Ordering> {
Some(self.cmp(&other))
}
}
impl Ord for $name {
#[inline]
fn cmp(&self, other: &$name) -> ::core::cmp::Ordering {
// We need to manually implement ordering because the words in our array
// are in little-endian order, i.e. the most significant word is last in
// the array, and the auto derive for array Ord compares the elements
// from first to last.
for i in 0..$n_words {
let self_word = self[$n_words - 1 - i];
let other_word = other[$n_words - 1 - i];
// If this is a signed type, start with signed comparison on the
// most-significant word, then continue with unsigned comparisons on
// the rest of the words.
let res = if i == 0 && Self::IS_SIGNED_TYPE {
(self_word as i64).cmp(&(other_word as i64))
} else {
self_word.cmp(&other_word)
};
if res != ::core::cmp::Ordering::Equal {
return res;
}
}
::core::cmp::Ordering::Equal
}
}
impl ::core::ops::Neg for $name {
type Output = Self;
fn neg(self) -> Self::Output {
assert!(
$name::MIN != $name([::core::u64::MAX; $n_words]),
"attempt to negate unsigned number"
);
assert!(
self != $name::MIN,
"attempt to negate the minimum value, which would overflow"
);
(!self).wrapping_add($name::ONE)
}
}
impl $name {
/// Checked integer addition. Computes `self + rhs`, returning `None` if
/// overflow occurred.
pub fn checked_add<T>(self, other: T) -> Option<$name>
where T: Into<$name> {
let (res, flag) = self.overflowing_add(other);
if flag { None } else { Some(res) }
}
/// Saturating integer addition. Computes `self + rhs`, saturating at the
/// numeric bounds instead of overflowing.
pub fn saturating_add<T>(self, other: T) -> $name
where T: Into<$name> {
let (res, flag) = self.overflowing_add(other);
if flag { Self::MAX } else { res }
}
/// Calculates `self + rhs`
///
/// Returns a tuple of the addition along with a boolean indicating whether
/// an arithmetic overflow would occur. If an overflow would have occurred
/// then the wrapped value is returned.
pub fn overflowing_add<T>(self, other: T) -> ($name, bool)
where T: Into<$name> {
let $name(ref me) = self;
let other = other.into();
let $name(ref you) = other;
let mut ret = [0u64; $n_words];
let mut carry = 0u64;
for i in 0..$n_words {
let (res, flag) = me[i].overflowing_add(carry);
carry = flag as u64;
let (res, flag) = res.overflowing_add(you[i]);
carry += flag as u64;
ret[i] = res;
}
let ret = Self(ret);
let overflow = if !Self::IS_SIGNED_TYPE {
carry > 0
} else {
self != Self::MIN &&
other != Self::MIN &&
(self.is_negative() == other.is_negative()) &&
(self.is_negative() != ret.is_negative())
};
(ret, overflow)
}
/// Wrapping (modular) addition. Computes `self + rhs`, wrapping around at
/// the boundary of the type.
pub fn wrapping_add<T>(self, other: T) -> $name
where T: Into<$name> {
self.overflowing_add(other).0
}
/// Checked integer subtraction. Computes `self - rhs`, returning `None` if
/// overflow occurred.
pub fn checked_sub<T>(self, other: T) -> Option<$name>
where T: Into<$name> {
let (res, flag) = self.overflowing_sub(other);
if flag { None } else { Some(res) }
}
/// Saturating integer subtraction. Computes `self - rhs`, saturating at the
/// numeric bounds instead of overflowing.
pub fn saturating_sub<T>(self, other: T) -> $name
where T: Into<$name> {
let (res, flag) = self.overflowing_sub(other);
if flag { Self::MAX } else { res }
}
/// Calculates `self - rhs`
///
/// Returns a tuple of the subtraction along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would
/// have occurred then the wrapped value is returned.
pub fn overflowing_sub<T>(self, other: T) -> ($name, bool)
where T: Into<$name> {
let other = other.into();
if !Self::IS_SIGNED_TYPE {
(self.wrapping_add(!other).wrapping_add($name::ONE), self < other)
} else {
self.overflowing_add((!other).wrapping_add($name::ONE))
}
}
/// Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around
/// at the boundary of the type.
pub fn wrapping_sub<T>(self, other: T) -> $name
where T: Into<$name> {
self.overflowing_sub(other).0
}
/// Checked integer multiplication. Computes `self * rhs`, returning `None`
/// if overflow occurred.
pub fn checked_mul<T>(self, other: T) -> Option<$name>
where T: Into<$name> {
let (res, flag) = self.overflowing_mul(other);
if flag { None } else { Some(res) }
}
/// Saturating integer multiplication. Computes `self * rhs`, saturating at
/// the numeric bounds instead of overflowing.
pub fn saturating_mul<T>(self, other: T) -> $name
where T: Into<$name> {
let (res, flag) = self.overflowing_mul(other);
if flag { Self::MAX } else { res }
}
/// Wrapping (modular) multiplication. Computes `self * rhs`, wrapping
/// around at the boundary of the type.
pub fn wrapping_mul<T>(self, other: T) -> $name
where T: Into<$name> {
self.overflowing_mul(other).0
}
/// Calculates `self / rhs`
///
/// Returns a tuple of the divisor along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would
/// have occurred then the wrapped value is returned.
pub fn overflowing_div<T>(self, other: T) -> ($name, bool)
where T: Into<$name> {
let rhs = other.into();
match self.div_rem(rhs) {
Err(DivError::Overflow) => (Self::MIN, true),
res => (res.expect("Error occurred during bigint division").0, false),
}
}
/// Wrapping (modular) division. Calculates `self / rhs`,
/// wrapping around at the boundary of the type.
///
/// The only case where such wrapping can occur is when one divides
/// `MIN / -1` on a signed type (where MIN is the negative minimal value for
/// the type); this is equivalent to -MIN, a positive value that is
/// too large to represent in the type.
/// In such a case, this function returns MIN itself.
pub fn wrapping_div<T>(self, other: T) -> $name
where T: Into<$name> {
self.overflowing_div(other.into()).0
}
/// Checked integer division. Computes `self / rhs`,
/// returning None if `rhs == 0` or the division results in overflow.
pub fn checked_div<T>(self, other: T) -> Option<$name>
where T: Into<$name> {
self.div_rem(other.into()).ok().map(|(q, _)| q)
}
/// Saturating integer division. Computes `self / rhs`,
/// saturating at the numeric bounds instead of overflowing.
pub fn saturating_div<T>(self, other: T) -> $name
where T: Into<$name> {
let rhs = other.into();
match self.div_rem(rhs) {
Err(DivError::Overflow) => Self::MAX,
res => res.expect("Error occurred during bigint division").0,
}
}
/// Calculates the remainder when `self` is divided by `rhs`.
///
/// Returns a tuple of the remainder after dividing along with a boolean
/// indicating whether an arithmetic overflow would occur.
/// If an overflow would occur then 0 is returned.
pub fn overflowing_rem<T>(self, other: T) -> ($name, bool)
where T: Into<$name> {
let rhs = other.into();
match self.div_rem(rhs) {
Err(DivError::Overflow) => (Self::ZERO, true),
res => (res.expect("Error occurred during bigint division").1, false),
}
}
/// Wrapping (modular) remainder.
/// Computes self % rhs, wrapping around at the boundary of the type.
///
/// Such wrap-around never actually occurs mathematically;
/// implementation artifacts make x % y invalid for MIN / -1
/// on a signed type (where MIN is the negative minimal value).
/// In such a case, this function returns 0.
pub fn wrapping_rem<T>(self, other: T) -> $name
where T: Into<$name> {
self.overflowing_rem(other.into()).0
}
/// Checked integer remainder. Computes `self % rhs`,
/// returning None if `rhs == 0` or the division results in overflow.
pub fn checked_rem<T>(self, other: T) -> Option<$name>
where T: Into<$name> {
self.div_rem(other.into()).ok().map(|(_, r)| r)
}
/// Calculates the quotient of Euclidean division of `self` by `rhs`.
///
/// This computes the integer `q` such that `self = q * rhs + r`,
/// with `r = self.rem_euclid(rhs)` and `0 <= r < abs(rhs)`.
///
/// In other words, the result is `self / rhs` rounded to the integer `q`
/// such that `self >= q * rhs`. If `self > 0`,
/// this is equal to round towards zero (the default in Rust);
/// if `self < 0`, this is equal to round towards +/- infinity.
pub fn div_euclid<T>(self, other: T) -> $name
where T: Into<$name> {
self.div_rem_euclid(other.into())
.expect("Error occurred during bigint division")
.0
}
/// Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
///
/// Returns a tuple of the divisor along with a boolean indicating
/// whether an arithmetic overflow would occur.
/// If an overflow would occur then `self` is returned.
pub fn overflowing_div_euclid<T>(self, other: T) -> ($name, bool)
where T: Into<$name> {
match self.div_rem_euclid(other.into()) {
Err(DivError::Overflow) => (Self::MIN, true),
res => (res.expect("Error occurred during bigint division").0, false),
}
}
/// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`,
/// wrapping around at the boundary of the type.
///
/// Wrapping will only occur in `MIN / -1` on a signed type
/// (where MIN is the negative minimal value for the type).
/// This is equivalent to `-MIN`, a positive value
/// that is too large to represent in the type.
/// In this case, this method returns `MIN` itself.
pub fn wrapping_div_euclid<T>(self, other: T) -> $name
where T: Into<$name> {
self.overflowing_div_euclid(other.into()).0
}
/// Checked Euclidean division. Computes `self.div_euclid(rhs)`,
/// returning None if `rhs == 0` or the division results in overflow.
pub fn checked_div_euclid<T>(self, other: T) -> Option<$name>
where T: Into<$name> {
self.div_rem_euclid(other.into()).ok().map(|(q, _)| q)
}
/// Calculates the least nonnegative remainder of `self (mod rhs)`.
///
/// This is done as if by the Euclidean division algorithm –
/// given `r = self.rem_euclid(rhs)`, `self = rhs * self.div_euclid(rhs) +
/// r`, and `0 <= r < abs(rhs)`.
pub fn rem_euclid<T>(self, other: T) -> $name
where T: Into<$name> {
self.div_rem_euclid(other.into())
.expect("Error occurred during bigint division")
.1
}
/// Overflowing Euclidean remainder. Calculates `self.rem_euclid(rhs)`.
///
/// Returns a tuple of the remainder after dividing along with a boolean
/// indicating whether an arithmetic overflow would occur.
/// If an overflow would occur then 0 is returned.
pub fn overflowing_rem_euclid<T>(self, other: T) -> ($name, bool)
where T: Into<$name> {
match self.div_rem_euclid(other.into()) {
Err(DivError::Overflow) => (Self::ZERO, true),
res => (res.expect("Error occurred during bigint division").1, false),
}
}
/// Wrapping Euclidean remainder. Computes `self.rem_euclid(rhs)`,
/// wrapping around at the boundary of the type.
///
/// Wrapping will only occur in `MIN % -1` on a signed type
/// (where `MIN` is the negative minimal value for the type).
/// In this case, this method returns 0.
pub fn wrapping_rem_euclid<T>(self, other: T) -> $name
where T: Into<$name> {
self.overflowing_rem_euclid(other.into()).0
}
/// Checked Euclidean remainder. Computes `self.rem_euclid(rhs)`,
/// returning None if `rhs == 0` or the division results in overflow.
pub fn checked_rem_euclid<T>(self, other: T) -> Option<$name>
where T: Into<$name> {
self.div_rem_euclid(other.into()).ok().map(|(_, r)| r)
}
/// Checked shift left. Computes self << rhs,
/// returning None if rhs is larger than or equal to the number of bits in
/// self.
pub fn checked_shl(self, rhs: u32) -> Option<$name> {
match rhs < Self::BITS {
true => Some(self << (rhs as usize)),
false => None,
}
}
/// Checked shift right. Computes self >> rhs,
/// returning None if rhs is larger than or equal to the number of bits in
/// self.
pub fn checked_shr(self, rhs: u32) -> Option<$name> {
match rhs < Self::BITS {
true => Some(self >> (rhs as usize)),
false => None,
}
}
/// Wrapping (modular) negation. Computes -self,
/// wrapping around at the boundary of the type.
/// Since unsigned types do not have negative equivalents
/// all applications of this function will wrap (except for -0).
/// For values smaller than the corresponding signed type's maximum
/// the result is the same as casting the corresponding signed value.
/// Any larger values are equivalent to MAX + 1 - (val - MAX - 1)
/// where MAX is the corresponding signed type's maximum.
pub fn wrapping_neg(self) -> $name { (!self).wrapping_add(Self::ONE) }
}
impl<T> ::core::ops::Add<T> for $name
where T: Into<$name>
{
type Output = $name;
fn add(self, other: T) -> $name {
let (res, flag) = self.overflowing_add(other);
assert!(!flag, "attempt to add with overflow");
res
}
}
impl<T> ::core::ops::AddAssign<T> for $name
where T: Into<$name>
{
#[inline]
fn add_assign(&mut self, rhs: T) { self.0 = (*self + rhs).0 }
}
impl<T> ::core::ops::Sub<T> for $name
where T: Into<$name>
{
type Output = $name;
#[inline]
fn sub(self, other: T) -> $name {
let (res, flag) = self.overflowing_sub(other);
assert!(!flag, "attempt to subtract with overflow");
res
}
}
impl<T> ::core::ops::SubAssign<T> for $name
where T: Into<$name>
{
#[inline]
fn sub_assign(&mut self, rhs: T) { self.0 = (*self - rhs).0 }
}
impl<T> ::core::ops::Mul<T> for $name
where T: Into<$name>
{
type Output = $name;
fn mul(self, other: T) -> $name {
let (res, flag) = self.overflowing_mul(other);
assert!(!flag, "attempt to mul with overflow");
res
}
}
impl<T> ::core::ops::MulAssign<T> for $name
where T: Into<$name>
{
#[inline]
fn mul_assign(&mut self, rhs: T) { self.0 = (*self * rhs).0 }
}
impl<T> ::core::ops::Div<T> for $name
where T: Into<$name>
{
type Output = $name;
fn div(self, other: T) -> $name {
self.div_rem(other.into())
.expect("Error occurred during bigint division")
.0
}
}
impl<T> ::core::ops::DivAssign<T> for $name
where T: Into<$name>
{
#[inline]
fn div_assign(&mut self, rhs: T) { self.0 = (*self / rhs).0 }
}
impl<T> ::core::ops::Rem<T> for $name
where T: Into<$name>
{
type Output = $name;
fn rem(self, other: T) -> $name {
self.div_rem(other.into())
.expect("Error occurred during bigint division")
.1
}
}
impl<T> ::core::ops::RemAssign<T> for $name
where T: Into<$name>
{
#[inline]
fn rem_assign(&mut self, rhs: T) { self.0 = (*self % rhs).0 }
}
impl<T> ::core::ops::BitAnd<T> for $name
where T: Into<$name>
{
type Output = $name;
#[inline]
fn bitand(self, other: T) -> $name {
let $name(ref arr1) = self;
let $name(ref arr2) = other.into();
let mut ret = [0u64; $n_words];
for i in 0..$n_words {
ret[i] = arr1[i] & arr2[i];
}
$name(ret)
}
}
impl<T> ::core::ops::BitAndAssign<T> for $name
where T: Into<$name>
{
#[inline]
fn bitand_assign(&mut self, rhs: T) { self.0 = (*self & rhs).0 }
}
impl<T> ::core::ops::BitXor<T> for $name
where T: Into<$name>
{
type Output = $name;
#[inline]
fn bitxor(self, other: T) -> $name {
let $name(ref arr1) = self;
let $name(ref arr2) = other.into();
let mut ret = [0u64; $n_words];
for i in 0..$n_words {
ret[i] = arr1[i] ^ arr2[i];
}
$name(ret)
}
}
impl<T> ::core::ops::BitXorAssign<T> for $name
where T: Into<$name>
{
#[inline]
fn bitxor_assign(&mut self, rhs: T) { self.0 = (*self ^ rhs).0 }
}
impl<T> ::core::ops::BitOr<T> for $name
where T: Into<$name>
{
type Output = $name;
#[inline]
fn bitor(self, other: T) -> $name {
let $name(ref arr1) = self;
let $name(ref arr2) = other.into();
let mut ret = [0u64; $n_words];
for i in 0..$n_words {
ret[i] = arr1[i] | arr2[i];
}
$name(ret)
}
}
impl<T> ::core::ops::BitOrAssign<T> for $name
where T: Into<$name>
{
#[inline]
fn bitor_assign(&mut self, rhs: T) { self.0 = (*self | rhs).0 }
}
impl ::core::ops::Shl<usize> for $name {
type Output = $name;
fn shl(self, shift: usize) -> $name {
let $name(ref original) = self;
let mut ret = [0u64; $n_words];
let word_shift = shift / 64;
let bit_shift = shift % 64;
for i in 0..$n_words {
// Shift
if bit_shift < 64 && i + word_shift < $n_words {
ret[i + word_shift] += original[i] << bit_shift;
}
// Carry
if bit_shift > 0 && i + word_shift + 1 < $n_words {
ret[i + word_shift + 1] += original[i] >> (64 - bit_shift);
}
}
$name(ret)
}
}
impl ::core::ops::ShlAssign<usize> for $name {
#[inline]
fn shl_assign(&mut self, rhs: usize) { self.0 = (*self << rhs).0 }
}
impl ::core::ops::Shr<usize> for $name {
type Output = $name;
fn shr(self, shift: usize) -> $name {
let $name(ref original) = self;
let mut ret = [0u64; $n_words];
let word_shift = shift / 64;
let bit_shift = shift % 64;
for i in word_shift..$n_words {
// Shift
ret[i - word_shift] += original[i] >> bit_shift;
// Carry
if bit_shift > 0 && i < $n_words - 1 {
ret[i - word_shift] += original[i + 1] << (64 - bit_shift);
}
}
if self.is_negative() {
ret[$n_words - 1] |= 0x8000_0000_0000_0000
}
$name(ret)
}
}
impl ::core::ops::ShrAssign<usize> for $name {
#[inline]
fn shr_assign(&mut self, rhs: usize) { self.0 = (*self >> rhs).0 }
}
impl ::core::ops::Not for $name {
type Output = $name;
#[inline]
fn not(self) -> $name {
let $name(ref arr) = self;
let mut ret = [0u64; $n_words];
for i in 0..$n_words {
ret[i] = !arr[i];
}
$name(ret)