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

#[derive(Debug)]
pub struct SharedPtr<T: ?Sized> {
    rc: Option<Rc<T>>,
}

impl<T> SharedPtr<T> {
    #[inline]
    pub fn new(v: T) -> SharedPtr<T> {
        SharedPtr {
            rc: Some(Rc::new(v)),
        }
    }
    #[inline]
    pub fn write(&mut self, v: T) {
        self.rc = Some(Rc::new(v));
    }
    #[inline]
    pub fn assume_init(self) -> Option<Rc<T>> {
        self.rc
    }

}

impl<T: ?Sized> SharedPtr<T> {
    #[inline]
    pub fn zeroed() -> SharedPtr<T> {
        SharedPtr { rc: None }
    }

    #[inline]
    pub fn weak(&self) -> Option<Weak<T>> {
        self.rc.as_ref().map(Rc::downgrade)
    }
    #[inline]
    pub fn set_null(&mut self) {
        self.rc = None;
    }
    #[inline]
    pub fn is_null(&self) -> bool {
        self.rc.is_none()
    }

    /// if ptr is no unique,none will be returned, or Some(&mut T) be returned.
    #[inline]
    pub fn get_mut(&mut self) -> Option<&mut T> {
        if let Some(ref mut rc)=self.rc {
            Rc::get_mut(rc)
        }else{
            None
        }
    }
}

impl <T:Clone> SharedPtr<T> {
    #[inline]
    pub fn clone_inner(mut self)->Option<T>{
        if let Some(ref mut rc)=self.rc {
            Some(rc.as_ref().clone())
        }else{
            None
        }
    }
}

impl<T: ?Sized> Deref for SharedPtr<T> {
    type Target = Rc<T>;
    #[inline]
    fn deref(&self) -> &Self::Target {
        self.rc.as_ref().expect("null shared deref")
    }
}

impl<T: ?Sized> DerefMut for SharedPtr<T> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.rc.as_mut().expect("null shared deref mut")
    }
}

impl<T: ?Sized> Clone for SharedPtr<T> {
    #[inline]
    fn clone(&self) -> Self {
        Self {
            rc: self.rc.clone(),
        }
    }
}

impl<T: ?Sized> From<Rc<T>> for SharedPtr<T> {
    #[inline]
    fn from(r: Rc<T>) -> Self {
        Self { rc: Some(r) }
    }
}

impl<T: ?Sized> Default for SharedPtr<T> {
    #[inline]
    fn default() -> Self {
        SharedPtr::<T>::zeroed()
    }
}