Skip to main content

polynomials_ecc/
polynomials.rs

1use crate::{Domain, fft, ifft};
2use bls12_381::Scalar;
3
4/// The coefficients of a polynomial
5#[derive(Debug, PartialEq)]
6pub struct Polynomial(Vec<Scalar>);
7
8impl Polynomial {
9    /// Creates a new Polynomial given its coefficients
10    pub fn new(coeffs: Vec<Scalar>) -> Self {
11        Polynomial(coeffs)
12    }
13
14    /// Evaluates the polynomial at a given domain
15    pub fn evaluate(&self, domain: &Domain) -> Evaluations {
16        let mut evaluations = Evaluations(vec![Scalar::zero(); domain.len()]);
17        evaluations.0[..self.len()].copy_from_slice(self.0.as_slice());
18
19        fft(&mut evaluations.0, &domain.roots(), domain.len());
20        evaluations
21    }
22
23    /// Returns the length of the polynomial
24    pub fn len(&self) -> usize {
25        self.0.len()
26    }
27
28    /// Returns true if the polynomial is empty
29    pub fn is_empty(&self) -> bool {
30        self.0.len() == 0
31    }
32}
33
34/// The evaluations of a polynomial over a given domain
35#[derive(Debug)]
36pub struct Evaluations(Vec<Scalar>);
37
38impl Evaluations {
39    /// Interpolates the evaluations over a given domain to get a polynomial
40    pub fn interpolate(&self, domain: &Domain) -> Polynomial {
41        let mut polynomial = Polynomial(self.0.clone());
42
43        ifft(&mut polynomial.0, &domain.roots());
44
45        while polynomial.0.last() == Some(&Scalar::zero()) {
46            polynomial.0.pop();
47        }
48
49        polynomial
50    }
51
52    /// Returns the length of the evaluations
53    pub fn len(&self) -> usize {
54        self.0.len()
55    }
56
57    /// Returns true if the evaluations are empty
58    pub fn is_empty(&self) -> bool {
59        self.0.len() == 0
60    }
61}