Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add get_mut() for Mutex & RwLock #2856

Merged
merged 1 commit into from Sep 23, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
24 changes: 24 additions & 0 deletions tokio/src/sync/mutex.rs
Expand Up @@ -325,6 +325,30 @@ impl<T: ?Sized> Mutex<T> {
}
}

/// Returns a mutable reference to the underlying data.
///
/// Since this call borrows the `Mutex` mutably, no actual locking needs to
/// take place -- the mutable borrow statically guarantees no locks exist.
///
/// # Examples
///
/// ```
/// use tokio::sync::Mutex;
///
/// fn main() {
/// let mut mutex = Mutex::new(1);
///
/// let n = mutex.get_mut();
/// *n = 2;
/// }
/// ```
pub fn get_mut(&mut self) -> &mut T {
unsafe {
// Safety: This is https://github.com/rust-lang/rust/pull/76936
&mut *self.c.get()
}
}

/// Attempts to acquire the lock, and returns [`TryLockError`] if the lock
/// is currently held somewhere else.
///
Expand Down
24 changes: 24 additions & 0 deletions tokio/src/sync/rwlock.rs
Expand Up @@ -585,6 +585,30 @@ impl<T: ?Sized> RwLock<T> {
}
}

/// Returns a mutable reference to the underlying data.
///
/// Since this call borrows the `RwLock` mutably, no actual locking needs to
/// take place -- the mutable borrow statically guarantees no locks exist.
///
/// # Examples
///
/// ```
/// use tokio::sync::RwLock;
///
/// fn main() {
/// let mut lock = RwLock::new(1);
///
/// let n = lock.get_mut();
/// *n = 2;
/// }
/// ```
pub fn get_mut(&mut self) -> &mut T {
unsafe {
// Safety: This is https://github.com/rust-lang/rust/pull/76936
&mut *self.c.get()
}
}

/// Consumes the lock, returning the underlying data.
pub fn into_inner(self) -> T
where
Expand Down