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
use std::fmt::Write;
use std::num::ParseIntError;
pub trait ToHexString {
fn to_hex_string(&self) -> String;
}
pub trait FromHexString {
type Error;
fn from_hex_string(&self) -> Result<Vec<u8>,Self::Error>;
}
impl ToHexString for [u8] {
fn to_hex_string(&self) -> String {
let size = 2 + (2 * self.len());
let mut hexstr = String::with_capacity(size);
write!(hexstr,"0x").unwrap();
for b in self { write!(hexstr, "{:02x}", b).unwrap(); }
hexstr
}
}
impl FromHexString for str {
type Error = ParseIntError;
fn from_hex_string(&self) -> Result<Vec<u8>,Self::Error> {
let mut bytes : Vec<u8> = Vec::new();
let slice = if self.len() > 2 && &self[0..2] == "0x" {
&self[2..]
} else {
&self
};
for i in (0..slice.len()).step_by(2) {
let byte = u8::from_str_radix(&slice[i..i+2], 16)?;
bytes.push(byte);
}
Ok(bytes)
}
}