-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
field.rs
333 lines (294 loc) · 8.34 KB
/
field.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
use core::fmt;
use std::hash::{Hash, Hasher};
use std::ops::{Add, Div, Mul, Neg, Sub};
/// A field
///
/// <https://en.wikipedia.org/wiki/Field_(mathematics)>
pub trait Field:
Neg<Output = Self>
+ Add<Output = Self>
+ Sub<Output = Self>
+ Mul<Output = Self>
+ Div<Output = Self>
+ Eq
+ Copy
+ fmt::Debug
{
const CHARACTERISTIC: u64;
const ZERO: Self;
const ONE: Self;
/// Multiplicative inverse
fn inverse(self) -> Self;
/// Z-mod structure
fn integer_mul(self, a: i64) -> Self;
fn from_integer(a: i64) -> Self {
Self::ONE.integer_mul(a)
}
/// Iterate over all elements in this field
///
/// The iterator finishes only for finite fields.
type ElementsIter: Iterator<Item = Self>;
fn elements() -> Self::ElementsIter;
}
/// Prime field of order `P`, that is, finite field `GF(P) = ℤ/Pℤ`
///
/// Only primes `P` <= 2^63 - 25 are supported, because the field elements are represented by `i64`.
// TODO: Extend field implementation for any prime `P` by e.g. using u32 blocks.
#[derive(Clone, Copy)]
pub struct PrimeField<const P: u64> {
a: i64,
}
impl<const P: u64> PrimeField<P> {
/// Reduces the representation into the range [0, p)
fn reduce(self) -> Self {
let Self { a } = self;
let p: i64 = P.try_into().expect("module not fitting into signed 64 bit");
let a = a.rem_euclid(p);
assert!(a >= 0);
Self { a }
}
/// Returns the positive integer in the range [0, p) representing this element
pub fn to_integer(&self) -> u64 {
self.reduce().a as u64
}
}
impl<const P: u64> From<i64> for PrimeField<P> {
fn from(a: i64) -> Self {
Self { a }
}
}
impl<const P: u64> PartialEq for PrimeField<P> {
fn eq(&self, other: &Self) -> bool {
self.reduce().a == other.reduce().a
}
}
impl<const P: u64> Eq for PrimeField<P> {}
impl<const P: u64> Neg for PrimeField<P> {
type Output = Self;
fn neg(self) -> Self::Output {
Self { a: -self.a }
}
}
impl<const P: u64> Add for PrimeField<P> {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
Self {
a: self.a.checked_add(rhs.a).unwrap_or_else(|| {
let x = self.reduce();
let y = rhs.reduce();
x.a + y.a
}),
}
}
}
impl<const P: u64> Sub for PrimeField<P> {
type Output = Self;
fn sub(self, rhs: Self) -> Self::Output {
Self {
a: self.a.checked_sub(rhs.a).unwrap_or_else(|| {
let x = self.reduce();
let y = rhs.reduce();
x.a - y.a
}),
}
}
}
impl<const P: u64> Mul for PrimeField<P> {
type Output = Self;
fn mul(self, rhs: Self) -> Self::Output {
Self {
a: self.a.checked_mul(rhs.a).unwrap_or_else(|| {
let x = self.reduce();
let y = rhs.reduce();
x.a * y.a
}),
}
}
}
impl<const P: u64> Div for PrimeField<P> {
type Output = Self;
#[allow(clippy::suspicious_arithmetic_impl)]
fn div(self, rhs: Self) -> Self::Output {
self * rhs.inverse()
}
}
impl<const P: u64> fmt::Debug for PrimeField<P> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let x = self.reduce();
write!(f, "{}", x.reduce().a)
}
}
impl<const P: u64> Field for PrimeField<P> {
const CHARACTERISTIC: u64 = P;
const ZERO: Self = Self { a: 0 };
const ONE: Self = Self { a: 1 };
fn inverse(self) -> Self {
assert_ne!(self.a, 0);
Self {
a: mod_inverse(
self.a,
P.try_into().expect("module not fitting into signed 64 bit"),
),
}
}
fn integer_mul(self, mut n: i64) -> Self {
if n == 0 {
return Self::ZERO;
}
let mut x = self;
if n < 0 {
x = -x;
n = -n;
}
let mut y = Self::ZERO;
while n > 1 {
if n % 2 == 1 {
y = y + x;
n -= 1;
}
x = x + x;
n /= 2;
}
x + y
}
type ElementsIter = PrimeFieldElementsIter<P>;
fn elements() -> Self::ElementsIter {
PrimeFieldElementsIter::default()
}
}
#[derive(Default)]
pub struct PrimeFieldElementsIter<const P: u64> {
x: i64,
}
impl<const P: u64> Iterator for PrimeFieldElementsIter<P> {
type Item = PrimeField<P>;
fn next(&mut self) -> Option<Self::Item> {
if self.x as u64 == P {
None
} else {
let res = PrimeField::from_integer(self.x);
self.x += 1;
Some(res)
}
}
}
impl<const P: u64> Hash for PrimeField<P> {
fn hash<H: Hasher>(&self, state: &mut H) {
let Self { a } = self.reduce();
state.write_i64(a);
}
}
// TODO: should we use extended_euclidean_algorithm adjusted to i64?
fn mod_inverse(mut a: i64, mut b: i64) -> i64 {
let mut s = 1;
let mut t = 0;
let step = |x, y, q| (y, x - q * y);
while b != 0 {
let q = a / b;
(a, b) = step(a, b, q);
(s, t) = step(s, t, q);
}
assert!(a == 1 || a == -1);
a * s
}
#[cfg(test)]
mod tests {
use std::collections::HashSet;
use super::*;
#[test]
fn test_field_elements() {
fn test<const P: u64>() {
let expected: HashSet<PrimeField<P>> = (0..P as i64).map(Into::into).collect();
for gen in 1..P - 1 {
// every field element != 0 generates the whole field additively
let gen = PrimeField::from(gen as i64);
let mut generated: HashSet<PrimeField<P>> = std::iter::once(gen).collect();
let mut x = gen;
for _ in 0..P {
x = x + gen;
generated.insert(x);
}
assert_eq!(generated, expected);
}
}
test::<5>();
test::<7>();
test::<11>();
test::<13>();
test::<17>();
test::<19>();
test::<23>();
test::<71>();
test::<101>();
}
#[test]
fn large_prime_field() {
const P: u64 = 2_u64.pow(63) - 25; // largest prime fitting into i64
type F = PrimeField<P>;
let x = F::from(P as i64 - 1);
let y = x.inverse();
assert_eq!(x * y, F::ONE);
}
#[test]
fn inverse() {
fn test<const P: u64>() {
for x in -7..7 {
let x = PrimeField::<P>::from(x);
if x != PrimeField::ZERO {
// multiplicative
assert_eq!(x.inverse() * x, PrimeField::ONE);
assert_eq!(x * x.inverse(), PrimeField::ONE);
assert_eq!((x.inverse().a * x.a).rem_euclid(P as i64), 1);
assert_eq!(x / x, PrimeField::ONE);
}
// additive
assert_eq!(x + (-x), PrimeField::ZERO);
assert_eq!((-x) + x, PrimeField::ZERO);
assert_eq!(x - x, PrimeField::ZERO);
}
}
test::<5>();
test::<7>();
test::<11>();
test::<13>();
test::<17>();
test::<19>();
test::<23>();
test::<71>();
test::<101>();
}
#[test]
fn test_mod_inverse() {
assert_eq!(mod_inverse(-6, 7), 1);
assert_eq!(mod_inverse(-5, 7), -3);
assert_eq!(mod_inverse(-4, 7), -2);
assert_eq!(mod_inverse(-3, 7), 2);
assert_eq!(mod_inverse(-2, 7), 3);
assert_eq!(mod_inverse(-1, 7), -1);
assert_eq!(mod_inverse(1, 7), 1);
assert_eq!(mod_inverse(2, 7), -3);
assert_eq!(mod_inverse(3, 7), -2);
assert_eq!(mod_inverse(4, 7), 2);
assert_eq!(mod_inverse(5, 7), 3);
assert_eq!(mod_inverse(6, 7), -1);
}
#[test]
fn integer_mul() {
type F = PrimeField<23>;
for x in 0..23 {
let x = F { a: x };
for n in -7..7 {
assert_eq!(x.integer_mul(n), F { a: n * x.a });
}
}
}
#[test]
fn from_integer() {
type F = PrimeField<23>;
for x in -100..100 {
assert_eq!(F::from_integer(x), F { a: x });
}
assert_eq!(F::from(0), F::ZERO);
assert_eq!(F::from(1), F::ONE);
}
}