protect/
lib.rs

1#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)]
2#[repr(transparent)]
3pub struct Protect<T> {
4    value: T,
5}
6
7#[allow(clippy::missing_safety_doc)]
8impl<T> Protect<T> {
9    pub unsafe fn new_unchecked(value: T) -> Protect<T> {
10        Protect { value }
11    }
12
13    pub unsafe fn get_unchecked(&self) -> &T {
14        &self.value
15    }
16
17    #[allow(clippy::wrong_self_convention)]
18    pub unsafe fn get_unchecked_mut(&mut self) -> &mut T {
19        &mut self.value
20    }
21
22    pub unsafe fn into_inner_unchecked(self) -> T {
23        self.value
24    }
25}
26
27impl<T> Protect<T> {
28    pub fn new<P: Permit<T>>(permit: &mut P, value: T) -> Option<Protect<T>> {
29        permit.new(value)
30    }
31
32    pub fn get<P: Permit<T>>(&self, permit: &mut P) -> Option<&T> {
33        permit.get(self)
34    }
35
36    #[allow(clippy::wrong_self_convention)]
37    pub fn get_mut<P: Permit<T>>(&mut self, permit: &mut P) -> Option<&mut T> {
38        permit.get_mut(self)
39    }
40
41    #[allow(clippy::wrong_self_convention)]
42    pub fn into_inner<P: Permit<T>>(self, permit: &mut P) -> Option<T> {
43        permit.into_inner(self)
44    }
45}
46
47pub trait Permit<T> {
48    #[allow(clippy::new_ret_no_self)]
49    fn new(&mut self, value: T) -> Option<Protect<T>>;
50
51    fn get<'protect>(&mut self, value: &'protect Protect<T>) -> Option<&'protect T>;
52
53    #[allow(clippy::wrong_self_convention)]
54    fn get_mut<'protect>(&mut self, value: &'protect mut Protect<T>) -> Option<&'protect mut T>;
55
56    #[allow(clippy::wrong_self_convention)]
57    fn into_inner(&mut self, value: Protect<T>) -> Option<T>;
58}