use std::{fmt, str::FromStr};
pub struct FromStrVisitor<T> {
expecting: &'static str,
_marker: std::marker::PhantomData<T>,
}
impl<T> FromStrVisitor<T> {
pub fn expecting(expecting: &'static str) -> Self {
Self {
expecting,
_marker: std::marker::PhantomData::default(),
}
}
}
impl<'de, T: 'de> serde::de::Visitor<'de> for FromStrVisitor<T>
where
T: FromStr,
<T as FromStr>::Err: fmt::Display,
{
type Value = T;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str(self.expecting)
}
fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
s.parse::<T>().map_err(E::custom)
}
}