Derive Macro bytemuck::Zeroable

source ·
#[derive(Zeroable)]
{
    // Attributes available to this derive:
    #[zeroable]
}
Expand description

Derive the Zeroable trait for a struct

The macro ensures that the struct follows all the the safety requirements for the Zeroable trait.

The following constraints need to be satisfied for the macro to succeed

  • All fields in the struct must to implement Zeroable

Example

#[derive(Copy, Clone, Zeroable)]
#[repr(C)]
struct Test {
  a: u16,
  b: u16,
}

Custom bounds

Custom bounds for the derived Zeroable impl can be given using the #[zeroable(bound = "")] helper attribute.

Using this attribute additionally opts-in to “perfect derive” semantics, where instead of adding bounds for each generic type parameter, bounds are added for each field’s type.

Examples

#[derive(Clone, Zeroable)]
#[zeroable(bound = "")]
struct AlwaysZeroable<T> {
  a: PhantomData<T>,
}

AlwaysZeroable::<std::num::NonZeroU8>::zeroed();
#[derive(Clone, Zeroable)]
#[zeroable(bound = "T: Copy")]
struct ZeroableWhenTIsCopy<T> {
  a: PhantomData<T>,
}

ZeroableWhenTIsCopy::<String>::zeroed();

The restriction that all fields must be Zeroable is still applied, and this is enforced using the mentioned “perfect derive” semantics.

#[derive(Clone, Zeroable)]
#[zeroable(bound = "")]
struct ZeroableWhenTIsZeroable<T> {
  a: T,
}
ZeroableWhenTIsZeroable::<u32>::zeroed();
ZeroableWhenTIsZeroable::<String>::zeroed();