Trait half::slice::HalfBitsSliceExt
source · [−]pub trait HalfBitsSliceExt: SealedHalfBitsSlice {
fn reinterpret_cast<H>(&self) -> &[H]ⓘNotable traits for &'_ [u8]impl<'_> Read for &'_ [u8]impl<'_> Write for &'_ mut [u8]
where
H: SealedHalf;
fn reinterpret_cast_mut<H>(&mut self) -> &mut [H]ⓘNotable traits for &'_ [u8]impl<'_> Read for &'_ [u8]impl<'_> Write for &'_ mut [u8]
where
H: SealedHalf;
}
Expand description
Extensions to [u16]
slices to support reinterpret operations.
This trait is sealed and cannot be implemented outside of this crate.
Required Methods
Reinterprets a slice of u16
bits as a slice of f16
or bf16
numbers.
H
is the type to cast to, and must be either the f16
or bf16
type.
This is a zero-copy operation. The reinterpreted slice has the same lifetime and memory
location as self
.
Examples
let int_buffer = [f16::from_f32(1.).to_bits(), f16::from_f32(2.).to_bits(), f16::from_f32(3.).to_bits()];
let float_buffer: &[f16] = int_buffer.reinterpret_cast();
assert_eq!(float_buffer, [f16::from_f32(1.), f16::from_f32(2.), f16::from_f32(3.)]);
// You may have to specify the cast type directly if the compiler can't infer the type.
// The following is also valid in Rust.
let typed_buffer = int_buffer.reinterpret_cast::<f16>();
Reinterprets a mutable slice of u16
bits as a mutable slice of f16
or bf16
numbers.
H
is the type to cast to, and must be either the f16
or bf16
type.
This is a zero-copy operation. The transmuted slice has the same lifetime as the original,
which prevents mutating self
as long as the returned &mut [f16]
is borrowed.
Examples
let mut int_buffer = [f16::from_f32(1.).to_bits(), f16::from_f32(2.).to_bits(), f16::from_f32(3.).to_bits()];
{
let float_buffer: &mut [f16] = int_buffer.reinterpret_cast_mut();
assert_eq!(float_buffer, [f16::from_f32(1.), f16::from_f32(2.), f16::from_f32(3.)]);
// Mutating the f16 slice will mutating the original
float_buffer[0] = f16::from_f32(0.);
}
// Note that we need to drop float_buffer before using int_buffer again or we will get a borrow error.
assert_eq!(int_buffer, [f16::from_f32(0.).to_bits(), f16::from_f32(2.).to_bits(), f16::from_f32(3.).to_bits()]);
// You may have to specify the cast type directly if the compiler can't infer the type.
// The following is also valid in Rust.
let typed_buffer = int_buffer.reinterpret_cast_mut::<f16>();