Derive Macro zerocopy::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)]
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 be C-like (meaning that all variants have no fields) and it must have a variant with a discriminant of 0. See the reference for a description of how discriminant values are chosen.

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:

  1. its padding is soundly FromZeros, and
  2. 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.