-
Notifications
You must be signed in to change notification settings - Fork 72
/
Copy pathrc.rs
116 lines (94 loc) · 2.77 KB
/
rc.rs
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
105
106
107
108
109
110
111
112
113
114
115
116
// Single-threaded reference-counting pointers. ‘Rc’ stands for ‘Reference Counted’.
use std::collections::HashMap;
use std::rc::Rc;
use std::cell::{RefCell,RefMut};
pub fn rc_example() {
let rc = Rc::new(1);
let rc2 = rc.clone();
let rc3 = Rc::clone(&rc);
println!("rc2: {}, rc3:{}", rc2, rc3);
let my_weak = Rc::downgrade(&rc);
drop(rc);
drop(rc2);
drop(rc3);
println!("my_weak: {}", my_weak.upgrade().is_none());
}
pub fn rc_refcell_example() {
let shared_map: Rc<RefCell<_>> = Rc::new(RefCell::new(HashMap::new()));
// Create a new block to limit the scope of the dynamic borrow
{
let mut map: RefMut<_> = shared_map.borrow_mut();
map.insert("africa", 92388);
map.insert("kyoto", 11837);
map.insert("piccadilly", 11826);
map.insert("marbles", 38);
}
// Note that if we had not let the previous borrow of the cache fall out
// of scope then the subsequent borrow would cause a dynamic thread panic.
// This is the major hazard of using `RefCell`.
let total: i32 = shared_map.borrow().values().sum();
println!("{total}");
}
pub fn myrc_example() {
let s = example::Rc::new("hello world");
let s1 = s.clone();
let v = s1.value();
println!("myrc value: {}", v);
}
pub mod example {
use std::cell::Cell;
use std::marker::PhantomData;
use std::process::abort;
use std::ptr::NonNull;
pub struct Rc<T: ?Sized> {
ptr: NonNull<RcBox<T>>,
phantom: PhantomData<RcBox<T>>,
}
impl<T> Rc<T> {
pub fn new(t: T) -> Self {
let ptr = Box::new(RcBox {
strong: Cell::new(1),
refcount: Cell::new(1),
value: t,
});
let ptr = NonNull::new(Box::into_raw(ptr)).unwrap();
Self {
ptr: ptr,
phantom: PhantomData,
}
}
pub fn value(&self) -> &T {
&self.inner().value
}
}
struct RcBox<T: ?Sized> {
strong: Cell<usize>,
refcount: Cell<usize>,
value: T,
}
impl<T: ?Sized> Clone for Rc<T> {
fn clone(&self) -> Rc<T> {
self.inc_strong();
Rc {
ptr: self.ptr,
phantom: PhantomData,
}
}
}
trait RcBoxPtr<T: ?Sized> {
fn inner(&self) -> &RcBox<T>;
fn strong(&self) -> usize {
self.inner().strong.get()
}
fn inc_strong(&self) {
self.inner()
.strong
.set(self.strong().checked_add(1).unwrap_or_else(|| abort()));
}
}
impl<T: ?Sized> RcBoxPtr<T> for Rc<T> {
fn inner(&self) -> &RcBox<T> {
unsafe { self.ptr.as_ref() }
}
}
}