Size of `UnsafeCell`

In a recent issue, I’ve noticed the following line:

UnsafeCell<T> can be larger than T in some cases

Could someone give an example of how this is possible? I’m not sure if I can come up with one off the top of my head, and besides, isn’t being repr(transparent) a soundness property of UnsafeCell?

Yes, it is marked as #[rustc_pub_transparent]. I think OP is just wrong.

From the docs:

UnsafeCell<T> has the same in-memory representation as its inner type T.

Maybe they refer to what's mentioned later?

Special care has to be taken when converting a nested T inside of an Outer<T> type to an Outer<UnsafeCell<T>> type: this is not sound when the Outer<T> type enables niche optimizations. For example, the type Option<NonNull<u8>> is typically 8 bytes large on 64-bit platforms, but the type Option<UnsafeCell<NonNull<u8>>> takes up 16 bytes of space.

5 Likes

At first I thought it might be an edge-case for ZSTs, but then I found this in the Nomicon:

(UnsafeCell also uses the unstable no_niche, so its ABI is not actually guaranteed to be the same when nested in other types).

which refers to niche optimizations, as rikyborg quoted above.

Edit: a couple issues and a PR with more information:

6 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.