1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22

use std::convert::TryInto;
use std::error::Error;
use std::num::ParseIntError;
use std::str;

pub fn as_u128(val: &str) -> Result<u128, Box<dyn Error>> {
    let res = u128::from_le_bytes(decode_hex(val)?[..].try_into().unwrap());
    Ok(res)
}

pub fn as_bytes(val: &str) -> Result<Vec<u8>, Box<dyn Error>> {
    let res = decode_hex(val)?;
    Ok(res)
}

pub fn decode_hex(s: &str) -> Result<Vec<u8>, ParseIntError> {
    (0..s.len())
        .step_by(2)
        .map(|i| u8::from_str_radix(&s[i..i + 2], 16))
        .collect()
}