#[cfg(not(feature = "sync-mutex"))]
use core::cell::RefCell;
#[cfg(not(feature = "sync-mutex"))]
#[derive(Debug, Default)]
pub struct Shared<T>(RefCell<T>);
#[cfg(feature = "sync-mutex")]
#[derive(Debug, Default)]
pub struct Shared<T>(std::sync::RwLock<T>);
#[cfg(not(feature = "sync-mutex"))]
pub type Ref<'a, T> = core::cell::Ref<'a, T>;
#[cfg(feature = "sync-mutex")]
pub type Ref<'a, T> = std::sync::RwLockReadGuard<'a, T>;
#[cfg(not(feature = "sync-mutex"))]
pub type RefMut<'a, T> = core::cell::RefMut<'a, T>;
#[cfg(feature = "sync-mutex")]
pub type RefMut<'a, T> = std::sync::RwLockWriteGuard<'a, T>;
impl<T> Shared<T> {
#[must_use]
pub const fn new(value: T) -> Self {
#[cfg(not(feature = "sync-mutex"))]
{
Self(RefCell::new(value))
}
#[cfg(feature = "sync-mutex")]
{
Self(std::sync::RwLock::new(value))
}
}
pub fn borrow(&self) -> Ref<'_, T> {
#[cfg(not(feature = "sync-mutex"))]
{
self.0.borrow()
}
#[cfg(feature = "sync-mutex")]
{
self.0
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
}
pub fn borrow_mut(&self) -> RefMut<'_, T> {
#[cfg(not(feature = "sync-mutex"))]
{
self.0.borrow_mut()
}
#[cfg(feature = "sync-mutex")]
{
self.0
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
}
pub fn into_inner(self) -> T {
#[cfg(not(feature = "sync-mutex"))]
{
self.0.into_inner()
}
#[cfg(feature = "sync-mutex")]
{
self.0
.into_inner()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
}
}
#[cfg(all(feature = "sync-mutex", feature = "rustcrypto"))]
const _: () = {
const fn assert_send<T: Send>() {}
const fn assert_sync<T: Sync>() {}
assert_send::<crate::commissioning::commissioner::Commissioner>();
assert_send::<crate::ca::CertAuthority>();
assert_sync::<crate::ca::CertAuthority>();
assert_send::<crate::im::client::Subscription>();
assert_sync::<crate::im::client::Subscription>();
assert_send::<crate::im::client::ReportAssembler<1024>>();
assert_send::<Shared<u32>>();
assert_sync::<Shared<u32>>();
};
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn two_shared_borrows_are_live_at_once() {
let shared = Shared::new(41u32);
let first = shared.borrow();
let second = shared.borrow();
assert_eq!(*first + *second, 82);
}
#[test]
fn an_exclusive_borrow_writes_through() {
let shared = Shared::new(1u32);
*shared.borrow_mut() = 7;
assert_eq!(*shared.borrow(), 7);
assert_eq!(shared.into_inner(), 7);
}
}