virt_ic/
lib.rs

1pub mod board;
2pub mod chip;
3pub mod utilities;
4
5#[derive(Debug, Default, Clone, Copy, PartialEq)]
6#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
7pub enum State {
8    #[default]
9    Undefined,
10    Low,
11    High,
12    Analog(f32),
13}
14
15impl State {
16    pub fn feed_state(&mut self, state: State) -> Self {
17        match state {
18            State::Low if matches!(self, State::Undefined) => State::Low,
19            State::High => State::High,
20            State::Analog(_) if matches!(self, State::High) => State::High,
21            State::Analog(v) => {
22                if let State::Analog(bv) = self {
23                    if v < *bv {
24                        *self
25                    } else {
26                        State::Analog(v)
27                    }
28                } else {
29                    State::Analog(v)
30                }
31            }
32            State::Undefined | State::Low => *self,
33        }
34    }
35
36    pub fn as_analog(&self, conversion_target: f32) -> Self {
37        match self {
38            State::Undefined | State::Low => State::Analog(0.0),
39            State::High => Self::Analog(conversion_target),
40            State::Analog(_) => *self,
41        }
42    }
43
44    pub fn as_logic(&self, threshold: f32) -> Self {
45        match self {
46            State::Undefined => State::Low,
47            State::Low | State::High => *self,
48            State::Analog(v) => {
49                if *v >= threshold {
50                    State::High
51                } else {
52                    State::Low
53                }
54            }
55        }
56    }
57}
58
59impl From<State> for bool {
60    fn from(value: State) -> Self {
61        match value {
62            State::Undefined | State::Low => false,
63            State::High => true,
64            State::Analog(v) => v != 0.0,
65        }
66    }
67}
68
69impl From<bool> for State {
70    fn from(value: bool) -> Self {
71        if value {
72            State::High
73        } else {
74            State::Low
75        }
76    }
77}