Skip to content

Instantly share code, notes, and snippets.

@tesaguri
Created January 15, 2023 10:49
Show Gist options
  • Save tesaguri/c7c36db529e2b60023d12ffc811d27fc to your computer and use it in GitHub Desktop.
Save tesaguri/c7c36db529e2b60023d12ffc811d27fc to your computer and use it in GitHub Desktop.
serde: Deserialize a sequence into a given vector
use core::fmt;
use serde::de;
pub fn deserialize_into_vec<'de, T, D>(vec: &mut Vec<T>, deserializer: D) -> Result<(), D::Error>
where
T: de::Deserialize<'de>,
D: de::Deserializer<'de>,
{
struct Visitor<'a, T: 'a>(&'a mut Vec<T>);
impl<'de, 'a, T: de::Deserialize<'de>> de::Visitor<'de> for Visitor<'a, T> {
type Value = ();
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a sequence")
}
fn visit_seq<A: de::SeqAccess<'de>>(self, mut seq: A) -> Result<(), A::Error> {
if let Some(hint) = seq.size_hint() {
self.0.reserve(hint);
}
while let Some(t) = seq.next_element()? {
self.0.push(t);
}
Ok(())
}
}
deserializer.deserialize_seq(Visitor(vec))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
let mut v = Vec::<u32>::new();
deserialize_into_vec(&mut v, &mut serde_json::Deserializer::from_str("[1, 2]")).unwrap();
assert_eq!(v, [1, 2]);
deserialize_into_vec(&mut v, &mut serde_json::Deserializer::from_str("[3, 4]")).unwrap();
assert_eq!(v, [1, 2, 3, 4]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment