use crate::Codec;
use core::fmt;
use serde::{de, Deserialize, Deserializer};
impl<'de> Deserialize<'de> for Codec {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct CodecVisitor;
impl<'de> de::Visitor<'de> for CodecVisitor {
type Value = Codec;
fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(
fmt,
"borrowed str, str, String, borrowed byte array, byte buf, bytes, or sequence"
)
}
#[inline]
fn visit_borrowed_str<E>(self, s: &'de str) -> Result<Self::Value, E>
where
E: de::Error,
{
Self::Value::try_from(s).map_err(|e| de::Error::custom(e.to_string()))
}
#[inline]
fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
Self::Value::try_from(s).map_err(|e| de::Error::custom(e.to_string()))
}
#[inline]
fn visit_borrowed_bytes<E>(self, b: &'de [u8]) -> Result<Self::Value, E>
where
E: de::Error,
{
Self::Value::try_from(b).map_err(|e| de::Error::custom(e.to_string()))
}
#[inline]
fn visit_bytes<E>(self, b: &[u8]) -> Result<Self::Value, E>
where
E: de::Error,
{
Self::Value::try_from(b).map_err(|e| de::Error::custom(e.to_string()))
}
#[inline]
fn visit_seq<S>(self, mut seq: S) -> Result<Self::Value, S::Error>
where
S: de::SeqAccess<'de>,
{
const MAX_VARINT_LEN: usize = 19;
let mut v = Vec::with_capacity(MAX_VARINT_LEN.min(8));
while let Some(b) = seq.next_element()? {
if v.len() >= MAX_VARINT_LEN {
return Err(de::Error::custom(
"varint exceeds maximum length of 19 bytes",
));
}
v.push(b);
}
Self::Value::try_from(v.as_slice()).map_err(|e| de::Error::custom(e.to_string()))
}
}
deserializer.deserialize_any(CodecVisitor)
}
}