-
Notifications
You must be signed in to change notification settings - Fork 99
/
Copy pathhex_utils.rs
39 lines (34 loc) · 1.01 KB
/
hex_utils.rs
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
// This file is Copyright its original authors, visible in version control history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. You may not use this file except in
// accordance with one or both of these licenses.
use std::fmt::Write;
#[cfg(feature = "uniffi")]
pub fn to_vec(hex: &str) -> Option<Vec<u8>> {
let mut out = Vec::with_capacity(hex.len() / 2);
let mut b = 0;
for (idx, c) in hex.as_bytes().iter().enumerate() {
b <<= 4;
match *c {
b'A'..=b'F' => b |= c - b'A' + 10,
b'a'..=b'f' => b |= c - b'a' + 10,
b'0'..=b'9' => b |= c - b'0',
_ => return None,
}
if (idx & 1) == 1 {
out.push(b);
b = 0;
}
}
Some(out)
}
#[inline]
pub fn to_string(value: &[u8]) -> String {
let mut res = String::with_capacity(2 * value.len());
for v in value {
write!(&mut res, "{:02x}", v).expect("Unable to write");
}
res
}