Skip to content

Commit

Permalink
fix: ignore the length Serde provides
Browse files Browse the repository at this point in the history
Serde supplies the expected length of a tuple when deserializing. Prior
to this change it was ensured that this length also matches the length
of the CBOR encoded list.

Removing this check enables using `#[serde(default)]` when the data is
encoded as a tuple. Example:

    use serde_tuple::{Deserialize_tuple, Serialize_tuple};

    #[derive(Debug, Serialize_tuple, Deserialize_tuple)]
    struct Tree {
        height: u8,
        #[serde(default)]
        age: u8,
    }

    fn main() {
        // [3, 20]
        let tree1_cbor = b"\x82\x02\x14";
        let tree1: Tree = serde_ipld_dagcbor::from_slice(tree1_cbor).unwrap();
        println!("tree1: {:?}", tree1);

        // [5]
        let tree2_cbor = b"\x81\x05";
        let tree2: Tree = serde_ipld_dagcbor::from_slice(tree2_cbor).unwrap();
        println!("tree2: {:?}", tree2);
    }
  • Loading branch information
vmx committed Jan 29, 2025
1 parent 8930ea8 commit 1deff50
Showing 1 changed file with 7 additions and 5 deletions.
12 changes: 7 additions & 5 deletions src/de.rs
Original file line number Diff line number Diff line change
Expand Up @@ -454,14 +454,16 @@ impl<'de, 'a, R: dec::Read<'de>> Accessor<'a, R> {
) -> Result<Accessor<'a, R>, DecodeError<R::Error>> {
let array_start = dec::ArrayStart::decode(&mut de.reader)?;

if array_start.0 == Some(len) {
Ok(Accessor { de, len })
} else {
Err(DecodeError::RequireLength {
match array_start.0 {
Some(decoded_len) => Ok(Accessor {
de,
len: decoded_len,
}),
None => Err(DecodeError::RequireLength {
name: "tuple",
expect: len,
value: array_start.0.unwrap_or(0),
})
}),
}
}

Expand Down

0 comments on commit 1deff50

Please sign in to comment.