From 0f70530ee7cda68b68f2f8131b5866cfa937ee1f Mon Sep 17 00:00:00 2001 From: Daniel Henry-Mantilla Date: Wed, 23 Sep 2020 19:30:43 +0200 Subject: [PATCH] sync: add `get_mut()` for `Mutex,RwLock` (#2856) --- tokio/src/sync/mutex.rs | 24 ++++++++++++++++++++++++ tokio/src/sync/rwlock.rs | 24 ++++++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/tokio/src/sync/mutex.rs b/tokio/src/sync/mutex.rs index 71f0136f005..b2cf64d3607 100644 --- a/tokio/src/sync/mutex.rs +++ b/tokio/src/sync/mutex.rs @@ -325,6 +325,30 @@ impl Mutex { } } + /// 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. /// diff --git a/tokio/src/sync/rwlock.rs b/tokio/src/sync/rwlock.rs index 840889bace8..a84c4c123af 100644 --- a/tokio/src/sync/rwlock.rs +++ b/tokio/src/sync/rwlock.rs @@ -585,6 +585,30 @@ impl RwLock { } } + /// 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