Skip to content

Commit

Permalink
Add Mutex::{get_mut, into_inner}
Browse files Browse the repository at this point in the history
  • Loading branch information
taiki-e authored and cramertj committed Aug 30, 2019
1 parent d879db3 commit 73c6641
Showing 1 changed file with 37 additions and 1 deletion.
38 changes: 37 additions & 1 deletion futures-util/src/lock/mutex.rs
Expand Up @@ -67,10 +67,24 @@ impl<T> Mutex<T> {
pub fn new(t: T) -> Mutex<T> {
Mutex {
state: AtomicUsize::new(0),
value: UnsafeCell::new(t),
waiters: StdMutex::new(Slab::new()),
value: UnsafeCell::new(t),
}
}

/// Consumes this mutex, returning the underlying data.
///
/// # Examples
///
/// ```
/// use futures::lock::Mutex;
///
/// let mutex = Mutex::new(0);
/// assert_eq!(mutex.into_inner(), 0);
/// ```
pub fn into_inner(self) -> T {
self.value.into_inner()
}
}

impl<T: ?Sized> Mutex<T> {
Expand All @@ -97,6 +111,28 @@ 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
///
/// ```
/// # futures::executor::block_on(async {
/// use futures::lock::Mutex;
///
/// let mut mutex = Mutex::new(0);
/// *mutex.get_mut() = 10;
/// assert_eq!(*mutex.lock().await, 10);
/// # });
/// ```
pub fn get_mut(&mut self) -> &mut T {
// We know statically that there are no other references to `self`, so
// there's no need to lock the inner mutex.
unsafe { &mut *self.value.get() }
}

fn remove_waker(&self, wait_key: usize, wake_another: bool) {
if wait_key != WAIT_KEY_NONE {
let mut waiters = self.waiters.lock().unwrap();
Expand Down

0 comments on commit 73c6641

Please sign in to comment.