fitzgen / bumpalo

A fast bump allocation arena for Rust
https://docs.rs/bumpalo
Apache License 2.0
1.41k stars 111 forks source link

add serde serialization support #210

Closed keithamus closed 5 months ago

keithamus commented 1 year ago

This starts work on #63 by adding support for Serialize on Box and Vec, with some basic tests & docs.

I couldn't figure out the right way to implement DeserializeSeed for Vec. I'm a newcommer to rust so I think I need some pointers on how to handle that, as I'm struggling with lifetimes:


#[cfg(feature = "serde")]
impl<'a, T> DeserializeSeed<'a> for Vec<'a, T>
where
    T: Deserialize<'a>,
{
    type Value = ();

    fn deserialize<D>(mut self, deserializer: D) -> Result<Self::Value, D::Error>
    where
        D: Deserializer<'a>,
    {
        struct VecVisitor<'a, T: 'a>(&'a mut Vec<'a, T>);

        impl<'a, T> Visitor<'a> for VecVisitor<'a, T>
        where
            T: Deserialize<'a>,
        {
            type Value = ();

            fn expecting(
                &self,
                formatter: &mut core_alloc::fmt::Formatter,
            ) -> core_alloc::fmt::Result {
                Ok(())
            }

            fn visit_seq<V>(self, mut visitor: V) -> Result<(), V::Error>
            where
                V: SeqAccess<'a>,
            {
                while let Some(elem) = visitor.next_element()? {
                    self.0.push(elem);
                }
                Ok(())
            }
        }

        deserializer.deserialize_seq(VecVisitor::<'a>(self.as_mut()))
    }
}