How to use deku::input #323
-
Hello, first of all thanks for the crate! struct WriteBlock {
checksum: u8,
status: u8,
installdate: Date,
...
} I can successfully read the fields, but now I want to check whether the checksum is valid, maybe using #[deku(assert_eq = "calculate_checksum(deku::input, 200, 32)")] where 200 is the offset of the write block and 32 is the block size in bytes. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
The following example might help you: use deku::bitvec::{BitSlice, Msb0};
use deku::prelude::*;
#[derive(DekuRead, Debug, PartialEq, Eq)]
struct Block {
other: u16,
#[deku(assert_eq = "Self::calculate_checksum(deku::rest, 3)")]
checksum: u8,
field_a: u8,
field_b: u8,
field_c: u8,
}
impl Block {
pub fn calculate_checksum(deku_rest: &BitSlice<u8, Msb0>, block_size: usize) -> u8 {
let bytes: &[u8] = deku_rest.domain().region().unwrap().1;
bytes.iter().take(block_size).sum::<u8>()
}
}
fn main() {
let block = Block {
other: 0xffff,
checksum: 0b0000_0111,
field_a: 0b0000_0001,
field_b: 0b0000_0010,
field_c: 0b0000_0100,
};
let bytes = &[
0xff,
0xff,
0b0000_0111,
0b0000_0001,
0b0000_0010,
0b0000_0100,
];
let test_block = Block::from_bytes((bytes, 0)).unwrap().1;
assert_eq!(block, test_block);
} |
Beta Was this translation helpful? Give feedback.
The following example might help you: