1#![feature(test)]
7#![feature(const_trait_impl)]
8#![feature(const_default)]
9#![feature(const_convert)]
10#![feature(lock_value_accessors)]
11
12extern crate test;
14
15#[cfg(test)]
17mod benches;
18mod conversions;
19#[cfg(test)]
20mod tests;
21
22use std::sync::RwLock;
24
25use core::{
27 ops::{
28 Deref,
29 DerefMut
30 },
31 hash::{
32 Hash,
33 Hasher
34 }
35};
36
37
38#[derive(Debug)]
44pub struct Cage<Type: ?Sized> {
45 being: RwLock<Type>
46}
47
48impl<Type: ?Sized> Cage<Type> {
50 pub fn read<Returns>(&self, closure: impl FnOnce(&Type) -> Returns) -> Returns {
51 return closure(self.being.read().unwrap().deref())
52 }
53 pub fn write<Returns>(&self, closure: impl FnOnce(&mut Type) -> Returns) -> Returns {
54 return closure(self.being.write().unwrap().deref_mut())
55 }
56 pub const fn new(value: Type) -> Cage<Type> where Type: Sized {return Self {
57 being: RwLock::new(value)
58 }}
59 pub fn release(self) -> Type where Type: Sized {return self.being.into_inner().unwrap()}
60 pub fn replace(&self, value: Type) -> Type where Type: Sized {self.being.replace(value).unwrap()}
61 pub fn cloned(&self) -> Type where Type: Clone {self.being.read().unwrap().clone()}
62 pub fn get(&self) -> Type where Type: Copy {*self.being.read().unwrap()}
63}
64
65const impl<Type: [const] Default> Default for Cage<Type> {
67 fn default() -> Self {return Self::new(Type::default())}
68}
69
70impl<Type: Clone + ?Sized> Clone for Cage<Type> {
72 fn clone(&self) -> Self {return Self::new(self.read(|value| value.clone()))}
73}
74
75impl<Type: Hash + ?Sized> Hash for Cage<Type> {
77 fn hash<H: Hasher>(&self, state: &mut H) {return self.read(|value| value.hash(state))}
78}