1use std::time::Duration;
4
5use tokio::time::timeout;
6
7use crate::{Result, DEFAULT_TIMEOUT_DURATION};
8
9#[derive(Debug)]
14pub struct Mutex<T> {
15 inner: tokio::sync::Mutex<T>,
17 timeout: Duration,
19}
20
21impl<T> Mutex<T> {
22 pub fn new(value: T) -> Self {
24 Self { inner: tokio::sync::Mutex::new(value), timeout: DEFAULT_TIMEOUT_DURATION }
25 }
26
27 pub fn new_with_timeout(value: T, timeout: Duration) -> Self {
29 Self { inner: tokio::sync::Mutex::new(value), timeout }
30 }
31
32 pub async fn lock(&self) -> tokio::sync::MutexGuard<'_, T> {
39 let guard = match timeout(self.timeout, self.inner.lock()).await {
40 Ok(guard) => guard,
41 Err(_) => panic!(
42 "Timed out while waiting for `read` lock after {} seconds.",
43 self.timeout.as_secs()
44 ),
45 };
46
47 guard
48 }
49
50 pub async fn lock_err(&self) -> Result<tokio::sync::MutexGuard<'_, T>> {
55 let guard = timeout(self.timeout, self.inner.lock())
56 .await
57 .map_err(|_| crate::Error::LockTimeout(self.timeout.as_secs()))?;
58
59 Ok(guard)
60 }
61}
62
63impl<T> std::ops::Deref for Mutex<T> {
64 type Target = tokio::sync::Mutex<T>;
65
66 fn deref(&self) -> &Self::Target {
67 &self.inner
68 }
69}
70
71impl<T: Default> Default for Mutex<T> {
72 fn default() -> Self {
73 Self::new(T::default())
74 }
75}
76
77impl<T> From<T> for Mutex<T> {
78 fn from(value: T) -> Self {
79 Self::new(value)
80 }
81}