Skip to content

Commit

Permalink
Implement Drop for Mutex to drop the contents of the inner MaybeUninit
Browse files Browse the repository at this point in the history
  • Loading branch information
jannic committed Sep 19, 2024
1 parent f0cd528 commit ea9408d
Showing 1 changed file with 13 additions and 2 deletions.
15 changes: 13 additions & 2 deletions src/mutex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,10 @@ impl<T> Mutex<T> {
/// Unwraps the contained value, consuming the mutex.
#[inline]
pub fn into_inner(self) -> T {
// Safety: inner is always initialized
unsafe { self.inner.assume_init() }
// Safety:
// - inner is always initialized
// - self will be dropped at the end of the function, _not_ dropping the contents of MaybeUninit
unsafe { self.inner.as_ptr().read() }
}

/// Borrows the data for the duration of the critical section.
Expand Down Expand Up @@ -199,6 +201,15 @@ impl<T: Default> Mutex<RefCell<T>> {
}
}

impl<T> Drop for Mutex<T> {
fn drop(&mut self) {
// Safety:
// - inner is always initialized
// - self will be dropped at the end of the function, _not_ dropping the contents of MaybeUninit
core::mem::drop(unsafe { self.inner.as_ptr().read() });
}
}

// NOTE A `Mutex` can be used as a channel so the protected data must be `Send`
// to prevent sending non-Sendable stuff (e.g. access tokens) across different
// threads.
Expand Down

0 comments on commit ea9408d

Please sign in to comment.