serde icon indicating copy to clipboard operation
serde copied to clipboard

[Documentation] paremeter `len` in `serialize_struct` is hint, or must be exact?

Open arifd opened this issue 2 years ago • 2 comments
trafficstars

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!

arifd avatar Sep 14 '23 03:09 arifd

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.

disconnect3d avatar Sep 27 '23 11:09 disconnect3d

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.

arifd avatar Sep 27 '23 11:09 arifd