jec_rccow/
lib.rs

1use std::ops::{Deref, DerefMut};
2use std::rc::Rc;
3
4use std::fmt::Display;
5use std::fmt;
6
7
8#[derive(Clone,Debug)]
9pub struct RcCow<T>
10    where T: 'static
11{
12    data: Rc<T>,
13}
14
15impl<T> RcCow<T> {
16    pub fn to_mut(&mut self) -> &mut T
17        where T: Clone
18    {
19        Rc::make_mut(&mut self.data)
20    }
21
22    pub fn into_owned(self) -> T
23        where T: Clone
24    {
25        match Rc::try_unwrap(self.data.clone()) {
26            Ok(v) => v,
27            Err(_) => T::clone(&self.data),
28        }
29    }
30
31    pub fn unwrap(self) -> Rc<T> {
32        return self.data;
33    }
34}
35
36impl<T> Display for RcCow<T>
37    where T: Display
38{
39    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
40        self.data.fmt(f)
41    }
42}
43
44impl<T> Deref for RcCow<T> {
45    type Target = T;
46
47    fn deref(&self) -> &T {
48        self.data.deref()
49    }
50}
51
52impl<T> DerefMut for RcCow<T>
53    where T: Clone
54{
55    fn deref_mut(&mut self) -> &mut T {
56        Rc::make_mut(&mut self.data)
57    }
58}
59
60impl<T> RcCow<T> {
61    pub fn new(val: T) -> RcCow<T> {
62        RcCow { data: Rc::new(val) }
63    }
64}
65
66
67#[cfg(test)]
68mod test {
69    use super::*;
70
71    #[test]
72    fn stuff() {
73        let mut a = RcCow::new(5i32);
74        let mut b = a.clone();
75
76        *b += 1;
77        let mut c = b.clone();
78        *b += 2;
79
80        panic!("a: {}, b: {}, c: {}", a, b, c);
81    }
82}