Layout decoding logic given field reordering

repr(rust) provides no guarantee of field ordering of a struct in its memory layout.

even two different types that share all the same fields, of the same type, in the same order, are not guaranteed to be laid out the same when using the default Rust layout!

So I wonder how the rust-generated binary knows how to decode bytes corresponding to a struct in the memory? Is the information on the specific "reordering" stored somewhere?

The compiler knows how the fields are laid out because the compiler gets to choose how the fields are laid out.

I'm not sure I'd describe accessing a field normally in a program as "decoding". The compiler generates code to access the memory address it expects the field to be at, based on the base memory address of the whole struct.

So you might say the information about how structs are laid out is encoded in the CPU instructions that access the field.


The point is, a single binary is always generated by the same compiler (linking together pieces of code generated by different versions of the compiler is simply not supported). So if the compiler treats a given type consistently, then its field order will be the same in any scenario, so there's no need to store any explicit information about it at runtime.

1 Like