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

Support desugaring union into struct for safe field access #1853

Open
joshlf opened this issue Oct 8, 2024 · 0 comments
Open

Support desugaring union into struct for safe field access #1853

joshlf opened this issue Oct 8, 2024 · 0 comments

Comments

@joshlf
Copy link
Member

joshlf commented Oct 8, 2024

Credit to @kupiakos for this idea

Requirements

  • Should be able to generate safe accessors
  • Should be able to implement FromBytes/IntoBytes
  • Also TryFromBytes fields? Safe field accessor is still safe, but now fallible
    • How do we tell the attribute which fields are only TryFromBytes?
  • Should be able to codegen most of this based on a macro or proc macro attribute

Details

A macro or proc macro attribute that permits you to write a union. It is assumed that all fields are IntoBytes. It is assumed that all fields are FromBytes unless explicitly annotated as TryFromBytes.

#[zerocopy(union)]
union Foo {
    // No annotation => assumes this is FromBytes
    a: A,
    #[zerocopy(TryFromBytes)]
    b: B,
}

This desugars into a [u8; N] (wrapped in a type which guarantees the appropriate alignment) which provides safe accessor methods, e.g.:

#[repr(transparent)]
struct Foo(...);

impl Foo {
    // A: FromBytes
    fn a(&self) -> &A {
        
    }
    
    // B: TryFromBytes
    fn b(&self) -> Option<&B> {
        
    }
}

The internals could be represented, for example, as:

// This could live in `zerocopy::util::macro_util`
union UnionInner<T, Rest> {
    t: T,
    rest: Rest,
}

// Generated by the proc macro attribute
#[repr(transparent)]
struct Foo(AlignedBytes<UnionInner<A, UnionInner<B, C>>>);
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

1 participant