fuel_core_services/
sync.rs

1//! Wrappers for synchronization containers.
2
3use core::ops::Deref;
4
5/// Alias for `Arc<T>`
6pub type Shared<T> = std::sync::Arc<T>;
7
8/// A mutex that can safely be in async contexts and avoids deadlocks.
9#[derive(Default, Debug)]
10pub struct SharedMutex<T>(Shared<parking_lot::Mutex<T>>);
11
12impl<T> Clone for SharedMutex<T> {
13    fn clone(&self) -> Self {
14        Self(self.0.clone())
15    }
16}
17
18impl<T> Deref for SharedMutex<T> {
19    type Target = Shared<parking_lot::Mutex<T>>;
20
21    fn deref(&self) -> &Self::Target {
22        &self.0
23    }
24}
25
26impl<T> SharedMutex<T> {
27    /// Creates a new `SharedMutex` with the given value.
28    pub fn new(t: T) -> Self {
29        Self(Shared::new(parking_lot::Mutex::new(t)))
30    }
31
32    /// Apply a function to the inner value and return a value.
33    pub fn apply<R>(&self, f: impl FnOnce(&mut T) -> R) -> R {
34        let mut t = self.0.lock();
35        f(&mut t)
36    }
37}
38
39impl<T> From<T> for SharedMutex<T> {
40    fn from(t: T) -> Self {
41        Self::new(t)
42    }
43}