~tdeo/serde_bare

7538e31ada5beba4612a235ee3ae951ccd386660 — Enrico Lumetti 4 months ago 22c64dc
Do not accept sequences with no length information
2 files changed, 26 insertions(+), 5 deletions(-)

M src/error.rs
M src/ser.rs
M src/error.rs => src/error.rs +2 -0
@@ 16,6 16,7 @@ pub enum Error {
    InvalidUtf8,
    InvalidChar,

    SequenceLengthRequired,
    MapLengthRequired,
}



@@ 39,6 40,7 @@ impl Display for Error {
            Error::AnyUnsupported => formatter.write_str("BARE does not support any"),
            Error::InvalidUtf8 => formatter.write_str("invalid utf-8 in string"),
            Error::InvalidChar => formatter.write_str("invalid unicode codepoint in char"),
            Error::SequenceLengthRequired => formatter.write_str("sequence length required"),
            Error::MapLengthRequired => formatter.write_str("map length required"),
        }
    }

M src/ser.rs => src/ser.rs +24 -5
@@ 176,12 176,11 @@ where
        value.serialize(self)
    }

    /// BARE type if len is None: []type
    /// BARE type if len is Some: \[len\]type
    /// BARE type if len is Some: []type
    /// BARE type \[len\]type is never used for variable-length sequences
    /// Error::SequenceLengthRequired if len is None
    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
        if let Some(len) = len {
            Uint(len as u64).serialize(&mut *self)?;
        }
        Uint(len.ok_or(Error::SequenceLengthRequired)? as u64).serialize(&mut *self)?;
        Ok(self)
    }



@@ 415,3 414,23 @@ where
    value.serialize(&mut serializer)?;
    Ok(())
}

#[cfg(test)]
mod test {
    #[test]
    fn test_unbounded_sequence() {
        use serde::Serializer;
        let seq = [1, 2, 3];
        let vec = Vec::<u8>::new();
        let mut serializer = super::Serializer::new(vec);
        assert!(serializer
            .collect_seq(seq.iter().filter_map(|x| {
                if x % 2 == 0 {
                    Some(x)
                } else {
                    None
                }
            }))
            .is_err());
    }
}