diff options
Diffstat (limited to 'src/types/value.rs')
-rw-r--r-- | src/types/value.rs | 48 |
1 files changed, 48 insertions, 0 deletions
diff --git a/src/types/value.rs b/src/types/value.rs new file mode 100644 index 0000000..fe82710 --- /dev/null +++ b/src/types/value.rs @@ -0,0 +1,48 @@ +#[derive(Clone, Copy)] +pub enum Value { + Byte(u8), + Double(u16), +} + +impl From<Value> for usize { + fn from(value: Value) -> Self { + match value { + Value::Byte(byte) => byte.into(), + Value::Double(double) => double.into(), + } + } +} + +impl From<&Value> for usize { + fn from(value: &Value) -> Self { + (*value).into() + } +} + +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(()), + } + } +} |