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
#[macro_export]
macro_rules! group_operation {
    ($field:ident, $p:ident, $g:ident, $r:ident, $r2:ident, $r3:ident, $inv:ident) => {
        impl Group for $field {
            type Scalar = $field;

            const ADDITIVE_GENERATOR: Self = $field($g);
            const ADDITIVE_IDENTITY: Self = $field($r);

            fn zero() -> Self {
                Self(zero())
            }

            fn invert(self) -> Option<Self> {
                match invert(self.0, little_fermat($p), $r, $p, $inv) {
                    Some(x) => Some(Self(x)),
                    None => None,
                }
            }

            fn random(rand: impl RngCore) -> Self {
                Self(random_limbs(rand, $r2, $r3, $p, $inv))
            }
        }

        impl PartialEq for $field {
            fn eq(&self, other: &Self) -> bool {
                self.0[0] == other.0[0]
                    && self.0[1] == other.0[1]
                    && self.0[2] == other.0[2]
                    && self.0[3] == other.0[3]
            }
        }

        impl Eq for $field {}

        impl Add for $field {
            type Output = Self;

            #[inline]
            fn add(self, rhs: $field) -> Self {
                $field(add(self.0, rhs.0, $p))
            }
        }

        impl AddAssign for $field {
            fn add_assign(&mut self, rhs: $field) {
                self.0 = add(self.0, rhs.0, $p)
            }
        }

        impl Neg for $field {
            type Output = Self;

            #[inline]
            fn neg(self) -> Self {
                $field(neg(self.0, $p))
            }
        }

        impl Sub for $field {
            type Output = Self;

            #[inline]
            fn sub(self, rhs: $field) -> Self {
                $field(sub(self.0, rhs.0, $p))
            }
        }

        impl SubAssign for $field {
            fn sub_assign(&mut self, rhs: $field) {
                self.0 = sub(self.0, rhs.0, $p)
            }
        }

        impl Mul<<Self as Group>::Scalar> for $field {
            type Output = Self;

            #[inline]
            fn mul(self, rhs: $field) -> Self {
                $field(mul(self.0, rhs.0, $p, $inv))
            }
        }

        impl MulAssign<<Self as Group>::Scalar> for $field {
            fn mul_assign(&mut self, rhs: $field) {
                *self = $field(mul(self.0, rhs.0, $p, $inv))
            }
        }

        impl $field {
            pub const fn zero() -> Self {
                Self(zero())
            }

            pub const fn one() -> Self {
                Self($r)
            }
        }
    };
}

pub use group_operation;