Skip to content

Commit 7400886

Browse files
authored
Auto merge of #241 - Lucretiel:master, r=jdm
Use a custom Visitor in Deserialize This PR implements a simple custom `de::Visitor` for `Atom`, which allows for deserializing without unnecessary round-trips through a `String`.
2 parents 4d6929c + 58d0c57 commit 7400886

File tree

1 file changed

+28
-2
lines changed

1 file changed

+28
-2
lines changed

src/trivial_impls.rs

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,33 @@ impl<'a, Static: StaticAtomSet> Deserialize<'a> for Atom<Static> {
8787
where
8888
D: Deserializer<'a>,
8989
{
90-
let string: String = Deserialize::deserialize(deserializer)?;
91-
Ok(Atom::from(string))
90+
use serde::de;
91+
use std::marker::PhantomData;
92+
93+
struct AtomVisitor<Static: StaticAtomSet>(PhantomData<Static>);
94+
95+
impl<'de, Static: StaticAtomSet> de::Visitor<'de> for AtomVisitor<Static> {
96+
type Value = Atom<Static>;
97+
98+
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
99+
write!(formatter, "an Atom")
100+
}
101+
102+
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
103+
where
104+
E: de::Error,
105+
{
106+
Ok(Atom::from(v))
107+
}
108+
109+
fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
110+
where
111+
E: de::Error,
112+
{
113+
Ok(Atom::from(v))
114+
}
115+
}
116+
117+
deserializer.deserialize_str(AtomVisitor(PhantomData))
92118
}
93119
}

0 commit comments

Comments
 (0)