jam1garner / binrw

A Rust crate for helping parse and rebuild binary data using ✨macro magic✨.
https://binrw.rs
MIT License
585 stars 35 forks source link

Question: How to read N bytes into an Vector of complex objects? #195

Closed Mimoja closed 1 year ago

Mimoja commented 1 year ago

I have situation where I have (simplified)


#[derive(BinRead, BinWrite, Debug, Clone)]
pub struct EDK2VariableStore {
    pub size_in_bytes: u32,

    #[br(align_after = 4)]
    pub variables: Vec<VariableEntry>,

   pub something_else :u32,
    ....
}

#[derive(BinRead, BinWrite, Debug, Clone)]
pub struct VariableEntry {
   ...
    pub datalen: u32,
    #[br(count = datalen)]
    pub data: Vec<u8>,
}

Where the sum bytes consumed for Vec<VariableEntries> is size_in_bytes. (each VariableEntry aligned to 4 byte boundary)

I would assume I can do this with something from the helpers, but I can not really figure out how.

I would like something to the python equivalent

    while size != 0:
            data_size = file.read32()
            data = file.read(data_size)
            # append to variable list
            size = size - ( 4  + data_size)