sharksforarms / deku

Declarative binary reading and writing: bit-level, symmetric, serialization/deserialization
Apache License 2.0
1.05k stars 54 forks source link

Is there a way to pad by a variable number of bytes? #424

Closed markcorbinuk closed 2 months ago

markcorbinuk commented 3 months ago

Is there a way to add a variable amount of padding so that a data block can always be a multiple of N bytes?

For example, to pad the end of the data block with between 0 and 3 bytes so that 'data + padding' is always a multiple of 4 bytes:

#[derive(Debug, PartialEq, DekuRead, DekuWrite)]
#[deku(endian = "big")]

struct MyUdpMessage {
    .
    .
    .
    #[deku(update = "self.data.len()")]
    count: u16,
    #[deku(count = "count")]
    data: Vec<u8>,
    #[deku(count = "4 - (self.data.len() % 4)")]
    padding: Vec<u8>,
}
sharksforarms commented 3 months ago

Have you tried using the pad_bytes_after attribute?

https://docs.rs/deku/latest/deku/attributes/index.html#pad_bytes_after

markcorbinuk commented 3 months ago

Got it working - thanks.

I'd previously been trying the following which didn't work:

    #[deku(update = "self.data.len()")]
    count: u16,
    #[deku(count = "count", pad_after_bytes = "4 - (self.data.len() % 4)")]
    data: Vec<u8>,

...but this works:

    #[deku(update = "self.data.len()")]
    count: u16,
    #[deku(count = "count", pad_after_bytes = "4 - (count % 4)")]
    data: Vec<u8>,
sharksforarms commented 2 months ago

:+1:

Closing for now.