aboutsummaryrefslogtreecommitdiff
path: root/src/binary_state.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/binary_state.rs')
-rw-r--r--src/binary_state.rs56
1 files changed, 56 insertions, 0 deletions
diff --git a/src/binary_state.rs b/src/binary_state.rs
new file mode 100644
index 0000000..d512856
--- /dev/null
+++ b/src/binary_state.rs
@@ -0,0 +1,56 @@
1use core::str::FromStr;
2
3use crate::constants;
4
5pub struct InvalidBinaryState;
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub enum BinaryState {
9 On,
10 Off,
11}
12
13impl BinaryState {
14 pub fn as_str(&self) -> &'static str {
15 match self {
16 Self::On => constants::HA_SWITCH_STATE_ON,
17 Self::Off => constants::HA_SWITCH_STATE_OFF,
18 }
19 }
20
21 pub fn flip(self) -> Self {
22 match self {
23 Self::On => Self::Off,
24 Self::Off => Self::On,
25 }
26 }
27}
28
29impl core::fmt::Display for BinaryState {
30 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
31 f.write_str(self.as_str())
32 }
33}
34
35impl FromStr for BinaryState {
36 type Err = InvalidBinaryState;
37
38 fn from_str(s: &str) -> Result<Self, Self::Err> {
39 if s.eq_ignore_ascii_case(constants::HA_SWITCH_STATE_ON) {
40 return Ok(Self::On);
41 }
42 if s.eq_ignore_ascii_case(constants::HA_SWITCH_STATE_OFF) {
43 return Ok(Self::Off);
44 }
45 Err(InvalidBinaryState)
46 }
47}
48
49impl TryFrom<&[u8]> for BinaryState {
50 type Error = InvalidBinaryState;
51
52 fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
53 let string = str::from_utf8(value).map_err(|_| InvalidBinaryState)?;
54 string.parse()
55 }
56}