Conditionally parse past the end of the file #313
-
I have an optional field right at the end of my file. I'd like deku to attempt to read a byte and if that exists continue as normal, if not then end it right there. I wasn't able to find a combination of attributes that works here but there's a good chance I might be missing something obvious. Thank you! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
The use deku::prelude::*;
use std::convert::{TryFrom, TryInto};
#[derive(Debug, PartialEq, DekuRead, DekuWrite)]
struct DekuTest {
field_a: u8,
#[deku(cond = "!deku::rest.is_empty()")]
field_b: Option<u8>,
}
fn main() {
{
let test_data: &[u8] = [
0xAB,
]
.as_ref();
let test_deku = DekuTest::try_from(test_data).unwrap();
assert_eq!(
DekuTest {
field_a: 0xAB,
field_b: None,
},
test_deku
);
let test_deku: Vec<u8> = test_deku.try_into().unwrap();
assert_eq!(test_data.to_vec(), test_deku);
}
{
let test_data: &[u8] = [
0xAB,
0xBA,
]
.as_ref();
let test_deku = DekuTest::try_from(test_data).unwrap();
assert_eq!(
DekuTest {
field_a: 0xAB,
field_b: Some(0xBA),
},
test_deku
);
let test_deku: Vec<u8> = test_deku.try_into().unwrap();
assert_eq!(test_data.to_vec(), test_deku);
}
} |
Beta Was this translation helpful? Give feedback.
The
cond
attribute is what you're looking for. You can checkdeku::rest
which provides the remaining data to be read, here's an example: