Derive Macro FromZeros
#[derive(FromZeros)]
Expand description
Analyzes whether a type is FromZeros
.
This derive analyzes, at compile time, whether the annotated type satisfies
the safety conditions of FromZeros
and implements FromZeros
if it is
sound to do so. This derive can be applied to structs, enums, and unions;
e.g.:
#[derive(FromZeros)]
struct MyStruct {
...
}
#[derive(FromZeros)]
#[repr(u8)]
enum MyEnum {
...
}
#[derive(FromZeros, Immutable)]
union MyUnion {
...
}
§Analysis
This section describes, roughly, the analysis performed by this derive to
determine whether it is sound to implement FromZeros
for a given type.
Unless you are modifying the implementation of this derive, or attempting to
manually implement FromZeros
for a type yourself, you don’t need to read
this section.
If a type has the following properties, then this derive can implement
FromZeros
for that type:
- If the type is a struct, all of its fields must be
FromZeros
. - If the type is an enum:
- It must have a defined representation (
repr
sC
,u8
,u16
,u32
,u64
,usize
,i8
,i16
,i32
,i64
, orisize
). - It must have a variant with a discriminant/tag of
0
, and its fields must beFromZeros
. See the reference for a description of discriminant values are specified. - The fields of that variant must be
FromZeros
.
- It must have a defined representation (
This analysis is subject to change. Unsafe code may only rely on the
documented safety conditions of FromZeros
, and must not rely on the
implementation details of this derive.
§Why isn’t an explicit representation required for structs?
Neither this derive, nor the safety conditions of FromZeros
, requires
that structs are marked with #[repr(C)]
.
Per the Rust reference,
The representation of a type can change the padding between fields, but does not change the layout of the fields themselves.
Since the layout of structs only consists of padding bytes and field bytes,
a struct is soundly FromZeros
if:
- its padding is soundly
FromZeros
, and - its fields are soundly
FromZeros
.
The answer to the first question is always yes: padding bytes do not have any validity constraints. A discussion of this question in the Unsafe Code Guidelines Working Group concluded that it would be virtually unimaginable for future versions of rustc to add validity constraints to padding bytes.
Whether a struct is soundly FromZeros
therefore solely depends on whether
its fields are FromZeros
.