Skip to content

Best way to convert between Option<T> and sentinel value for reading AND writing. #421

Answered by wcampbell0x2a
Lehona asked this question in Q&A
Discussion options

You must be logged in to vote

I think I would just use my own enum:

use deku::prelude::*;
use dbg_hex::dbg_hex;

#[derive(Debug, DekuWrite, DekuRead)]
#[deku(type = "u32")]
enum Value {
    #[deku(id = 0xffffffff)]
    None,
    #[deku(id_pat = "_")]
    Some(u32)
}

fn main() {
    let data = [0xff, 0xff, 0xff, 0xff];
    let v = Value::from_bytes((&data, 0)).unwrap().1;
    assert_eq!(data, &*v.to_bytes().unwrap());
    dbg_hex!(v);
    let data = [0x01, 0x02, 0x03, 0x04];
    let v = Value::from_bytes((&data, 0)).unwrap().1;
    assert_eq!(data, &*v.to_bytes().unwrap());
    dbg_hex!(v);
}
[examples/312.rs:17:5] v = None
[examples/312.rs:21:5] v = Some(
    0x4030201,
)

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by wcampbell0x2a
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