use std::time::Duration;
use tokio::time::timeout;
use crate::{Result, DEFAULT_TIMEOUT_DURATION};
#[derive(Debug)]
pub struct Mutex<T> {
inner: tokio::sync::Mutex<T>,
timeout: Duration,
}
impl<T> Mutex<T> {
pub fn new(value: T) -> Self {
Self { inner: tokio::sync::Mutex::new(value), timeout: DEFAULT_TIMEOUT_DURATION }
}
pub fn new_with_timeout(value: T, timeout: Duration) -> Self {
Self { inner: tokio::sync::Mutex::new(value), timeout }
}
pub async fn lock(&self) -> tokio::sync::MutexGuard<'_, T> {
let guard = match timeout(self.timeout, self.inner.lock()).await {
Ok(guard) => guard,
Err(_) => panic!(
"Timed out while waiting for `read` lock after {} seconds.",
self.timeout.as_secs()
),
};
guard
}
pub async fn lock_err(&self) -> Result<tokio::sync::MutexGuard<'_, T>> {
let guard = timeout(self.timeout, self.inner.lock())
.await
.map_err(|_| crate::Error::LockTimeout(self.timeout.as_secs()))?;
Ok(guard)
}
}
impl<T> std::ops::Deref for Mutex<T> {
type Target = tokio::sync::Mutex<T>;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl<T: Default> Default for Mutex<T> {
fn default() -> Self {
Self::new(T::default())
}
}
impl<T> From<T> for Mutex<T> {
fn from(value: T) -> Self {
Self::new(value)
}
}