pubsub_bus/shared.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
// *************************************************************************
//
// Copyright (c) 2025 Andrei Gramakov. All rights reserved.
//
// This file is licensed under the terms of the MIT license.
// For a copy, see: https://opensource.org/licenses/MIT
//
// site: https://agramakov.me
// e-mail: mail@agramakov.me
//
// *************************************************************************
use std::sync::{Arc, Mutex};
#[cfg(test)]
mod tests;
pub type Shared<ContentType> = Arc<Mutex<ContentType>>;
/// Convenience trait to add `into_shared()` to any type
pub trait IntoShared<ContentType> {
fn into_shared(self) -> Shared<ContentType>;
}
impl<ContentType> IntoShared<ContentType> for ContentType {
fn into_shared(self) -> Shared<ContentType> {
Arc::new(Mutex::new(self))
}
}
/// Trait to provide a `with` method for `Shared<ContentType>`
pub trait With<ContentType> {
fn with<F>(&mut self, f: F)
where
F: FnOnce(&mut ContentType);
}
impl<ContentType> With<ContentType> for Shared<ContentType> {
fn with<F>(&mut self, f: F)
where
F: FnOnce(&mut ContentType),
{
let mut shared = self.lock().unwrap();
f(&mut shared);
}
}