Stream: t-lang/wg-unsafe-code-guidelines

Topic: Understanding tuple layout


Elichai Turkel (Feb 02 2020 at 09:45, on Zulip):

Hi,
I read the explanation(https://rust-lang.github.io/unsafe-code-guidelines/layout/structs-and-tuples.html#tuple-types) of tuples layout and I want to make sure I understand it correctly.

does it mean that this is sound code? transmute::<(bool, &u8), _>((true, &6u8));
Can I be confident that all tuples of the same "type" will have the same memory layout and can be safely casted to raw pointers, pass through ffi but only dereferenced on the rust side?
I know this is true in structs only as long as you use literally the same struct (ie 2 different structs can have different memory alignment and ordering even if they look the same).

So this is isn't sound: struct A<'a> {b: bool, u: &'au8}; struct B<'a> {b: bool, u: &'au8}; transmute::<B, A>(A{b: true, a: &7u8});

Sebastian Köln (Feb 02 2020 at 14:06, on Zulip):

The transmuting of A and B definitely isn't sound. Passing a pointer to a type and then turning that into a reference of the same type should be sound. Including any tuple type.

Elichai Turkel (Feb 02 2020 at 21:51, on Zulip):

@Sebastian Köln hehe, I tried adding things that has special soundness requirements and haven't thought about the storing ref to a temp.

But what you're saying is that 2 tuples with the same data are the same type

Sebastian Köln (Feb 02 2020 at 21:52, on Zulip):

yes, (T, U) == (T, U)

Sebastian Köln (Feb 02 2020 at 21:53, on Zulip):

the guidelines you linked make that very clear:

an anonymous tuple type (T1..Tn) of arity N is laid out "as if" there were a corresponding tuple struct declared in libcore

Sebastian Köln (Feb 02 2020 at 21:54, on Zulip):

so unless you manage to link against multiple libcores…

Sebastian Köln (Feb 02 2020 at 21:55, on Zulip):

(which could happen if the caller and callee are different libraries)

Last update: Feb 25 2020 at 04:00UTC