sharedptr/
Rc.rs

1use std::ops::{Deref, DerefMut};
2use std::rc::{Rc, Weak};
3
4#[derive(Debug)]
5pub struct SharedPtr<T: ?Sized> {
6    rc: Option<Rc<T>>,
7}
8
9impl<T> SharedPtr<T> {
10    #[inline]
11    pub fn new(v: T) -> SharedPtr<T> {
12        SharedPtr {
13            rc: Some(Rc::new(v)),
14        }
15    }
16    #[inline]
17    pub fn write(&mut self, v: T) {
18        self.rc = Some(Rc::new(v));
19    }
20    #[inline]
21    pub fn assume_init(self) -> Option<Rc<T>> {
22        self.rc
23    }
24
25}
26
27impl<T: ?Sized> SharedPtr<T> {
28    #[inline]
29    pub fn zeroed() -> SharedPtr<T> {
30        SharedPtr { rc: None }
31    }
32
33    #[inline]
34    pub fn weak(&self) -> Option<Weak<T>> {
35        self.rc.as_ref().map(Rc::downgrade)
36    }
37    #[inline]
38    pub fn set_null(&mut self) {
39        self.rc = None;
40    }
41    #[inline]
42    pub fn is_null(&self) -> bool {
43        self.rc.is_none()
44    }
45
46    /// if ptr is no unique,none will be returned, or Some(&mut T) be returned.
47    #[inline]
48    pub fn get_mut(&mut self) -> Option<&mut T> {
49        if let Some(ref mut rc)=self.rc {
50            Rc::get_mut(rc)
51        }else{
52            None
53        }
54    }
55}
56
57impl <T:Clone> SharedPtr<T> {
58    #[inline]
59    pub fn clone_inner(mut self)->Option<T>{
60        if let Some(ref mut rc)=self.rc {
61            Some(rc.as_ref().clone())
62        }else{
63            None
64        }
65    }
66}
67
68impl<T: ?Sized> Deref for SharedPtr<T> {
69    type Target = Rc<T>;
70    #[inline]
71    fn deref(&self) -> &Self::Target {
72        self.rc.as_ref().expect("null shared deref")
73    }
74}
75
76impl<T: ?Sized> DerefMut for SharedPtr<T> {
77    #[inline]
78    fn deref_mut(&mut self) -> &mut Self::Target {
79        self.rc.as_mut().expect("null shared deref mut")
80    }
81}
82
83impl<T: ?Sized> Clone for SharedPtr<T> {
84    #[inline]
85    fn clone(&self) -> Self {
86        Self {
87            rc: self.rc.clone(),
88        }
89    }
90}
91
92impl<T: ?Sized> From<Rc<T>> for SharedPtr<T> {
93    #[inline]
94    fn from(r: Rc<T>) -> Self {
95        Self { rc: Some(r) }
96    }
97}
98
99impl<T: ?Sized> Default for SharedPtr<T> {
100    #[inline]
101    fn default() -> Self {
102        SharedPtr::<T>::zeroed()
103    }
104}