fraktor_utils_std_rs/
sync_mutex.rs

1use std::sync::Mutex;
2
3use fraktor_utils_core_rs::sync::sync_mutex_like::SyncMutexLike;
4
5use crate::sync_mutex_guard::StdSyncMutexGuard;
6
7#[cfg(test)]
8mod tests;
9
10/// Mutex wrapper backed by [`std::sync::Mutex`].
11pub struct StdSyncMutex<T>(Mutex<T>);
12
13impl<T> StdSyncMutex<T> {
14  /// Creates a new mutex-backed value.
15  #[must_use]
16  pub fn new(value: T) -> Self {
17    Self(Mutex::new(value))
18  }
19
20  /// Consumes the mutex and returns the inner value.
21  pub fn into_inner(self) -> T {
22    match self.0.into_inner() {
23      | Ok(value) => value,
24      | Err(poisoned) => poisoned.into_inner(),
25    }
26  }
27
28  /// Locks the mutex and returns the guard.
29  pub fn lock(&self) -> StdSyncMutexGuard<'_, T> {
30    match self.0.lock() {
31      | Ok(guard) => StdSyncMutexGuard { guard },
32      | Err(poisoned) => StdSyncMutexGuard { guard: poisoned.into_inner() },
33    }
34  }
35}
36
37impl<T> SyncMutexLike<T> for StdSyncMutex<T> {
38  type Guard<'a>
39    = StdSyncMutexGuard<'a, T>
40  where
41    T: 'a;
42
43  fn new(value: T) -> Self {
44    StdSyncMutex::new(value)
45  }
46
47  fn into_inner(self) -> T {
48    StdSyncMutex::into_inner(self)
49  }
50
51  fn lock(&self) -> Self::Guard<'_> {
52    StdSyncMutex::lock(self)
53  }
54}