I refused transmutation. *mut (raw pointers) in Rust are very similar to C pointers, so this was easy:
#[repr(C, packed)] // necessary #[derive(Debug)] // not necessary struct my_struct { foo: u16, bar: u8, } fn main() { let v: Vec<u8> = vec![1, 2, 3]; let buffer = v.as_slice(); let mut s_safe: Option<&my_struct> = None; let c_buf = buffer.as_ptr(); let s = c_buf as *mut my_struct; unsafe { // took these out of the unsafe block, as Peter suggested // let c_buf = buffer.as_ptr(); // let s = c_buf as *mut my_struct; let ref s2 = *s; s_safe = Some(s2); } println!("here is the struct: {:?}", s_safe.unwrap()); }
Of course, the unsafe tag is not joking. But the way I use it, I know that my buffer is full and takes proper precautions related to the content later.
source share