summaryrefslogtreecommitdiff
path: root/src/tokens/value.rs
blob: e421bd57e4148270be96d001d3dd819f5131a50d (plain) (blame)
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
pub enum Value {
    Byte(u8),
    Double(u16),
}

impl std::fmt::Display for Value {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        match self {
            Self::Byte(value) => write!(f, "0x{value:02x}"),
            Self::Double(value) => write!(f, "0x{value:04x}"),
        }
    }
}


impl std::str::FromStr for Value {
    type Err = ();

    fn from_str(token: &str) -> Result<Self, Self::Err> {
        match token.len() {
            2 => match u8::from_str_radix(&token, 16) {
                Ok(value) => Ok(Value::Byte(value)),
                Err(_) => Err(()),
            }
            4 => match u16::from_str_radix(&token, 16) {
                Ok(value) => Ok(Value::Double(value)),
                Err(_) => Err(()),
            }
            _ => Err(()),
        }
    }
}