pub unsafe trait FromBytes { }Expand description
Types for which any byte pattern is valid.
WARNING: Do not implement this trait yourself! Instead, use
#[derive(FromBytes)].
FromBytes types can safely be deserialized from an untrusted sequence of
bytes because any byte sequence corresponds to a valid instance of the type.
FromBytes is ignorant of byte order. For byte order-aware types, see the
byteorder module.
§Safety
If T: FromBytes, then unsafe code may assume that it is sound to treat any
initialized sequence of bytes of length size_of::<T>() as a T. If a type
is marked as FromBytes which violates this contract, it may cause
undefined behavior.
If a type has the following properties, then it is safe to implement
FromBytes for that type:
- If the type is a struct:
- All of its fields must implement
FromBytes
- All of its fields must implement
- 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 (
reprsC,u8,u16,u32,u64,usize,i8,i16,i32,i64, orisize). - The maximum number of discriminants must be used (so that every possible
bit pattern is a valid one). Be very careful when using the
C,usize, orisizerepresentations, as their size is platform-dependent.
§Rationale
§Why isn’t an explicit representation required for structs?
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 FromBytes if:
- its padding is soundly
FromBytes, and - its fields are soundly
FromBytes.
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 FromBytes therefore solely depends on whether
its fields are FromBytes.