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    #[inline]
44    pub const fn new(value: Type) -> Cage<Type> {return Self {
45        being: RwLock::new(value)
46    }}
47    #[inline]
48    pub fn release(self) -> Type {return self.being.into_inner().unwrap()}
49    #[inline]
50    pub fn replace(&self, value: Type) -> Type {self.being.replace(value).unwrap()}
51}
52
53//> CAGE -> IMPLEMENTATION
54impl<Type: ?Sized> Cage<Type> {
55    #[inline]
56    pub fn read<Returns>(&self, closure: impl FnOnce(&Type) -> Returns) -> Returns {return closure(self.being.read().unwrap().deref())}
57    #[inline]
58    pub fn write<Returns>(&self, closure: impl FnOnce(&mut Type) -> Returns) -> Returns {return closure(self.being.write().unwrap().deref_mut())}
59}
60
61//> CAGE -> COPY IMPLEMENTATION
62impl<Type: Copy> Cage<Type> {
63    #[inline]
64    pub fn get(&self) -> Type {*self.being.read().unwrap()}
65}
66
67//> CAGE -> CLONE IMPLEMENTATION
68impl<Type: Clone> Cage<Type> {
69    #[inline]
70    pub fn cloned(&self) -> Type {self.being.read().unwrap().clone()}
71}
72
73//> CAGE -> DEFAULT
74const impl<Type: [const] Default> Default for Cage<Type> {
75    #[inline]
76    fn default() -> Self {return Self::new(Type::default())}
77}