Expand description
Safe casting
unsafe
is employed quite a lot to handle all the casting between types.
I’ve attempted to build abstractions here to cover the invariants that must
be maintained for this casting to be safe and sound. These are:
- The bit pattern of the underlying memory must be valid for the target
type. This is provided by the trait
AllBitPatternsValid
. It’s implemented for the relevant primative types. - The alignment requirements of the target type must be satisfied. We use
the
AlignOf
trait to determine the alignment of the target type. We can’t rely onstd::mem::align_of
because we want to use it to constrain input types, and we can’t do that without const generics, which are still an unstable Rust feature. We useAlignedSlice
for byte slices with an alignment attached. Seealigned_bytes
. - The size of the data must match. We check this at run-time. When casting
from slices to
Sized
types we only perform the cast if the sizes match. Similarly when casting between slices we only perform the cast if the input slice size is a multiple of the element size
Structs
Error returned by try_cast_slice_to
and try_cast_slice_to_mut
if the
size of the slice doesn’t match the size of the desination type.
Traits
Get the alignment of a type as a aligned_bytes::Alignment
If a type implements this trait it’s a promise that all representations of underlying memory are valid for this type.
Functions
Safely cast an &AlignedSlice
to &T
where T: Sized
Safely cast a &mut AlignedSlice
to &mut T
where T: Sized