@@ -311,12 +311,23 @@ mod lazy {
311311 // value (an aliasing violation). To avoid setting the "I'm running a
312312 // destructor" flag we just use `mem::replace` which should sequence the
313313 // operations a little differently and make this safe to call.
314+ //
315+ // `ptr` can be dereferenced safely since it was obtained from
316+ // `UnsafeCell::get`, which should not return a non-aligned or NUL pointer.
317+ // What's more a `LazyKeyInner` can only be created with `new`, which ensures
318+ // `inner` is correctly initialized and all calls to methods on `LazyKeyInner`
319+ // will leave `inner` initialized too.
314320 unsafe {
315321 let _ = mem:: replace ( & mut * ptr, Some ( value) ) ;
316322 }
317323
318- // SAFETY: the *ptr operation is made safe by the `mem::replace`
319- // call above that made sure a valid value is present behind it.
324+ // SAFETY: the `*ptr` operation is made safe by the `mem::replace`
325+ // call above combined with `ptr` being correct from the beginning
326+ // (see previous SAFETY: comment above).
327+ //
328+ // Plus, with the call to `mem::replace` it is guaranteed there is
329+ // a `Some` behind `ptr`, not a `None` so `unreachable_unchecked`
330+ // will never be reached.
320331 unsafe {
321332 // After storing `Some` we want to get a reference to the contents of
322333 // what we just stored. While we could use `unwrap` here and it should
@@ -333,8 +344,8 @@ mod lazy {
333344 #[ allow( unused) ]
334345 pub unsafe fn take ( & mut self ) -> Option < T > {
335346 // SAFETY: The other methods hand out references while taking &self.
336- // As such, calling this method when such references are still alive
337- // will fail because it takes a &mut self, conflicting with them .
347+ // As such, callers of this method must ensure no `&` and `&mut` are
348+ // available and used at the same time .
338349 unsafe { ( * self . inner . get ( ) ) . take ( ) }
339350 }
340351 }
@@ -448,9 +459,9 @@ pub mod fast {
448459 // LLVM issue: https://bugs.llvm.org/show_bug.cgi?id=41722
449460 #[ cold]
450461 unsafe fn try_initialize < F : FnOnce ( ) -> T > ( & self , init : F ) -> Option < & ' static T > {
451- // SAFETY: See comment above.
462+ // SAFETY: See comment above (this function doc) .
452463 if !mem:: needs_drop :: < T > ( ) || unsafe { self . try_register_dtor ( ) } {
453- // SAFETY: See comment above.
464+ // SAFETY: See comment above (his function doc) .
454465 Some ( unsafe { self . inner . initialize ( init) } )
455466 } else {
456467 None
0 commit comments