Skip to content
Discussion options

You must be logged in to vote

let bytes:&[u8] = unsafe { core::mem::transmute::<&[f32], &[u8]>(sample) };

If you have a slice of samples, I would not recommend this, as directly transmuting between slices is UB if I recall, plus the size will most likely be wrong. Do something like this instead:

pub fn slice_to_u8_slice<T>(slice: &[T]) -> &[u8] {
    unsafe { core::slice::from_raw_parts(slice.as_ptr().cast(), core::mem::size_of_val(slice)) }
}
let bytes = slice_to_u8_slice(&[
    0.0f32, 0.5f32, 1.0f32, 0.5f32, 0.0f32, -0.5f32, -1.0f32, -0.5f32,
]);

If you only want to convert one sample then I would probably create a trait akin to this:

pub trait Buf: Sized {
    fn buf(&self) -> &[u8] {
        unsafe {
         …

Replies: 3 comments

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by roderickvd
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
4 participants
Converted from issue

This discussion was converted from issue #396 on August 17, 2026 20:37.