How are optional values supposed to work? #278
-
I am confused about the behaviour of Why is the expected size different when deserializing? I've put together a code demonstration to show what I mean: use binrw::{BinReaderExt, BinWrite};
#[binrw::binrw]
#[brw(little)]
#[derive(Debug, Eq, PartialEq)]
pub struct MyStruct {
value: u32,
}
#[binrw::binrw]
#[brw(little)]
#[derive(Debug, Eq, PartialEq)]
pub struct Demo {
some_value: Option<MyStruct>,
none_value: Option<MyStruct>,
}
fn test(demo: Demo) -> Result<bool, binrw::error::Error> {
//write to data
let mut data = Vec::new();
let mut cursor = std::io::Cursor::new(&mut data);
demo.write_le(&mut cursor)?;
cursor.set_position(0);
//read from data
let roundtrip_demo: Demo = cursor.read_le()?;
//return whether data matches
Ok(roundtrip_demo == demo)
}
fn main() -> Result<(), binrw::error::Error> {
let demo1 = Demo {
some_value: Some(MyStruct { value: 1 }),
none_value: Some(MyStruct { value: 2 }),
};
println!("demo1 result {:?}", test(demo1));
let demo2 = Demo {
some_value: Some(MyStruct { value: 1 }),
none_value: None,
};
println!("demo2 result {:?}", test(demo2));
Ok(())
} This is the output:
Is there documentation for this that I failed to find? Am I missing something that should be a compiler error when it's not there? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
https://docs.rs/binrw/latest/binrw/docs/attribute/index.html#conditional-values I think you always need to link the Option to a condition based on a previosly parsed field. How else would it be possible to decide if it is okay, that there is no value or simply a parsing error? In reality you would most likely use a separate field with either a version or lenght to decide how many bytes you need to parse |
Beta Was this translation helpful? Give feedback.
https://docs.rs/binrw/latest/binrw/docs/attribute/index.html#conditional-values
I think you always need to link the Option to a condition based on a previosly parsed field. How else would it be possible to decide if it is okay, that there is no value or simply a parsing error?
In reality you would most likely use a separate field with either a version or lenght to decide how many bytes you need to parse