[][src]Module gvariant::casting

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 on std::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 use AlignedSlice for byte slices with an alignment attached. See aligned_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

WrongSize

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

AlignOf

Get the alignment of a type as a aligned_bytes::Alignment

AllBitPatternsValid

If a type implements this trait it's a promise that all representations of underlying memory are valid for this type. That means any struct must be repr(C) or ``repr(transparent)and be made up of members that are alsoAllBitPatternsValid` and have no padding.

Functions

try_cast_slice_to

Safely cast an &AlignedSlice to &T where T: Sized

try_cast_slice_to_mut

Safely cast a &mut AlignedSlice to &mut T where T: Sized