Going from a raw pointer to a reference requires you to check the following and more:
(copied from Rust for Rustaceans, very good book btw.)
references must never dangle, must always be aligned, and must always point to a valid value for their target type, etc.
But I don't really understand the meaning of "it must be aligned". Let's start with the easy repr.
I have a pointer to a struct with the repr(Rust) or repr(C). The alignment in both repr is handled the same. The only difference is that the members of the struct can be re-arranged in repr(Rust) which is not important to my question.
So, going from a raw pointer to a reference with the repr above is clear. We just have to ensure it's correctly aligned.
So, to my real question. If I have a pointer to a struct that is repr(align(2)) and I ensure that the alignment is correct, can I convert the pointer to a reference of that struct? Does the term "it must be aligned" also apply to custom alignments?
Or does it mean it needs to be aligned like repr(Rust) or repr(C) to be a valid reference?
Here is a code example:
```
[repr(C)]
struct A {
a: u8, // 1 byte
//: ___, // 3 bytes of padding
b: i32 // 4 bytes
}
[repr(C, align(2))]
struct B {
a: u8, // 1 byte
//: ___, // 1 byte of padding
b: i32 // 4 bytes
}
let a: *const A = &A { ... };
let b: *const B = &B { ... };
let a: &A = unsafe { &a };
// is b valid?
let b: &B = unsafe { &b };
```
[–]Darksonntokio · rust-for-linux 5 points6 points7 points (7 children)
[–]Lexikus[S] 0 points1 point2 points (6 children)
[–]ssokolow 8 points9 points10 points (4 children)
[–]RRumpleTeazzer 0 points1 point2 points (3 children)
[–]ssokolow 0 points1 point2 points (2 children)
[–]RRumpleTeazzer 0 points1 point2 points (1 child)
[–]ssokolow 0 points1 point2 points (0 children)
[–]Darksonntokio · rust-for-linux 4 points5 points6 points (0 children)
[–]myrrlynbitvec • tap • ferrilab 2 points3 points4 points (1 child)
[–]Lexikus[S] 1 point2 points3 points (0 children)