1#![feature(test)]
7#![feature(const_trait_impl)]
8#![feature(const_default)]
9#![feature(lock_value_accessors)]
10
11extern crate test;
13
14#[cfg(test)]
16mod benches;
17mod derivations;
18#[cfg(test)]
19mod tests;
20
21use std::{ops::{Deref, DerefMut}, sync::{
23 RwLock,
24 RwLockReadGuard,
25 RwLockWriteGuard
26}};
27
28
29#[derive(Debug)]
35pub struct Cage<Type: ?Sized> {
36 being: RwLock<Type>
37}
38
39impl<Type: Sized> Cage<Type> {
41 #[inline]
42 pub const fn new(value: Type) -> Cage<Type> {return Self {
43 being: RwLock::new(value)
44 }}
45 #[inline]
46 pub fn release(self) -> Type {return self.being.into_inner().unwrap()}
47 #[inline]
48 pub fn replace(&self, value: Type) -> Type {self.being.replace(value).unwrap()}
49}
50
51impl<Type: ?Sized> Cage<Type> {
53 #[inline]
54 pub fn read<'valid>(&'valid self) -> RwLockReadGuard<'valid, Type> {return self.being.read().unwrap()}
55 #[inline]
56 pub fn write<'valid>(&'valid self) -> RwLockWriteGuard<'valid, Type> {return self.being.write().unwrap()}
57 #[inline]
58 pub fn with<Returns>(&self, closure: impl FnOnce(&Type) -> Returns) -> Returns {return closure(self.read().deref())}
59 #[inline]
60 pub fn with_mut<Returns>(&self, closure: impl FnOnce(&mut Type) -> Returns) -> Returns {return closure(self.write().deref_mut())}
61}
62
63impl<Type: Copy> Cage<Type> {
65 #[inline]
66 pub fn get(&self) -> Type {*self.read()}
67}
68
69impl<Type: Clone> Cage<Type> {
71 #[inline]
72 pub fn cloned(&self) -> Type {self.read().clone()}
73}
74
75const impl<Type: [const] Default> Default for Cage<Type> {
77 #[inline]
78 fn default() -> Self {return Self::new(Type::default())}
79}