Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cant "count" from Some(field) directly - need as_ref().unwrap() #407

Open
sempervictus opened this issue Jan 19, 2024 · 1 comment
Open

Comments

@sempervictus
Copy link

When writing

...
    #[deku(skip, cond = "*status != vec![0xFA,0xFF] || hdr.sub_packets < 3")]
    svc_dsc: Option<SvcDesc>,
    #[deku(count = "svc_dsc.length")]
    #[deku(skip, cond = "*status != vec![0xFA,0xFF] || hdr.sub_packets < 3")]
    svc_name: Vec<u8>,
...

the compiler can't figure out how to reference the length struct member from svc_dsc because it's wrapped in an Option.

error[E0609]: no field `length` on type `&Option<SvcDesc>`
   --> src/ano.rs:106:20
    |
106 |     #[deku(count = "svc_dsc.length")]
    |                    ^^^^^^^^^^^^^^^^

Since the macro notation doesn't allow use of

    #[deku(skip, cond = "*status != vec![0xFA,0xFF] || hdr.sub_packets < 3")]
    svc_dsc: Option<SvcDesc>,
    #[deku(count = "Some(svc_dsc).length")]
    #[deku(skip, cond = "*status != vec![0xFA,0xFF] || hdr.sub_packets < 3")]
    svc_name: Vec<u8>,

either due to

error[E0609]: no field `length` on type `Option<&Option<SvcDesc>>`
   --> src/ano.rs:106:20
    |
106 |     #[deku(count = "Some(svc_dsc).length")]
    |                    ^^^^^^^^^^^^^^^^^^^^^^

It doesn't like getting dereferenced or unwrapped due to the borrow checker either 😄.

I finally did figure out that you can unwrap the reference to the Option by writing this as

    #[deku(skip, cond = "*status != vec![0xFA,0xFF] || hdr.sub_packets < 3")]
    svc_dsc: Option<SvcDesc>,
    #[deku(count = "svc_dsc.as_ref().unwrap().length")]
    #[deku(skip, cond = "*status != vec![0xFA,0xFF] || hdr.sub_packets < 3")]
    svc_name: Vec<u8>,

but it was somewhat confounding there for a bit.
Think it's worth looking at some sugar to handle options directly or at least documenting the access pattern for newcomers.

@wcampbell0x2a
Copy link
Collaborator

Oh interesting, if this isn't in a deku derive macro you get a better error:

error[E0609]: no field `len` on type `Option<Len>`
  --> examples/example.rs:16:7
   |
16 |     a.len;
   |       ^^^ unknown field
   |
help: one of the expressions' fields has a field of the same name
   |
16 |     a.unwrap().len;
   |       +++++++++

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants