sharksforarms / deku

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

How to read repeatedly? #300

Closed goldwind-ting closed 1 year ago

goldwind-ting commented 1 year ago

For example the data is like:

6bits-16bits-6bits-16bits-6bits-16bits

#[derive(Debug, PartialEq, DekuRead, DekuWrite)]
struct DekuTest {
    #[deku(bits = "6")]
    field_a: u8,
    #[deku(bits = 16)]
    field_b: u16,
}

And how to read the bytes to a Vec<DekuTest>?

wcampbell0x2a commented 1 year ago

The following should work for you. from_bytes makes the abstraction easy; keeping track of byte array and the offset from previous read:

use deku::prelude::*;

#[derive(Debug, PartialEq, DekuRead, DekuWrite)]
struct DekuTest {
    #[deku(bits = "6")]
    field_a: u8,
    field_b: u16,
}

fn main() {
    let bytes = [
        0b11111100, 0b00000000, 0b00000011, 0b11110000, 0b00000000, 0b00001111,
    ]
    .as_slice();

    let mut ret = vec![];
    let mut rest = (bytes, 0);
    while let Ok((local_rest, t)) = DekuTest::from_bytes(rest) {
        rest = local_rest;
        ret.push(t);
    }
    println!("{:02x?}", ret);
    // [DekuTest { field_a: 3f, field_b: 00 }, DekuTest { field_a: 3f, field_b: 00 }]
}
goldwind-ting commented 1 year ago

The following should work for you. from_bytes makes the abstraction easy; keeping track of byte array and the offset from previous read:

use deku::prelude::*;

#[derive(Debug, PartialEq, DekuRead, DekuWrite)]
struct DekuTest {
    #[deku(bits = "6")]
    field_a: u8,
    field_b: u16,
}

fn main() {
    let bytes = [
        0b11111100, 0b00000000, 0b00000011, 0b11110000, 0b00000000, 0b00001111,
    ]
    .as_slice();

    let mut ret = vec![];
    let mut rest = (bytes, 0);
    while let Ok((local_rest, t)) = DekuTest::from_bytes(rest) {
        rest = local_rest;
        ret.push(t);
    }
    println!("{:02x?}", ret);
    // [DekuTest { field_a: 3f, field_b: 00 }, DekuTest { field_a: 3f, field_b: 00 }]
}

Thanks!