Yeah, I did the same until I thought about it further. Maybe it will not be a practical problem ever, though.
But for now (as also said in the original thread), I prefer to rely on std::slice::from_raw_parts
, I think. That is part of stable Rust:
fn trns(slice: &[u16]) -> &[u8] {
let ptr = slice as *const [u16] as *const [u8];
unsafe { &*ptr }
}
fn safer_trns(slice: &[u16]) -> &[u8] {
unsafe {
std::slice::from_raw_parts(
slice as *const [u16] as *const u8,
slice.len(),
)
}
}
fn useful_trns(slice: &[u16]) -> &[u8] {
unsafe {
std::slice::from_raw_parts(
slice as *const [u16] as *const u8,
std::mem::size_of_val(slice),
)
}
}
fn main() {
let x = [1, 2, 3, 4, 5];
let y1 = trns(&x);
let y2 = safer_trns(&x);
let y3 = useful_trns(&x);
println!("{y1:?}");
println!("{y2:?}");
println!("{y3:?}");
}
Output:
[1, 0, 2, 0, 3]
[1, 0, 2, 0, 3]
[1, 0, 2, 0, 3, 0, 4, 0, 5, 0]