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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
/// # speedy_refs::Rc
/// `Rc<T>` is a reference-counted pointer type that allows multiple shared references
/// to a value of type `T`. It tracks the number of references and automatically deallocates
/// the value when the last reference is dropped.
///
/// # Implementation
/// The `Rc<T>` type is implemented as a thin wrapper around a raw pointer to an `Inner<T>` struct,
/// which contains the value of type `T` and a reference count stored in a `std::cell::UnsafeCell<usize>`.
/// - The value passed to the new() is used together with a count to form an `Inner` type. let's call it `inner`.
/// - `inner` is moved to the heap
/// - A pointer to the heap memory of `inner` is kept by the `Rc` struct
/// - When the last Rc is dropped, `inner` is deallocated
///
/// # Weak References
///
/// This `Rc<T>` implementation does not provide a way to distinguish between strong and weak references.
/// Forming reference cycles with `Rc<T>` instances can lead to memory leaks, even after all strong references have been dropped.
/// To avoid memory leaks caused by reference cycles, we recommend that you use `std::rc::Rc` when the use case it likely
/// to form reference cycles.
///
///
/// # Examples
///
/// ```
/// use speedy_refs::Rc;
///
/// let value = Rc::new(42);
///
/// let reference1 = Rc::clone(&value);
/// let reference2 = Rc::clone(&value);
///
/// assert_eq!(*value, 42);
/// assert_eq!(*reference1, 42);
/// assert_eq!(*reference2, 42);
///
/// drop(reference1);
///
/// assert_eq!(*value, 42);
/// assert_eq!(*reference2, 42);
///
/// drop(reference2);
///
/// // value is deallocated here
/// ```
;
/// Cloning An `Rc<T>` only creates a new pointer to the same content.
///
/// For this reason T has no Clone bound.
/// # Inner
/// A helper struct for `Rc` that stores the value and the reference count
/// for a shared value of type `T`. It is used to implement reference counting for the `Rc` type.
///
/// The first field of `Inner` is the value of type `T` being shared by one or more `Rc`
/// instances. The second field is an `UnsafeCell<usize>` that is used to store the reference count
/// of the shared value. The `UnsafeCell` allows for interior mutability, which is necessary to
/// increment or decrement the reference count from immutable context.
;