Trait zerocopy::AsBytes

source ·
pub unsafe trait AsBytes { }
Expand description

Types which are safe to treat as an immutable byte slice.

AsBytes types can be safely viewed as a slice of bytes. In particular, this means that, in any valid instance of the type, none of the bytes of the instance are uninitialized. This precludes the following types:

  • Structs with internal padding
  • Unions in which not all variants have the same length

Safety

If T: AsBytes, then unsafe code may assume that it is sound to treat any instance of the type as an immutable [u8] of the appropriate length. If a type is marked as AsBytes which violates this contract, it may cause undefined behavior.

If a type has the following properties, then it is safe to implement AsBytes for that type:

  • If the type is a struct:
    • It must be repr(C) or repr(transparent)
    • If it is repr(C), its layout must have no inter-field padding (this can be accomplished either by using repr(packed) or by manually adding padding fields)
    • All of its fields must implement AsBytes
  • If the type is an enum:
    • It must be a C-like enum (meaning that all variants have no fields)
    • It must be repr(u8), repr(u16), repr(u32), or repr(u64)

Implementations on Foreign Types

Implementors