Derive Macro bytemuck_derive::Pod

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

Derive the Pod trait for a struct

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

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

  • All fields in the struct must implement Pod
  • The struct must be #[repr(C)] or #[repr(transparent)]
  • The struct must not contain any padding bytes
  • The struct contains no generic parameters, if it is not #[repr(transparent)]

§Examples

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

#[derive(Copy, Clone, Pod, Zeroable)]
#[repr(transparent)]
struct Generic<A, B> {
  a: A,
  b: PhantomData<B>,
}

If the struct is generic, it must be #[repr(transparent)] also.

#[derive(Copy, Clone, Pod, Zeroable)]
#[repr(C)] // must be `#[repr(transparent)]`
struct Generic<A> {
  a: A,
}

If the struct is generic and #[repr(transparent)], then it is only Pod when all of its generics are Pod, not just its fields.

#[derive(Copy, Clone, Pod, Zeroable)]
#[repr(transparent)]
struct Generic<A, B> {
  a: A,
  b: PhantomData<B>,
}

let _: u32 = bytemuck::cast(Generic { a: 4u32, b: PhantomData::<u32> });
struct NotPod;

let _: u32 = bytemuck::cast(Generic { a: 4u32, b: PhantomData::<NotPod> });