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
use std::ops::{Deref, DerefMut};
use std::rc::Rc;

use std::fmt::Display;
use std::fmt;


#[derive(Clone,Debug)]
pub struct RcCow<T>
    where T: 'static
{
    data: Rc<T>,
}

impl<T> RcCow<T> {
    pub fn to_mut(&mut self) -> &mut T
        where T: Clone
    {
        Rc::make_mut(&mut self.data)
    }

    pub fn into_owned(self) -> T
        where T: Clone
    {
        match Rc::try_unwrap(self.data.clone()) {
            Ok(v) => v,
            Err(_) => T::clone(&self.data),
        }
    }

    pub fn unwrap(self) -> Rc<T> {
        return self.data;
    }
}

impl<T> Display for RcCow<T>
    where T: Display
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.data.fmt(f)
    }
}

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

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

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

impl<T> RcCow<T> {
    pub fn new(val: T) -> RcCow<T> {
        RcCow { data: Rc::new(val) }
    }
}


#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn stuff() {
        let mut a = RcCow::new(5i32);
        let mut b = a.clone();

        *b += 1;
        let mut c = b.clone();
        *b += 2;

        panic!("a: {}, b: {}, c: {}", a, b, c);
    }
}