Skip to main content

libutils_cage/
mod.rs

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