[−][src]Trait bytes_cast::BytesCast
Marks a type as safe to interpret from bytes without copying.
Safety
For a type to implement this trait:
- All bit patterns must be valid. (This excludes
bool, enums, etc.) - There must not be an alignment requirement. (
align_of() == 1)
Deriving
Instead of writing unsafe impl blocks this trait should be derived.
#[derive(BytesCast)] on a type definition invokes a procedural macro
that implements the trait after checking that the type:
- Is a
struct - Is not generic
- Has a
#[repr(C)]or#[repr(transparent)]attribute - Has
align_of() == 1 - Only has fields whose respective type implement
BytesCast.
Failing any of these checks causes a compile-time error.
This excludes some types that could implement BytesCast without memory safety
issue:
- By choice: disabling field reordering with
repris not about memory safety but making memory layout / field offsets predictable. - By necessity: generics would make
align_ofpotentially depend on type parameters and not possible to statically check at the struct definition site.
Finally, mandating BytesCast for all fields means they also have align_of() == 1 and therefore the struct does not have any padding.
This makes memory layout / field offsets easier to reason about.
Provided methods
pub fn from_bytes(bytes: &[u8]) -> Result<(&Self, &[u8]), FromBytesError>[src]
Interpret the start of the given slice of bytes as reference to this type.
If the given input is large enough, returns a tuple of the new reference and the remaining of the bytes.
pub fn slice_from_bytes(
bytes: &[u8],
slice_len: usize
) -> Result<(&[Self], &[u8]), FromBytesError>[src]
bytes: &[u8],
slice_len: usize
) -> Result<(&[Self], &[u8]), FromBytesError>
Interpret the start of the given slice of bytes as slice of this type.
If the given input is large enough, returns a tuple of the new slice and the remaining of the bytes.