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
use crate::{
bititerator::{BitIteratorBE, BitIteratorLE},
io::{Read, Result as IoResult, Write},
rand::UniformRand,
FromBits,
FromBytes,
ToBits,
ToBytes,
};
use num_bigint::BigUint;
use rand::{
distributions::{Distribution, Standard},
Rng,
};
use std::fmt::{Debug, Display};
biginteger!(BigInteger64, 1);
biginteger!(BigInteger128, 2);
biginteger!(BigInteger256, 4);
biginteger!(BigInteger320, 5);
biginteger!(BigInteger384, 6);
biginteger!(BigInteger768, 12);
biginteger!(BigInteger832, 13);
pub trait BigInteger:
ToBits
+ FromBits
+ ToBytes
+ FromBytes
+ Copy
+ Clone
+ Debug
+ Default
+ Display
+ Eq
+ Ord
+ Send
+ Sized
+ Sync
+ 'static
+ UniformRand
+ AsMut<[u64]>
+ AsRef<[u64]>
+ From<u64>
{
const NUM_LIMBS: usize;
fn add_nocarry(&mut self, other: &Self) -> bool;
fn sub_noborrow(&mut self, other: &Self) -> bool;
fn mul2(&mut self);
fn muln(&mut self, amt: u32);
fn div2(&mut self);
fn divn(&mut self, amt: u32);
fn is_odd(&self) -> bool;
fn is_even(&self) -> bool;
fn is_zero(&self) -> bool;
fn num_bits(&self) -> u32;
fn get_bit(&self, i: usize) -> bool;
fn to_biguint(&self) -> BigUint;
fn find_wnaf(&self) -> Vec<i64>;
}
pub mod arithmetic {
#[inline(always)]
pub fn adc(a: u64, b: u64, carry: &mut u64) -> u64 {
let tmp = u128::from(a) + u128::from(b) + u128::from(*carry);
*carry = (tmp >> 64) as u64;
tmp as u64
}
#[inline(always)]
pub fn sbb(a: u64, b: u64, borrow: &mut u64) -> u64 {
let tmp = (1u128 << 64) + u128::from(a) - u128::from(b) - u128::from(*borrow);
*borrow = if tmp >> 64 == 0 { 1 } else { 0 };
tmp as u64
}
#[inline(always)]
pub fn mac_with_carry(a: u64, b: u64, c: u64, carry: &mut u64) -> u64 {
let tmp = (u128::from(a)) + u128::from(b) * u128::from(c) + u128::from(*carry);
*carry = (tmp >> 64) as u64;
tmp as u64
}
}
impl BigInteger256 {
pub fn from_u128(num: u128) -> Self {
let mut bytes = [0u8; 32];
num.write_le(bytes.as_mut()).unwrap();
Self::read_le(&bytes[..]).unwrap()
}
pub fn to_u128(&self) -> u128 {
let mut bytes = [0u8; 32];
self.write_le(bytes.as_mut()).unwrap();
u128::read_le(&bytes[..16]).unwrap()
}
}