-
Notifications
You must be signed in to change notification settings - Fork 278
/
Copy pathmod.rs
1308 lines (1170 loc) · 34.6 KB
/
mod.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
use crate::{
bits::{BitIteratorBE, BitIteratorLE},
const_for, UniformRand,
};
#[allow(unused)]
use ark_ff_macros::unroll_for_loops;
use ark_serialize::{
CanonicalDeserialize, CanonicalSerialize, Compress, SerializationError, Valid, Validate,
};
use ark_std::{
borrow::Borrow,
// convert::TryFrom,
fmt::{Debug, Display, UpperHex},
io::{Read, Write},
ops::{
BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Not, Shl, ShlAssign, Shr,
ShrAssign,
},
rand::{
distributions::{Distribution, Standard},
Rng,
},
str::FromStr,
vec::*,
Zero,
};
use num_bigint::BigUint;
use zeroize::Zeroize;
#[macro_use]
pub mod arithmetic;
#[derive(Copy, Clone, PartialEq, Eq, Hash, Zeroize)]
pub struct BigInt<const N: usize>(pub [u64; N]);
impl<const N: usize> Default for BigInt<N> {
fn default() -> Self {
Self([0u64; N])
}
}
impl<const N: usize> CanonicalSerialize for BigInt<N> {
fn serialize_with_mode<W: Write>(
&self,
writer: W,
compress: Compress,
) -> Result<(), SerializationError> {
self.0.serialize_with_mode(writer, compress)
}
fn serialized_size(&self, compress: Compress) -> usize {
self.0.serialized_size(compress)
}
}
impl<const N: usize> Valid for BigInt<N> {
fn check(&self) -> Result<(), SerializationError> {
self.0.check()
}
}
impl<const N: usize> CanonicalDeserialize for BigInt<N> {
fn deserialize_with_mode<R: Read>(
reader: R,
compress: Compress,
validate: Validate,
) -> Result<Self, SerializationError> {
Ok(BigInt(<[u64; N]>::deserialize_with_mode(
reader, compress, validate,
)?))
}
}
/// Construct a [`struct@BigInt<N>`] element from a literal string.
///
/// # Panics
///
/// If the integer represented by the string cannot fit in the number
/// of limbs of the `BigInt`, this macro results in a
/// * compile-time error if used in a const context
/// * run-time error otherwise.
///
/// # Usage
/// ```rust
/// # use ark_ff::BigInt;
/// const ONE: BigInt<6> = BigInt!("1");
///
/// fn check_correctness() {
/// assert_eq!(ONE, BigInt::from(1u8));
/// }
/// ```
#[macro_export]
macro_rules! BigInt {
($c0:expr) => {{
let (is_positive, limbs) = $crate::ark_ff_macros::to_sign_and_limbs!($c0);
assert!(is_positive);
let mut integer = $crate::BigInt::zero();
assert!(integer.0.len() >= limbs.len());
$crate::const_for!((i in 0..(limbs.len())) {
integer.0[i] = limbs[i];
});
integer
}};
}
#[doc(hidden)]
macro_rules! const_modulo {
($a:expr, $divisor:expr) => {{
// Stupid slow base-2 long division taken from
// https://en.wikipedia.org/wiki/Division_algorithm
assert!(!$divisor.const_is_zero());
let mut remainder = Self::new([0u64; N]);
let mut i = ($a.num_bits() - 1) as isize;
let mut carry;
while i >= 0 {
(remainder, carry) = remainder.const_mul2_with_carry();
remainder.0[0] |= $a.get_bit(i as usize) as u64;
if remainder.const_geq($divisor) || carry {
let (r, borrow) = remainder.const_sub_with_borrow($divisor);
remainder = r;
assert!(borrow == carry);
}
i -= 1;
}
remainder
}};
}
impl<const N: usize> BigInt<N> {
pub const fn new(value: [u64; N]) -> Self {
Self(value)
}
pub const fn zero() -> Self {
Self([0u64; N])
}
pub const fn one() -> Self {
let mut one = Self::zero();
one.0[0] = 1;
one
}
#[doc(hidden)]
pub const fn const_is_even(&self) -> bool {
self.0[0] % 2 == 0
}
#[doc(hidden)]
pub const fn const_is_odd(&self) -> bool {
self.0[0] % 2 == 1
}
#[doc(hidden)]
pub const fn mod_4(&self) -> u8 {
// To compute n % 4, we need to simply look at the
// 2 least significant bits of n, and check their value mod 4.
(((self.0[0] << 62) >> 62) % 4) as u8
}
/// Compute a right shift of `self`
/// This is equivalent to a (saturating) division by 2.
#[doc(hidden)]
pub const fn const_shr(&self) -> Self {
let mut result = *self;
let mut t = 0;
crate::const_for!((i in 0..N) {
let a = result.0[N - i - 1];
let t2 = a << 63;
result.0[N - i - 1] >>= 1;
result.0[N - i - 1] |= t;
t = t2;
});
result
}
const fn const_geq(&self, other: &Self) -> bool {
const_for!((i in 0..N) {
let a = self.0[N - i - 1];
let b = other.0[N - i - 1];
if a < b {
return false;
} else if a > b {
return true;
}
});
true
}
/// Compute the largest integer `s` such that `self = 2**s * t + 1` for odd `t`.
#[doc(hidden)]
pub const fn two_adic_valuation(mut self) -> u32 {
assert!(self.const_is_odd());
let mut two_adicity = 0;
// Since `self` is odd, we can always subtract one
// without a borrow
self.0[0] -= 1;
while self.const_is_even() {
self = self.const_shr();
two_adicity += 1;
}
two_adicity
}
/// Compute the smallest odd integer `t` such that `self = 2**s * t + 1` for some
/// integer `s = self.two_adic_valuation()`.
#[doc(hidden)]
pub const fn two_adic_coefficient(mut self) -> Self {
assert!(self.const_is_odd());
// Since `self` is odd, we can always subtract one
// without a borrow
self.0[0] -= 1;
while self.const_is_even() {
self = self.const_shr();
}
assert!(self.const_is_odd());
self
}
/// Divide `self` by 2, rounding down if necessary.
/// That is, if `self.is_odd()`, compute `(self - 1)/2`.
/// Else, compute `self/2`.
#[doc(hidden)]
pub const fn divide_by_2_round_down(mut self) -> Self {
if self.const_is_odd() {
self.0[0] -= 1;
}
self.const_shr()
}
/// Find the number of bits in the binary decomposition of `self`.
#[doc(hidden)]
pub const fn const_num_bits(self) -> u32 {
((N - 1) * 64) as u32 + (64 - self.0[N - 1].leading_zeros())
}
#[inline]
pub(crate) const fn const_sub_with_borrow(mut self, other: &Self) -> (Self, bool) {
let mut borrow = 0;
const_for!((i in 0..N) {
self.0[i] = sbb!(self.0[i], other.0[i], &mut borrow);
});
(self, borrow != 0)
}
#[inline]
pub(crate) const fn const_add_with_carry(mut self, other: &Self) -> (Self, bool) {
let mut carry = 0;
crate::const_for!((i in 0..N) {
self.0[i] = adc!(self.0[i], other.0[i], &mut carry);
});
(self, carry != 0)
}
const fn const_mul2_with_carry(mut self) -> (Self, bool) {
let mut last = 0;
crate::const_for!((i in 0..N) {
let a = self.0[i];
let tmp = a >> 63;
self.0[i] <<= 1;
self.0[i] |= last;
last = tmp;
});
(self, last != 0)
}
pub(crate) const fn const_is_zero(&self) -> bool {
let mut is_zero = true;
crate::const_for!((i in 0..N) {
is_zero &= self.0[i] == 0;
});
is_zero
}
/// Computes the Montgomery R constant modulo `self`.
#[doc(hidden)]
pub const fn montgomery_r(&self) -> Self {
let two_pow_n_times_64 = crate::const_helpers::RBuffer([0u64; N], 1);
const_modulo!(two_pow_n_times_64, self)
}
/// Computes the Montgomery R2 constant modulo `self`.
#[doc(hidden)]
pub const fn montgomery_r2(&self) -> Self {
let two_pow_n_times_64_square = crate::const_helpers::R2Buffer([0u64; N], [0u64; N], 1);
const_modulo!(two_pow_n_times_64_square, self)
}
}
impl<const N: usize> BigInteger for BigInt<N> {
const NUM_LIMBS: usize = N;
#[unroll_for_loops(6)]
#[inline]
fn add_with_carry(&mut self, other: &Self) -> bool {
let mut carry = 0;
for i in 0..N {
carry = arithmetic::adc_for_add_with_carry(&mut self.0[i], other.0[i], carry);
}
carry != 0
}
#[unroll_for_loops(6)]
#[inline]
fn sub_with_borrow(&mut self, other: &Self) -> bool {
let mut borrow = 0;
for i in 0..N {
borrow = arithmetic::sbb_for_sub_with_borrow(&mut self.0[i], other.0[i], borrow);
}
borrow != 0
}
#[inline]
#[allow(unused)]
fn mul2(&mut self) -> bool {
#[cfg(all(target_arch = "x86_64", feature = "asm"))]
#[allow(unsafe_code)]
{
let mut carry = 0;
for i in 0..N {
unsafe {
use core::arch::x86_64::_addcarry_u64;
carry = _addcarry_u64(carry, self.0[i], self.0[i], &mut self.0[i])
};
}
carry != 0
}
#[cfg(not(all(target_arch = "x86_64", feature = "asm")))]
{
let mut last = 0;
for i in 0..N {
let a = &mut self.0[i];
let tmp = *a >> 63;
*a <<= 1;
*a |= last;
last = tmp;
}
last != 0
}
}
#[inline]
fn muln(&mut self, mut n: u32) {
if n >= (64 * N) as u32 {
*self = Self::from(0u64);
return;
}
while n >= 64 {
let mut t = 0;
for i in 0..N {
core::mem::swap(&mut t, &mut self.0[i]);
}
n -= 64;
}
if n > 0 {
let mut t = 0;
#[allow(unused)]
for i in 0..N {
let a = &mut self.0[i];
let t2 = *a >> (64 - n);
*a <<= n;
*a |= t;
t = t2;
}
}
}
#[inline]
fn mul(&self, other: &Self) -> (Self, Self) {
if self.is_zero() || other.is_zero() {
let zero = Self::zero();
return (zero, zero);
}
let mut r = crate::const_helpers::MulBuffer::zeroed();
let mut carry = 0;
for i in 0..N {
for j in 0..N {
r[i + j] = mac_with_carry!(r[i + j], self.0[i], other.0[j], &mut carry);
}
r.b1[i] = carry;
carry = 0;
}
(Self(r.b0), Self(r.b1))
}
#[inline]
fn mul_low(&self, other: &Self) -> Self {
if self.is_zero() || other.is_zero() {
return Self::zero();
}
let mut res = Self::zero();
let mut carry = 0;
for i in 0..N {
for j in 0..(N - i) {
res.0[i + j] = mac_with_carry!(res.0[i + j], self.0[i], other.0[j], &mut carry);
}
carry = 0;
}
res
}
#[inline]
fn mul_high(&self, other: &Self) -> Self {
self.mul(other).1
}
#[inline]
fn div2(&mut self) {
let mut t = 0;
for a in self.0.iter_mut().rev() {
let t2 = *a << 63;
*a >>= 1;
*a |= t;
t = t2;
}
}
#[inline]
fn divn(&mut self, mut n: u32) {
if n >= (64 * N) as u32 {
*self = Self::from(0u64);
return;
}
while n >= 64 {
let mut t = 0;
for i in 0..N {
core::mem::swap(&mut t, &mut self.0[N - i - 1]);
}
n -= 64;
}
if n > 0 {
let mut t = 0;
#[allow(unused)]
for i in 0..N {
let a = &mut self.0[N - i - 1];
let t2 = *a << (64 - n);
*a >>= n;
*a |= t;
t = t2;
}
}
}
#[inline]
fn is_odd(&self) -> bool {
self.0[0] & 1 == 1
}
#[inline]
fn is_even(&self) -> bool {
!self.is_odd()
}
#[inline]
fn is_zero(&self) -> bool {
self.0.iter().all(Zero::is_zero)
}
#[inline]
fn num_bits(&self) -> u32 {
let mut ret = N as u32 * 64;
for i in self.0.iter().rev() {
let leading = i.leading_zeros();
ret -= leading;
if leading != 64 {
break;
}
}
ret
}
#[inline]
fn get_bit(&self, i: usize) -> bool {
if i >= 64 * N {
false
} else {
let limb = i / 64;
let bit = i - (64 * limb);
(self.0[limb] & (1 << bit)) != 0
}
}
#[inline]
fn from_bits_be(bits: &[bool]) -> Self {
let mut bits = bits.to_vec();
bits.reverse();
Self::from_bits_le(&bits)
}
fn from_bits_le(bits: &[bool]) -> Self {
let mut res = Self::zero();
for (bits64, res_i) in bits.chunks(64).zip(&mut res.0) {
for (i, bit) in bits64.iter().enumerate() {
*res_i |= (*bit as u64) << i;
}
}
res
}
#[inline]
fn to_bytes_be(&self) -> Vec<u8> {
let mut le_bytes = self.to_bytes_le();
le_bytes.reverse();
le_bytes
}
#[inline]
fn to_bytes_le(&self) -> Vec<u8> {
self.0.iter().flat_map(|&limb| limb.to_le_bytes()).collect()
}
}
impl<const N: usize> UpperHex for BigInt<N> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{:016X}", BigUint::from(*self))
}
}
impl<const N: usize> Debug for BigInt<N> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{:?}", BigUint::from(*self))
}
}
impl<const N: usize> Display for BigInt<N> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{}", BigUint::from(*self))
}
}
impl<const N: usize> Ord for BigInt<N> {
#[inline]
#[cfg_attr(target_arch = "x86_64", unroll_for_loops(12))]
fn cmp(&self, other: &Self) -> core::cmp::Ordering {
use core::cmp::Ordering;
#[cfg(target_arch = "x86_64")]
for i in 0..N {
let a = &self.0[N - i - 1];
let b = &other.0[N - i - 1];
match a.cmp(b) {
Ordering::Equal => {},
order => return order,
};
}
#[cfg(not(target_arch = "x86_64"))]
for (a, b) in self.0.iter().rev().zip(other.0.iter().rev()) {
if let order @ (Ordering::Less | Ordering::Greater) = a.cmp(b) {
return order;
}
}
Ordering::Equal
}
}
impl<const N: usize> PartialOrd for BigInt<N> {
#[inline]
fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl<const N: usize> Distribution<BigInt<N>> for Standard {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> BigInt<N> {
BigInt([(); N].map(|_| rng.gen()))
}
}
impl<const N: usize> AsMut<[u64]> for BigInt<N> {
#[inline]
fn as_mut(&mut self) -> &mut [u64] {
&mut self.0
}
}
impl<const N: usize> AsRef<[u64]> for BigInt<N> {
#[inline]
fn as_ref(&self) -> &[u64] {
&self.0
}
}
impl<const N: usize> From<u64> for BigInt<N> {
#[inline]
fn from(val: u64) -> BigInt<N> {
let mut repr = Self::default();
repr.0[0] = val;
repr
}
}
impl<const N: usize> From<u32> for BigInt<N> {
#[inline]
fn from(val: u32) -> BigInt<N> {
let mut repr = Self::default();
repr.0[0] = val.into();
repr
}
}
impl<const N: usize> From<u16> for BigInt<N> {
#[inline]
fn from(val: u16) -> BigInt<N> {
let mut repr = Self::default();
repr.0[0] = val.into();
repr
}
}
impl<const N: usize> From<u8> for BigInt<N> {
#[inline]
fn from(val: u8) -> BigInt<N> {
let mut repr = Self::default();
repr.0[0] = val.into();
repr
}
}
impl<const N: usize> TryFrom<BigUint> for BigInt<N> {
type Error = ();
/// Returns `Err(())` if the bit size of `val` is more than `N * 64`.
#[inline]
fn try_from(val: num_bigint::BigUint) -> Result<BigInt<N>, Self::Error> {
let bytes = val.to_bytes_le();
if bytes.len() > N * 8 {
Err(())
} else {
let mut limbs = [0u64; N];
bytes.chunks(8).enumerate().for_each(|(i, chunk)| {
let mut chunk_padded = [0u8; 8];
chunk_padded[..chunk.len()].copy_from_slice(chunk);
limbs[i] = u64::from_le_bytes(chunk_padded)
});
Ok(Self(limbs))
}
}
}
impl<const N: usize> FromStr for BigInt<N> {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
let biguint = BigUint::from_str(s).map_err(|_| ())?;
Self::try_from(biguint)
}
}
impl<const N: usize> From<BigInt<N>> for BigUint {
#[inline]
fn from(val: BigInt<N>) -> num_bigint::BigUint {
BigUint::from_bytes_le(&val.to_bytes_le())
}
}
impl<const N: usize> From<BigInt<N>> for num_bigint::BigInt {
#[inline]
fn from(val: BigInt<N>) -> num_bigint::BigInt {
use num_bigint::Sign;
let sign = if val.is_zero() {
Sign::NoSign
} else {
Sign::Plus
};
num_bigint::BigInt::from_bytes_le(sign, &val.to_bytes_le())
}
}
impl<B: Borrow<Self>, const N: usize> BitXorAssign<B> for BigInt<N> {
fn bitxor_assign(&mut self, rhs: B) {
(0..N).for_each(|i| self.0[i] ^= rhs.borrow().0[i])
}
}
impl<B: Borrow<Self>, const N: usize> BitXor<B> for BigInt<N> {
type Output = Self;
fn bitxor(mut self, rhs: B) -> Self::Output {
self ^= rhs;
self
}
}
impl<B: Borrow<Self>, const N: usize> BitAndAssign<B> for BigInt<N> {
fn bitand_assign(&mut self, rhs: B) {
(0..N).for_each(|i| self.0[i] &= rhs.borrow().0[i])
}
}
impl<B: Borrow<Self>, const N: usize> BitAnd<B> for BigInt<N> {
type Output = Self;
fn bitand(mut self, rhs: B) -> Self::Output {
self &= rhs;
self
}
}
impl<B: Borrow<Self>, const N: usize> BitOrAssign<B> for BigInt<N> {
fn bitor_assign(&mut self, rhs: B) {
(0..N).for_each(|i| self.0[i] |= rhs.borrow().0[i])
}
}
impl<B: Borrow<Self>, const N: usize> BitOr<B> for BigInt<N> {
type Output = Self;
fn bitor(mut self, rhs: B) -> Self::Output {
self |= rhs;
self
}
}
impl<const N: usize> ShrAssign<u32> for BigInt<N> {
/// Computes the bitwise shift right operation in place.
///
/// Differently from the built-in numeric types (u8, u32, u64, etc.) this
/// operation does *not* return an underflow error if the number of bits
/// shifted is larger than N * 64. Instead the result will be saturated to
/// zero.
fn shr_assign(&mut self, mut rhs: u32) {
if rhs >= (64 * N) as u32 {
*self = Self::from(0u64);
return;
}
while rhs >= 64 {
let mut t = 0;
for limb in self.0.iter_mut().rev() {
core::mem::swap(&mut t, limb);
}
rhs -= 64;
}
if rhs > 0 {
let mut t = 0;
for a in self.0.iter_mut().rev() {
let t2 = *a << (64 - rhs);
*a >>= rhs;
*a |= t;
t = t2;
}
}
}
}
impl<const N: usize> Shr<u32> for BigInt<N> {
type Output = Self;
/// Computes bitwise shift right operation.
///
/// Differently from the built-in numeric types (u8, u32, u64, etc.) this
/// operation does *not* return an underflow error if the number of bits
/// shifted is larger than N * 64. Instead the result will be saturated to
/// zero.
fn shr(mut self, rhs: u32) -> Self::Output {
self >>= rhs;
self
}
}
impl<const N: usize> ShlAssign<u32> for BigInt<N> {
/// Computes the bitwise shift left operation in place.
///
/// Differently from the built-in numeric types (u8, u32, u64, etc.) this
/// operation does *not* return an overflow error if the number of bits
/// shifted is larger than N * 64. Instead, the overflow will be chopped
/// off.
fn shl_assign(&mut self, mut rhs: u32) {
if rhs >= (64 * N) as u32 {
*self = Self::from(0u64);
return;
}
while rhs >= 64 {
let mut t = 0;
for i in 0..N {
core::mem::swap(&mut t, &mut self.0[i]);
}
rhs -= 64;
}
if rhs > 0 {
let mut t = 0;
#[allow(unused)]
for i in 0..N {
let a = &mut self.0[i];
let t2 = *a >> (64 - rhs);
*a <<= rhs;
*a |= t;
t = t2;
}
}
}
}
impl<const N: usize> Shl<u32> for BigInt<N> {
type Output = Self;
/// Computes the bitwise shift left operation in place.
///
/// Differently from the built-in numeric types (u8, u32, u64, etc.) this
/// operation does *not* return an overflow error if the number of bits
/// shifted is larger than N * 64. Instead, the overflow will be chopped
/// off.
fn shl(mut self, rhs: u32) -> Self::Output {
self <<= rhs;
self
}
}
impl<const N: usize> Not for BigInt<N> {
type Output = Self;
fn not(self) -> Self::Output {
let mut result = Self::zero();
for i in 0..N {
result.0[i] = !self.0[i];
}
result
}
}
/// Compute the signed modulo operation on a u64 representation, returning the result.
/// If n % modulus > modulus / 2, return modulus - n
/// # Example
/// ```
/// use ark_ff::signed_mod_reduction;
/// let res = signed_mod_reduction(6u64, 8u64);
/// assert_eq!(res, -2i64);
/// ```
pub fn signed_mod_reduction(n: u64, modulus: u64) -> i64 {
let t = (n % modulus) as i64;
if t as u64 >= (modulus / 2) {
t - (modulus as i64)
} else {
t
}
}
pub type BigInteger64 = BigInt<1>;
pub type BigInteger128 = BigInt<2>;
pub type BigInteger256 = BigInt<4>;
pub type BigInteger320 = BigInt<5>;
pub type BigInteger384 = BigInt<6>;
pub type BigInteger448 = BigInt<7>;
pub type BigInteger768 = BigInt<12>;
pub type BigInteger832 = BigInt<13>;
#[cfg(test)]
mod tests;
/// This defines a `BigInteger`, a smart wrapper around a
/// sequence of `u64` limbs, least-significant limb first.
// TODO: get rid of this trait once we can use associated constants in const generics.
pub trait BigInteger:
CanonicalSerialize
+ CanonicalDeserialize
+ Copy
+ Clone
+ Debug
+ Default
+ Display
+ Eq
+ Ord
+ Send
+ Sized
+ Sync
+ 'static
+ UniformRand
+ Zeroize
+ AsMut<[u64]>
+ AsRef<[u64]>
+ From<u64>
+ From<u32>
+ From<u16>
+ From<u8>
+ TryFrom<BigUint, Error = ()>
+ FromStr
+ Into<BigUint>
+ BitXorAssign<Self>
+ for<'a> BitXorAssign<&'a Self>
+ BitXor<Self, Output = Self>
+ for<'a> BitXor<&'a Self, Output = Self>
+ BitAndAssign<Self>
+ for<'a> BitAndAssign<&'a Self>
+ BitAnd<Self, Output = Self>
+ for<'a> BitAnd<&'a Self, Output = Self>
+ BitOrAssign<Self>
+ for<'a> BitOrAssign<&'a Self>
+ BitOr<Self, Output = Self>
+ for<'a> BitOr<&'a Self, Output = Self>
+ Shr<u32, Output = Self>
+ ShrAssign<u32>
+ Shl<u32, Output = Self>
+ ShlAssign<u32>
{
/// Number of 64-bit limbs representing `Self`.
const NUM_LIMBS: usize;
/// Add another [`BigInteger`] to `self`. This method stores the result in `self`,
/// and returns a carry bit.
///
/// # Example
///
/// ```
/// use ark_ff::{biginteger::BigInteger64 as B, BigInteger as _};
///
/// // Basic
/// let (mut one, mut x) = (B::from(1u64), B::from(2u64));
/// let carry = x.add_with_carry(&one);
/// assert_eq!(x, B::from(3u64));
/// assert_eq!(carry, false);
///
/// // Edge-Case
/// let mut x = B::from(u64::MAX);
/// let carry = x.add_with_carry(&one);
/// assert_eq!(x, B::from(0u64));
/// assert_eq!(carry, true)
/// ```
fn add_with_carry(&mut self, other: &Self) -> bool;
/// Subtract another [`BigInteger`] from this one. This method stores the result in
/// `self`, and returns a borrow.
///
/// # Example
///
/// ```
/// use ark_ff::{biginteger::BigInteger64 as B, BigInteger as _};
///
/// // Basic
/// let (mut one_sub, two, mut three_sub) = (B::from(1u64), B::from(2u64), B::from(3u64));
/// let borrow = three_sub.sub_with_borrow(&two);
/// assert_eq!(three_sub, one_sub);
/// assert_eq!(borrow, false);
///
/// // Edge-Case
/// let borrow = one_sub.sub_with_borrow(&two);
/// assert_eq!(one_sub, B::from(u64::MAX));
/// assert_eq!(borrow, true);
/// ```
fn sub_with_borrow(&mut self, other: &Self) -> bool;
/// Performs a leftwise bitshift of this number, effectively multiplying
/// it by 2. Overflow is ignored.
/// # Example
///
/// ```
/// use ark_ff::{biginteger::BigInteger64 as B, BigInteger as _};
///
/// // Basic
/// let mut two_mul = B::from(2u64);
/// two_mul.mul2();
/// assert_eq!(two_mul, B::from(4u64));
///
/// // Edge-Cases
/// let mut zero = B::from(0u64);
/// zero.mul2();
/// assert_eq!(zero, B::from(0u64));
///
/// let mut arr: [bool; 64] = [false; 64];
/// arr[0] = true;
/// let mut mul = B::from_bits_be(&arr);
/// mul.mul2();
/// assert_eq!(mul, B::from(0u64));
/// ```
fn mul2(&mut self) -> bool;
/// Performs a leftwise bitshift of this number by n bits, effectively multiplying
/// it by 2^n. Overflow is ignored.
/// # Example
///
/// ```
/// use ark_ff::{biginteger::BigInteger64 as B, BigInteger as _};
///