cfx_storage/utils/
guarded_value.rs1use std::ops::{Deref, DerefMut};
8
9#[derive(Clone)]
14pub struct NonCopy<T: ?Sized>(pub T);
15
16pub struct GuardedValue<GuardType, ValueType> {
19 guard: GuardType,
20 value: ValueType,
21}
22
23impl<GuardType, ValueType> GuardedValue<GuardType, ValueType> {
24 pub fn new(guard: GuardType, value: ValueType) -> Self {
25 Self { guard, value }
26 }
27
28 pub fn into(self) -> (GuardType, ValueType) { (self.guard, self.value) }
31}
32
33impl<'a, GuardType: 'a + Deref<Target = TargetType>, TargetType>
34 GuardedValue<GuardType, NonCopy<&'a TargetType>>
35{
36 pub fn new_derefed(guard: GuardType) -> Self {
37 let derefed: *const TargetType = &*guard;
38 Self {
39 guard,
40 value: NonCopy(unsafe { &*derefed } as &'a TargetType),
41 }
42 }
43}
44
45impl<'a, GuardType: 'a + DerefMut<Target = TargetType>, TargetType>
46 GuardedValue<GuardType, &'a mut TargetType>
47{
48 pub fn new_derefed_mut(mut guard: GuardType) -> Self {
49 let derefed_mut: *mut TargetType = &mut *guard;
50 Self {
51 guard,
52 value: unsafe { &mut *derefed_mut } as &'a mut TargetType,
53 }
54 }
55}
56
57impl<GuardType, ValueType> AsRef<ValueType>
58 for GuardedValue<GuardType, ValueType>
59{
60 fn as_ref(&self) -> &ValueType { &self.value }
61}
62
63impl<GuardType, ValueType> AsMut<ValueType>
64 for GuardedValue<GuardType, ValueType>
65{
66 fn as_mut(&mut self) -> &mut ValueType { &mut self.value }
67}
68
69impl<GuardType, ValueType: Deref> Deref for GuardedValue<GuardType, ValueType> {
73 type Target = ValueType::Target;
74
75 fn deref(&self) -> &Self::Target { self.value.deref() }
76}
77
78impl<GuardType, ValueType: DerefMut> DerefMut
79 for GuardedValue<GuardType, ValueType>
80{
81 fn deref_mut(&mut self) -> &mut Self::Target { self.value.deref_mut() }
82}
83
84impl<T: ?Sized> Deref for NonCopy<T> {
91 type Target = T;
92
93 fn deref(&self) -> &Self::Target { &self.0 }
94}
95
96impl<T: ?Sized> DerefMut for NonCopy<T> {
97 fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 }
98}