Best way to parse an Option<T> based on the contents of the field itself #312
-
|
I have a field like this: I have a feeling that some combination of Thank you for this library and your work on it! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
In this case, use deku::prelude::*;
use std::convert::{TryFrom, TryInto};
#[derive(Debug, PartialEq, DekuRead, DekuWrite)]
struct DekuTest {
#[deku(map = "|field: i32| -> Result<_, DekuError> { if field != -2147483647 { Ok(Some(field)) } else { Ok(None) } }")]
retainer_id: Option<i32>
}
fn main() {
{
let test_data = (-2147483647i32).to_le_bytes();
let test_deku = DekuTest::try_from(test_data.as_slice()).unwrap();
assert_eq!(
DekuTest {
retainer_id: None,
},
test_deku
);
let test_deku: Vec<u8> = test_deku.try_into().unwrap();
assert!(test_deku.is_empty());
}
{
let test_data = (-12345i32).to_le_bytes();
let test_deku = DekuTest::try_from(test_data.as_slice()).unwrap();
assert_eq!(
DekuTest {
retainer_id: Some(-12345),
},
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.
In this case,
mapis how I would approach it since you're still reading the value, but transforming the result based on the value.skip,condanddefaultcan be used to completely bypass reading. Here we always want to read.