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