Convert u8 buffer to structure in Rust

I have a byte buffer of unknown size, and I want to create a local struct variable that points to the memory of the beginning of the buffer. Following what I would do in C, I tried many different things in Rust and kept getting errors. This is my last attempt:

use std::mem::{transmute, size_of}; #[repr(C, packed)] struct my_struct { foo: u16, bar: u8, } fn main() { let v: Vec<u8> = vec![1, 2, 3]; let buffer = v.as_slice(); let s: my_struct = unsafe { transmute(buffer[..size_of::<my_struct>()]) }; } 

I get an error with the following messages:

  • flag std::marker::Sized not implemented for [u8]
  • note: [u8] does not have a constant size known at compile time
  • Note: std::mem::transmute is required
+5
source share
2 answers

You can use std::ptr::read and std::ptr::write to directly read / write objects in place (there are other methods in checking std::ptr ).

In your case, it is as simple as:

 fn main() { let v: Vec<u8> = vec![1, 2, 3]; let s: MyStruct = unsafe { std::ptr::read(v.as_ptr() as *const _) }; println!("here is the struct: {:?}", s); } 

I personally recommend that you wrap it in a reusable fashion and do a length check in the source buffer before trying to read.

+6
source

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.

0
source

Source: https://habr.com/ru/post/1264812/


All Articles