Conversation

Jarkko Sakkinen

Edited 1 year ago

I hope I got this right (safety-proprty), i.e. so that references are enforced to have equal life-time:

impl<'a> From<&'a Header> for &'a [u8] {
    fn from(value: &Header) -> Self {
        // SAFETY: out-of-boundary is not possible, given that the size constraint
        // exists in the struct definition. The lifetime parameter links the lifetime
        // of the header reference to the slice.
        unsafe { from_raw_parts((value as *const Header) as *const u8, size_of::<Header>()) }
    }
}

#rustlang

1
0
0

@jarkko I believe that's safe, provided Header has no padding, otherwise, you could have potentially uninitialized values for some of the bytes

You might be interested in `#[derive(AsBytes)]` from the zerocopy crate: https://docs.rs/zerocopy/latest/zerocopy/trait.AsBytes.html, which checks for that at compile time, and exposes a safe API

2
0
1
@Dr_Emann This was a good tip. I want to refactor this as a zero-copy thing overally but doing these primitives takes time because you really have to think through, I was going to add cast from bytes next. Saves time!
1
0
0

@jarkko 👍 awesome, glad I could help!

1
0
0
@Dr_Emann Yeah, I was not doing that because I can but because I had to :-) Good lesson anyway with the type system, learned a lot even though the snippet is only few lines.
0
0
0