sync: add get_mut() for Mutex,RwLock (#2856)

This commit is contained in:
Daniel Henry-Mantilla
2020-09-23 10:30:43 -07:00
committed by GitHub
parent 3114d9e826
commit 0f70530ee7
2 changed files with 48 additions and 0 deletions
+24
View File
@@ -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.
///
+24
View File
@@ -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