ralfbiedert / cheats.rs

Rust Language Cheat Sheet - https://cheats.rs
https://cheats.rs
4.14k stars 395 forks source link

#[repr(Rust)] layout #192

Closed yhx-12243 closed 8 months ago

yhx-12243 commented 8 months ago

The Rust specification does not specify how the memory layout of the struct in default representation is, even though in standard library, e.g., Vec<T>.

And this happens actually: Rust 1.76.0 changes Vec's layout from (ptr, capacity, len) into (capacity, ptr, len).

So I think the cheatsheet may need to be optimized in some ways.

Reference: https://rust.godbolt.org/z/KeGdWe46c

ralfbiedert commented 8 months ago

Maybe I misunderstand, but we already have a disclaimer that you are not allowed to transmute unless you have representation guarantees which I think Vec doesn't give, neither for it being repr(C), nor for these fields to be in a particular order if it were.

So from that perspective all depictions are merely illustrative anyways, and the point is to depict what's contained, not where exactly that resides.

yhx-12243 commented 8 months ago

What I means is that in Memory Layout > Standard Library Types chapter, the Vec<T> is drawn with a specific order. Is this appropriate (need not change) or to be changed?

Or maybe adding some comments will be better?

ralfbiedert commented 8 months ago

The std docs for Vec say:

Most fundamentally, Vec is and always will be a (pointer, capacity, length) triplet. No more, no less. The order of these fields is completely unspecified [...]

However, they also give this specific example (pointer, capacity, length) for illustrative purposes; and I think we are no different in that respect.

That said, I can understand that the disclaimer we have is 1-2 pages away and it might be misleading for some people that jump into that section without reading the context; maybe repeating that hint might be warranted.