@@ -311,12 +311,23 @@ mod lazy {
311
311
// value (an aliasing violation). To avoid setting the "I'm running a
312
312
// destructor" flag we just use `mem::replace` which should sequence the
313
313
// 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.
314
320
unsafe {
315
321
let _ = mem:: replace ( & mut * ptr, Some ( value) ) ;
316
322
}
317
323
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.
320
331
unsafe {
321
332
// After storing `Some` we want to get a reference to the contents of
322
333
// what we just stored. While we could use `unwrap` here and it should
@@ -333,8 +344,8 @@ mod lazy {
333
344
#[ allow( unused) ]
334
345
pub unsafe fn take ( & mut self ) -> Option < T > {
335
346
// 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 .
338
349
unsafe { ( * self . inner . get ( ) ) . take ( ) }
339
350
}
340
351
}
@@ -448,9 +459,9 @@ pub mod fast {
448
459
// LLVM issue: https://bugs.llvm.org/show_bug.cgi?id=41722
449
460
#[ cold]
450
461
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) .
452
463
if !mem:: needs_drop :: < T > ( ) || unsafe { self . try_register_dtor ( ) } {
453
- // SAFETY: See comment above.
464
+ // SAFETY: See comment above (his function doc) .
454
465
Some ( unsafe { self . inner . initialize ( init) } )
455
466
} else {
456
467
None
0 commit comments