I'm quite lost with the behavior that I am producing here, and really can't see what I've been doing wrong.
I have a struct:
#[derive(Debug)]
struct MyStruct {
a: u8,
b: u8,
c: u16,
d: u16,
e: u16,
}
and I perform some unsafe
magic on this (okay, that's already wrong ):
impl MyStruct {
fn my_func(&self) -> &[u8] {
unsafe {
slice::from_raw_parts_mut(
self as *const _ as *mut u8,
8, // == mem::size_of::<Self>(), right?
)
}
}
}
I then put random (not overflowing) values in a MyStruct
instance, run MyStruct::my_func
on a ref to that instance, print the result of this along with the original struct
, and I get this:
p: [108, 3, 148, 38, 0, 0, 15, 7]
s: MyStruct { a: 15, b: 7, c: 876, d: 9876, e: 0 }
See this example live here.
Reinterpreting my u16
's as two u8
's (don't know if having different sizes of integers plays a role here), one can see that no data is lost or corrupted, it's just in a completely different order (always the same):
original | new byte position
1 | 7
2 | 8
3 | 2
4 | 1
5 | 3
6 | 4
7 | 5
8 | 6
Since this order seems quite random however, I feel that I've made something wrong.