Skip to main content

ps_ecc/polynomial/methods/
set.rs

1use std::cmp::Ordering::{Equal, Greater, Less};
2
3use crate::Polynomial;
4
5impl Polynomial {
6    /// Sets the coefficient of degree `idx` to `value`.
7    ///
8    /// If `value` is non-zero and `idx` exceeds the current degree, the degree
9    /// increases to `idx`. If `value` is zero and `idx` equals the current degree,
10    /// the degree decreases to the next non-zero coefficient.
11    ///
12    /// # Panics
13    ///
14    /// Panics if `idx` exceeds 254, the maximum degree of a polynomial over GF(256).
15    pub fn set(&mut self, idx: u8, value: u8) {
16        self.coefficients[idx as usize] = value;
17
18        match (idx.cmp(&self.degree), value) {
19            (Equal, 0) => self.trim_degree(),
20            (Greater, 1..) => self.degree = idx,
21            (Less, ..) | (Greater, 0) | (Equal, 1..) => {}
22        }
23    }
24}
25
26#[cfg(test)]
27mod tests {
28    use crate::Polynomial;
29
30    #[test]
31    fn set_below_degree() {
32        let mut p = Polynomial {
33            degree: 3,
34            ..Default::default()
35        };
36
37        p.coefficients[3] = 5;
38
39        p.set(1, 7);
40
41        assert_eq!(p.coefficients[1], 7);
42        assert_eq!(p.degree, 3);
43    }
44
45    #[test]
46    fn set_at_degree_nonzero() {
47        let mut p = Polynomial {
48            degree: 2,
49            ..Default::default()
50        };
51
52        p.coefficients[2] = 3;
53
54        p.set(2, 9);
55
56        assert_eq!(p.coefficients[2], 9);
57        assert_eq!(p.degree, 2);
58    }
59
60    #[test]
61    fn set_at_degree_zero_trims() {
62        let mut p = Polynomial {
63            degree: 3,
64            ..Default::default()
65        };
66
67        p.coefficients[0] = 1;
68        p.coefficients[1] = 2;
69        p.coefficients[3] = 4;
70
71        p.set(3, 0);
72
73        assert_eq!(p.coefficients[3], 0);
74        assert_eq!(p.degree, 1);
75    }
76
77    #[test]
78    fn set_above_degree_nonzero() {
79        let mut p = Polynomial {
80            degree: 1,
81            ..Default::default()
82        };
83
84        p.coefficients[1] = 1;
85
86        p.set(5, 3);
87
88        assert_eq!(p.coefficients[5], 3);
89        assert_eq!(p.degree, 5);
90    }
91
92    #[test]
93    fn set_above_degree_zero() {
94        let mut p = Polynomial {
95            degree: 2,
96            ..Default::default()
97        };
98
99        p.coefficients[2] = 1;
100
101        p.set(5, 0);
102
103        assert_eq!(p.coefficients[5], 0);
104        assert_eq!(p.degree, 2);
105    }
106
107    #[test]
108    fn set_trims_to_zero_polynomial() {
109        let mut p = Polynomial {
110            degree: 0,
111            ..Default::default()
112        };
113
114        p.coefficients[0] = 5;
115
116        p.set(0, 0);
117
118        assert_eq!(p.coefficients[0], 0);
119        assert_eq!(p.degree, 0);
120    }
121}