Skip to main content

cradle_shared/
mutex.rs

1use std::sync::{Arc, Mutex, MutexGuard};
2
3/// Wrapper around an `Arc<Mutex<T>>` type
4/// Used to simplify the code a bit
5pub struct CradleMutex<T>(pub Arc<Mutex<T>>);
6impl<T> CradleMutex<T> {
7    /// Creates a new [`CradleMutex`] item for the given type `T`
8    pub fn new(t: T) -> CradleMutex<T> {
9        CradleMutex(Arc::new(Mutex::new(t)))
10    }
11    /// Creates a new [`CradleMutex`] from an existing `Arc<Mutex<T>>`
12    pub fn new_from_arc(arc: Arc<Mutex<T>>) -> CradleMutex<T> {
13        CradleMutex(arc)
14    }
15
16    /// Returns the locked version of the inner item
17    pub fn lock(&self) -> MutexGuard<'_, T> {
18        self.0.lock().unwrap()
19    }
20
21    /// Converts self into an `Arc<Mutex<T>>`
22    /// Calls `Arc::clone()`
23    pub fn to_arc(&self) -> Arc<Mutex<T>> {
24        self.0.clone()
25    }
26    /// Converts the inner `Arc` into a `*const c_void` pointer
27    pub fn to_raw_ptr(&self) -> *const std::ffi::c_void {
28        Arc::into_raw(self.0.clone()) as *const std::ffi::c_void
29    }
30}
31
32impl<T: Default> Default for CradleMutex<T> {
33    fn default() -> CradleMutex<T> {
34        CradleMutex(Arc::new(Mutex::new(T::default())))
35    }
36}
37
38impl<T> Clone for CradleMutex<T> {
39    fn clone(&self) -> Self {
40        CradleMutex(self.0.clone())
41    }
42}