ryna/structures/
mut_cell.rs

1use std::cell::UnsafeCell;
2
3#[derive(Debug)]
4pub struct MutCell<T> where T: Clone + PartialEq + Default {
5    inner: UnsafeCell<T>
6}
7
8impl<T: Clone + PartialEq + Default> Clone for MutCell<T> {
9    fn clone(&self) -> Self {
10        Self { inner: UnsafeCell::new(self.borrow().clone()) }
11    }
12}
13
14impl<T: Clone + PartialEq + Default> PartialEq for MutCell<T> {
15    fn eq(&self, other: &Self) -> bool {
16        self.borrow() == other.borrow()
17    }
18} 
19
20impl<T: Clone + PartialEq + Default> MutCell<T> {
21    pub fn new(obj: T) -> Self {
22        MutCell { inner: UnsafeCell::new(obj) }
23    }
24
25    #[allow(clippy::should_implement_trait)]
26    #[inline(always)]
27    pub fn borrow(&self) -> &T {
28        unsafe { &*self.inner.get() }
29    }
30
31    #[allow(clippy::should_implement_trait)]
32    #[allow(clippy::mut_from_ref)]
33    #[inline(always)]
34    pub fn borrow_mut(&self) -> &mut T {
35        unsafe { &mut *self.inner.get() }
36    }
37
38    #[inline(always)]
39    pub fn as_ptr(&self) -> *mut T {
40        self.inner.get()
41    }
42
43    #[inline(always)]
44    pub fn take(&self) -> T {
45        std::mem::take(self.borrow_mut())
46    }
47}
48
49impl<T: Clone + PartialEq + Default> Eq for MutCell<T> {}