Get size of `NonNull<T>` for `T: ?Sized`?

I have a NonNull<T> (T: ?Sized), and I need to get the size of its referent. Is there any way to do this on stable Rust? I will accept crazy hacks as long as they're sound.

I know that the NonNull<T> points to an initialized sequence of bytes, and I know that it is valid for reads, but I don't know that it contains a valid T. E.g., if materializing a &T to an invalid T were sound (it isn't), I'd be willing to materialize a &T and then call mem::size_of_val.


I think this is still an open question. There's at least one faction arguing that the validity of the referee is only a safety invariant of the reference, not a validity invariant. After all, AFAIK MIRI doesn't check that slice::from_raw_parts::<NonZeroU32>(p, n) actually points to non-zero memory.

The "official" way might go through something like, but that's not stable yet.

The std::intrinsics version of size_of_val actually takes a raw pointer.

Which probably doesn't help you much, as you want a stable way to emulate a size_of_val_raw.

1 Like

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.