From 0000bb3afb84f4cdbf1ea359308a347870ce23b2 Mon Sep 17 00:00:00 2001 From: Joshua Liebow-Feeser Date: Sat, 7 Sep 2024 20:28:57 -0700 Subject: [PATCH] Add safety comment for MaybeUninit UnsafeCell (#1620) Closes #896 --- src/util.rs | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/src/util.rs b/src/util.rs index 0720f184dd..354b81d610 100644 --- a/src/util.rs +++ b/src/util.rs @@ -110,10 +110,19 @@ impl ValidityVariance for Invariant { unsafe impl TransparentWrapper for MaybeUninit { type Inner = T; - // SAFETY: Per [1], `MaybeUninit` has `UnsafeCell`s covering the same - // byte ranges as `Inner = T`. + // SAFETY: `MaybeUninit` has `UnsafeCell`s covering the same byte ranges + // as `Inner = T`. This is not explicitly documented, but it can be + // inferred. Per [1] in the preceding safety comment, `MaybeUninit` has + // the same size as `T`. Further, note the signature of + // `MaybeUninit::assume_init_ref` [2]: + // + // pub unsafe fn assume_init_ref(&self) -> &T + // + // If the argument `&MaybeUninit` and the returned `&T` had `UnsafeCell`s + // at different offsets, this would be unsound. Its existence is proof that + // this is not the case. // - // [1] TODO(#896): Write a safety proof before the next stable release. + // [2] https://doc.rust-lang.org/1.81.0/std/mem/union.MaybeUninit.html#method.assume_init_ref type UnsafeCellVariance = Covariant; // SAFETY: Per [1], `MaybeUninit` has the same layout as `T`, and thus // has the same alignment as `T`. @@ -280,7 +289,7 @@ unsafe impl TransparentWrapper for UnsafeCell { // subsequent sentence in the documentation makes it clear that this is the // intention. // - // [1] Per https://doc.rust-lang.org/std/cell/struct.UnsafeCell.html#memory-layout: + // [1] Per https://doc.rust-lang.org/1.81.0/core/cell/struct.UnsafeCell.html#memory-layout: // // `UnsafeCell` has the same in-memory representation as its inner type // `T`. A consequence of this guarantee is that it is possible to convert