Skip to main content

snarkvm_fields/
fp_256.rs

1// Copyright (c) 2019-2026 Provable Inc.
2// This file is part of the snarkVM library.
3
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at:
7
8// http://www.apache.org/licenses/LICENSE-2.0
9
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use crate::{
17    FftField,
18    Field,
19    FieldError,
20    FieldParameters,
21    LegendreSymbol,
22    One,
23    PoseidonDefaultField,
24    PoseidonDefaultParameters,
25    PrimeField,
26    SquareRootField,
27    Zero,
28    impl_add_sub_from_field_ref,
29    impl_mul_div_from_field_ref,
30};
31use snarkvm_utilities::{
32    FromBytes,
33    ToBits,
34    ToBytes,
35    biginteger::{BigInteger as _BigInteger, BigInteger256 as BigInteger, arithmetic as fa},
36    serialize::CanonicalDeserialize,
37};
38
39use std::{
40    cmp::{Ord, Ordering, PartialOrd},
41    fmt::{Debug, Display, Formatter, Result as FmtResult},
42    io::{Read, Result as IoResult, Write},
43    marker::PhantomData,
44    ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign},
45    str::FromStr,
46};
47use zeroize::Zeroize;
48
49pub trait Fp256Parameters: FieldParameters<BigInteger = BigInteger> {}
50
51#[derive(Copy, Clone, Default, PartialEq, Eq, Hash, Zeroize)]
52pub struct Fp256<P: Fp256Parameters>(pub BigInteger, #[doc(hidden)] pub PhantomData<P>);
53
54impl<P: Fp256Parameters> Fp256<P> {
55    #[inline]
56    fn is_valid(&self) -> bool {
57        self.0 < P::MODULUS
58    }
59
60    #[inline]
61    fn reduce(&mut self) {
62        if !self.is_valid() {
63            self.0.sub_noborrow(&P::MODULUS);
64        }
65    }
66
67    #[inline(always)]
68    #[allow(clippy::too_many_arguments)]
69    fn mont_reduce(
70        &mut self,
71        r0: u64,
72        mut r1: u64,
73        mut r2: u64,
74        mut r3: u64,
75        mut r4: u64,
76        mut r5: u64,
77        mut r6: u64,
78        mut r7: u64,
79    ) {
80        // The Montgomery reduction here is based on Algorithm 14.32 in
81        // Handbook of Applied Cryptography
82        // <http://cacr.uwaterloo.ca/hac/about/chap14.pdf>.
83
84        let k = r0.wrapping_mul(P::INV);
85        let mut carry = 0;
86        fa::mac_with_carry(r0, k, P::MODULUS.0[0], &mut carry);
87        r1 = fa::mac_with_carry(r1, k, P::MODULUS.0[1], &mut carry);
88        r2 = fa::mac_with_carry(r2, k, P::MODULUS.0[2], &mut carry);
89        r3 = fa::mac_with_carry(r3, k, P::MODULUS.0[3], &mut carry);
90        carry = fa::adc(&mut r4, 0, carry);
91        let carry2 = carry;
92        let k = r1.wrapping_mul(P::INV);
93        let mut carry = 0;
94        fa::mac_with_carry(r1, k, P::MODULUS.0[0], &mut carry);
95        r2 = fa::mac_with_carry(r2, k, P::MODULUS.0[1], &mut carry);
96        r3 = fa::mac_with_carry(r3, k, P::MODULUS.0[2], &mut carry);
97        r4 = fa::mac_with_carry(r4, k, P::MODULUS.0[3], &mut carry);
98        carry = fa::adc(&mut r5, carry2, carry);
99        let carry2 = carry;
100        let k = r2.wrapping_mul(P::INV);
101        let mut carry = 0;
102        fa::mac_with_carry(r2, k, P::MODULUS.0[0], &mut carry);
103        r3 = fa::mac_with_carry(r3, k, P::MODULUS.0[1], &mut carry);
104        r4 = fa::mac_with_carry(r4, k, P::MODULUS.0[2], &mut carry);
105        r5 = fa::mac_with_carry(r5, k, P::MODULUS.0[3], &mut carry);
106        carry = fa::adc(&mut r6, carry2, carry);
107        let carry2 = carry;
108        let k = r3.wrapping_mul(P::INV);
109        let mut carry = 0;
110        fa::mac_with_carry(r3, k, P::MODULUS.0[0], &mut carry);
111        r4 = fa::mac_with_carry(r4, k, P::MODULUS.0[1], &mut carry);
112        r5 = fa::mac_with_carry(r5, k, P::MODULUS.0[2], &mut carry);
113        r6 = fa::mac_with_carry(r6, k, P::MODULUS.0[3], &mut carry);
114        fa::adc(&mut r7, carry2, carry);
115        (self.0).0[0] = r4;
116        (self.0).0[1] = r5;
117        (self.0).0[2] = r6;
118        (self.0).0[3] = r7;
119        self.reduce();
120    }
121}
122
123impl<P: Fp256Parameters> Zero for Fp256<P> {
124    #[inline]
125    fn zero() -> Self {
126        Self(BigInteger::from(0), PhantomData)
127    }
128
129    #[inline]
130    fn is_zero(&self) -> bool {
131        self.0.is_zero()
132    }
133}
134
135impl<P: Fp256Parameters> One for Fp256<P> {
136    #[inline]
137    fn one() -> Self {
138        Self(P::R, PhantomData)
139    }
140
141    #[inline]
142    fn is_one(&self) -> bool {
143        self.0 == P::R
144    }
145}
146
147impl<P: Fp256Parameters> Field for Fp256<P> {
148    type BasePrimeField = Self;
149
150    // 256/64 = 4 limbs.
151    impl_field_from_random_bytes_with_flags!(4);
152
153    fn from_base_prime_field(other: Self::BasePrimeField) -> Self {
154        other
155    }
156
157    /// Returns the constant 2^{-1}.
158    fn half() -> Self {
159        // Compute 1/2 `(p+1)/2` as `1/2`.
160        // This is cheaper than `Self::one().double().inverse()`
161        let mut two_inv = P::MODULUS;
162        two_inv.add_nocarry(&1u64.into());
163        two_inv.div2();
164        Self::from_bigint(two_inv).unwrap() // Guaranteed to be valid.
165    }
166
167    fn sum_of_products<'a>(a: &'a [Self], b: &'a [Self]) -> Self {
168        // For a single `a x b` multiplication, operand scanning (schoolbook) takes each
169        // limb of `a` in turn, and multiplies it by all of the limbs of `b` to compute
170        // the result as a double-width intermediate representation, which is then fully
171        // reduced at the end. Here however we have pairs of multiplications (a_i, b_i),
172        // the results of which are summed.
173        //
174        // The intuition for this algorithm is two-fold:
175        // - We can interleave the operand scanning for each pair, by processing the jth
176        //   limb of each `a_i` together. As these have the same offset within the overall
177        //   operand scanning flow, their results can be summed directly.
178        // - We can interleave the multiplication and reduction steps, resulting in a
179        //   single bitshift by the limb size after each iteration. This means we only
180        //   need to store a single extra limb overall, instead of keeping around all the
181        //   intermediate results and eventually having twice as many limbs.
182
183        // Algorithm 2, line 2
184        let (u0, u1, u2, u3) = (0..4).fold((0, 0, 0, 0), |(u0, u1, u2, u3), j| {
185            // Algorithm 2, line 3
186            // For each pair in the overall sum of products:
187            let (t0, t1, t2, t3, mut t4) =
188                a.iter().zip(b).fold((u0, u1, u2, u3, 0), |(t0, t1, t2, t3, mut t4), (a, b)| {
189                    // Compute digit_j x row and accumulate into `u`.
190                    let mut carry = 0;
191                    let t0 = fa::mac_with_carry(t0, a.0.0[j], b.0.0[0], &mut carry);
192                    let t1 = fa::mac_with_carry(t1, a.0.0[j], b.0.0[1], &mut carry);
193                    let t2 = fa::mac_with_carry(t2, a.0.0[j], b.0.0[2], &mut carry);
194                    let t3 = fa::mac_with_carry(t3, a.0.0[j], b.0.0[3], &mut carry);
195                    let _ = fa::adc(&mut t4, 0, carry);
196
197                    (t0, t1, t2, t3, t4)
198                });
199
200            // Algorithm 2, lines 4-5
201            // This is a single step of the usual Montgomery reduction process.
202            let k = t0.wrapping_mul(P::INV);
203            let mut carry = 0;
204            let _ = fa::mac_with_carry(t0, k, P::MODULUS.0[0], &mut carry);
205            let r1 = fa::mac_with_carry(t1, k, P::MODULUS.0[1], &mut carry);
206            let r2 = fa::mac_with_carry(t2, k, P::MODULUS.0[2], &mut carry);
207            let r3 = fa::mac_with_carry(t3, k, P::MODULUS.0[3], &mut carry);
208            let _ = fa::adc(&mut t4, 0, carry);
209            let r4 = t4;
210
211            (r1, r2, r3, r4)
212        });
213
214        // Because we represent F_p elements in non-redundant form, we need a final
215        // conditional subtraction to ensure the output is in range.
216        let mut result = Self(BigInteger([u0, u1, u2, u3]), PhantomData);
217        result.reduce();
218        result
219    }
220
221    #[inline]
222    fn double(&self) -> Self {
223        let mut temp = *self;
224        temp.double_in_place();
225        temp
226    }
227
228    #[inline]
229    fn double_in_place(&mut self) {
230        // This cannot exceed the backing capacity.
231        self.0.mul2();
232        // However, it may need to be reduced.
233        self.reduce();
234    }
235
236    #[inline]
237    fn characteristic<'a>() -> &'a [u64] {
238        P::MODULUS.as_ref()
239    }
240
241    #[inline]
242    fn square(&self) -> Self {
243        let mut temp = *self;
244        temp.square_in_place();
245        temp
246    }
247
248    #[inline]
249    fn square_in_place(&mut self) -> &mut Self {
250        // i = 0
251        let mut carry = 0;
252        let r1 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[1], &mut carry);
253        let r2 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[2], &mut carry);
254        let r3 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[3], &mut carry);
255        let r4 = carry;
256        let mut carry = 0;
257        let r3 = fa::mac_with_carry(r3, (self.0).0[1], (self.0).0[2], &mut carry);
258        let r4 = fa::mac_with_carry(r4, (self.0).0[1], (self.0).0[3], &mut carry);
259        let r5 = carry;
260        let mut carry = 0;
261        let r5 = fa::mac_with_carry(r5, (self.0).0[2], (self.0).0[3], &mut carry);
262        let r6 = carry;
263
264        let mut r7 = r6 >> 63;
265        let r6 = (r6 << 1) | (r5 >> 63);
266        let mut r5 = (r5 << 1) | (r4 >> 63);
267        let r4 = (r4 << 1) | (r3 >> 63);
268        let mut r3 = (r3 << 1) | (r2 >> 63);
269        let r2 = (r2 << 1) | (r1 >> 63);
270        let mut r1 = r1 << 1;
271
272        let mut carry = 0;
273        let r0 = fa::mac_with_carry(0, (self.0).0[0], (self.0).0[0], &mut carry);
274        carry = fa::adc(&mut r1, 0, carry);
275        let r2 = fa::mac_with_carry(r2, (self.0).0[1], (self.0).0[1], &mut carry);
276        carry = fa::adc(&mut r3, 0, carry);
277        let r4 = fa::mac_with_carry(r4, (self.0).0[2], (self.0).0[2], &mut carry);
278        carry = fa::adc(&mut r5, 0, carry);
279        let r6 = fa::mac_with_carry(r6, (self.0).0[3], (self.0).0[3], &mut carry);
280        fa::adc(&mut r7, 0, carry);
281
282        self.mont_reduce(r0, r1, r2, r3, r4, r5, r6, r7);
283        self
284    }
285
286    #[inline]
287    fn inverse(&self) -> Option<Self> {
288        if self.is_zero() {
289            None
290        } else {
291            // Guajardo Kumar Paar Pelzl
292            // Efficient Software-Implementation of Finite Fields with Applications to
293            // Cryptography
294            // Algorithm 16 (BEA for Inversion in Fp)
295
296            let one = BigInteger::from(1);
297
298            let mut u = self.0;
299            let mut v = P::MODULUS;
300            let mut b = Self(P::R2, PhantomData); // Avoids unnecessary reduction step.
301            let mut c = Self::zero();
302
303            while u != one && v != one {
304                while u.is_even() {
305                    u.div2();
306
307                    if b.0.is_even() {
308                        b.0.div2();
309                    } else {
310                        b.0.add_nocarry(&P::MODULUS);
311                        b.0.div2();
312                    }
313                }
314
315                while v.is_even() {
316                    v.div2();
317
318                    if c.0.is_even() {
319                        c.0.div2();
320                    } else {
321                        c.0.add_nocarry(&P::MODULUS);
322                        c.0.div2();
323                    }
324                }
325
326                if v < u {
327                    u.sub_noborrow(&v);
328                    b.sub_assign(&c);
329                } else {
330                    v.sub_noborrow(&u);
331                    c.sub_assign(&b);
332                }
333            }
334
335            if u == one { Some(b) } else { Some(c) }
336        }
337    }
338
339    fn inverse_in_place(&mut self) -> Option<&mut Self> {
340        if let Some(inverse) = self.inverse() {
341            *self = inverse;
342            Some(self)
343        } else {
344            None
345        }
346    }
347
348    #[inline]
349    fn frobenius_map(&mut self, _: usize) {
350        // No-op: No effect in a prime field.
351    }
352}
353
354impl<P: Fp256Parameters> PrimeField for Fp256<P> {
355    type BigInteger = BigInteger;
356    type Parameters = P;
357
358    #[inline]
359    fn from_bigint(r: BigInteger) -> Option<Self> {
360        let mut r = Fp256(r, PhantomData);
361        if r.is_zero() {
362            Some(r)
363        } else if r.is_valid() {
364            r *= &Fp256(P::R2, PhantomData);
365            Some(r)
366        } else {
367            None
368        }
369    }
370
371    #[inline]
372    fn to_bigint(&self) -> BigInteger {
373        let mut tmp = self.0;
374        let mut r = tmp.0;
375        // Montgomery Reduction
376        let k = r[0].wrapping_mul(P::INV);
377        let mut carry = 0;
378        fa::mac_with_carry(r[0], k, P::MODULUS.0[0], &mut carry);
379        r[1] = fa::mac_with_carry(r[1], k, P::MODULUS.0[1], &mut carry);
380        r[2] = fa::mac_with_carry(r[2], k, P::MODULUS.0[2], &mut carry);
381        r[3] = fa::mac_with_carry(r[3], k, P::MODULUS.0[3], &mut carry);
382        r[0] = carry;
383
384        let k = r[1].wrapping_mul(P::INV);
385        let mut carry = 0;
386        fa::mac_with_carry(r[1], k, P::MODULUS.0[0], &mut carry);
387        r[2] = fa::mac_with_carry(r[2], k, P::MODULUS.0[1], &mut carry);
388        r[3] = fa::mac_with_carry(r[3], k, P::MODULUS.0[2], &mut carry);
389        r[0] = fa::mac_with_carry(r[0], k, P::MODULUS.0[3], &mut carry);
390        r[1] = carry;
391
392        let k = r[2].wrapping_mul(P::INV);
393        let mut carry = 0;
394        fa::mac_with_carry(r[2], k, P::MODULUS.0[0], &mut carry);
395        r[3] = fa::mac_with_carry(r[3], k, P::MODULUS.0[1], &mut carry);
396        r[0] = fa::mac_with_carry(r[0], k, P::MODULUS.0[2], &mut carry);
397        r[1] = fa::mac_with_carry(r[1], k, P::MODULUS.0[3], &mut carry);
398        r[2] = carry;
399
400        let k = r[3].wrapping_mul(P::INV);
401        let mut carry = 0;
402        fa::mac_with_carry(r[3], k, P::MODULUS.0[0], &mut carry);
403        r[0] = fa::mac_with_carry(r[0], k, P::MODULUS.0[1], &mut carry);
404        r[1] = fa::mac_with_carry(r[1], k, P::MODULUS.0[2], &mut carry);
405        r[2] = fa::mac_with_carry(r[2], k, P::MODULUS.0[3], &mut carry);
406        r[3] = carry;
407
408        tmp.0 = r;
409        tmp
410    }
411
412    #[inline]
413    fn decompose(
414        &self,
415        q1: &[u64; 4],
416        q2: &[u64; 4],
417        b1: Self,
418        b2: Self,
419        r128: Self,
420        half_r: &[u64; 8],
421    ) -> (Self, Self, bool, bool) {
422        let mul_short = |a: &[u64; 4], b: &[u64; 4]| -> [u64; 8] {
423            // Schoolbook multiplication
424            let mut carry = 0;
425            let r0 = fa::mac_with_carry(0, a[0], b[0], &mut carry);
426            let r1 = fa::mac_with_carry(0, a[0], b[1], &mut carry);
427            let r2 = fa::mac_with_carry(0, a[0], b[2], &mut carry);
428            let r3 = carry;
429
430            let mut carry = 0;
431            let r1 = fa::mac_with_carry(r1, a[1], b[0], &mut carry);
432            let r2 = fa::mac_with_carry(r2, a[1], b[1], &mut carry);
433            let r3 = fa::mac_with_carry(r3, a[1], b[2], &mut carry);
434            let r4 = carry;
435
436            let mut carry = 0;
437            let r2 = fa::mac_with_carry(r2, a[2], b[0], &mut carry);
438            let r3 = fa::mac_with_carry(r3, a[2], b[1], &mut carry);
439            let r4 = fa::mac_with_carry(r4, a[2], b[2], &mut carry);
440            let r5 = carry;
441
442            let mut carry = 0;
443            let r3 = fa::mac_with_carry(r3, a[3], b[0], &mut carry);
444            let r4 = fa::mac_with_carry(r4, a[3], b[1], &mut carry);
445            let r5 = fa::mac_with_carry(r5, a[3], b[2], &mut carry);
446            let r6 = carry;
447
448            [r0, r1, r2, r3, r4, r5, r6, 0]
449        };
450
451        let round = |a: &mut [u64; 8]| -> Self {
452            let mut carry = 0;
453            // NOTE: can the first 4 be omitted?
454            carry = fa::adc(&mut a[0], half_r[0], carry);
455            carry = fa::adc(&mut a[1], half_r[1], carry);
456            carry = fa::adc(&mut a[2], half_r[2], carry);
457            carry = fa::adc(&mut a[3], half_r[3], carry);
458            carry = fa::adc(&mut a[4], half_r[4], carry);
459            carry = fa::adc(&mut a[5], half_r[5], carry);
460            carry = fa::adc(&mut a[6], half_r[6], carry);
461            _ = fa::adc(&mut a[7], half_r[7], carry);
462            Self::from_bigint(BigInteger([a[4], a[5], a[6], a[7]])).unwrap()
463        };
464
465        let alpha = |x: &Self, q: &[u64; 4]| -> Self {
466            let mut a = mul_short(&x.to_bigint().0, q);
467            round(&mut a)
468        };
469
470        let alpha1 = alpha(self, q1);
471        let alpha2 = alpha(self, q2);
472        let z1 = alpha1 * b1;
473        let z2 = alpha2 * b2;
474
475        let mut k1 = *self - z1 - alpha2;
476        let mut k2 = z2 - alpha1;
477        let mut k1_neg = false;
478        let mut k2_neg = false;
479
480        if k1 > r128 {
481            k1 = -k1;
482            k1_neg = true;
483        }
484
485        if k2 > r128 {
486            k2 = -k2;
487            k2_neg = true;
488        }
489
490        (k1, k2, k1_neg, k2_neg)
491    }
492}
493
494impl<P: Fp256Parameters> FftField for Fp256<P> {
495    type FftParameters = P;
496
497    #[inline]
498    fn two_adic_root_of_unity() -> Self {
499        Self(P::TWO_ADIC_ROOT_OF_UNITY, PhantomData)
500    }
501
502    #[inline]
503    fn large_subgroup_root_of_unity() -> Option<Self> {
504        Some(Self(P::LARGE_SUBGROUP_ROOT_OF_UNITY?, PhantomData))
505    }
506
507    #[inline]
508    fn multiplicative_generator() -> Self {
509        Self(P::GENERATOR, PhantomData)
510    }
511}
512
513impl<P: Fp256Parameters> SquareRootField for Fp256<P> {
514    #[inline]
515    fn legendre(&self) -> LegendreSymbol {
516        use crate::LegendreSymbol::*;
517
518        // s = self^((MODULUS - 1) // 2)
519        let mut s = self.pow(P::MODULUS_MINUS_ONE_DIV_TWO);
520        s.reduce();
521
522        if s.is_zero() {
523            Zero
524        } else if s.is_one() {
525            QuadraticResidue
526        } else {
527            QuadraticNonResidue
528        }
529    }
530
531    #[inline]
532    fn sqrt(&self) -> Option<Self> {
533        sqrt_impl!(Self, P, self)
534    }
535
536    fn sqrt_in_place(&mut self) -> Option<&mut Self> {
537        (*self).sqrt().map(|sqrt| {
538            *self = sqrt;
539            self
540        })
541    }
542}
543
544/// `Fp` elements are ordered lexicographically.
545impl<P: Fp256Parameters> Ord for Fp256<P> {
546    #[inline(always)]
547    fn cmp(&self, other: &Self) -> Ordering {
548        self.to_bigint().cmp(&other.to_bigint())
549    }
550}
551
552impl<P: Fp256Parameters> PartialOrd for Fp256<P> {
553    #[inline(always)]
554    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
555        Some(self.cmp(other))
556    }
557}
558
559impl<P: Fp256Parameters + PoseidonDefaultParameters> PoseidonDefaultField for Fp256<P> {}
560
561impl_primefield_from_int!(Fp256, u128, Fp256Parameters);
562impl_primefield_from_int!(Fp256, u64, Fp256Parameters);
563impl_primefield_from_int!(Fp256, u32, Fp256Parameters);
564impl_primefield_from_int!(Fp256, u16, Fp256Parameters);
565impl_primefield_from_int!(Fp256, u8, Fp256Parameters);
566
567impl_primefield_standard_sample!(Fp256, Fp256Parameters);
568
569impl_add_sub_from_field_ref!(Fp256, Fp256Parameters);
570impl_mul_div_from_field_ref!(Fp256, Fp256Parameters);
571
572impl<P: Fp256Parameters> ToBits for Fp256<P> {
573    fn write_bits_le(&self, vec: &mut Vec<bool>) {
574        let initial_len = vec.len();
575        self.to_bigint().write_bits_le(vec);
576        vec.truncate(initial_len + P::MODULUS_BITS as usize);
577    }
578
579    fn write_bits_be(&self, vec: &mut Vec<bool>) {
580        let initial_len = vec.len();
581        self.write_bits_le(vec);
582        vec[initial_len..].reverse();
583    }
584
585    fn num_bits() -> Option<usize> {
586        Some(256)
587    }
588}
589
590impl<P: Fp256Parameters> ToBytes for Fp256<P> {
591    #[inline]
592    fn write_le<W: Write>(&self, writer: W) -> IoResult<()> {
593        self.to_bigint().write_le(writer)
594    }
595}
596
597impl<P: Fp256Parameters> FromBytes for Fp256<P> {
598    #[inline]
599    fn read_le<R: Read>(reader: R) -> IoResult<Self> {
600        BigInteger::read_le(reader).and_then(|b| match Self::from_bigint(b) {
601            Some(f) => Ok(f),
602            None => Err(FieldError::InvalidFieldElement.into()),
603        })
604    }
605}
606
607impl<P: Fp256Parameters> FromStr for Fp256<P> {
608    type Err = FieldError;
609
610    /// Interpret a string of numbers as a (congruent) prime field element.
611    /// Does not accept unnecessary leading zeroes or a blank string.
612    fn from_str(s: &str) -> Result<Self, Self::Err> {
613        if s.is_empty() {
614            return Err(FieldError::ParsingEmptyString);
615        }
616
617        if s == "0" {
618            return Ok(Self::zero());
619        }
620
621        let mut res = Self::zero();
622
623        let ten =
624            Self::from_bigint(<Self as PrimeField>::BigInteger::from(10)).ok_or(FieldError::InvalidFieldElement)?;
625
626        let mut first_digit = true;
627
628        for c in s.chars() {
629            match c.to_digit(10) {
630                Some(c) => {
631                    if first_digit {
632                        if c == 0 {
633                            return Err(FieldError::InvalidString);
634                        }
635
636                        first_digit = false;
637                    }
638
639                    res.mul_assign(&ten);
640                    res.add_assign(
641                        &Self::from_bigint(<Self as PrimeField>::BigInteger::from(u64::from(c)))
642                            .ok_or(FieldError::InvalidFieldElement)?,
643                    );
644                }
645                None => return Err(FieldError::ParsingNonDigitCharacter),
646            }
647        }
648
649        if !res.is_valid() { Err(FieldError::InvalidFieldElement) } else { Ok(res) }
650    }
651}
652
653impl<P: Fp256Parameters> Debug for Fp256<P> {
654    #[inline]
655    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
656        write!(f, "{}", self.to_bigint())
657    }
658}
659
660impl<P: Fp256Parameters> Display for Fp256<P> {
661    #[inline]
662    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
663        write!(f, "{}", self.to_bigint())
664    }
665}
666
667impl<P: Fp256Parameters> Neg for Fp256<P> {
668    type Output = Self;
669
670    #[inline]
671    fn neg(self) -> Self {
672        if !self.is_zero() {
673            let mut tmp = P::MODULUS;
674            tmp.sub_noborrow(&self.0);
675            Self(tmp, PhantomData)
676        } else {
677            self
678        }
679    }
680}
681
682impl<P: Fp256Parameters> Add<&'_ Fp256<P>> for Fp256<P> {
683    type Output = Self;
684
685    #[inline]
686    fn add(self, other: &Self) -> Self {
687        let mut result = self;
688        result.add_assign(other);
689        result
690    }
691}
692
693impl<P: Fp256Parameters> Sub<&'_ Fp256<P>> for Fp256<P> {
694    type Output = Self;
695
696    #[inline]
697    fn sub(self, other: &Self) -> Self {
698        let mut result = self;
699        result.sub_assign(other);
700        result
701    }
702}
703
704impl<P: Fp256Parameters> Mul<&'_ Fp256<P>> for Fp256<P> {
705    type Output = Self;
706
707    #[inline]
708    fn mul(self, other: &Self) -> Self {
709        let mut result = self;
710        result.mul_assign(other);
711        result
712    }
713}
714
715impl<P: Fp256Parameters> Div<&'_ Fp256<P>> for Fp256<P> {
716    type Output = Self;
717
718    #[inline]
719    fn div(self, other: &Self) -> Self {
720        let mut result = self;
721        result.mul_assign(&other.inverse().unwrap());
722        result
723    }
724}
725
726impl<P: Fp256Parameters> AddAssign<&'_ Self> for Fp256<P> {
727    #[inline]
728    fn add_assign(&mut self, other: &Self) {
729        // This cannot exceed the backing capacity.
730        self.0.add_nocarry(&other.0);
731        // However, it may need to be reduced.
732        self.reduce();
733    }
734}
735
736impl<P: Fp256Parameters> SubAssign<&'_ Self> for Fp256<P> {
737    #[inline]
738    fn sub_assign(&mut self, other: &Self) {
739        // If `other` is larger than `self`, add the modulus to self first.
740        if other.0 > self.0 {
741            self.0.add_nocarry(&P::MODULUS);
742        }
743
744        self.0.sub_noborrow(&other.0);
745    }
746}
747
748impl<P: Fp256Parameters> MulAssign<&'_ Self> for Fp256<P> {
749    #[inline]
750    fn mul_assign(&mut self, other: &Self) {
751        let mut r = [0u64; 4];
752        let mut carry1 = 0u64;
753        let mut carry2 = 0u64;
754
755        // Iteration 0.
756        r[0] = fa::mac(r[0], (self.0).0[0], (other.0).0[0], &mut carry1);
757        let k = r[0].wrapping_mul(P::INV);
758        fa::mac_discard(r[0], k, P::MODULUS.0[0], &mut carry2);
759        r[1] = fa::mac_with_carry(r[1], (self.0).0[1], (other.0).0[0], &mut carry1);
760        r[0] = fa::mac_with_carry(r[1], k, P::MODULUS.0[1], &mut carry2);
761
762        r[2] = fa::mac_with_carry(r[2], (self.0).0[2], (other.0).0[0], &mut carry1);
763        r[1] = fa::mac_with_carry(r[2], k, P::MODULUS.0[2], &mut carry2);
764
765        r[3] = fa::mac_with_carry(r[3], (self.0).0[3], (other.0).0[0], &mut carry1);
766        r[2] = fa::mac_with_carry(r[3], k, P::MODULUS.0[3], &mut carry2);
767        r[3] = carry1 + carry2;
768
769        // Iteration 1.
770        r[0] = fa::mac(r[0], (self.0).0[0], (other.0).0[1], &mut carry1);
771        let k = r[0].wrapping_mul(P::INV);
772        fa::mac_discard(r[0], k, P::MODULUS.0[0], &mut carry2);
773        r[1] = fa::mac_with_carry(r[1], (self.0).0[1], (other.0).0[1], &mut carry1);
774        r[0] = fa::mac_with_carry(r[1], k, P::MODULUS.0[1], &mut carry2);
775
776        r[2] = fa::mac_with_carry(r[2], (self.0).0[2], (other.0).0[1], &mut carry1);
777        r[1] = fa::mac_with_carry(r[2], k, P::MODULUS.0[2], &mut carry2);
778
779        r[3] = fa::mac_with_carry(r[3], (self.0).0[3], (other.0).0[1], &mut carry1);
780        r[2] = fa::mac_with_carry(r[3], k, P::MODULUS.0[3], &mut carry2);
781        r[3] = carry1 + carry2;
782
783        // Iteration 2.
784        r[0] = fa::mac(r[0], (self.0).0[0], (other.0).0[2], &mut carry1);
785        let k = r[0].wrapping_mul(P::INV);
786        fa::mac_discard(r[0], k, P::MODULUS.0[0], &mut carry2);
787        r[1] = fa::mac_with_carry(r[1], (self.0).0[1], (other.0).0[2], &mut carry1);
788        r[0] = fa::mac_with_carry(r[1], k, P::MODULUS.0[1], &mut carry2);
789
790        r[2] = fa::mac_with_carry(r[2], (self.0).0[2], (other.0).0[2], &mut carry1);
791        r[1] = fa::mac_with_carry(r[2], k, P::MODULUS.0[2], &mut carry2);
792
793        r[3] = fa::mac_with_carry(r[3], (self.0).0[3], (other.0).0[2], &mut carry1);
794        r[2] = fa::mac_with_carry(r[3], k, P::MODULUS.0[3], &mut carry2);
795        r[3] = carry1 + carry2;
796
797        // Iteration 3.
798        r[0] = fa::mac(r[0], (self.0).0[0], (other.0).0[3], &mut carry1);
799        let k = r[0].wrapping_mul(P::INV);
800        fa::mac_discard(r[0], k, P::MODULUS.0[0], &mut carry2);
801        r[1] = fa::mac_with_carry(r[1], (self.0).0[1], (other.0).0[3], &mut carry1);
802        r[0] = fa::mac_with_carry(r[1], k, P::MODULUS.0[1], &mut carry2);
803
804        r[2] = fa::mac_with_carry(r[2], (self.0).0[2], (other.0).0[3], &mut carry1);
805        r[1] = fa::mac_with_carry(r[2], k, P::MODULUS.0[2], &mut carry2);
806
807        r[3] = fa::mac_with_carry(r[3], (self.0).0[3], (other.0).0[3], &mut carry1);
808        r[2] = fa::mac_with_carry(r[3], k, P::MODULUS.0[3], &mut carry2);
809        r[3] = carry1 + carry2;
810
811        (self.0).0 = r;
812        self.reduce();
813    }
814}
815
816impl<P: Fp256Parameters> DivAssign<&'_ Self> for Fp256<P> {
817    #[inline]
818    fn div_assign(&mut self, other: &Self) {
819        self.mul_assign(&other.inverse().unwrap());
820    }
821}