diff options
author | Daniel Henry-Mantilla <daniel.henry.mantilla@gmail.com> | 2020-09-23 19:30:43 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-09-23 10:30:43 -0700 |
commit | 0f70530ee7cda68b68f2f8131b5866cfa937ee1f (patch) | |
tree | 6fb41fc6853bd65de6e83e0ac4ca0b897fb081ec /tokio/src/sync | |
parent | 3114d9e826e5aa1948d394a7d6d488f61ab1da97 (diff) |
sync: add `get_mut()` for `Mutex,RwLock` (#2856)
Diffstat (limited to 'tokio/src/sync')
-rw-r--r-- | tokio/src/sync/mutex.rs | 24 | ||||
-rw-r--r-- | tokio/src/sync/rwlock.rs | 24 |
2 files changed, 48 insertions, 0 deletions
diff --git a/tokio/src/sync/mutex.rs b/tokio/src/sync/mutex.rs index 71f0136f..b2cf64d3 100644 --- a/tokio/src/sync/mutex.rs +++ b/tokio/src/sync/mutex.rs @@ -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. /// diff --git a/tokio/src/sync/rwlock.rs b/tokio/src/sync/rwlock.rs index 840889ba..a84c4c12 100644 --- a/tokio/src/sync/rwlock.rs +++ b/tokio/src/sync/rwlock.rs @@ -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 |