bitwarden_encoding/
serde.rs

1use std::str::FromStr;
2
3/// A serde visitor that converts a string to a type that implements `FromStr`.
4pub struct FromStrVisitor<T>(std::marker::PhantomData<T>);
5impl<T> FromStrVisitor<T> {
6    /// Create a new `FromStrVisitor` for the given type.
7    pub fn new() -> Self {
8        Self::default()
9    }
10}
11impl<T> Default for FromStrVisitor<T> {
12    fn default() -> Self {
13        Self(Default::default())
14    }
15}
16impl<T: FromStr> serde::de::Visitor<'_> for FromStrVisitor<T>
17where
18    T::Err: std::fmt::Debug,
19{
20    type Value = T;
21
22    fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
23        write!(f, "a valid string")
24    }
25
26    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
27    where
28        E: serde::de::Error,
29    {
30        T::from_str(v).map_err(|e| E::custom(format!("{e:?}")))
31    }
32}