1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
use crate::{Error, Result};
use atomic_refcell::{AtomicRef, AtomicRefCell, AtomicRefMut};
use std::{
    any::type_name,
    marker::PhantomData,
    mem,
    ops::{Deref, DerefMut},
};

// Remove generics of inner cell.
// The AtomicRefCell is boxed and a raw pointer is acquired. This is needed to circumvent borrowed
// temporary inside RwLockGuard. Since cells are never removed partially from the ResourceManager,
// this is safe.
// The pointer is valid for the entire lifetime of cell.
pub struct Cell {
    pub(crate) inner: *mut AtomicRefCell<dyn Storage>,
}

// Since Storage implements Send + Sync, this is safe.
unsafe impl Send for Cell {}
unsafe impl Sync for Cell {}

impl Cell {
    // A raw pointer to the internally boxed AtomicRefCell is stored. The pointer is
    // valid as long as self because caches can never be individually removed
    pub fn new<T: Storage>(value: T) -> Self {
        Self {
            inner: Box::into_raw(Box::new(AtomicRefCell::new(value))),
        }
    }

    pub fn borrow<'a, T: Storage>(&self) -> Result<CellRef<'a, T>> {
        let borrow = unsafe {
            (*self.inner)
                .try_borrow()
                .map_err(|_| Error::Borrow(type_name::<T>()))?
        };

        CellRef::new(borrow)
    }

    pub fn borrow_mut<'a, T: Storage>(&self) -> Result<CellRefMut<'a, T>> {
        let borrow = unsafe {
            (*self.inner)
                .try_borrow_mut()
                .map_err(|_| Error::BorrowMut(type_name::<T>()))?
        };

        CellRefMut::new(borrow)
    }
}

impl Drop for Cell {
    fn drop(&mut self) {
        unsafe { mem::drop(Box::from_raw(self.inner)) };
    }
}

pub struct CellRef<'a, T> {
    pub(crate) value: &'a T,
    pub(crate) borrow: AtomicRef<'a, dyn Storage>,
    pub(crate) marker: PhantomData<T>,
}

impl<'a, T> CellRef<'a, T>
where
    T: 'static,
{
    #[inline]
    pub fn new(borrow: AtomicRef<'a, dyn Storage>) -> Result<Self> {
        let data = borrow
            .deref()
            .as_any()
            .downcast_ref::<T>()
            .expect("Failed to downcast cell") as *const _;

        Ok(Self {
            value: unsafe { &*data },
            borrow,
            marker: PhantomData,
        })
    }

    // Transforms the borrowed cell.
    #[inline]
    pub fn map<U: 'static, F: FnOnce(&T) -> &U>(self, f: F) -> CellRef<'a, U> {
        CellRef {
            value: f(self.value),
            borrow: self.borrow,
            marker: PhantomData,
        }
    }

    // Fallible version of [`map`].
    #[inline]
    pub fn try_map<U: 'static, F: FnOnce(&T) -> std::result::Result<&U, E>, E>(
        self,
        f: F,
    ) -> std::result::Result<CellRef<'a, U>, E> {
        Ok(CellRef {
            value: f(self.value)?,
            borrow: self.borrow,
            marker: PhantomData,
        })
    }
}

impl<'a, T> Deref for CellRef<'a, T> {
    type Target = T;

    #[inline]
    fn deref(&self) -> &Self::Target {
        self.value
    }
}

pub struct CellRefMut<'a, T> {
    pub(crate) value: &'a mut T,
    pub(crate) borrow: AtomicRefMut<'a, dyn Storage>,
    pub(crate) marker: PhantomData<T>,
}

impl<'a, T> CellRefMut<'a, T>
where
    T: 'static,
{
    #[inline]
    pub fn new(mut borrow: AtomicRefMut<'a, dyn Storage>) -> Result<Self> {
        let data = borrow
            .deref_mut()
            .as_any_mut()
            .downcast_mut::<T>()
            .expect("Failed to downcast cell") as *mut _;

        Ok(Self {
            value: unsafe { &mut *data },
            borrow,
            marker: PhantomData,
        })
    }

    // Transforms the borrowed cell.
    #[inline]
    pub fn map<U: 'static, F: FnOnce(&mut T) -> &mut U>(self, f: F) -> CellRefMut<'a, U> {
        CellRefMut {
            value: f(self.value),
            borrow: self.borrow,
            marker: PhantomData,
        }
    }

    // Fallible version of [`map`].
    #[inline]
    pub fn try_map<U: 'static, F: FnOnce(&mut T) -> std::result::Result<&mut U, E>, E>(
        self,
        f: F,
    ) -> std::result::Result<CellRefMut<'a, U>, E> {
        Ok(CellRefMut {
            value: f(self.value)?,
            borrow: self.borrow,
            marker: PhantomData,
        })
    }
}

impl<'a, T> Deref for CellRefMut<'a, T> {
    type Target = T;

    #[inline]
    fn deref(&self) -> &Self::Target {
        self.value
    }
}

impl<'a, T> DerefMut for CellRefMut<'a, T> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.value
    }
}

pub trait Storage: 'static + Send {
    fn as_any(&self) -> &dyn std::any::Any;

    fn as_any_mut(&mut self) -> &mut dyn std::any::Any;
}

impl<T> Storage for T
where
    T: 'static + Sized + Send,
{
    #[inline]
    fn as_any(&self) -> &dyn std::any::Any {
        self as &dyn std::any::Any
    }

    #[inline]
    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
        self as &mut dyn std::any::Any
    }
}