Derive Macro zerocopy::AsBytes

source ·
#[derive(AsBytes)]
Expand description

Analyzes whether a type is AsBytes.

This derive analyzes, at compile time, whether the annotated type satisfies the safety conditions of AsBytes and implements AsBytes if it is sound to do so. This derive can be applied to structs, enums, and unions; e.g.:

#[derive(AsBytes)]
#[repr(C)]
struct MyStruct {
    ...
}

#[derive(AsBytes)]
#[repr(u8)]
enum MyEnum {
    ...
}

#[derive(AsBytes)]
#[repr(C)]
union MyUnion {
    ...
}

§Error Messages

Due to the way that the custom derive for AsBytes is implemented, you may get an error like this:

error[E0277]: the trait bound `HasPadding<Foo, true>: ShouldBe<false>` is not satisfied
  --> lib.rs:23:10
   |
 1 | #[derive(AsBytes)]
   |          ^^^^^^^ the trait `ShouldBe<false>` is not implemented for `HasPadding<Foo, true>`
   |
   = help: the trait `ShouldBe<VALUE>` is implemented for `HasPadding<T, VALUE>`

This error indicates that the type being annotated has padding bytes, which is illegal for AsBytes types. Consider reducing the alignment of some fields by using types in the byteorder module, adding explicit struct fields where those padding bytes would be, or using #[repr(packed)]. See the Rust Reference’s page on type layout for more information about type layout and padding.

§Analysis

This section describes, roughly, the analysis performed by this derive to determine whether it is sound to implement AsBytes for a given type. Unless you are modifying the implementation of this derive, or attempting to manually implement AsBytes for a type yourself, you don’t need to read this section.

If a type has the following properties, then this derive can implement AsBytes for that type:

  • If the type is a struct:
    • It must have a defined representation (repr(C), repr(transparent), or repr(packed)).
    • All of its fields must be AsBytes.
    • Its layout must have no padding. This is always true for repr(transparent) and repr(packed). For repr(C), see the layout algorithm described in the Rust Reference.
  • If the type is an enum:
    • It must be a C-like enum (meaning that all variants have no fields).
    • It must have a defined representation (reprs C, u8, u16, u32, u64, usize, i8, i16, i32, i64, or isize).
  • The type must not contain any UnsafeCells (this is required in order for it to be sound to construct a &[u8] and a &T to the same region of memory). The type may contain references or pointers to UnsafeCells so long as those values can themselves be initialized from zeroes (AsBytes is not currently implemented for, e.g., Option<&UnsafeCell<_>>, but it could be one day).

This analysis is subject to change. Unsafe code may only rely on the documented safety conditions of FromBytes, and must not rely on the implementation details of this derive.