use crate::Field;
use rand::{thread_rng, Rng};
#[derive(PartialEq, Debug)]
pub struct Polynomial<Fq: Field> {
coefficients: Vec<Fq>,
}
impl<Fq: Field> Polynomial<Fq> {
pub fn from_intercept(intercept: Fq, degree: usize) -> Polynomial<Fq> {
let mut result = Vec::with_capacity(degree);
for _ in 1..degree {
result.push(thread_rng().gen::<Fq>());
}
result.push(intercept);
Polynomial {
coefficients: result,
}
}
pub fn evaluate_at(&self, x: Fq) -> Fq {
self.coefficients
.iter()
.skip(1)
.fold(*self.coefficients.first().unwrap(), |result, &a_i| {
a_i + (result * x)
})
}
}
#[cfg(test)]
mod test {
use crate::gf256::GF256;
use crate::polynomial::Polynomial;
use crate::Field;
quickcheck! {
fn test_eval_at_zero(intercept: GF256) -> bool {
let poly = Polynomial::from_intercept(intercept, 4);
poly.evaluate_at(GF256::zero()) == intercept
}
fn test_eval_at_one(intercept: GF256) -> bool {
let poly = Polynomial::from_intercept(intercept, 4);
let sum_coeff = poly.coefficients.iter().fold(GF256::zero(), |sum, &x| sum + x);
poly.evaluate_at(GF256::one()) == sum_coeff
}
}
}