Skip to content

Limiting the size of a compound structure / enum that can be browsed by the reader #488

@Nabellaleen

Description

@Nabellaleen

My input data is quite complex, but always has a format where structures are preceded by a byte giving the length of the structure to come.

Within a compound structure, the last fields are sometimes not supplied. The only way to know that reading is complete is to know that all the bytes indicated upstream have been consumed, and that the next structure has started.

Here is an example :

#[test]
fn test_uncomplete_structure() {
    #[derive(Debug, PartialEq)]
    #[deku_derive(DekuRead)]
    struct Data {
        #[deku(read_all)]
        pub blocks: Vec<Block>,
    }
    #[derive(Debug, PartialEq)]
    #[deku_derive(DekuRead)]
    struct Block {
        pub size: u8,
        pub data: BlockType,
    }
    #[derive(Debug, PartialEq)]
    #[deku_derive(DekuRead)]
    #[deku(id_type = "u8")]
    enum BlockType {
        #[deku(id = 1)]
        Block1(Block1),
        #[deku(id = 2)]
        Block2(Block2),
    }
    #[derive(Debug, PartialEq)]
    #[deku_derive(DekuRead)]
    struct Block1 {
        pub field1_size: u8,
        pub field1: u16,
        pub field2_size: u8,
        pub field2: u64,
    }
    #[derive(Debug, PartialEq)]
    #[deku_derive(DekuRead)]
    struct Block2;

    let buffer = &[
        // 1st Block, type 1
        4, // Size: 4
            1, // ID: 1
                2, 0x12, 0x34, // Field 1, size 2
                // No Field 2
        // 2nd Block, type 1
        6, // Size: Y
            1, // ID: 2
                1, 0x56, // Field 1, size 1 (casted into u16)
                2, 0x78, 0x9A // Field 2, size 2
    ];

    let (_rest, val) = Data::from_bytes((buffer, 0)).unwrap();
    assert_eq!(val.blocks.len(), 2);
    assert_eq!(val.blocks[0].size, 4);
    assert_eq!(val.blocks[1].size, 6);
}

How could I handle this case ? Is there a way to handle the second field of the first block ?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions