Skip to content

Support desugaring union into struct for safe field access #1853

@joshlf

Description

@joshlf

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>>>);

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions