From 0d32d71fb7e2eda43dee05ce07c35990119a3843 Mon Sep 17 00:00:00 2001 From: Wolfgang Bumiller Date: Wed, 29 May 2019 10:27:24 +0200 Subject: [PATCH] tools: add AsyncMutex::new_locked Allows creating a pre-locked mutex, returning the mutex and a guard. Signed-off-by: Wolfgang Bumiller --- src/tools/async_mutex.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/tools/async_mutex.rs b/src/tools/async_mutex.rs index 12832146..bd6cb06b 100644 --- a/src/tools/async_mutex.rs +++ b/src/tools/async_mutex.rs @@ -1,6 +1,7 @@ use std::marker::PhantomData; -use futures::Poll; +use failure::{bail, Error}; +use futures::{Async, Poll}; use futures::future::Future; use tokio::sync::lock::Lock as TokioLock; pub use tokio::sync::lock::LockGuard as AsyncLockGuard; @@ -21,6 +22,15 @@ impl AsyncMutex { _error: PhantomData, } } + + pub fn new_locked(value: T) -> Result<(Self, AsyncLockGuard), Error> { + let mut this = Self::new(value); + let guard = match this.0.poll_lock() { + Async::Ready(guard) => guard, + _ => bail!("failed to create locked mutex"), + }; + Ok((this, guard)) + } } /// Represents a lock to be held in the future: