bytemuck

Function must_cast_slice

Source
pub const fn must_cast_slice<A: NoUninit, B: AnyBitPattern>(a: &[A]) -> &[B]
Expand description

Convert &[A] into &[B] (possibly with a change in length) if infalliable, or fail to compile.

  • input.as_ptr() as usize == output.as_ptr() as usize
  • input.len() * size_of::<A>() == output.len() * size_of::<B>()

§Failure

  • If the target type has a greater alignment requirement.
  • If the target element type doesn’t evenly fit into the the current element type (eg: 3 u16 values is 1.5 u32 values, so that’s a failure).
  • Similarly, you can’t convert from a non-ZST to a ZST (e.g. 3 u8 values is not any number of () values).

§Examples

let indicies: &[u16] = &[1, 2, 3];
// compiles:
let bytes: &[u8] = bytemuck::must_cast_slice(indicies);
let zsts: &[()] = &[(), (), ()];
// compiles:
let bytes: &[u8] = bytemuck::must_cast_slice(zsts);
// fails to compile (bytes.len() might not be a multiple of 2):
let byte_pairs : &[[u8; 2]] = bytemuck::must_cast_slice(bytes);
// fails to compile (alignment requirements increased):
let indicies : &[u16] = bytemuck::must_cast_slice(byte_pairs);
let bytes: &[u8] = &[];
// fails to compile: (bytes.len() might not be 0)
let zsts: &[()] = bytemuck::must_cast_slice(bytes);