lozizol/model/vuint/
parse.rs1use super::{Vuint, VuintError};
2use fmt::Debug;
3use std::{fmt, str};
4
5impl str::FromStr for Vuint<'static> {
6 type Err = ParseError;
7
8 fn from_str(s: &str) -> Result<Self, Self::Err> {
9 match s.as_bytes() {
10 [b'0', b'x', ..] | [b'0', b'X', ..] => {
11 if let Ok(bytes) = hex::decode(&s[2..]) {
12 Ok(Vuint::try_from_bytes(bytes)?)
13 } else {
14 Err(ParseError::InvalidHex)
15 }
16 }
17 _ => Err(ParseError::UnrecognizedInput),
18 }
19 }
20}
21
22#[derive(Debug, Copy, Clone, Eq, PartialEq)]
24pub enum ParseError {
25 InvalidHex,
26 UnrecognizedInput,
27 ConversionError(VuintError),
28}
29
30impl From<VuintError> for ParseError {
31 fn from(e: VuintError) -> Self {
32 ParseError::ConversionError(e)
33 }
34}
35
36impl fmt::Display for ParseError {
37 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38 match self {
39 ParseError::ConversionError(e) => write!(f, " {}", e),
40 ParseError::InvalidHex => write!(f, "Vuint parse error: hexadecimal value is invalid"),
41 ParseError::UnrecognizedInput => {
42 write!(f, "Vuint parse error: unrecognized input, try prefix the value with format, such as 0x...")
43 }
44 }
45 }
46}
47
48impl std::error::Error for ParseError {}
49
50#[test]
51fn test_parse_vuint() {
52 k9::assert_equal!("0x817F".parse::<Vuint>().unwrap(), Vuint::from(&255u8));
53}
54
55#[test]
56fn fail_test_parse_vuint_unrecognized() {
57 k9::assert_equal!("817F".parse::<Vuint>(), Err(ParseError::UnrecognizedInput));
58}
59
60#[test]
61fn fail_test_parse_vuint_invalid_hex() {
62 k9::assert_equal!("0x817_".parse::<Vuint>(), Err(ParseError::InvalidHex));
63 k9::assert_equal!("0x817".parse::<Vuint>(), Err(ParseError::InvalidHex));
64 k9::assert_equal!("0x817z".parse::<Vuint>(), Err(ParseError::InvalidHex));
65}