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
//! Copy-on-Write pointers.
//!
//! Thin wrappers around the standard library ref-counted pointers that clones
//! on `DerefMut` if reference count is greater than 1.

use std::ops::Deref;
use std::ops::DerefMut;
use std::rc::Rc;
use std::sync::Arc;

pub struct RcCow<T>(pub Rc<T>);

impl<T: Clone> RcCow<T> {
    pub fn new(value: T) -> RcCow<T> {
        RcCow(Rc::new(value))
    }
}

impl<T> Clone for RcCow<T> {
    fn clone(&self) -> RcCow<T> {
        RcCow(self.0.clone())
    }
}

impl<T> Deref for RcCow<T> {
    type Target = T;

    fn deref(&self) -> &T {
        self.0.deref()
    }
}

impl<T: Clone> DerefMut for RcCow<T> {
    fn deref_mut(&mut self) -> &mut T {
        Rc::make_mut(&mut self.0)
    }
}

pub struct ArcCow<T>(pub Arc<T>);

impl<T: Clone> ArcCow<T> {
    pub fn new(value: T) -> ArcCow<T> {
        ArcCow(Arc::new(value))
    }
}

impl<T> Clone for ArcCow<T> {
    fn clone(&self) -> ArcCow<T> {
        ArcCow(self.0.clone())
    }
}

impl<T> Deref for ArcCow<T> {
    type Target = T;

    fn deref(&self) -> &T {
        self.0.deref()
    }
}

impl<T: Clone> DerefMut for ArcCow<T> {
    fn deref_mut(&mut self) -> &mut T {
        Arc::make_mut(&mut self.0)
    }
}