ps_ecc/polynomial/methods/
first_n_coefficients.rs1use crate::{polynomial::constants::POLYNOMIAL_MAX_COEFFICIENTS, Polynomial};
2
3impl Polynomial {
4 #[must_use]
8 pub fn first_n_coefficients(&self, n: usize) -> &[u8] {
9 &self.coefficients[..n.min(POLYNOMIAL_MAX_COEFFICIENTS)]
10 }
11}
12
13#[cfg(test)]
14mod tests {
15 use crate::Polynomial;
16
17 #[test]
18 fn exact_size() {
19 let mut p = Polynomial::default();
20
21 p.set(0, 1);
22 p.set(1, 2);
23 p.set(2, 3);
24
25 assert_eq!(p.first_n_coefficients(3), &[1, 2, 3]);
26 }
27
28 #[test]
29 fn zeros_beyond_degree() {
30 let mut p = Polynomial::default();
31
32 p.set(0, 1);
33 p.set(1, 2);
34
35 assert_eq!(p.first_n_coefficients(5), &[1, 2, 0, 0, 0]);
36 }
37
38 #[test]
39 fn truncates() {
40 let mut p = Polynomial::default();
41
42 p.set(0, 1);
43 p.set(1, 2);
44 p.set(2, 3);
45 p.set(3, 4);
46 p.set(4, 5);
47
48 assert_eq!(p.first_n_coefficients(3), &[1, 2, 3]);
49 }
50
51 #[test]
52 fn zero_polynomial() {
53 let p = Polynomial::default();
54
55 assert_eq!(p.first_n_coefficients(3), &[0, 0, 0]);
56 }
57
58 #[test]
59 fn n_is_zero() {
60 let mut p = Polynomial::default();
61
62 p.set(0, 1);
63
64 assert_eq!(p.first_n_coefficients(0), &[]);
65 }
66
67 #[test]
68 fn n_is_255() {
69 let mut p = Polynomial::default();
70
71 p.set(0, 1);
72
73 let result = p.first_n_coefficients(255);
74
75 assert_eq!(result.len(), 255);
76 assert_eq!(result[0], 1);
77 assert!(result[1..].iter().all(|&x| x == 0));
78 }
79
80 #[test]
81 fn n_exceeds_255_clamps() {
82 let mut p = Polynomial::default();
83
84 p.set(0, 1);
85 p.set(1, 2);
86
87 let result = p.first_n_coefficients(300);
88
89 assert_eq!(result.len(), 255);
90 }
91}