Function bytemuck::must_cast_slice

source ·
pub fn must_cast_slice<A: NoUninit, B: AnyBitPattern>(a: &[A]) -> &[B]
Available on crate feature must_cast only.
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 between a ZST and a non-ZST.

§Examples

let indicies: &[u16] = &[1, 2, 3];
// compiles:
let bytes: &[u8] = bytemuck::must_cast_slice(indicies);
// 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);