From 6391912bc4fdb9bb67c829c588249ecc8405f595 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Fri, 22 Nov 2024 15:47:59 +0100 Subject: [PATCH] feat: Add and improve poly monic function with testcases Make a polynomial monic by dividing all field elements with the leading element --- src/utils/poly.rs | 45 +++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 43 insertions(+), 2 deletions(-) diff --git a/src/utils/poly.rs b/src/utils/poly.rs index bb05366..e624361 100644 --- a/src/utils/poly.rs +++ b/src/utils/poly.rs @@ -219,6 +219,22 @@ impl Polynomial { *fieldelement = fieldelement.clone() / divident.clone(); } + while !self.polynomial.is_empty() + && self + .polynomial + .last() + .unwrap() + .as_ref() + .iter() + .all(|&x| x == 0) + { + self.polynomial.pop(); + } + + if self.is_empty() { + self = Polynomial::new(vec![FieldElement::new(vec![0; 16])]); + } + self } } @@ -1047,7 +1063,6 @@ mod tests { let result = element1.pow_mod(10000000, modulus); assert!(!result.is_zero()) - //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); } #[test] @@ -1069,6 +1084,32 @@ mod tests { let result = element1.monic(); assert_eq!(json!(result.to_c_array()), expected); - //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); + } + + #[test] + fn test_poly_monic_poly_zero() { + let json1 = json!(["AAAAAAAAAAAAAAAAAAAAAA=="]); + let expected = json!(["AAAAAAAAAAAAAAAAAAAAAA=="]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + + let result = element1.monic(); + + assert_eq!(json!(result.to_c_array()), expected); + } + + #[test] + fn test_poly_monic_poly_multiple_zero() { + let json1 = json!([ + "AAAAAAAAAAAAAAAAAAAAAA==", + "AAAAAAAAAAAAAAAAAAAAAA==", + "AAAAAAAAAAAAAAAAAAAAAA==", + "AAAAAAAAAAAAAAAAAAAAAA==" + ]); + let expected = json!(["AAAAAAAAAAAAAAAAAAAAAA=="]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + + let result = element1.monic(); + + assert_eq!(json!(result.to_c_array()), expected); } }