Skip to content

Commit

Permalink
fix: deserialize SmallVec without Vec alloc
Browse files Browse the repository at this point in the history
  • Loading branch information
baszalmstra committed May 29, 2022
1 parent 530cd9c commit bb2f2c6
Showing 1 changed file with 28 additions and 5 deletions.
33 changes: 28 additions & 5 deletions src/internal/small_vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,13 +126,36 @@ impl<T: serde::Serialize> serde::Serialize for SmallVec<T> {
#[cfg(feature = "serde")]
impl<'de, T: serde::Deserialize<'de>> serde::Deserialize<'de> for SmallVec<T> {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let items: Vec<T> = serde::Deserialize::deserialize(d)?;
struct SmallVecVisitor<T> {
marker: std::marker::PhantomData<T>,
}

impl<'de, T> serde::de::Visitor<'de> for SmallVecVisitor<T>
where
T: serde::Deserialize<'de>,
{
type Value = SmallVec<T>;

fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a sequence")
}

let mut v = Self::empty();
for item in items {
v.push(item);
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: serde::de::SeqAccess<'de>,
{
let mut values = SmallVec::empty();
while let Some(value) = seq.next_element()? {
values.push(value);
}
Ok(values)
}
}
Ok(v)

let visitor = SmallVecVisitor {
marker: Default::default(),
};
d.deserialize_seq(visitor)
}
}

Expand Down

0 comments on commit bb2f2c6

Please sign in to comment.