binrw icon indicating copy to clipboard operation
binrw copied to clipboard

Accessing bytes representation from `calc` directive

Open Holzhaus opened this issue 2 years ago • 1 comments

Sometimes it's necessary to have access the serialized bytes instead of the deserialized data, e.g. for calculating a checksum over parts of the serialized data:

#[binread]
#[brw(big)]
struct Foo {
    field1: u32,
    field2: u16,
    field3: u16,
    field4: u32,

    /// CRC16 checksum over bytes of fields 1 - 4
    #[br(temp, assert(crc16_checksum == ???)]
    #[bw(calc = ???)]
    crc16_checksum: u16,
}

It would be great if binrw provided some way to do that.

Holzhaus avatar Feb 25 '22 21:02 Holzhaus

You could read the bytes into a vec, seek back, and then read the fields using #[br(restore_position)]. however, I'm not sure what to do when writing.

kitlith avatar Feb 26 '22 21:02 kitlith