Skip to content

Best way to parse an Option<T> based on the contents of the field itself #312

Answered by sharksforarms
lfrancke asked this question in Q&A
Discussion options

You must be logged in to vote

In this case, map is how I would approach it since you're still reading the value, but transforming the result based on the value. skip, cond and default can be used to completely bypass reading. Here we always want to read.

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

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@lfrancke
Comment options

@sharksforarms
Comment options

Answer selected by lfrancke
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants