Skip to main content

primefield/
traits.rs

1use crate::ByteOrder;
2
3/// Extension trait for [`ff::Field`], intended as a place to put optimizable arithmetic operations.
4///
5/// The idea is future versions of this crate can add provided methods which are useful in dense
6/// field arithmetic like `primeorder`'s RCB implementation, and `primefield` can potentially
7/// automatically plug in optimized implementations when available.
8// TODO(tarcieri): add some methods to this trait, e.g. `add_and_mul`, `mul_and_add`
9pub trait FieldExt: ff::Field {}
10
11/// Extension trait for [`ff::PrimeField`] which enables specifying the endianness in which
12/// [`ff::PrimeField::Repr`] is encoded.
13// TODO(tarcieri): remove this if/whenever zkcrypto/rfcs#4 lands. See also: zkcrypto/ff#158
14pub trait PrimeFieldExt: FieldExt + ff::PrimeField {
15    /// Endianness used when encoding [`ff::PrimeField::Repr`].
16    const REPR_ENDIANNESS: ByteOrder = ByteOrder::BigEndian;
17
18    /// Encode `self` using a big endian representation.
19    fn to_be_repr(&self) -> Self::Repr {
20        let mut repr = self.to_repr();
21
22        if Self::REPR_ENDIANNESS == ByteOrder::LittleEndian {
23            repr.as_mut().reverse();
24        }
25
26        repr
27    }
28
29    /// Encode `self` using a little endian representation.
30    fn to_le_repr(&self) -> Self::Repr {
31        let mut repr = self.to_repr();
32
33        if Self::REPR_ENDIANNESS == ByteOrder::BigEndian {
34            repr.as_mut().reverse();
35        }
36
37        repr
38    }
39}