Join GitHub today
GitHub is home to over 50 million developers working together to host and review code, manage projects, and build software together.
Sign upPossible `deserialize_into()` method? #252
Closed
Comments
|
This is waiting on a bincode release, but you could implement that function today as: // [dependencies]
// bincode = { git = "https://github.com/TyOverby/bincode" }
use serde::de::{Deserialize, DeserializeSeed, Deserializer};
fn deserialize_into<'de, T>(bytes: &'de [u8], mut target: T) -> bincode::Result<T>
where
T: Deserialize<'de>,
{
struct InPlace<'a, T>(&'a mut T);
impl<'a, 'de, T> DeserializeSeed<'de> for InPlace<'a, T>
where
T: Deserialize<'de>,
{
type Value = ();
fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: Deserializer<'de>,
{
T::deserialize_in_place(deserializer, self.0)
}
}
bincode::config().deserialize_seed(InPlace(&mut target), bytes)?;
Ok(target)
} |
|
Thank you! Let me get my head around this and I'll re-open if I can't figure out what is going on. :D |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm new here, and perhaps this is old news, but I'd love to have a method
with the point being that any allocations already present in
targetcan be re-used. So, if I am deserializing aVec<String>I might reasonably have aVec<String>already on hand (perhaps I've just previously deserialized and processed such a thing) with a bunch of allocations ready to be populated.This is a bit like
Clone's methodclone_from(&mut self, other: &T)which has some decent performance properties. Also, it is a bit analogous to Recycler (edit: specifically the recreate method) which hasn't been used in forever, but which gives about a 2x performance bump inVec<Vec<String>>cloning.Anyhow, maybe this is a non-goal, but it's something I'm looking at right now as a clear perf speedbump in some code (I have owned
Ttypes being dropped because I don't know how to hand the resources to bincode to use for deserialization). Also very possible that there is a clever pattern that lets bincode do this and I don't know it, in which case I apologize!