use rustc_hex::{FromHex, FromHexError, ToHex};
use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer};
use std::{ops, str};
#[derive(Debug, PartialEq)]
pub struct Bytes(Vec<u8>);
impl ops::Deref for Bytes {
type Target = [u8];
fn deref(&self) -> &Self::Target { &self.0 }
}
impl<'a> Deserialize<'a> for Bytes {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'a> {
let s = String::deserialize(deserializer)?;
let data = s
.from_hex()
.map_err(|e| Error::custom(format!("Invalid hex value {}", e)))?;
Ok(Bytes(data))
}
}
impl Serialize for Bytes {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer {
serializer.serialize_str(&self.0.to_hex::<String>())
}
}
impl str::FromStr for Bytes {
type Err = FromHexError;
fn from_str(s: &str) -> Result<Self, Self::Err> { s.from_hex().map(Bytes) }
}
impl From<&'static str> for Bytes {
fn from(s: &'static str) -> Self {
s.parse().unwrap_or_else(|_| {
panic!("invalid string literal for {}: '{}'", stringify!(Self), s)
})
}
}
impl From<Vec<u8>> for Bytes {
fn from(v: Vec<u8>) -> Self { Bytes(v) }
}
impl From<Bytes> for Vec<u8> {
fn from(b: Bytes) -> Self { b.0 }
}