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

Topic: Can validity invariants be violated if we fix them?

Thom Chiovoloni (Dec 08 2019 at 02:48, on Zulip):

So, I have a function which takes a &mut usize which came from transmute::<&mut NonNull<u8>, &mut usize> (or the equivalent). This function needs to be unsafe, since it could cause a NonNull<u8> to have all-bits-zero, which is obviously illegal. I'm wondering if the constraint it has is that it must leave the usize as non-zero when it returns, or if the usize must never be zeroed.

Specifically, for various reasons (this is a simplified version of my actual case), it's more efficient for me to write a zero, and then check, rather than performing the check first, so I'd like to do that.

It's not clear if this is legal though. It does mean that 'memory that elsewhere in the code is represented as a NonNull<T> ' -- which on its face sounds like UB, but given that I have an &mut reference to the memory in question, the NonNull shouldn't be "active" (there's probably a better term for this), and so maybe it's allowed?

I mocked up something with (hopefully) equivalent safety properties here:, and miri doesn't complain, but that's not actually a guarantee, so I figured I'd ask.

(Note: I've simplified my actual case, which is in implementing an SSO optimized string, but I can get into details if needed, or even provide code closer to my actual example)

Last update: May 26 2020 at 11:10UTC