Skip to content

Commit

Permalink
Merge #214
Browse files Browse the repository at this point in the history
214: Explain safety of `unsync::OnceCell::get(&self)` in more detail r=matklad a=Enselic

Background: I'm working on improving my unsafe Rust skills, and figuring out how `once_cell` works is one way to do that. By more elaborately explaining why `unsync::OnceCell::get(&self)` is safely implemented, I hope to help others increase their understanding of unsafe Rust as well.

(It was not obvious to me at first why `unsync::OnceCell::get(&self)` was safe. But I think I figured it out now.)

Co-authored-by: Martin Nordholts <[email protected]>
  • Loading branch information
bors[bot] and Enselic authored Jan 2, 2023
2 parents af9d29c + cc07949 commit d706539
Showing 1 changed file with 4 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -454,7 +454,10 @@ pub mod unsync {
/// Returns `None` if the cell is empty.
#[inline]
pub fn get(&self) -> Option<&T> {
// Safe due to `inner`'s invariant
// Safe due to `inner`'s invariant of being written to at most once.
// Had multiple writes to `inner` been allowed, a reference to the
// value we return now would become dangling by a write of a
// different value later.
unsafe { &*self.inner.get() }.as_ref()
}

Expand Down

0 comments on commit d706539

Please sign in to comment.