serde
serde copied to clipboard
[Documentation] paremeter `len` in `serialize_struct` is hint, or must be exact?
Hi David, Incredible crate, as you already know!
https://docs.rs/serde/1.0.188/serde/trait.Serializer.html#tymethod.serialize_struct
Say I have this function:
impl Serialize for Foo {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let mut state = serializer.serialize_struct("Foo", 1)?;
if let Some(bar) = self.bar {
state.serialize_field("bar", bar)?;
}
state.end()
}
}
It's not clear if I have to check the option and report the exact len, or if I can get away with hinting the len.
Thanks!
Hey,
I don't have an answer to this question but I am curious to know that as well. I bet that the length is usually a hint and we probably can't know for sure if it isn't saved into the resulting bytes without being checked against the number of serialized fields. And in that case, this can lead to bugs...
Fwiw the discrepancies when we pass different length then the number of serialize_field calls we make can be detected with a lint written in Dylint (see write Rust lints without forking Clippy) which can be seen here.
Good point! This makes me think it's just a hint for preallocation, since why would they trust us when they can count it themselves.