1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
use core::str::FromStr;
use crate::constants;
#[derive(Debug)]
pub struct InvalidBinaryState;
impl core::fmt::Display for InvalidBinaryState {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("invalid binary state, allowed values are 'ON' and 'OFF' (case insensitive)")
}
}
impl core::error::Error for InvalidBinaryState {}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BinaryState {
On,
Off,
}
impl BinaryState {
pub fn as_str(&self) -> &'static str {
match self {
Self::On => constants::HA_SWITCH_STATE_ON,
Self::Off => constants::HA_SWITCH_STATE_OFF,
}
}
pub fn flip(self) -> Self {
match self {
Self::On => Self::Off,
Self::Off => Self::On,
}
}
}
impl core::fmt::Display for BinaryState {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(self.as_str())
}
}
impl FromStr for BinaryState {
type Err = InvalidBinaryState;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if s.eq_ignore_ascii_case(constants::HA_SWITCH_STATE_ON) {
return Ok(Self::On);
}
if s.eq_ignore_ascii_case(constants::HA_SWITCH_STATE_OFF) {
return Ok(Self::Off);
}
Err(InvalidBinaryState)
}
}
impl TryFrom<&[u8]> for BinaryState {
type Error = InvalidBinaryState;
fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
let string = str::from_utf8(value).map_err(|_| InvalidBinaryState)?;
string.parse()
}
}
|