etcommon_util/
lib.rs

1
2#[derive(Debug)]
3/// Errors exhibited from `read_hex`.
4pub enum ParseHexError {
5    InvalidCharacter,
6    TooLong,
7    TooShort,
8    Other
9}
10
11/// Parses a given hex string and return a list of bytes if
12/// succeeded. The string can optionally start by `0x`, which
13/// indicates that it is a hex representation.
14pub fn read_hex(s: &str) -> Result<Vec<u8>, ParseHexError> {
15    if s.starts_with("0x") {
16        return read_hex(&s[2..s.len()]);
17    }
18
19    if s.len() & 1 == 1 {
20        let mut new_s = "0".to_string();
21        new_s.push_str(s);
22        return read_hex(&new_s);
23    }
24
25    let mut res = Vec::<u8>::new();
26
27    let mut cur = 0;
28    let mut len = 0;
29    for c in s.chars() {
30        len += 1;
31        let v_option = c.to_digit(16);
32        if v_option.is_none() {
33            return Err(ParseHexError::InvalidCharacter);
34        }
35        let v = v_option.unwrap();
36        if len == 1 {
37            cur += v * 16;
38        } else { // len == 2
39            cur += v;
40        }
41        if len == 2 {
42            res.push(cur as u8);
43            cur = 0;
44            len = 0;
45        }
46    }
47
48    return Ok(res);
49}