Skip to content

Commit

Permalink
sync: add get_mut() for Mutex,RwLock (#2856)
Browse files Browse the repository at this point in the history
  • Loading branch information
danielhenrymantilla committed Sep 23, 2020
1 parent 3114d9e commit 0f70530
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
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

0 comments on commit 0f70530

Please sign in to comment.