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
#![cfg_attr(test, deny(warnings))]
#![deny(missing_docs)]

//! # RcMut
//!
//! An unchecked shared mutability primitive.
//!
//! RcMut provides unchecked shared mutability and ownership.
//! It is extremely unsafe to use directly.
//!

use std::cell::UnsafeCell;
use std::sync::Arc;
use std::rc::Rc;
use std::mem;

/// A reference counted smart pointer with unrestricted mutability.
pub struct RcMut<T> {
    inner: Rc<UnsafeCell<T>>
}

impl<T> Clone for RcMut<T> {
    fn clone(&self) -> RcMut<T> {
        RcMut { inner: self.inner.clone() }
    }
}

impl<T> RcMut<T> {
    /// Create a new RcMut for a value.
    pub fn new(val: T) -> RcMut<T> {
        RcMut {
            inner: Rc::new(UnsafeCell::new(val))
        }
    }

    /// Retrieve the inner Rc as a reference.
    pub unsafe fn as_rc(&self) -> &Rc<T> {
        mem::transmute(&self.inner)
    }

    /// Retrieve the inner Rc as a mutable reference.
    pub unsafe fn as_rc_mut(&mut self) -> &mut Rc<T> {
        mem::transmute(&mut self.inner)
    }

    /// Get a reference to the value.
    pub unsafe fn borrow(&self) -> &T {
        mem::transmute(self.inner.get())
    }

    /// Get a mutable reference to the value.
    pub unsafe fn borrow_mut(&mut self) -> &mut T {
        mem::transmute(self.inner.get())
    }
}

/// A reference counted smart pointer with unrestricted mutability.
pub struct ArcMut<T> {
    inner: Arc<UnsafeCell<T>>
}

impl<T> Clone for ArcMut<T> {
    fn clone(&self) -> ArcMut<T> {
        ArcMut { inner: self.inner.clone() }
    }
}

impl<T> ArcMut<T> {
    /// Create a new ArcMut for a value.
    pub fn new(val: T) -> ArcMut<T> {
        ArcMut {
            inner: Arc::new(UnsafeCell::new(val))
        }
    }

    /// Retrieve the inner Rc as a reference.
    pub unsafe fn as_arc(&self) -> &Arc<T> {
        mem::transmute(&self.inner)
    }

    /// Retrieve the inner Rc as a mutable reference.
    pub unsafe fn as_arc_mut(&mut self) -> &mut Arc<T> {
        mem::transmute(&mut self.inner)
    }

    /// Get a reference to the value.
    pub unsafe fn borrow(&self) -> &T {
        mem::transmute(self.inner.get())
    }

    /// Get a mutable reference to the value.
    pub unsafe fn borrow_mut(&mut self) -> &mut T {
        mem::transmute(self.inner.get())
    }
}