Deserialization of a Vec<u8>

Hello,

I'm reading data from a serial port and I have to split the data into smaller pieces and store the data maybe in a struct or just variables with these sizes 8bytes, 4bytes, 4bytes, 4bytes, 4bytes, 4bytes, 4bytes, 4bytes, 4bytes (with a total of 40 bytes) but I can't find a simple solution to that.
The data is collected like this:

let mut serial_buf: Vec<u8> = vec![0; 40];
data_port.read(serial_buf.as_mut_slice()).expect("Found no data!");

Thanks!

Use bytemuck.

#[derive(Clone, Copy, Debug, Default, Pod, Zeroable)]
#[repr(C)]
pub struct Data {
    head: [u8; 8],
    tail: [[u8; 4]; 8],
}

pub fn example<R: Read>(mut data_port: R) -> Data {
    let mut data = Data::default();
    let serial_buf = bytes_of_mut(&mut data);
    data_port.read(serial_buf).expect("Found no data!");
    data
}
2 Likes

Thank you! That looks like a beautiful solution!
But sadly the compiler does not agree:

error[E0277]: the trait bound `Data: Pod` is not satisfied
   --> src\main.rs:114:35
    |
114 |     let serial_buf = bytes_of_mut(&mut data);
    |                      ------------ ^^^^^^^^^ the trait `Pod` is not implemented for `Data`
    |                      |
    |                      required by a bound introduced by this call
    |
    = help: the following other types implement trait `Pod`:
              ()
              ManuallyDrop<T>
              Option<T>
              PhantomData<T>
              PhantomPinned
              Wrapping<T>
              [T; 0]
              [T; 1024]
            and 60 others
    = note: required for `Data` to implement `NoUninit`
note: required by a bound in `bytes_of_mut`

Will I have to implement 'Pod' for the struct?

You can derive it...

//                                    vvvvvvvvvvvvv
#[derive(Clone, Copy, Debug, Default, Pod, Zeroable)]
#[repr(C)] // <-- also required
pub struct Data {

The playground I linked compiles for example.

2 Likes

It turned out that the solution compiles on my Mac but not on my Windows system.
I guess I have some issues with lib dependencies. Have to clean up my Windows environment ...

Update:
Everything works just fine if I add the features to the Cargo.toml

[dependencies]
bytemuck = { version = "1.13.1", features = ["derive", "zeroable_maybe_uninit"] }

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.