summaryrefslogtreecommitdiff
path: root/src/types.rs
blob: 7403c62600c5ab6f7401627cac37afb0f0b2b851 (plain)
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
use std::fmt::{Display, Error, Formatter};

#[derive(Copy, Clone, Debug, PartialEq)]
pub enum Value {
    Boolean(bool),
    Unsigned(u32),
    Signed(i32),
    Floating(f64),
    RawHex(u8),
}

impl Value {
    pub fn from_bool(v: bool) -> Value {
        Value::Boolean(v)
    }
    pub fn from_unsigned(v: u32) -> Value {
        Value::Unsigned(v)
    }
    pub fn from_signed(v: i32) -> Value {
        Value::Signed(v)
    }
    pub fn from_floating(v: f64) -> Value {
        Value::Floating(v)
    }
    pub fn from_raw(v: u8) -> Value {
        Value::RawHex(v)
    }
}

impl Display for Value {
    fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
        match *self {
            Value::Boolean(b) => write!(f, "b:{}", b),
            Value::Unsigned(u) => write!(f, "u:{}", u),
            Value::Signed(s) => write!(f, "s:{}", s),
            Value::Floating(v) => write!(f, "f:{}", v),
            Value::RawHex(h) => write!(f, "r:{:02X}", h),
        }
    }
}

impl From<bool> for Value {
    fn from(v: bool) -> Self {
        Value::from_bool(v)
    }
}

impl From<u8> for Value {
    fn from(v: u8) -> Self {
        Value::from_unsigned(v as u32)
    }
}

impl From<u16> for Value {
    fn from(v: u16) -> Self {
        Value::from_unsigned(v as u32)
    }
}

impl From<u32> for Value {
    fn from(v: u32) -> Self {
        Value::from_unsigned(v)
    }
}

impl From<i8> for Value {
    fn from(v: i8) -> Self {
        Value::from_signed(v as i32)
    }
}

impl From<i16> for Value {
    fn from(v: i16) -> Self {
        Value::from_signed(v as i32)
    }
}

impl From<i32> for Value {
    fn from(v: i32) -> Self {
        Value::from_signed(v)
    }
}

impl From<f64> for Value {
    fn from(v: f64) -> Self {
        Value::from_floating(v)
    }
}

#[derive(Clone, Debug)]
pub struct NamedValue {
    name: String,
    value: Option<Value>,
}

impl NamedValue {
    pub fn new(name: &str, value: Option<Value>) -> NamedValue {
        NamedValue {
            name: name.into(),
            value: value,
        }
    }

    pub fn get_name(&self) -> &str {
        self.name.as_ref()
    }

    pub fn get_value(&self) -> Option<Value> {
        self.value
    }
}