shared_type/
shared.rs

1// *************************************************************************
2//
3// Copyright (c) 2025 Andrei Gramakov. All rights reserved.
4//
5// This file is licensed under the terms of the MIT license.
6// For a copy, see: https://opensource.org/licenses/MIT
7//
8// site:    https://agramakov.me
9// e-mail:  mail@agramakov.me
10//
11// *************************************************************************
12use std::sync::{Arc, Mutex};
13
14#[cfg(test)]
15mod tests;
16
17pub type Shared<T> = Arc<Mutex<T>>;
18
19/// Convenience trait to add `into_shared()` to any type
20pub trait IntoShared<T> {
21    fn into_shared(self) -> Shared<T>;
22}
23
24impl<T> IntoShared<T> for T {
25    fn into_shared(self) -> Shared<T> {
26        Arc::new(Mutex::new(self))
27    }
28}
29
30pub trait WithSharedInner<T> {
31    /// Waits for the lock to become available and then calls the closure
32    fn with_inner<F, R>(&self, func: F) -> Option<R>
33    where
34        F: FnOnce(&mut T) -> R;
35
36    /// Immediately locks the mutex and calls the closure
37    fn try_with_inner<F, R>(&self, func: F) -> Option<R>
38    where
39        F: FnOnce(&mut T) -> R;
40}
41
42impl<T> WithSharedInner<T> for Shared<T> {
43    fn with_inner<F, R>(&self, func: F) -> Option<R>
44    where
45        F: FnOnce(&mut T) -> R,
46    {
47        self.lock().ok().map(|mut guard| func(&mut *guard))
48    }
49
50    fn try_with_inner<F, R>(&self, func: F) -> Option<R>
51    where
52        F: FnOnce(&mut T) -> R,
53    {
54        self.try_lock().ok().map(|mut guard| func(&mut *guard))
55    }
56}