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
use std::cell::UnsafeCell;

#[derive(Debug)]
pub struct MutCell<T> where T: Clone + PartialEq + Default {
    inner: UnsafeCell<T>
}

impl<T: Clone + PartialEq + Default> Clone for MutCell<T> {
    fn clone(&self) -> Self {
        Self { inner: UnsafeCell::new(self.borrow().clone()) }
    }
}

impl<T: Clone + PartialEq + Default> PartialEq for MutCell<T> {
    fn eq(&self, other: &Self) -> bool {
        self.borrow() == other.borrow()
    }
} 

impl<T: Clone + PartialEq + Default> MutCell<T> {
    pub fn new(obj: T) -> Self {
        MutCell { inner: UnsafeCell::new(obj) }
    }

    #[allow(clippy::should_implement_trait)]
    #[inline(always)]
    pub fn borrow(&self) -> &T {
        unsafe { &*self.inner.get() }
    }

    #[allow(clippy::should_implement_trait)]
    #[allow(clippy::mut_from_ref)]
    #[inline(always)]
    pub fn borrow_mut(&self) -> &mut T {
        unsafe { &mut *self.inner.get() }
    }

    #[inline(always)]
    pub fn as_ptr(&self) -> *mut T {
        self.inner.get()
    }

    #[inline(always)]
    pub fn take(&self) -> T {
        std::mem::take(self.borrow_mut())
    }
}

impl<T: Clone + PartialEq + Default> Eq for MutCell<T> {}