Support desugaring union into struct for safe field access
- Dominant language
- Rust
- Stars
- 2.6k
- Forks
- 179
- Avg merge
- 1d 19h
- Merged PRs (30d)
- 29
Description
*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`.
```rust
#[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.:
```rust
#[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:
```rust
// This could live in `zerocopy::util::macro_util`
union UnionInner {
t: T,
rest: Rest,
}
// Generated by the proc macro attribute
#[repr(transparent)]
struct Foo(AlignedBytes>>);
```
Contributor guide
Assessment
This issue has not been assessed yet.