cradle-shared 0.1.1

Shared utilities in use by the Cradle agent and cli
Documentation
use std::sync::{Arc, Mutex, MutexGuard};

/// Wrapper around an `Arc<Mutex<T>>` type
/// Used to simplify the code a bit
pub struct CradleMutex<T>(pub Arc<Mutex<T>>);
impl<T> CradleMutex<T> {
    /// Creates a new [`CradleMutex`] item for the given type `T`
    pub fn new(t: T) -> CradleMutex<T> {
        CradleMutex(Arc::new(Mutex::new(t)))
    }
    /// Creates a new [`CradleMutex`] from an existing `Arc<Mutex<T>>`
    pub fn new_from_arc(arc: Arc<Mutex<T>>) -> CradleMutex<T> {
        CradleMutex(arc)
    }

    /// Returns the locked version of the inner item
    pub fn lock(&self) -> MutexGuard<'_, T> {
        self.0.lock().unwrap()
    }

    /// Converts self into an `Arc<Mutex<T>>`
    /// Calls `Arc::clone()`
    pub fn to_arc(&self) -> Arc<Mutex<T>> {
        self.0.clone()
    }
    /// Converts the inner `Arc` into a `*const c_void` pointer
    pub fn to_raw_ptr(&self) -> *const std::ffi::c_void {
        Arc::into_raw(self.0.clone()) as *const std::ffi::c_void
    }
}

impl<T: Default> Default for CradleMutex<T> {
    fn default() -> CradleMutex<T> {
        CradleMutex(Arc::new(Mutex::new(T::default())))
    }
}

impl<T> Clone for CradleMutex<T> {
    fn clone(&self) -> Self {
        CradleMutex(self.0.clone())
    }
}