continuous_blocks/
hysteresis.rs1#[derive(Debug, Clone, Copy, PartialEq)]
10pub struct Hysteresis {
11 pub high: f64,
12 pub low: f64,
13}
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum HysteresisError {
17 LowExceedsHigh,
18}
19
20impl Hysteresis {
21 pub fn new(high: f64, low: f64) -> Result<Self, HysteresisError> {
22 if low > high {
23 return Err(HysteresisError::LowExceedsHigh);
24 }
25 Ok(Hysteresis { high, low })
26 }
27
28 pub fn step(&self, prev_state: bool, x: f64) -> bool {
31 if prev_state {
32 x >= self.low
33 } else {
34 x > self.high
35 }
36 }
37}
38
39#[cfg(test)]
40mod tests {
41 use super::*;
42
43 #[test]
44 fn rises_above_high_to_turn_on() {
45 let h = Hysteresis::new(1.0, -1.0).unwrap();
46 assert!(!h.step(false, 0.5));
47 assert!(h.step(false, 1.5));
48 }
49
50 #[test]
51 fn stays_on_inside_the_band() {
52 let h = Hysteresis::new(1.0, -1.0).unwrap();
53 assert!(h.step(true, 0.0));
54 assert!(h.step(true, -0.5));
55 }
56
57 #[test]
58 fn falls_below_low_to_turn_off() {
59 let h = Hysteresis::new(1.0, -1.0).unwrap();
60 assert!(!h.step(true, -1.5));
61 }
62
63 #[test]
64 fn stays_off_inside_the_band() {
65 let h = Hysteresis::new(1.0, -1.0).unwrap();
66 assert!(!h.step(false, 0.0));
67 assert!(!h.step(false, 0.9));
68 }
69
70 #[test]
71 fn boundary_values_are_inclusive_of_staying_in_the_current_state() {
72 let h = Hysteresis::new(1.0, -1.0).unwrap();
73 assert!(h.step(true, -1.0));
75 assert!(!h.step(false, 1.0));
77 }
78
79 #[test]
80 fn low_exceeding_high_is_rejected_not_a_panic() {
81 assert_eq!(
82 Hysteresis::new(-1.0, 1.0),
83 Err(HysteresisError::LowExceedsHigh)
84 );
85 }
86}