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;
17#[cfg(test)]
18mod tests;
19
20use std::sync::RwLock;
22
23use core::{
25 ops::{
26 Deref,
27 DerefMut
28 },
29 hash::{
30 Hash,
31 Hasher
32 }
33};
34
35
36#[derive(Debug)]
42pub struct Cage<Type: ?Sized> {
43 being: RwLock<Type>
44}
45
46impl<Type: ?Sized> Cage<Type> {
48 pub fn read<Returns>(&self, closure: impl FnOnce(&Type) -> Returns) -> Returns {
49 return closure(self.being.read().unwrap().deref())
50 }
51 pub fn write<Returns>(&self, closure: impl FnOnce(&mut Type) -> Returns) -> Returns {
52 return closure(self.being.write().unwrap().deref_mut())
53 }
54 pub const fn new(value: Type) -> Cage<Type> where Type: Sized {return Self {
55 being: RwLock::new(value)
56 }}
57 pub fn release(self) -> Type where Type: Sized {return self.being.into_inner().unwrap()}
58 pub fn replace(&self, value: Type) -> Type where Type: Sized {self.being.replace(value).unwrap()}
59 pub fn cloned(&self) -> Type where Type: Clone {self.being.read().unwrap().clone()}
60 pub fn get(&self) -> Type where Type: Copy {*self.being.read().unwrap()}
61}
62
63const impl<Type: [const] Default> Default for Cage<Type> {
65 fn default() -> Self {return Self::new(Type::default())}
66}
67
68impl<Type: Clone + ?Sized> Clone for Cage<Type> {
70 fn clone(&self) -> Self {return Self::new(self.read(|value| value.clone()))}
71}
72
73impl<Type: Hash + ?Sized> Hash for Cage<Type> {
75 fn hash<H: Hasher>(&self, state: &mut H) {return self.read(|value| value.hash(state))}
76}