binary_tree/
cow.rs

1//! Copy-on-Write pointers.
2//!
3//! Thin wrappers around the standard library ref-counted pointers that clones
4//! on `DerefMut` if reference count is greater than 1.
5
6use std::ops::Deref;
7use std::ops::DerefMut;
8use std::rc::Rc;
9use std::sync::Arc;
10
11pub struct RcCow<T>(pub Rc<T>);
12
13impl<T: Clone> RcCow<T> {
14    pub fn new(value: T) -> RcCow<T> {
15        RcCow(Rc::new(value))
16    }
17}
18
19impl<T> Clone for RcCow<T> {
20    fn clone(&self) -> RcCow<T> {
21        RcCow(self.0.clone())
22    }
23}
24
25impl<T> Deref for RcCow<T> {
26    type Target = T;
27
28    fn deref(&self) -> &T {
29        self.0.deref()
30    }
31}
32
33impl<T: Clone> DerefMut for RcCow<T> {
34    fn deref_mut(&mut self) -> &mut T {
35        Rc::make_mut(&mut self.0)
36    }
37}
38
39pub struct ArcCow<T>(pub Arc<T>);
40
41impl<T: Clone> ArcCow<T> {
42    pub fn new(value: T) -> ArcCow<T> {
43        ArcCow(Arc::new(value))
44    }
45}
46
47impl<T> Clone for ArcCow<T> {
48    fn clone(&self) -> ArcCow<T> {
49        ArcCow(self.0.clone())
50    }
51}
52
53impl<T> Deref for ArcCow<T> {
54    type Target = T;
55
56    fn deref(&self) -> &T {
57        self.0.deref()
58    }
59}
60
61impl<T: Clone> DerefMut for ArcCow<T> {
62    fn deref_mut(&mut self) -> &mut T {
63        Arc::make_mut(&mut self.0)
64    }
65}