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::{ops::{Deref, DerefMut}, sync::{
23    RwLock,
24    RwLockReadGuard,
25    RwLockWriteGuard
26}};
27
28
29//^
30//^ CAGE
31//^
32
33//> CAGE -> DEFINITION
34#[derive(Debug)]
35pub struct Cage<Type: ?Sized> {
36    being: RwLock<Type>
37}
38
39//> CAGE -> SIZED IMPLEMENTATION
40impl<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
51//> CAGE -> IMPLEMENTATION
52impl<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
63//> CAGE -> COPY IMPLEMENTATION
64impl<Type: Copy> Cage<Type> {
65    #[inline]
66    pub fn get(&self) -> Type {*self.read()}
67}
68
69//> CAGE -> CLONE IMPLEMENTATION
70impl<Type: Clone> Cage<Type> {
71    #[inline]
72    pub fn cloned(&self) -> Type {self.read().clone()}
73}
74
75//> CAGE -> DEFAULT
76const impl<Type: [const] Default> Default for Cage<Type> {
77    #[inline]
78    fn default() -> Self {return Self::new(Type::default())}
79}