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

/// A mutable memory location that clones its contents on retrieval.
pub struct CloningCell<T: Clone>(UnsafeCell<T>);

impl<T: Clone> CloningCell<T> {
    /// Creates a new `CloningCell` containing the given value.
    ///
    /// # Example
    ///
    /// ```
    /// use mitochondria::CloningCell;
    ///
    /// let c = CloningCell::new("Hello cytosol!".to_owned());
    /// ```
    #[inline]
    pub fn new(value: T) -> Self {
        CloningCell(UnsafeCell::new(value))
    }

    /// Returns a clone of the contained value.
    ///
    /// # Example
    ///
    /// ```
    /// use mitochondria::CloningCell;
    ///
    /// let c = CloningCell::new("Hello lysosome!".to_owned());
    ///
    /// let greeting = c.get();
    /// ```
    #[inline]
    pub fn get(&self) -> T {
        unsafe { (*self.0.get()).clone() }
    }

    /// Sets the contained value.
    ///
    /// # Example
    ///
    /// ```
    /// use mitochondria::CloningCell;
    ///
    /// let c = CloningCell::new("Hello vacuole!".to_owned());
    ///
    /// c.set("Hello cytoskeleton!".to_owned());
    /// ```
    #[inline]
    pub fn set(&self, value: T) {
        unsafe { *self.0.get() = value; } 
    }
}