Skip to main content

libutils_cage/
mod.rs

1//^
2//^ HEAD
3//^
4
5//> HEAD -> FEATURES
6#![feature(test)]
7#![feature(const_trait_impl)]
8#![feature(const_default)]
9#![feature(lock_value_accessors)]
10
11//> HEAD -> CRATES
12extern crate test;
13
14//> HEAD -> MODULES
15#[cfg(test)]
16mod benches;
17mod derivations;
18#[cfg(test)]
19mod tests;
20
21//> HEAD -> STD
22use std::sync::RwLock;
23
24//> HEAD -> CORE
25use core::ops::{
26    Deref,
27    DerefMut
28};
29
30
31//^
32//^ CAGE
33//^
34
35//> CAGE -> DEFINITION
36#[derive(Debug)]
37pub struct Cage<Type: ?Sized> {
38    being: RwLock<Type>
39}
40
41//> CAGE -> SIZED IMPLEMENTATION
42impl<Type: Sized> Cage<Type> {
43    pub const fn new(value: Type) -> Cage<Type> {return Self {
44        being: RwLock::new(value)
45    }}
46    pub fn release(self) -> Type {return self.being.into_inner().unwrap()}
47    pub fn replace(&self, value: Type) -> Type {self.being.replace(value).unwrap()}
48}
49
50//> CAGE -> IMPLEMENTATION
51impl<Type: ?Sized> Cage<Type> {
52    pub fn read<Returns>(&self, closure: impl FnOnce(&Type) -> Returns) -> Returns {return closure(self.being.read().unwrap().deref())}
53    pub fn write<Returns>(&self, closure: impl FnOnce(&mut Type) -> Returns) -> Returns {return closure(self.being.write().unwrap().deref_mut())}
54}
55
56//> CAGE -> COPY IMPLEMENTATION
57impl<Type: Copy> Cage<Type> {
58    pub fn get(&self) -> Type {*self.being.read().unwrap()}
59}
60
61//> CAGE -> CLONE IMPLEMENTATION
62impl<Type: Clone> Cage<Type> {
63    pub fn cloned(&self) -> Type {self.being.read().unwrap().clone()}
64}
65
66//> CAGE -> DEFAULT
67const impl<Type: [const] Default> Default for Cage<Type> {
68    fn default() -> Self {return Self::new(Type::default())}
69}