Skip to content

Implement a derive macro#14

Open
jac3km4 wants to merge 2 commits intoandylokandy:masterfrom
jac3km4:derive-macro
Open

Implement a derive macro#14
jac3km4 wants to merge 2 commits intoandylokandy:masterfrom
jac3km4:derive-macro

Conversation

@jac3km4
Copy link
Copy Markdown

@jac3km4 jac3km4 commented Feb 10, 2024

Another PR with some of my changes.
This adds derive macros for TryRead and TryWrite.

Some notes:

  • supports borrowed types as long as the target of the macro has exactly one lifetime
  • doesn't support enums, only structs
  • by default it generates impls where the Ctx is set to Endian, this is the most ergonomic option, but it could be made more flexible with a macro attribute in the future
  • there's a #[byte(read_ctx/write_ctx = ...)] field attribute that allows specifying custom context per field, the context expression can use values of preceding fields in the struct
  • the resulting impl is a bit awkward to use sometimes because try_write is defined to take self by value, which necessitates cloning - this could be worked around by having the derive generate an impl for &Self, but that'll not work when you nest structs, I think the best option would be to re-define TryWrite to take &self instead of self
  • this PR would be pretty easy to extend to derive the Measure trait I've added in another PR

Usage

#[derive(Debug, Clone, PartialEq, TryWrite, TryRead)]
struct Named<'a> {
    id: u32,
    timestamp: f64,
    #[byte(read_ctx = Str::Delimiter(0), write_ctx = NONE)]
    str: &'a str,
}

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

Successfully merging this pull request may close these issues.

1 participant