pub unsafe trait BytesCast {
// Provided methods
fn from_bytes(bytes: &[u8]) -> Result<(&Self, &[u8]), FromBytesError>
where Self: Sized { ... }
fn slice_from_bytes(
bytes: &[u8],
slice_len: usize,
) -> Result<(&[Self], &[u8]), FromBytesError>
where Self: Sized { ... }
fn as_bytes(&self) -> &[u8] { ... }
}
Expand description
Marks a type as safe to interpret from and to bytes without copying.
§Safety
For a type to implement this trait:
- All initialized bit patterns must be valid. (This excludes
bool
, enums, etc.) - There must not be an alignment requirement. (
align_of() == 1
) - There must be no padding or otherwise uninitialized bytes
§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
repr
is not about memory safety but making memory layout / field offsets predictable. - By necessity: generics would make
align_of
potentially depend on type parameters and not possible to statically check at the struct definition site.
Provided Methods§
Sourcefn from_bytes(bytes: &[u8]) -> Result<(&Self, &[u8]), FromBytesError>where
Self: Sized,
fn from_bytes(bytes: &[u8]) -> Result<(&Self, &[u8]), FromBytesError>where
Self: Sized,
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.
Sourcefn slice_from_bytes(
bytes: &[u8],
slice_len: usize,
) -> Result<(&[Self], &[u8]), FromBytesError>where
Self: Sized,
fn slice_from_bytes(
bytes: &[u8],
slice_len: usize,
) -> Result<(&[Self], &[u8]), FromBytesError>where
Self: Sized,
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.