use core::fmt;
use core::marker::PhantomData;
use serde::de::{Error, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use crate::prelude::*;
pub fn serialize<S, T>(data: T, s: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
T: Serialize + DisplayHex,
{
serialize_lower(data, s)
}
pub fn serialize_lower<S, T>(data: T, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
T: Serialize + DisplayHex,
{
if !serializer.is_human_readable() {
serde::Serialize::serialize(&data, serializer)
} else {
serializer.collect_str(&format_args!("{:x}", data.as_hex()))
}
}
pub fn serialize_upper<S, T>(data: T, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
T: Serialize + DisplayHex,
{
if !serializer.is_human_readable() {
serde::Serialize::serialize(&data, serializer)
} else {
serializer.collect_str(&format_args!("{:X}", data.as_hex()))
}
}
pub fn deserialize<'de, D, T>(d: D) -> Result<T, D::Error>
where
D: Deserializer<'de>,
T: Deserialize<'de> + FromHex,
{
struct HexVisitor<T>(PhantomData<T>);
impl<'de, T> Visitor<'de> for HexVisitor<T>
where
T: FromHex,
{
type Value = T;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("an ASCII hex string")
}
fn visit_str<E: Error>(self, data: &str) -> Result<Self::Value, E> {
FromHex::from_hex(data).map_err(Error::custom)
}
}
if !d.is_human_readable() {
serde::Deserialize::deserialize(d)
} else {
d.deserialize_map(HexVisitor(PhantomData))
}
}