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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
#![no_std]
#![forbid(unsafe_code)]

#![doc = include_str!("../README.md")]

#[cfg_attr(test, macro_use)]
extern crate alloc;

use core::cell::{RefCell, BorrowError, BorrowMutError};
use alloc::rc::{Rc, Weak};

/// An error resulting from [`MutRc::with_mut`].
#[derive(Debug)]
pub enum MutateError {
    /// The shared value is already borrowed.
    /// This can be caused if the same shared value is accessed from within [`MutRc::with`] or [`MutRc::with_mut`].
    BorrowMutError(BorrowMutError),
    /// There exists an aliasing [`Rc<T>`] returned by [`MutRc::finalize`] on the same shared value.
    Finalized,
}

/// A temporarily-mutable version of [`Rc`].
/// 
/// [`MutRc<T>`] is essentially equivalent to [`Rc<RefCell<T>>`] except that it can be "finalized" into an [`Rc<T>`] once mutation is no longer needed.
/// This operation preserves the original aliasing topology, and is useful for initializing aliasing structures
/// that initially need mutability, but later can be converted to an immutable form.
/// 
/// All operations on [`MutRc`] are guaranteed to not panic.
#[derive(Debug, Default)]
pub struct MutRc<T>(Rc<RefCell<Rc<T>>>);
impl<T> MutRc<T> {
    /// Creates a new, unaliased instance of [`MutRc<T>`] with the given initial value.
    pub fn new(value: T) -> Self {
        Self(Rc::new(RefCell::new(Rc::new(value))))
    }
    /// Accesses the shared value immutably, optionally returning the result of the callback.
    /// 
    /// This operation can fail if the shared value is already borrowed mutably (i.e., if called from within [`MutRc::with_mut`] on the same shared value).
    pub fn with<U, F: FnOnce(&T) -> U>(&self, f: F) -> Result<U, BorrowError> {
        Ok(f(&*self.0.try_borrow()?))
    }
    /// Accesses the shared value mutably, optionally returning the result of the callback.
    /// 
    /// This operation can fail if the shared value is already borrowed (i.e., if called from within [`MutRc::with`] or [`MutRc::with_mut`] on the same shared value),
    /// or if there exists an aliasing [`Rc<T>`] returned by [`MutRc::finalize`] on the same shared value.
    /// 
    /// If recursion is needed, but mutation is not, consider using [`MutRc::with`] instead.
    pub fn with_mut<U, F: FnOnce(&mut T) -> U>(&self, f: F) -> Result<U, MutateError> {
        match self.0.try_borrow_mut() {
            Ok(mut x) => match Rc::get_mut(&mut *x) {
                Some(x) => Ok(f(x)),
                None => Err(MutateError::Finalized),
            }
            Err(e) => Err(MutateError::BorrowMutError(e)),
        }
    }
    /// Finalizes the value into an (immutable) aliasing instance of [`Rc<T>`].
    /// While this aliasing [`Rc<T>`] exists, all subsequent calls to [`MutRc::with_mut`] on the same shared value will fail.
    /// 
    /// This operation can fail if the shared value is already borrowed mutably (i.e., if called from within [`MutRc::with_mut`] on the same shared value).
    pub fn finalize(&self) -> Result<Rc<T>, BorrowError> {
        Ok(self.0.try_borrow()?.clone())
    }

    // -------------------------------------------------------------

    /// Gets a copy of the currently stored value.
    pub fn get(&self) -> Result<T, BorrowError> where T: Copy {
        self.with(|x| *x)
    }
    /// Gets a clone of the currently stored value.
    pub fn get_clone(&self) -> Result<T, BorrowError> where T: Clone {
        self.with(Clone::clone)
    }
    /// Takes the currently stored value and replaces it with the default value.
    pub fn take(&self) -> Result<T, MutateError> where T: Default {
        self.with_mut(core::mem::take)
    }
    /// Replaces the currently stored value and returns the previous value.
    pub fn replace(&self, value: T) -> Result<T, MutateError> {
        self.with_mut(|x| core::mem::replace(x, value))
    }
    /// Sets the currently stored value.
    pub fn set(&self, value: T) -> Result<(), MutateError> {
        self.with_mut(|x| *x = value)
    }

    // -------------------------------------------------------------

    /// Checks if two instances of [`MutRc<T>`] are aliases to the same value.
    pub fn ptr_eq(this: &MutRc<T>, other: &MutRc<T>) -> bool {
        Rc::ptr_eq(&this.0, &other.0)
    }

    // -------------------------------------------------------------

    /// Downgrades this [`MutRc`] into a [`MutWeak`].
    pub fn downgrade(this: &Self) -> MutWeak<T> {
        MutWeak(Rc::downgrade(&this.0))
    }
}
impl<T> Clone for MutRc<T> {
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}
impl<T> From<T> for MutRc<T> {
    fn from(value: T) -> Self {
        Self::new(value)
    }
}

/// A weak reference counted version of [`MutRc`].
pub struct MutWeak<T>(Weak<RefCell<Rc<T>>>);
impl<T> MutWeak<T> {
    /// Checks if two instances of [`MutWeak`] are (weak) aliases to the same value.
    pub fn ptr_eq(this: &Self, other: &MutWeak<T>) -> bool {
        this.0.ptr_eq(&other.0)
    }

    // -------------------------------------------------------------

    /// Attempts to upgrade the weak reference back to a strong reference.
    pub fn upgrade(&self) -> Option<MutRc<T>> {
        self.0.upgrade().map(MutRc)
    }
}
impl<T> Clone for MutWeak<T> {
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

#[test]
fn test_basic() {
    #[derive(Debug)]
    struct NoClone(i32);

    let a = MutRc::new(NoClone(45));
    let b = a.clone();
    let c = MutRc::new(NoClone(45));

    assert!(MutRc::ptr_eq(&a, &b));
    assert!(!MutRc::ptr_eq(&a, &c));
    assert!(!MutRc::ptr_eq(&b, &c));

    assert_eq!(a.with(|x| x.0).unwrap(), 45);
    assert_eq!(b.with(|x| x.0).unwrap(), 45);
    assert_eq!(c.with(|x| x.0).unwrap(), 45);

    a.with_mut(|x| x.0 = -23).unwrap();

    match a.with_mut(|_| a.with_mut(|_| ())) {
        Ok(Err(MutateError::BorrowMutError(_))) => (),
        x => panic!("{x:?}"),
    }

    assert_eq!(a.with(|x| x.0).unwrap(), -23);
    assert_eq!(b.with(|x| x.0).unwrap(), -23);
    assert_eq!(c.with(|x| x.0).unwrap(), 45);

    assert_eq!(a.with(|_| a.with(|x| x.0).unwrap()).unwrap(), -23);
    assert_eq!(b.with(|_| b.with(|x| x.0).unwrap()).unwrap(), -23);
    assert_eq!(c.with(|_| c.with(|x| x.0).unwrap()).unwrap(), 45);

    a.finalize().unwrap();
    b.finalize().unwrap();
    c.finalize().unwrap();

    b.with_mut(|x| x.0 = 17).unwrap();
    c.with_mut(|x| x.0 = 12).unwrap();

    assert_eq!(a.with(|_| a.with(|x| x.0).unwrap()).unwrap(), 17);
    assert_eq!(b.with(|_| b.with(|x| x.0).unwrap()).unwrap(), 17);
    assert_eq!(c.with(|_| c.with(|x| x.0).unwrap()).unwrap(), 12);

    let fa = a.finalize().unwrap();
    let fb = b.finalize().unwrap();
    let fc = c.finalize().unwrap();

    match (a.with_mut(|_| ()), b.with_mut(|_| ()), c.with_mut(|_| ())) {
        (Err(MutateError::Finalized), Err(MutateError::Finalized), Err(MutateError::Finalized)) => (),
        x => panic!("{x:?}"),
    }

    assert!(Rc::ptr_eq(&fa, &fb));
    assert!(!Rc::ptr_eq(&fa, &fc));
    assert!(!Rc::ptr_eq(&fb, &fc));

    assert_eq!(fa.0, 17);
    assert_eq!(fb.0, 17);
    assert_eq!(fc.0, 12);

    assert_eq!(a.with(|x| x.0).unwrap(), 17);
    assert_eq!(b.with(|x| x.0).unwrap(), 17);
    assert_eq!(c.with(|x| x.0).unwrap(), 12);

    assert_eq!(a.with(|_| a.with(|x| x.0).unwrap()).unwrap(), 17);
    assert_eq!(b.with(|_| b.with(|x| x.0).unwrap()).unwrap(), 17);
    assert_eq!(c.with(|_| c.with(|x| x.0).unwrap()).unwrap(), 12);
}
#[test]
fn test_traits() {
    let a: MutRc<i32> = Default::default();
    assert_eq!(a.with(|x| *x).unwrap(), 0);
    let fa = a.finalize().unwrap();
    assert_eq!(*fa, 0);

    let s = format!("{a:?}");
    assert!(!s.is_empty());

    let b: MutRc<u64> = 475.into();
    assert_eq!(b.with(|x| *x).unwrap(), 475);
    let fb = b.finalize().unwrap();
    assert_eq!(*fb, 475);
}
#[test]
fn test_extra() {
    #[derive(Default, Clone, Copy)]
    struct Thing(i32);

    let a = MutRc::new(Thing(23));
    let b = a.clone();

    assert_eq!(a.get().unwrap().0, 23);
    assert_eq!(a.get_clone().unwrap().0, 23);
    assert_eq!(b.get().unwrap().0, 23);
    assert_eq!(b.get_clone().unwrap().0, 23);
    assert!(MutRc::ptr_eq(&a, &b));

    assert_eq!(b.replace(Thing(44)).unwrap().0, 23);
    assert_eq!(a.get().unwrap().0, 44);
    assert_eq!(a.get_clone().unwrap().0, 44);
    assert_eq!(b.get().unwrap().0, 44);
    assert_eq!(b.get_clone().unwrap().0, 44);
    assert!(MutRc::ptr_eq(&a, &b));

    assert_eq!(a.take().unwrap().0, 44);
    assert_eq!(a.get().unwrap().0, 0);
    assert_eq!(a.get_clone().unwrap().0, 0);
    assert_eq!(b.get().unwrap().0, 0);
    assert_eq!(b.get_clone().unwrap().0, 0);
    assert!(MutRc::ptr_eq(&a, &b));

    assert_eq!(b.set(Thing(47)).unwrap(), ());
    assert_eq!(a.get().unwrap().0, 47);
    assert_eq!(a.get_clone().unwrap().0, 47);
    assert_eq!(b.get().unwrap().0, 47);
    assert_eq!(b.get_clone().unwrap().0, 47);
    assert!(MutRc::ptr_eq(&a, &b));
}
#[test]
fn test_weak() {
    #[derive(Default)]
    struct NoClone(i32);

    let a = MutRc::new(NoClone(32));
    let b = a.clone();
    let c = MutRc::downgrade(&a);
    let d = MutRc::downgrade(&b);
    let e = MutRc::new(NoClone(32));
    let f = MutRc::downgrade(&e);

    assert!(MutWeak::ptr_eq(&c, &d));
    assert!(!MutWeak::ptr_eq(&c, &f));
    assert!(!MutWeak::ptr_eq(&d, &f));

    assert!(MutWeak::ptr_eq(&c.clone(), &c.clone()));
    assert!(MutWeak::ptr_eq(&c.clone(), &d.clone()));
    assert!(MutWeak::ptr_eq(&d.clone(), &d.clone()));
    assert!(MutWeak::ptr_eq(&f.clone(), &f.clone()));
    assert!(!MutWeak::ptr_eq(&c.clone(), &f.clone()));
    assert!(!MutWeak::ptr_eq(&d.clone(), &f.clone()));

    assert!(MutRc::ptr_eq(&c.upgrade().unwrap(), &a));
    assert!(MutRc::ptr_eq(&d.upgrade().unwrap(), &a));
    assert!(MutRc::ptr_eq(&f.upgrade().unwrap(), &e));

    drop(a);

    assert!(MutRc::ptr_eq(&c.upgrade().unwrap(), &b));
    assert!(MutRc::ptr_eq(&d.upgrade().unwrap(), &b));
    assert!(MutRc::ptr_eq(&f.upgrade().unwrap(), &e));

    drop(b);

    assert!(c.upgrade().is_none());
    assert!(d.upgrade().is_none());
    assert!(MutRc::ptr_eq(&f.upgrade().unwrap(), &e));

    drop(e);

    assert!(c.upgrade().is_none());
    assert!(d.upgrade().is_none());
    assert!(f.upgrade().is_none());
}