2020-09-29 03:46:54 +00:00
|
|
|
//! Provides utilities for parsing 0x-prefixed hex strings.
|
|
|
|
|
2019-03-15 02:31:30 +00:00
|
|
|
use serde::de::{self, Visitor};
|
|
|
|
use std::fmt;
|
|
|
|
|
2020-09-29 03:46:54 +00:00
|
|
|
/// Encode `data` as a 0x-prefixed hex string.
|
2019-03-15 02:31:30 +00:00
|
|
|
pub fn encode<T: AsRef<[u8]>>(data: T) -> String {
|
2020-05-17 11:16:48 +00:00
|
|
|
let hex = hex::encode(data);
|
2019-03-15 02:31:30 +00:00
|
|
|
let mut s = "0x".to_string();
|
|
|
|
s.push_str(hex.as_str());
|
|
|
|
s
|
|
|
|
}
|
|
|
|
|
2020-09-29 03:46:54 +00:00
|
|
|
/// Decode `data` from a 0x-prefixed hex string.
|
|
|
|
pub fn decode(s: &str) -> Result<Vec<u8>, String> {
|
|
|
|
if s.starts_with("0x") {
|
|
|
|
hex::decode(&s[2..]).map_err(|e| format!("invalid hex: {:?}", e))
|
|
|
|
} else {
|
|
|
|
Err("hex must have 0x prefix".to_string())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-03-15 02:31:30 +00:00
|
|
|
pub struct PrefixedHexVisitor;
|
|
|
|
|
|
|
|
impl<'de> Visitor<'de> for PrefixedHexVisitor {
|
|
|
|
type Value = Vec<u8>;
|
|
|
|
|
|
|
|
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
|
|
|
formatter.write_str("a hex string with 0x prefix")
|
|
|
|
}
|
|
|
|
|
|
|
|
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
|
|
|
|
where
|
|
|
|
E: de::Error,
|
|
|
|
{
|
|
|
|
if value.starts_with("0x") {
|
|
|
|
Ok(hex::decode(&value[2..])
|
|
|
|
.map_err(|e| de::Error::custom(format!("invalid hex ({:?})", e)))?)
|
|
|
|
} else {
|
|
|
|
Err(de::Error::custom("missing 0x prefix"))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-03-26 04:44:01 +00:00
|
|
|
pub struct HexVisitor;
|
|
|
|
|
|
|
|
impl<'de> Visitor<'de> for HexVisitor {
|
|
|
|
type Value = Vec<u8>;
|
|
|
|
|
|
|
|
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
|
|
|
formatter.write_str("a hex string (irrelevant of prefix)")
|
|
|
|
}
|
|
|
|
|
|
|
|
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
|
|
|
|
where
|
|
|
|
E: de::Error,
|
|
|
|
{
|
|
|
|
Ok(hex::decode(value.trim_start_matches("0x"))
|
|
|
|
.map_err(|e| de::Error::custom(format!("invalid hex ({:?})", e)))?)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-03-15 02:31:30 +00:00
|
|
|
#[cfg(test)]
|
|
|
|
mod test {
|
|
|
|
use super::*;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn encoding() {
|
|
|
|
let bytes = vec![0, 255];
|
|
|
|
let hex = encode(&bytes);
|
|
|
|
assert_eq!(hex.as_str(), "0x00ff");
|
|
|
|
|
|
|
|
let bytes = vec![];
|
|
|
|
let hex = encode(&bytes);
|
|
|
|
assert_eq!(hex.as_str(), "0x");
|
|
|
|
|
|
|
|
let bytes = vec![1, 2, 3];
|
|
|
|
let hex = encode(&bytes);
|
|
|
|
assert_eq!(hex.as_str(), "0x010203");
|
|
|
|
}
|
|
|
|
}
|