]>
Commit | Line | Data |
---|---|---|
041b39d2 XL |
1 | //! Single-threaded reference-counting pointers. 'Rc' stands for 'Reference |
2 | //! Counted'. | |
1a4d82fc | 3 | //! |
476ff2be | 4 | //! The type [`Rc<T>`][`Rc`] provides shared ownership of a value of type `T`, |
cc61c64b | 5 | //! allocated in the heap. Invoking [`clone`][clone] on [`Rc`] produces a new |
e74abb32 XL |
6 | //! pointer to the same allocation in the heap. When the last [`Rc`] pointer to a |
7 | //! given allocation is destroyed, the value stored in that allocation (often | |
8 | //! referred to as "inner value") is also dropped. | |
1a4d82fc | 9 | //! |
8bb4bdeb | 10 | //! Shared references in Rust disallow mutation by default, and [`Rc`] |
ea8adc8c | 11 | //! is no exception: you cannot generally obtain a mutable reference to |
8bb4bdeb XL |
12 | //! something inside an [`Rc`]. If you need mutability, put a [`Cell`] |
13 | //! or [`RefCell`] inside the [`Rc`]; see [an example of mutability | |
14 | //! inside an Rc][mutability]. | |
1a4d82fc | 15 | //! |
476ff2be SL |
16 | //! [`Rc`] uses non-atomic reference counting. This means that overhead is very |
17 | //! low, but an [`Rc`] cannot be sent between threads, and consequently [`Rc`] | |
9e0c209e | 18 | //! does not implement [`Send`][send]. As a result, the Rust compiler |
476ff2be | 19 | //! will check *at compile time* that you are not sending [`Rc`]s between |
9e0c209e SL |
20 | //! threads. If you need multi-threaded, atomic reference counting, use |
21 | //! [`sync::Arc`][arc]. | |
22 | //! | |
cc61c64b | 23 | //! The [`downgrade`][downgrade] method can be used to create a non-owning |
476ff2be | 24 | //! [`Weak`] pointer. A [`Weak`] pointer can be [`upgrade`][upgrade]d |
e74abb32 XL |
25 | //! to an [`Rc`], but this will return [`None`] if the value stored in the allocation has |
26 | //! already been dropped. In other words, `Weak` pointers do not keep the value | |
27 | //! inside the allocation alive; however, they *do* keep the allocation | |
28 | //! (the backing store for the inner value) alive. | |
9e0c209e | 29 | //! |
476ff2be SL |
30 | //! A cycle between [`Rc`] pointers will never be deallocated. For this reason, |
31 | //! [`Weak`] is used to break cycles. For example, a tree could have strong | |
32 | //! [`Rc`] pointers from parent nodes to children, and [`Weak`] pointers from | |
9e0c209e SL |
33 | //! children back to their parents. |
34 | //! | |
476ff2be SL |
35 | //! `Rc<T>` automatically dereferences to `T` (via the [`Deref`] trait), |
36 | //! so you can call `T`'s methods on a value of type [`Rc<T>`][`Rc`]. To avoid name | |
13cf67c4 XL |
37 | //! clashes with `T`'s methods, the methods of [`Rc<T>`][`Rc`] itself are associated |
38 | //! functions, called using function-like syntax: | |
9e0c209e SL |
39 | //! |
40 | //! ``` | |
c30ab7b3 SL |
41 | //! use std::rc::Rc; |
42 | //! let my_rc = Rc::new(()); | |
43 | //! | |
9e0c209e SL |
44 | //! Rc::downgrade(&my_rc); |
45 | //! ``` | |
46 | //! | |
e74abb32 XL |
47 | //! [`Weak<T>`][`Weak`] does not auto-dereference to `T`, because the inner value may have |
48 | //! already been dropped. | |
9e0c209e | 49 | //! |
7cac9316 XL |
50 | //! # Cloning references |
51 | //! | |
e74abb32 XL |
52 | //! Creating a new reference to the same allocation as an existing reference counted pointer |
53 | //! is done using the `Clone` trait implemented for [`Rc<T>`][`Rc`] and [`Weak<T>`][`Weak`]. | |
7cac9316 XL |
54 | //! |
55 | //! ``` | |
56 | //! use std::rc::Rc; | |
57 | //! let foo = Rc::new(vec![1.0, 2.0, 3.0]); | |
58 | //! // The two syntaxes below are equivalent. | |
59 | //! let a = foo.clone(); | |
60 | //! let b = Rc::clone(&foo); | |
61 | //! // a and b both point to the same memory location as foo. | |
62 | //! ``` | |
63 | //! | |
64 | //! The `Rc::clone(&from)` syntax is the most idiomatic because it conveys more explicitly | |
65 | //! the meaning of the code. In the example above, this syntax makes it easier to see that | |
66 | //! this code is creating a new reference rather than copying the whole content of foo. | |
67 | //! | |
1a4d82fc JJ |
68 | //! # Examples |
69 | //! | |
70 | //! Consider a scenario where a set of `Gadget`s are owned by a given `Owner`. | |
71 | //! We want to have our `Gadget`s point to their `Owner`. We can't do this with | |
72 | //! unique ownership, because more than one gadget may belong to the same | |
476ff2be | 73 | //! `Owner`. [`Rc`] allows us to share an `Owner` between multiple `Gadget`s, |
1a4d82fc JJ |
74 | //! and have the `Owner` remain allocated as long as any `Gadget` points at it. |
75 | //! | |
9e0c209e | 76 | //! ``` |
1a4d82fc JJ |
77 | //! use std::rc::Rc; |
78 | //! | |
79 | //! struct Owner { | |
9e0c209e | 80 | //! name: String, |
1a4d82fc JJ |
81 | //! // ...other fields |
82 | //! } | |
83 | //! | |
84 | //! struct Gadget { | |
85aaf69f | 85 | //! id: i32, |
9e0c209e | 86 | //! owner: Rc<Owner>, |
1a4d82fc JJ |
87 | //! // ...other fields |
88 | //! } | |
89 | //! | |
90 | //! fn main() { | |
9e0c209e SL |
91 | //! // Create a reference-counted `Owner`. |
92 | //! let gadget_owner: Rc<Owner> = Rc::new( | |
93 | //! Owner { | |
94 | //! name: "Gadget Man".to_string(), | |
95 | //! } | |
1a4d82fc JJ |
96 | //! ); |
97 | //! | |
9e0c209e | 98 | //! // Create `Gadget`s belonging to `gadget_owner`. Cloning the `Rc<Owner>` |
e74abb32 | 99 | //! // gives us a new pointer to the same `Owner` allocation, incrementing |
9e0c209e SL |
100 | //! // the reference count in the process. |
101 | //! let gadget1 = Gadget { | |
102 | //! id: 1, | |
7cac9316 | 103 | //! owner: Rc::clone(&gadget_owner), |
9e0c209e SL |
104 | //! }; |
105 | //! let gadget2 = Gadget { | |
106 | //! id: 2, | |
7cac9316 | 107 | //! owner: Rc::clone(&gadget_owner), |
9e0c209e | 108 | //! }; |
1a4d82fc | 109 | //! |
9e0c209e | 110 | //! // Dispose of our local variable `gadget_owner`. |
1a4d82fc JJ |
111 | //! drop(gadget_owner); |
112 | //! | |
9e0c209e SL |
113 | //! // Despite dropping `gadget_owner`, we're still able to print out the name |
114 | //! // of the `Owner` of the `Gadget`s. This is because we've only dropped a | |
115 | //! // single `Rc<Owner>`, not the `Owner` it points to. As long as there are | |
e74abb32 XL |
116 | //! // other `Rc<Owner>` pointing at the same `Owner` allocation, it will remain |
117 | //! // live. The field projection `gadget1.owner.name` works because | |
9e0c209e | 118 | //! // `Rc<Owner>` automatically dereferences to `Owner`. |
1a4d82fc JJ |
119 | //! println!("Gadget {} owned by {}", gadget1.id, gadget1.owner.name); |
120 | //! println!("Gadget {} owned by {}", gadget2.id, gadget2.owner.name); | |
121 | //! | |
9e0c209e SL |
122 | //! // At the end of the function, `gadget1` and `gadget2` are destroyed, and |
123 | //! // with them the last counted references to our `Owner`. Gadget Man now | |
124 | //! // gets destroyed as well. | |
1a4d82fc JJ |
125 | //! } |
126 | //! ``` | |
127 | //! | |
c34b1796 | 128 | //! If our requirements change, and we also need to be able to traverse from |
476ff2be | 129 | //! `Owner` to `Gadget`, we will run into problems. An [`Rc`] pointer from `Owner` |
e74abb32 XL |
130 | //! to `Gadget` introduces a cycle. This means that their |
131 | //! reference counts can never reach 0, and the allocation will never be destroyed: | |
132 | //! a memory leak. In order to get around this, we can use [`Weak`] | |
9e0c209e | 133 | //! pointers. |
1a4d82fc | 134 | //! |
c34b1796 | 135 | //! Rust actually makes it somewhat difficult to produce this loop in the first |
9e0c209e | 136 | //! place. In order to end up with two values that point at each other, one of |
476ff2be | 137 | //! them needs to be mutable. This is difficult because [`Rc`] enforces |
9e0c209e | 138 | //! memory safety by only giving out shared references to the value it wraps, |
c34b1796 | 139 | //! and these don't allow direct mutation. We need to wrap the part of the |
476ff2be | 140 | //! value we wish to mutate in a [`RefCell`], which provides *interior |
c34b1796 | 141 | //! mutability*: a method to achieve mutability through a shared reference. |
476ff2be | 142 | //! [`RefCell`] enforces Rust's borrowing rules at runtime. |
1a4d82fc | 143 | //! |
9e0c209e | 144 | //! ``` |
1a4d82fc JJ |
145 | //! use std::rc::Rc; |
146 | //! use std::rc::Weak; | |
147 | //! use std::cell::RefCell; | |
148 | //! | |
149 | //! struct Owner { | |
150 | //! name: String, | |
e9174d1e | 151 | //! gadgets: RefCell<Vec<Weak<Gadget>>>, |
1a4d82fc JJ |
152 | //! // ...other fields |
153 | //! } | |
154 | //! | |
155 | //! struct Gadget { | |
85aaf69f | 156 | //! id: i32, |
e9174d1e | 157 | //! owner: Rc<Owner>, |
1a4d82fc JJ |
158 | //! // ...other fields |
159 | //! } | |
160 | //! | |
161 | //! fn main() { | |
9e0c209e SL |
162 | //! // Create a reference-counted `Owner`. Note that we've put the `Owner`'s |
163 | //! // vector of `Gadget`s inside a `RefCell` so that we can mutate it through | |
164 | //! // a shared reference. | |
165 | //! let gadget_owner: Rc<Owner> = Rc::new( | |
e9174d1e SL |
166 | //! Owner { |
167 | //! name: "Gadget Man".to_string(), | |
9e0c209e | 168 | //! gadgets: RefCell::new(vec![]), |
e9174d1e | 169 | //! } |
1a4d82fc JJ |
170 | //! ); |
171 | //! | |
9e0c209e SL |
172 | //! // Create `Gadget`s belonging to `gadget_owner`, as before. |
173 | //! let gadget1 = Rc::new( | |
174 | //! Gadget { | |
175 | //! id: 1, | |
7cac9316 | 176 | //! owner: Rc::clone(&gadget_owner), |
9e0c209e SL |
177 | //! } |
178 | //! ); | |
179 | //! let gadget2 = Rc::new( | |
180 | //! Gadget { | |
181 | //! id: 2, | |
7cac9316 | 182 | //! owner: Rc::clone(&gadget_owner), |
9e0c209e SL |
183 | //! } |
184 | //! ); | |
185 | //! | |
186 | //! // Add the `Gadget`s to their `Owner`. | |
187 | //! { | |
188 | //! let mut gadgets = gadget_owner.gadgets.borrow_mut(); | |
189 | //! gadgets.push(Rc::downgrade(&gadget1)); | |
190 | //! gadgets.push(Rc::downgrade(&gadget2)); | |
1a4d82fc | 191 | //! |
9e0c209e SL |
192 | //! // `RefCell` dynamic borrow ends here. |
193 | //! } | |
1a4d82fc | 194 | //! |
9e0c209e SL |
195 | //! // Iterate over our `Gadget`s, printing their details out. |
196 | //! for gadget_weak in gadget_owner.gadgets.borrow().iter() { | |
1a4d82fc | 197 | //! |
9e0c209e | 198 | //! // `gadget_weak` is a `Weak<Gadget>`. Since `Weak` pointers can't |
e74abb32 | 199 | //! // guarantee the allocation still exists, we need to call |
9e0c209e SL |
200 | //! // `upgrade`, which returns an `Option<Rc<Gadget>>`. |
201 | //! // | |
e74abb32 | 202 | //! // In this case we know the allocation still exists, so we simply |
9e0c209e SL |
203 | //! // `unwrap` the `Option`. In a more complicated program, you might |
204 | //! // need graceful error handling for a `None` result. | |
205 | //! | |
206 | //! let gadget = gadget_weak.upgrade().unwrap(); | |
1a4d82fc JJ |
207 | //! println!("Gadget {} owned by {}", gadget.id, gadget.owner.name); |
208 | //! } | |
209 | //! | |
9e0c209e SL |
210 | //! // At the end of the function, `gadget_owner`, `gadget1`, and `gadget2` |
211 | //! // are destroyed. There are now no strong (`Rc`) pointers to the | |
212 | //! // gadgets, so they are destroyed. This zeroes the reference count on | |
213 | //! // Gadget Man, so he gets destroyed as well. | |
1a4d82fc JJ |
214 | //! } |
215 | //! ``` | |
476ff2be | 216 | //! |
3dfed10e XL |
217 | //! [clone]: Clone::clone |
218 | //! [`Cell`]: core::cell::Cell | |
219 | //! [`RefCell`]: core::cell::RefCell | |
220 | //! [send]: core::marker::Send | |
476ff2be | 221 | //! [arc]: ../../std/sync/struct.Arc.html |
3dfed10e XL |
222 | //! [`Deref`]: core::ops::Deref |
223 | //! [downgrade]: Rc::downgrade | |
224 | //! [upgrade]: Weak::upgrade | |
225 | //! [mutability]: core::cell#introducing-mutability-inside-of-something-immutable | |
1a4d82fc | 226 | |
85aaf69f | 227 | #![stable(feature = "rust1", since = "1.0.0")] |
62682a34 | 228 | |
c34b1796 | 229 | #[cfg(not(test))] |
9fa01778 | 230 | use crate::boxed::Box; |
c34b1796 | 231 | #[cfg(test)] |
62682a34 SL |
232 | use std::boxed::Box; |
233 | ||
ea8adc8c | 234 | use core::any::Any; |
e9174d1e | 235 | use core::borrow; |
1a4d82fc | 236 | use core::cell::Cell; |
62682a34 | 237 | use core::cmp::Ordering; |
dfeec247 | 238 | use core::convert::{From, TryFrom}; |
1a4d82fc | 239 | use core::fmt; |
3157f602 | 240 | use core::hash::{Hash, Hasher}; |
7cac9316 | 241 | use core::intrinsics::abort; |
416331ca | 242 | use core::iter; |
dfeec247 | 243 | use core::marker::{self, PhantomData, Unpin, Unsize}; |
f035d41b | 244 | use core::mem::{self, align_of_val_raw, forget, size_of_val}; |
dfeec247 | 245 | use core::ops::{CoerceUnsized, Deref, DispatchFromDyn, Receiver}; |
0bf4aa26 | 246 | use core::pin::Pin; |
2c00a5a8 | 247 | use core::ptr::{self, NonNull}; |
f9f354fc | 248 | use core::slice::from_raw_parts_mut; |
d9579d0f | 249 | |
1b1a35ee | 250 | use crate::alloc::{box_free, handle_alloc_error, AllocError, AllocRef, Global, Layout}; |
f9f354fc | 251 | use crate::borrow::{Cow, ToOwned}; |
9fa01778 XL |
252 | use crate::string::String; |
253 | use crate::vec::Vec; | |
1a4d82fc | 254 | |
416331ca XL |
255 | #[cfg(test)] |
256 | mod tests; | |
257 | ||
ba9703b0 XL |
258 | // This is repr(C) to future-proof against possible field-reordering, which |
259 | // would interfere with otherwise safe [into|from]_raw() of transmutable | |
260 | // inner types. | |
261 | #[repr(C)] | |
d9579d0f | 262 | struct RcBox<T: ?Sized> { |
85aaf69f | 263 | strong: Cell<usize>, |
d9579d0f AL |
264 | weak: Cell<usize>, |
265 | value: T, | |
1a4d82fc JJ |
266 | } |
267 | ||
041b39d2 XL |
268 | /// A single-threaded reference-counting pointer. 'Rc' stands for 'Reference |
269 | /// Counted'. | |
9e0c209e SL |
270 | /// |
271 | /// See the [module-level documentation](./index.html) for more details. | |
1a4d82fc | 272 | /// |
9e0c209e | 273 | /// The inherent methods of `Rc` are all associated functions, which means |
0731742a | 274 | /// that you have to call them as e.g., [`Rc::get_mut(&mut value)`][get_mut] instead of |
476ff2be | 275 | /// `value.get_mut()`. This avoids conflicts with methods of the inner |
9e0c209e | 276 | /// type `T`. |
476ff2be SL |
277 | /// |
278 | /// [get_mut]: #method.get_mut | |
ba9703b0 | 279 | #[cfg_attr(not(test), rustc_diagnostic_item = "Rc")] |
d9579d0f AL |
280 | #[stable(feature = "rust1", since = "1.0.0")] |
281 | pub struct Rc<T: ?Sized> { | |
2c00a5a8 | 282 | ptr: NonNull<RcBox<T>>, |
60c5eb7d | 283 | phantom: PhantomData<RcBox<T>>, |
d9579d0f | 284 | } |
1a4d82fc | 285 | |
92a42be0 | 286 | #[stable(feature = "rust1", since = "1.0.0")] |
d9579d0f | 287 | impl<T: ?Sized> !marker::Send for Rc<T> {} |
92a42be0 | 288 | #[stable(feature = "rust1", since = "1.0.0")] |
d9579d0f AL |
289 | impl<T: ?Sized> !marker::Sync for Rc<T> {} |
290 | ||
92a42be0 SL |
291 | #[unstable(feature = "coerce_unsized", issue = "27732")] |
292 | impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Rc<U>> for Rc<T> {} | |
d9579d0f | 293 | |
dfeec247 | 294 | #[unstable(feature = "dispatch_from_dyn", issue = "none")] |
a1dfa0c6 XL |
295 | impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Rc<U>> for Rc<T> {} |
296 | ||
416331ca | 297 | impl<T: ?Sized> Rc<T> { |
1b1a35ee XL |
298 | #[inline(always)] |
299 | fn inner(&self) -> &RcBox<T> { | |
300 | // This unsafety is ok because while this Rc is alive we're guaranteed | |
301 | // that the inner pointer is valid. | |
302 | unsafe { self.ptr.as_ref() } | |
303 | } | |
304 | ||
416331ca | 305 | fn from_inner(ptr: NonNull<RcBox<T>>) -> Self { |
dfeec247 | 306 | Self { ptr, phantom: PhantomData } |
416331ca XL |
307 | } |
308 | ||
309 | unsafe fn from_ptr(ptr: *mut RcBox<T>) -> Self { | |
f035d41b | 310 | Self::from_inner(unsafe { NonNull::new_unchecked(ptr) }) |
416331ca XL |
311 | } |
312 | } | |
313 | ||
1a4d82fc JJ |
314 | impl<T> Rc<T> { |
315 | /// Constructs a new `Rc<T>`. | |
316 | /// | |
317 | /// # Examples | |
318 | /// | |
319 | /// ``` | |
320 | /// use std::rc::Rc; | |
321 | /// | |
85aaf69f | 322 | /// let five = Rc::new(5); |
1a4d82fc | 323 | /// ``` |
85aaf69f | 324 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 325 | pub fn new(value: T) -> Rc<T> { |
416331ca XL |
326 | // There is an implicit weak pointer owned by all the strong |
327 | // pointers, which ensures that the weak destructor never frees | |
328 | // the allocation while the strong destructor is running, even | |
329 | // if the weak pointer is stored inside the strong one. | |
f9f354fc XL |
330 | Self::from_inner( |
331 | Box::leak(box RcBox { strong: Cell::new(1), weak: Cell::new(1), value }).into(), | |
332 | ) | |
1a4d82fc | 333 | } |
62682a34 | 334 | |
1b1a35ee XL |
335 | /// Constructs a new `Rc<T>` using a weak reference to itself. Attempting |
336 | /// to upgrade the weak reference before this function returns will result | |
337 | /// in a `None` value. However, the weak reference may be cloned freely and | |
338 | /// stored for use at a later time. | |
339 | #[unstable(feature = "arc_new_cyclic", issue = "75861")] | |
340 | pub fn new_cyclic(data_fn: impl FnOnce(&Weak<T>) -> T) -> Rc<T> { | |
341 | // Construct the inner in the "uninitialized" state with a single | |
342 | // weak reference. | |
343 | let uninit_ptr: NonNull<_> = Box::leak(box RcBox { | |
344 | strong: Cell::new(0), | |
345 | weak: Cell::new(1), | |
346 | value: mem::MaybeUninit::<T>::uninit(), | |
347 | }) | |
348 | .into(); | |
349 | ||
350 | let init_ptr: NonNull<RcBox<T>> = uninit_ptr.cast(); | |
351 | ||
352 | let weak = Weak { ptr: init_ptr }; | |
353 | ||
354 | // It's important we don't give up ownership of the weak pointer, or | |
355 | // else the memory might be freed by the time `data_fn` returns. If | |
356 | // we really wanted to pass ownership, we could create an additional | |
357 | // weak pointer for ourselves, but this would result in additional | |
358 | // updates to the weak reference count which might not be necessary | |
359 | // otherwise. | |
360 | let data = data_fn(&weak); | |
361 | ||
362 | unsafe { | |
363 | let inner = init_ptr.as_ptr(); | |
364 | ptr::write(&raw mut (*inner).value, data); | |
365 | ||
366 | let prev_value = (*inner).strong.get(); | |
367 | debug_assert_eq!(prev_value, 0, "No prior strong references should exist"); | |
368 | (*inner).strong.set(1); | |
369 | } | |
370 | ||
371 | let strong = Rc::from_inner(init_ptr); | |
372 | ||
373 | // Strong references should collectively own a shared weak reference, | |
374 | // so don't run the destructor for our old weak reference. | |
375 | mem::forget(weak); | |
376 | strong | |
377 | } | |
378 | ||
e1599b0c XL |
379 | /// Constructs a new `Rc` with uninitialized contents. |
380 | /// | |
381 | /// # Examples | |
382 | /// | |
383 | /// ``` | |
384 | /// #![feature(new_uninit)] | |
385 | /// #![feature(get_mut_unchecked)] | |
386 | /// | |
387 | /// use std::rc::Rc; | |
388 | /// | |
389 | /// let mut five = Rc::<u32>::new_uninit(); | |
390 | /// | |
391 | /// let five = unsafe { | |
392 | /// // Deferred initialization: | |
393 | /// Rc::get_mut_unchecked(&mut five).as_mut_ptr().write(5); | |
394 | /// | |
395 | /// five.assume_init() | |
396 | /// }; | |
397 | /// | |
398 | /// assert_eq!(*five, 5) | |
399 | /// ``` | |
400 | #[unstable(feature = "new_uninit", issue = "63291")] | |
401 | pub fn new_uninit() -> Rc<mem::MaybeUninit<T>> { | |
402 | unsafe { | |
3dfed10e XL |
403 | Rc::from_ptr(Rc::allocate_for_layout( |
404 | Layout::new::<T>(), | |
405 | |layout| Global.alloc(layout), | |
406 | |mem| mem as *mut RcBox<mem::MaybeUninit<T>>, | |
407 | )) | |
e1599b0c XL |
408 | } |
409 | } | |
410 | ||
60c5eb7d XL |
411 | /// Constructs a new `Rc` with uninitialized contents, with the memory |
412 | /// being filled with `0` bytes. | |
413 | /// | |
414 | /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and | |
415 | /// incorrect usage of this method. | |
416 | /// | |
417 | /// # Examples | |
418 | /// | |
419 | /// ``` | |
420 | /// #![feature(new_uninit)] | |
421 | /// | |
422 | /// use std::rc::Rc; | |
423 | /// | |
424 | /// let zero = Rc::<u32>::new_zeroed(); | |
425 | /// let zero = unsafe { zero.assume_init() }; | |
426 | /// | |
427 | /// assert_eq!(*zero, 0) | |
428 | /// ``` | |
429 | /// | |
1b1a35ee | 430 | /// [zeroed]: mem::MaybeUninit::zeroed |
60c5eb7d XL |
431 | #[unstable(feature = "new_uninit", issue = "63291")] |
432 | pub fn new_zeroed() -> Rc<mem::MaybeUninit<T>> { | |
433 | unsafe { | |
3dfed10e XL |
434 | Rc::from_ptr(Rc::allocate_for_layout( |
435 | Layout::new::<T>(), | |
436 | |layout| Global.alloc_zeroed(layout), | |
437 | |mem| mem as *mut RcBox<mem::MaybeUninit<T>>, | |
438 | )) | |
60c5eb7d XL |
439 | } |
440 | } | |
441 | ||
0731742a XL |
442 | /// Constructs a new `Pin<Rc<T>>`. If `T` does not implement `Unpin`, then |
443 | /// `value` will be pinned in memory and unable to be moved. | |
444 | #[stable(feature = "pin", since = "1.33.0")] | |
445 | pub fn pin(value: T) -> Pin<Rc<T>> { | |
0bf4aa26 XL |
446 | unsafe { Pin::new_unchecked(Rc::new(value)) } |
447 | } | |
448 | ||
e74abb32 | 449 | /// Returns the inner value, if the `Rc` has exactly one strong reference. |
62682a34 | 450 | /// |
3dfed10e | 451 | /// Otherwise, an [`Err`] is returned with the same `Rc` that was |
c30ab7b3 | 452 | /// passed in. |
62682a34 | 453 | /// |
54a0048b SL |
454 | /// This will succeed even if there are outstanding weak references. |
455 | /// | |
62682a34 SL |
456 | /// # Examples |
457 | /// | |
458 | /// ``` | |
62682a34 SL |
459 | /// use std::rc::Rc; |
460 | /// | |
461 | /// let x = Rc::new(3); | |
462 | /// assert_eq!(Rc::try_unwrap(x), Ok(3)); | |
463 | /// | |
464 | /// let x = Rc::new(4); | |
7cac9316 | 465 | /// let _y = Rc::clone(&x); |
9e0c209e | 466 | /// assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4); |
62682a34 SL |
467 | /// ``` |
468 | #[inline] | |
e9174d1e SL |
469 | #[stable(feature = "rc_unique", since = "1.4.0")] |
470 | pub fn try_unwrap(this: Self) -> Result<T, Self> { | |
476ff2be | 471 | if Rc::strong_count(&this) == 1 { |
62682a34 | 472 | unsafe { |
e9174d1e SL |
473 | let val = ptr::read(&*this); // copy the contained object |
474 | ||
ff7c6d11 | 475 | // Indicate to Weaks that they can't be promoted by decrementing |
e9174d1e SL |
476 | // the strong count, and then remove the implicit "strong weak" |
477 | // pointer while also handling drop logic by just crafting a | |
478 | // fake Weak. | |
1b1a35ee | 479 | this.inner().dec_strong(); |
54a0048b | 480 | let _weak = Weak { ptr: this.ptr }; |
e9174d1e | 481 | forget(this); |
62682a34 SL |
482 | Ok(val) |
483 | } | |
484 | } else { | |
e9174d1e | 485 | Err(this) |
62682a34 SL |
486 | } |
487 | } | |
ea8adc8c | 488 | } |
e9174d1e | 489 | |
e1599b0c XL |
490 | impl<T> Rc<[T]> { |
491 | /// Constructs a new reference-counted slice with uninitialized contents. | |
492 | /// | |
493 | /// # Examples | |
494 | /// | |
495 | /// ``` | |
496 | /// #![feature(new_uninit)] | |
497 | /// #![feature(get_mut_unchecked)] | |
498 | /// | |
499 | /// use std::rc::Rc; | |
500 | /// | |
501 | /// let mut values = Rc::<[u32]>::new_uninit_slice(3); | |
502 | /// | |
503 | /// let values = unsafe { | |
504 | /// // Deferred initialization: | |
505 | /// Rc::get_mut_unchecked(&mut values)[0].as_mut_ptr().write(1); | |
506 | /// Rc::get_mut_unchecked(&mut values)[1].as_mut_ptr().write(2); | |
507 | /// Rc::get_mut_unchecked(&mut values)[2].as_mut_ptr().write(3); | |
508 | /// | |
509 | /// values.assume_init() | |
510 | /// }; | |
511 | /// | |
512 | /// assert_eq!(*values, [1, 2, 3]) | |
513 | /// ``` | |
514 | #[unstable(feature = "new_uninit", issue = "63291")] | |
515 | pub fn new_uninit_slice(len: usize) -> Rc<[mem::MaybeUninit<T>]> { | |
dfeec247 | 516 | unsafe { Rc::from_ptr(Rc::allocate_for_slice(len)) } |
e1599b0c | 517 | } |
3dfed10e XL |
518 | |
519 | /// Constructs a new reference-counted slice with uninitialized contents, with the memory being | |
520 | /// filled with `0` bytes. | |
521 | /// | |
522 | /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and | |
523 | /// incorrect usage of this method. | |
524 | /// | |
525 | /// # Examples | |
526 | /// | |
527 | /// ``` | |
528 | /// #![feature(new_uninit)] | |
529 | /// | |
530 | /// use std::rc::Rc; | |
531 | /// | |
532 | /// let values = Rc::<[u32]>::new_zeroed_slice(3); | |
533 | /// let values = unsafe { values.assume_init() }; | |
534 | /// | |
535 | /// assert_eq!(*values, [0, 0, 0]) | |
536 | /// ``` | |
537 | /// | |
1b1a35ee | 538 | /// [zeroed]: mem::MaybeUninit::zeroed |
3dfed10e XL |
539 | #[unstable(feature = "new_uninit", issue = "63291")] |
540 | pub fn new_zeroed_slice(len: usize) -> Rc<[mem::MaybeUninit<T>]> { | |
541 | unsafe { | |
542 | Rc::from_ptr(Rc::allocate_for_layout( | |
543 | Layout::array::<T>(len).unwrap(), | |
544 | |layout| Global.alloc_zeroed(layout), | |
545 | |mem| { | |
546 | ptr::slice_from_raw_parts_mut(mem as *mut T, len) | |
547 | as *mut RcBox<[mem::MaybeUninit<T>]> | |
548 | }, | |
549 | )) | |
550 | } | |
551 | } | |
e1599b0c XL |
552 | } |
553 | ||
554 | impl<T> Rc<mem::MaybeUninit<T>> { | |
555 | /// Converts to `Rc<T>`. | |
556 | /// | |
557 | /// # Safety | |
558 | /// | |
559 | /// As with [`MaybeUninit::assume_init`], | |
e74abb32 | 560 | /// it is up to the caller to guarantee that the inner value |
e1599b0c XL |
561 | /// really is in an initialized state. |
562 | /// Calling this when the content is not yet fully initialized | |
563 | /// causes immediate undefined behavior. | |
564 | /// | |
1b1a35ee | 565 | /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init |
e1599b0c XL |
566 | /// |
567 | /// # Examples | |
568 | /// | |
569 | /// ``` | |
570 | /// #![feature(new_uninit)] | |
571 | /// #![feature(get_mut_unchecked)] | |
572 | /// | |
573 | /// use std::rc::Rc; | |
574 | /// | |
575 | /// let mut five = Rc::<u32>::new_uninit(); | |
576 | /// | |
577 | /// let five = unsafe { | |
578 | /// // Deferred initialization: | |
579 | /// Rc::get_mut_unchecked(&mut five).as_mut_ptr().write(5); | |
580 | /// | |
581 | /// five.assume_init() | |
582 | /// }; | |
583 | /// | |
584 | /// assert_eq!(*five, 5) | |
585 | /// ``` | |
586 | #[unstable(feature = "new_uninit", issue = "63291")] | |
587 | #[inline] | |
588 | pub unsafe fn assume_init(self) -> Rc<T> { | |
589 | Rc::from_inner(mem::ManuallyDrop::new(self).ptr.cast()) | |
590 | } | |
591 | } | |
592 | ||
593 | impl<T> Rc<[mem::MaybeUninit<T>]> { | |
594 | /// Converts to `Rc<[T]>`. | |
595 | /// | |
596 | /// # Safety | |
597 | /// | |
598 | /// As with [`MaybeUninit::assume_init`], | |
e74abb32 | 599 | /// it is up to the caller to guarantee that the inner value |
e1599b0c XL |
600 | /// really is in an initialized state. |
601 | /// Calling this when the content is not yet fully initialized | |
602 | /// causes immediate undefined behavior. | |
603 | /// | |
1b1a35ee | 604 | /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init |
e1599b0c XL |
605 | /// |
606 | /// # Examples | |
607 | /// | |
608 | /// ``` | |
609 | /// #![feature(new_uninit)] | |
610 | /// #![feature(get_mut_unchecked)] | |
611 | /// | |
612 | /// use std::rc::Rc; | |
613 | /// | |
614 | /// let mut values = Rc::<[u32]>::new_uninit_slice(3); | |
615 | /// | |
616 | /// let values = unsafe { | |
617 | /// // Deferred initialization: | |
618 | /// Rc::get_mut_unchecked(&mut values)[0].as_mut_ptr().write(1); | |
619 | /// Rc::get_mut_unchecked(&mut values)[1].as_mut_ptr().write(2); | |
620 | /// Rc::get_mut_unchecked(&mut values)[2].as_mut_ptr().write(3); | |
621 | /// | |
622 | /// values.assume_init() | |
623 | /// }; | |
624 | /// | |
625 | /// assert_eq!(*values, [1, 2, 3]) | |
626 | /// ``` | |
627 | #[unstable(feature = "new_uninit", issue = "63291")] | |
628 | #[inline] | |
629 | pub unsafe fn assume_init(self) -> Rc<[T]> { | |
f035d41b | 630 | unsafe { Rc::from_ptr(mem::ManuallyDrop::new(self).ptr.as_ptr() as _) } |
e1599b0c XL |
631 | } |
632 | } | |
633 | ||
ea8adc8c | 634 | impl<T: ?Sized> Rc<T> { |
476ff2be SL |
635 | /// Consumes the `Rc`, returning the wrapped pointer. |
636 | /// | |
637 | /// To avoid a memory leak the pointer must be converted back to an `Rc` using | |
638 | /// [`Rc::from_raw`][from_raw]. | |
639 | /// | |
3dfed10e | 640 | /// [from_raw]: Rc::from_raw |
9e0c209e SL |
641 | /// |
642 | /// # Examples | |
643 | /// | |
644 | /// ``` | |
9e0c209e SL |
645 | /// use std::rc::Rc; |
646 | /// | |
dc9dc135 | 647 | /// let x = Rc::new("hello".to_owned()); |
476ff2be | 648 | /// let x_ptr = Rc::into_raw(x); |
dc9dc135 | 649 | /// assert_eq!(unsafe { &*x_ptr }, "hello"); |
476ff2be | 650 | /// ``` |
8bb4bdeb XL |
651 | #[stable(feature = "rc_raw", since = "1.17.0")] |
652 | pub fn into_raw(this: Self) -> *const T { | |
ba9703b0 XL |
653 | let ptr = Self::as_ptr(&this); |
654 | mem::forget(this); | |
655 | ptr | |
656 | } | |
657 | ||
658 | /// Provides a raw pointer to the data. | |
659 | /// | |
660 | /// The counts are not affected in any way and the `Rc` is not consumed. The pointer is valid | |
661 | /// for as long there are strong counts in the `Rc`. | |
662 | /// | |
663 | /// # Examples | |
664 | /// | |
665 | /// ``` | |
ba9703b0 XL |
666 | /// use std::rc::Rc; |
667 | /// | |
668 | /// let x = Rc::new("hello".to_owned()); | |
669 | /// let y = Rc::clone(&x); | |
670 | /// let x_ptr = Rc::as_ptr(&x); | |
671 | /// assert_eq!(x_ptr, Rc::as_ptr(&y)); | |
672 | /// assert_eq!(unsafe { &*x_ptr }, "hello"); | |
673 | /// ``` | |
f9f354fc | 674 | #[stable(feature = "weak_into_raw", since = "1.45.0")] |
ba9703b0 | 675 | pub fn as_ptr(this: &Self) -> *const T { |
dfeec247 | 676 | let ptr: *mut RcBox<T> = NonNull::as_ptr(this.ptr); |
dfeec247 | 677 | |
f035d41b XL |
678 | // SAFETY: This cannot go through Deref::deref or Rc::inner because |
679 | // this is required to retain raw/mut provenance such that e.g. `get_mut` can | |
680 | // write through the pointer after the Rc is recovered through `from_raw`. | |
681 | unsafe { &raw const (*ptr).value } | |
476ff2be SL |
682 | } |
683 | ||
ba9703b0 XL |
684 | /// Constructs an `Rc<T>` from a raw pointer. |
685 | /// | |
686 | /// The raw pointer must have been previously returned by a call to | |
687 | /// [`Rc<U>::into_raw`][into_raw] where `U` must have the same size | |
688 | /// and alignment as `T`. This is trivially true if `U` is `T`. | |
689 | /// Note that if `U` is not `T` but has the same size and alignment, this is | |
690 | /// basically like transmuting references of different types. See | |
691 | /// [`mem::transmute`][transmute] for more information on what | |
692 | /// restrictions apply in this case. | |
476ff2be | 693 | /// |
ba9703b0 XL |
694 | /// The user of `from_raw` has to make sure a specific value of `T` is only |
695 | /// dropped once. | |
476ff2be | 696 | /// |
ba9703b0 XL |
697 | /// This function is unsafe because improper use may lead to memory unsafety, |
698 | /// even if the returned `Rc<T>` is never accessed. | |
476ff2be | 699 | /// |
3dfed10e XL |
700 | /// [into_raw]: Rc::into_raw |
701 | /// [transmute]: core::mem::transmute | |
476ff2be SL |
702 | /// |
703 | /// # Examples | |
9e0c209e | 704 | /// |
9e0c209e | 705 | /// ``` |
476ff2be SL |
706 | /// use std::rc::Rc; |
707 | /// | |
dc9dc135 | 708 | /// let x = Rc::new("hello".to_owned()); |
476ff2be SL |
709 | /// let x_ptr = Rc::into_raw(x); |
710 | /// | |
711 | /// unsafe { | |
712 | /// // Convert back to an `Rc` to prevent leak. | |
713 | /// let x = Rc::from_raw(x_ptr); | |
dc9dc135 | 714 | /// assert_eq!(&*x, "hello"); |
476ff2be | 715 | /// |
e1599b0c | 716 | /// // Further calls to `Rc::from_raw(x_ptr)` would be memory-unsafe. |
476ff2be SL |
717 | /// } |
718 | /// | |
719 | /// // The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling! | |
720 | /// ``` | |
8bb4bdeb XL |
721 | #[stable(feature = "rc_raw", since = "1.17.0")] |
722 | pub unsafe fn from_raw(ptr: *const T) -> Self { | |
f035d41b | 723 | let offset = unsafe { data_offset(ptr) }; |
ea8adc8c XL |
724 | |
725 | // Reverse the offset to find the original RcBox. | |
726 | let fake_ptr = ptr as *mut RcBox<T>; | |
f035d41b | 727 | let rc_ptr = unsafe { set_data_ptr(fake_ptr, (ptr as *mut u8).offset(-offset)) }; |
7cac9316 | 728 | |
f035d41b | 729 | unsafe { Self::from_ptr(rc_ptr) } |
cc61c64b | 730 | } |
cc61c64b | 731 | |
3dfed10e | 732 | /// Creates a new [`Weak`] pointer to this allocation. |
d9579d0f AL |
733 | /// |
734 | /// # Examples | |
735 | /// | |
736 | /// ``` | |
d9579d0f AL |
737 | /// use std::rc::Rc; |
738 | /// | |
739 | /// let five = Rc::new(5); | |
740 | /// | |
e9174d1e | 741 | /// let weak_five = Rc::downgrade(&five); |
d9579d0f | 742 | /// ``` |
e9174d1e SL |
743 | #[stable(feature = "rc_weak", since = "1.4.0")] |
744 | pub fn downgrade(this: &Self) -> Weak<T> { | |
1b1a35ee | 745 | this.inner().inc_weak(); |
8faf50e0 XL |
746 | // Make sure we do not create a dangling Weak |
747 | debug_assert!(!is_dangling(this.ptr)); | |
54a0048b | 748 | Weak { ptr: this.ptr } |
d9579d0f | 749 | } |
d9579d0f | 750 | |
3dfed10e | 751 | /// Gets the number of [`Weak`] pointers to this allocation. |
9e0c209e SL |
752 | /// |
753 | /// # Examples | |
754 | /// | |
755 | /// ``` | |
9e0c209e SL |
756 | /// use std::rc::Rc; |
757 | /// | |
758 | /// let five = Rc::new(5); | |
759 | /// let _weak_five = Rc::downgrade(&five); | |
760 | /// | |
761 | /// assert_eq!(1, Rc::weak_count(&five)); | |
762 | /// ``` | |
62682a34 | 763 | #[inline] |
476ff2be | 764 | #[stable(feature = "rc_counts", since = "1.15.0")] |
b039eaaf | 765 | pub fn weak_count(this: &Self) -> usize { |
1b1a35ee | 766 | this.inner().weak() - 1 |
b039eaaf | 767 | } |
62682a34 | 768 | |
e74abb32 | 769 | /// Gets the number of strong (`Rc`) pointers to this allocation. |
9e0c209e SL |
770 | /// |
771 | /// # Examples | |
772 | /// | |
773 | /// ``` | |
9e0c209e SL |
774 | /// use std::rc::Rc; |
775 | /// | |
776 | /// let five = Rc::new(5); | |
7cac9316 | 777 | /// let _also_five = Rc::clone(&five); |
9e0c209e SL |
778 | /// |
779 | /// assert_eq!(2, Rc::strong_count(&five)); | |
780 | /// ``` | |
62682a34 | 781 | #[inline] |
476ff2be | 782 | #[stable(feature = "rc_counts", since = "1.15.0")] |
b039eaaf | 783 | pub fn strong_count(this: &Self) -> usize { |
1b1a35ee | 784 | this.inner().strong() |
b039eaaf | 785 | } |
62682a34 | 786 | |
3dfed10e | 787 | /// Returns `true` if there are no other `Rc` or [`Weak`] pointers to |
e74abb32 | 788 | /// this allocation. |
62682a34 | 789 | #[inline] |
cc61c64b | 790 | fn is_unique(this: &Self) -> bool { |
e9174d1e | 791 | Rc::weak_count(this) == 0 && Rc::strong_count(this) == 1 |
62682a34 SL |
792 | } |
793 | ||
e74abb32 | 794 | /// Returns a mutable reference into the given `Rc`, if there are |
3dfed10e | 795 | /// no other `Rc` or [`Weak`] pointers to the same allocation. |
62682a34 | 796 | /// |
476ff2be | 797 | /// Returns [`None`] otherwise, because it is not safe to |
9e0c209e SL |
798 | /// mutate a shared value. |
799 | /// | |
800 | /// See also [`make_mut`][make_mut], which will [`clone`][clone] | |
e74abb32 | 801 | /// the inner value when there are other pointers. |
9e0c209e | 802 | /// |
3dfed10e XL |
803 | /// [make_mut]: Rc::make_mut |
804 | /// [clone]: Clone::clone | |
62682a34 SL |
805 | /// |
806 | /// # Examples | |
807 | /// | |
808 | /// ``` | |
62682a34 SL |
809 | /// use std::rc::Rc; |
810 | /// | |
811 | /// let mut x = Rc::new(3); | |
812 | /// *Rc::get_mut(&mut x).unwrap() = 4; | |
813 | /// assert_eq!(*x, 4); | |
814 | /// | |
7cac9316 | 815 | /// let _y = Rc::clone(&x); |
62682a34 SL |
816 | /// assert!(Rc::get_mut(&mut x).is_none()); |
817 | /// ``` | |
818 | #[inline] | |
e9174d1e SL |
819 | #[stable(feature = "rc_unique", since = "1.4.0")] |
820 | pub fn get_mut(this: &mut Self) -> Option<&mut T> { | |
dfeec247 | 821 | if Rc::is_unique(this) { unsafe { Some(Rc::get_mut_unchecked(this)) } } else { None } |
1a4d82fc | 822 | } |
9e0c209e | 823 | |
e74abb32 | 824 | /// Returns a mutable reference into the given `Rc`, |
e1599b0c XL |
825 | /// without any check. |
826 | /// | |
827 | /// See also [`get_mut`], which is safe and does appropriate checks. | |
828 | /// | |
3dfed10e | 829 | /// [`get_mut`]: Rc::get_mut |
e1599b0c XL |
830 | /// |
831 | /// # Safety | |
832 | /// | |
e74abb32 | 833 | /// Any other `Rc` or [`Weak`] pointers to the same allocation must not be dereferenced |
e1599b0c XL |
834 | /// for the duration of the returned borrow. |
835 | /// This is trivially the case if no such pointers exist, | |
836 | /// for example immediately after `Rc::new`. | |
837 | /// | |
838 | /// # Examples | |
839 | /// | |
840 | /// ``` | |
841 | /// #![feature(get_mut_unchecked)] | |
842 | /// | |
843 | /// use std::rc::Rc; | |
844 | /// | |
845 | /// let mut x = Rc::new(String::new()); | |
846 | /// unsafe { | |
847 | /// Rc::get_mut_unchecked(&mut x).push_str("foo") | |
848 | /// } | |
849 | /// assert_eq!(*x, "foo"); | |
850 | /// ``` | |
851 | #[inline] | |
852 | #[unstable(feature = "get_mut_unchecked", issue = "63292")] | |
853 | pub unsafe fn get_mut_unchecked(this: &mut Self) -> &mut T { | |
1b1a35ee XL |
854 | // We are careful to *not* create a reference covering the "count" fields, as |
855 | // this would conflict with accesses to the reference counts (e.g. by `Weak`). | |
856 | unsafe { &mut (*this.ptr.as_ptr()).value } | |
e1599b0c XL |
857 | } |
858 | ||
9e0c209e | 859 | #[inline] |
8bb4bdeb | 860 | #[stable(feature = "ptr_eq", since = "1.17.0")] |
e74abb32 XL |
861 | /// Returns `true` if the two `Rc`s point to the same allocation |
862 | /// (in a vein similar to [`ptr::eq`]). | |
9e0c209e SL |
863 | /// |
864 | /// # Examples | |
865 | /// | |
866 | /// ``` | |
9e0c209e SL |
867 | /// use std::rc::Rc; |
868 | /// | |
869 | /// let five = Rc::new(5); | |
7cac9316 | 870 | /// let same_five = Rc::clone(&five); |
9e0c209e SL |
871 | /// let other_five = Rc::new(5); |
872 | /// | |
873 | /// assert!(Rc::ptr_eq(&five, &same_five)); | |
874 | /// assert!(!Rc::ptr_eq(&five, &other_five)); | |
875 | /// ``` | |
e74abb32 | 876 | /// |
3dfed10e | 877 | /// [`ptr::eq`]: core::ptr::eq |
9e0c209e | 878 | pub fn ptr_eq(this: &Self, other: &Self) -> bool { |
7cac9316 | 879 | this.ptr.as_ptr() == other.ptr.as_ptr() |
9e0c209e | 880 | } |
1a4d82fc JJ |
881 | } |
882 | ||
1a4d82fc | 883 | impl<T: Clone> Rc<T> { |
9e0c209e SL |
884 | /// Makes a mutable reference into the given `Rc`. |
885 | /// | |
e74abb32 XL |
886 | /// If there are other `Rc` pointers to the same allocation, then `make_mut` will |
887 | /// [`clone`] the inner value to a new allocation to ensure unique ownership. This is also | |
dc9dc135 | 888 | /// referred to as clone-on-write. |
9e0c209e | 889 | /// |
e74abb32 XL |
890 | /// If there are no other `Rc` pointers to this allocation, then [`Weak`] |
891 | /// pointers to this allocation will be disassociated. | |
1a4d82fc | 892 | /// |
dc9dc135 XL |
893 | /// See also [`get_mut`], which will fail rather than cloning. |
894 | /// | |
3dfed10e XL |
895 | /// [`clone`]: Clone::clone |
896 | /// [`get_mut`]: Rc::get_mut | |
1a4d82fc JJ |
897 | /// |
898 | /// # Examples | |
899 | /// | |
900 | /// ``` | |
901 | /// use std::rc::Rc; | |
902 | /// | |
e9174d1e SL |
903 | /// let mut data = Rc::new(5); |
904 | /// | |
9e0c209e | 905 | /// *Rc::make_mut(&mut data) += 1; // Won't clone anything |
7cac9316 | 906 | /// let mut other_data = Rc::clone(&data); // Won't clone inner data |
9e0c209e SL |
907 | /// *Rc::make_mut(&mut data) += 1; // Clones inner data |
908 | /// *Rc::make_mut(&mut data) += 1; // Won't clone anything | |
909 | /// *Rc::make_mut(&mut other_data) *= 2; // Won't clone anything | |
e9174d1e | 910 | /// |
e74abb32 | 911 | /// // Now `data` and `other_data` point to different allocations. |
e9174d1e SL |
912 | /// assert_eq!(*data, 8); |
913 | /// assert_eq!(*other_data, 12); | |
1a4d82fc | 914 | /// ``` |
dc9dc135 | 915 | /// |
e74abb32 | 916 | /// [`Weak`] pointers will be disassociated: |
dc9dc135 XL |
917 | /// |
918 | /// ``` | |
919 | /// use std::rc::Rc; | |
920 | /// | |
921 | /// let mut data = Rc::new(75); | |
922 | /// let weak = Rc::downgrade(&data); | |
923 | /// | |
924 | /// assert!(75 == *data); | |
925 | /// assert!(75 == *weak.upgrade().unwrap()); | |
926 | /// | |
927 | /// *Rc::make_mut(&mut data) += 1; | |
928 | /// | |
929 | /// assert!(76 == *data); | |
930 | /// assert!(weak.upgrade().is_none()); | |
931 | /// ``` | |
1a4d82fc | 932 | #[inline] |
e9174d1e SL |
933 | #[stable(feature = "rc_unique", since = "1.4.0")] |
934 | pub fn make_mut(this: &mut Self) -> &mut T { | |
935 | if Rc::strong_count(this) != 1 { | |
936 | // Gotta clone the data, there are other Rcs | |
937 | *this = Rc::new((**this).clone()) | |
938 | } else if Rc::weak_count(this) != 0 { | |
939 | // Can just steal the data, all that's left is Weaks | |
940 | unsafe { | |
7cac9316 | 941 | let mut swap = Rc::new(ptr::read(&this.ptr.as_ref().value)); |
e9174d1e | 942 | mem::swap(this, &mut swap); |
1b1a35ee | 943 | swap.inner().dec_strong(); |
e9174d1e SL |
944 | // Remove implicit strong-weak ref (no need to craft a fake |
945 | // Weak here -- we know other Weaks can clean up for us) | |
1b1a35ee | 946 | swap.inner().dec_weak(); |
e9174d1e SL |
947 | forget(swap); |
948 | } | |
1a4d82fc | 949 | } |
c34b1796 AL |
950 | // This unsafety is ok because we're guaranteed that the pointer |
951 | // returned is the *only* pointer that will ever be returned to T. Our | |
952 | // reference count is guaranteed to be 1 at this point, and we required | |
953 | // the `Rc<T>` itself to be `mut`, so we're returning the only possible | |
e74abb32 | 954 | // reference to the allocation. |
dfeec247 | 955 | unsafe { &mut this.ptr.as_mut().value } |
1a4d82fc JJ |
956 | } |
957 | } | |
958 | ||
8faf50e0 | 959 | impl Rc<dyn Any> { |
ea8adc8c | 960 | #[inline] |
8faf50e0 | 961 | #[stable(feature = "rc_downcast", since = "1.29.0")] |
a1dfa0c6 | 962 | /// Attempt to downcast the `Rc<dyn Any>` to a concrete type. |
ea8adc8c XL |
963 | /// |
964 | /// # Examples | |
965 | /// | |
966 | /// ``` | |
ea8adc8c XL |
967 | /// use std::any::Any; |
968 | /// use std::rc::Rc; | |
969 | /// | |
a1dfa0c6 | 970 | /// fn print_if_string(value: Rc<dyn Any>) { |
ea8adc8c XL |
971 | /// if let Ok(string) = value.downcast::<String>() { |
972 | /// println!("String ({}): {}", string.len(), string); | |
973 | /// } | |
974 | /// } | |
975 | /// | |
e74abb32 XL |
976 | /// let my_string = "Hello World".to_string(); |
977 | /// print_if_string(Rc::new(my_string)); | |
978 | /// print_if_string(Rc::new(0i8)); | |
ea8adc8c | 979 | /// ``` |
8faf50e0 | 980 | pub fn downcast<T: Any>(self) -> Result<Rc<T>, Rc<dyn Any>> { |
ea8adc8c | 981 | if (*self).is::<T>() { |
94b46f34 XL |
982 | let ptr = self.ptr.cast::<RcBox<T>>(); |
983 | forget(self); | |
416331ca | 984 | Ok(Rc::from_inner(ptr)) |
ea8adc8c XL |
985 | } else { |
986 | Err(self) | |
987 | } | |
988 | } | |
989 | } | |
990 | ||
3b2f2976 | 991 | impl<T: ?Sized> Rc<T> { |
416331ca | 992 | /// Allocates an `RcBox<T>` with sufficient space for |
e74abb32 | 993 | /// a possibly-unsized inner value where the value has the layout provided. |
416331ca XL |
994 | /// |
995 | /// The function `mem_to_rcbox` is called with the data pointer | |
996 | /// and must return back a (potentially fat)-pointer for the `RcBox<T>`. | |
e1599b0c | 997 | unsafe fn allocate_for_layout( |
416331ca | 998 | value_layout: Layout, |
1b1a35ee | 999 | allocate: impl FnOnce(Layout) -> Result<NonNull<[u8]>, AllocError>, |
dfeec247 | 1000 | mem_to_rcbox: impl FnOnce(*mut u8) -> *mut RcBox<T>, |
416331ca XL |
1001 | ) -> *mut RcBox<T> { |
1002 | // Calculate layout using the given value layout. | |
a1dfa0c6 XL |
1003 | // Previously, layout was calculated on the expression |
1004 | // `&*(ptr as *const RcBox<T>)`, but this created a misaligned | |
1005 | // reference (see #54908). | |
dfeec247 | 1006 | let layout = Layout::new::<RcBox<()>>().extend(value_layout).unwrap().0.pad_to_align(); |
3b2f2976 | 1007 | |
416331ca | 1008 | // Allocate for the layout. |
3dfed10e | 1009 | let ptr = allocate(layout).unwrap_or_else(|_| handle_alloc_error(layout)); |
3b2f2976 | 1010 | |
a1dfa0c6 | 1011 | // Initialize the RcBox |
3dfed10e | 1012 | let inner = mem_to_rcbox(ptr.as_non_null_ptr().as_ptr()); |
f035d41b XL |
1013 | unsafe { |
1014 | debug_assert_eq!(Layout::for_value(&*inner), layout); | |
3b2f2976 | 1015 | |
f035d41b XL |
1016 | ptr::write(&mut (*inner).strong, Cell::new(1)); |
1017 | ptr::write(&mut (*inner).weak, Cell::new(1)); | |
1018 | } | |
3b2f2976 XL |
1019 | |
1020 | inner | |
1021 | } | |
1022 | ||
e74abb32 | 1023 | /// Allocates an `RcBox<T>` with sufficient space for an unsized inner value |
416331ca XL |
1024 | unsafe fn allocate_for_ptr(ptr: *const T) -> *mut RcBox<T> { |
1025 | // Allocate for the `RcBox<T>` using the given value. | |
f035d41b | 1026 | unsafe { |
3dfed10e XL |
1027 | Self::allocate_for_layout( |
1028 | Layout::for_value(&*ptr), | |
1029 | |layout| Global.alloc(layout), | |
1030 | |mem| set_data_ptr(ptr as *mut T, mem) as *mut RcBox<T>, | |
1031 | ) | |
f035d41b | 1032 | } |
416331ca XL |
1033 | } |
1034 | ||
3b2f2976 XL |
1035 | fn from_box(v: Box<T>) -> Rc<T> { |
1036 | unsafe { | |
83c7162d XL |
1037 | let box_unique = Box::into_unique(v); |
1038 | let bptr = box_unique.as_ptr(); | |
3b2f2976 XL |
1039 | |
1040 | let value_size = size_of_val(&*bptr); | |
1041 | let ptr = Self::allocate_for_ptr(bptr); | |
1042 | ||
1043 | // Copy value as bytes | |
1044 | ptr::copy_nonoverlapping( | |
1045 | bptr as *const T as *const u8, | |
1046 | &mut (*ptr).value as *mut _ as *mut u8, | |
dfeec247 XL |
1047 | value_size, |
1048 | ); | |
3b2f2976 XL |
1049 | |
1050 | // Free the allocation without dropping its contents | |
83c7162d | 1051 | box_free(box_unique); |
3b2f2976 | 1052 | |
416331ca | 1053 | Self::from_ptr(ptr) |
3b2f2976 XL |
1054 | } |
1055 | } | |
1056 | } | |
1057 | ||
416331ca XL |
1058 | impl<T> Rc<[T]> { |
1059 | /// Allocates an `RcBox<[T]>` with the given length. | |
1060 | unsafe fn allocate_for_slice(len: usize) -> *mut RcBox<[T]> { | |
f035d41b | 1061 | unsafe { |
3dfed10e XL |
1062 | Self::allocate_for_layout( |
1063 | Layout::array::<T>(len).unwrap(), | |
1064 | |layout| Global.alloc(layout), | |
1065 | |mem| ptr::slice_from_raw_parts_mut(mem as *mut T, len) as *mut RcBox<[T]>, | |
1066 | ) | |
f035d41b | 1067 | } |
416331ca XL |
1068 | } |
1069 | } | |
1070 | ||
1071 | /// Sets the data pointer of a `?Sized` raw pointer. | |
1072 | /// | |
1073 | /// For a slice/trait object, this sets the `data` field and leaves the rest | |
1074 | /// unchanged. For a sized raw pointer, this simply sets the pointer. | |
3b2f2976 | 1075 | unsafe fn set_data_ptr<T: ?Sized, U>(mut ptr: *mut T, data: *mut U) -> *mut T { |
f035d41b XL |
1076 | unsafe { |
1077 | ptr::write(&mut ptr as *mut _ as *mut *mut u8, data as *mut u8); | |
1078 | } | |
3b2f2976 XL |
1079 | ptr |
1080 | } | |
1081 | ||
1082 | impl<T> Rc<[T]> { | |
f9f354fc | 1083 | /// Copy elements from slice into newly allocated Rc<\[T\]> |
416331ca XL |
1084 | /// |
1085 | /// Unsafe because the caller must either take ownership or bind `T: Copy` | |
3b2f2976 | 1086 | unsafe fn copy_from_slice(v: &[T]) -> Rc<[T]> { |
f035d41b XL |
1087 | unsafe { |
1088 | let ptr = Self::allocate_for_slice(v.len()); | |
1089 | ptr::copy_nonoverlapping(v.as_ptr(), &mut (*ptr).value as *mut [T] as *mut T, v.len()); | |
1090 | Self::from_ptr(ptr) | |
1091 | } | |
3b2f2976 | 1092 | } |
3b2f2976 | 1093 | |
416331ca XL |
1094 | /// Constructs an `Rc<[T]>` from an iterator known to be of a certain size. |
1095 | /// | |
1096 | /// Behavior is undefined should the size be wrong. | |
1097 | unsafe fn from_iter_exact(iter: impl iter::Iterator<Item = T>, len: usize) -> Rc<[T]> { | |
3b2f2976 XL |
1098 | // Panic guard while cloning T elements. |
1099 | // In the event of a panic, elements that have been written | |
1100 | // into the new RcBox will be dropped, then the memory freed. | |
1101 | struct Guard<T> { | |
94b46f34 | 1102 | mem: NonNull<u8>, |
3b2f2976 XL |
1103 | elems: *mut T, |
1104 | layout: Layout, | |
1105 | n_elems: usize, | |
1106 | } | |
1107 | ||
1108 | impl<T> Drop for Guard<T> { | |
1109 | fn drop(&mut self) { | |
3b2f2976 XL |
1110 | unsafe { |
1111 | let slice = from_raw_parts_mut(self.elems, self.n_elems); | |
1112 | ptr::drop_in_place(slice); | |
1113 | ||
416331ca | 1114 | Global.dealloc(self.mem, self.layout); |
3b2f2976 XL |
1115 | } |
1116 | } | |
1117 | } | |
1118 | ||
f035d41b XL |
1119 | unsafe { |
1120 | let ptr = Self::allocate_for_slice(len); | |
3b2f2976 | 1121 | |
f035d41b XL |
1122 | let mem = ptr as *mut _ as *mut u8; |
1123 | let layout = Layout::for_value(&*ptr); | |
3b2f2976 | 1124 | |
f035d41b XL |
1125 | // Pointer to first element |
1126 | let elems = &mut (*ptr).value as *mut [T] as *mut T; | |
3b2f2976 | 1127 | |
f035d41b | 1128 | let mut guard = Guard { mem: NonNull::new_unchecked(mem), elems, layout, n_elems: 0 }; |
3b2f2976 | 1129 | |
f035d41b XL |
1130 | for (i, item) in iter.enumerate() { |
1131 | ptr::write(elems.add(i), item); | |
1132 | guard.n_elems += 1; | |
1133 | } | |
416331ca | 1134 | |
f035d41b XL |
1135 | // All clear. Forget the guard so it doesn't free the new RcBox. |
1136 | forget(guard); | |
416331ca | 1137 | |
f035d41b XL |
1138 | Self::from_ptr(ptr) |
1139 | } | |
416331ca XL |
1140 | } |
1141 | } | |
3b2f2976 | 1142 | |
416331ca XL |
1143 | /// Specialization trait used for `From<&[T]>`. |
1144 | trait RcFromSlice<T> { | |
1145 | fn from_slice(slice: &[T]) -> Self; | |
1146 | } | |
3b2f2976 | 1147 | |
416331ca XL |
1148 | impl<T: Clone> RcFromSlice<T> for Rc<[T]> { |
1149 | #[inline] | |
1150 | default fn from_slice(v: &[T]) -> Self { | |
dfeec247 | 1151 | unsafe { Self::from_iter_exact(v.iter().cloned(), v.len()) } |
3b2f2976 XL |
1152 | } |
1153 | } | |
1154 | ||
1155 | impl<T: Copy> RcFromSlice<T> for Rc<[T]> { | |
1156 | #[inline] | |
1157 | fn from_slice(v: &[T]) -> Self { | |
1158 | unsafe { Rc::copy_from_slice(v) } | |
1159 | } | |
1160 | } | |
1161 | ||
d9579d0f AL |
1162 | #[stable(feature = "rust1", since = "1.0.0")] |
1163 | impl<T: ?Sized> Deref for Rc<T> { | |
1164 | type Target = T; | |
1165 | ||
1166 | #[inline(always)] | |
1167 | fn deref(&self) -> &T { | |
1168 | &self.inner().value | |
1169 | } | |
1170 | } | |
1a4d82fc | 1171 | |
dfeec247 | 1172 | #[unstable(feature = "receiver_trait", issue = "none")] |
0731742a XL |
1173 | impl<T: ?Sized> Receiver for Rc<T> {} |
1174 | ||
d9579d0f | 1175 | #[stable(feature = "rust1", since = "1.0.0")] |
32a655c1 | 1176 | unsafe impl<#[may_dangle] T: ?Sized> Drop for Rc<T> { |
9e0c209e | 1177 | /// Drops the `Rc`. |
d9579d0f AL |
1178 | /// |
1179 | /// This will decrement the strong reference count. If the strong reference | |
c30ab7b3 | 1180 | /// count reaches zero then the only other references (if any) are |
b7449926 | 1181 | /// [`Weak`], so we `drop` the inner value. |
d9579d0f AL |
1182 | /// |
1183 | /// # Examples | |
1184 | /// | |
1185 | /// ``` | |
d9579d0f AL |
1186 | /// use std::rc::Rc; |
1187 | /// | |
9e0c209e | 1188 | /// struct Foo; |
d9579d0f | 1189 | /// |
9e0c209e SL |
1190 | /// impl Drop for Foo { |
1191 | /// fn drop(&mut self) { | |
1192 | /// println!("dropped!"); | |
1193 | /// } | |
d9579d0f | 1194 | /// } |
d9579d0f | 1195 | /// |
9e0c209e | 1196 | /// let foo = Rc::new(Foo); |
7cac9316 | 1197 | /// let foo2 = Rc::clone(&foo); |
d9579d0f | 1198 | /// |
9e0c209e SL |
1199 | /// drop(foo); // Doesn't print anything |
1200 | /// drop(foo2); // Prints "dropped!" | |
d9579d0f AL |
1201 | /// ``` |
1202 | fn drop(&mut self) { | |
1203 | unsafe { | |
1b1a35ee XL |
1204 | self.inner().dec_strong(); |
1205 | if self.inner().strong() == 0 { | |
9e0c209e | 1206 | // destroy the contained object |
1b1a35ee | 1207 | ptr::drop_in_place(Self::get_mut_unchecked(self)); |
d9579d0f | 1208 | |
9e0c209e SL |
1209 | // remove the implicit "strong weak" pointer now that we've |
1210 | // destroyed the contents. | |
1b1a35ee | 1211 | self.inner().dec_weak(); |
d9579d0f | 1212 | |
1b1a35ee | 1213 | if self.inner().weak() == 0 { |
94b46f34 | 1214 | Global.dealloc(self.ptr.cast(), Layout::for_value(self.ptr.as_ref())); |
d9579d0f AL |
1215 | } |
1216 | } | |
1217 | } | |
1218 | } | |
1219 | } | |
1220 | ||
d9579d0f AL |
1221 | #[stable(feature = "rust1", since = "1.0.0")] |
1222 | impl<T: ?Sized> Clone for Rc<T> { | |
9e0c209e | 1223 | /// Makes a clone of the `Rc` pointer. |
d9579d0f | 1224 | /// |
e74abb32 | 1225 | /// This creates another pointer to the same allocation, increasing the |
9e0c209e | 1226 | /// strong reference count. |
d9579d0f AL |
1227 | /// |
1228 | /// # Examples | |
1229 | /// | |
1230 | /// ``` | |
d9579d0f AL |
1231 | /// use std::rc::Rc; |
1232 | /// | |
1233 | /// let five = Rc::new(5); | |
1234 | /// | |
0bf4aa26 | 1235 | /// let _ = Rc::clone(&five); |
d9579d0f AL |
1236 | /// ``` |
1237 | #[inline] | |
1238 | fn clone(&self) -> Rc<T> { | |
1b1a35ee | 1239 | self.inner().inc_strong(); |
416331ca | 1240 | Self::from_inner(self.ptr) |
d9579d0f AL |
1241 | } |
1242 | } | |
1a4d82fc | 1243 | |
85aaf69f | 1244 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
1245 | impl<T: Default> Default for Rc<T> { |
1246 | /// Creates a new `Rc<T>`, with the `Default` value for `T`. | |
1247 | /// | |
1248 | /// # Examples | |
1249 | /// | |
1250 | /// ``` | |
1251 | /// use std::rc::Rc; | |
1a4d82fc | 1252 | /// |
85aaf69f | 1253 | /// let x: Rc<i32> = Default::default(); |
9e0c209e | 1254 | /// assert_eq!(*x, 0); |
1a4d82fc JJ |
1255 | /// ``` |
1256 | #[inline] | |
1a4d82fc JJ |
1257 | fn default() -> Rc<T> { |
1258 | Rc::new(Default::default()) | |
1259 | } | |
1260 | } | |
1261 | ||
0731742a XL |
1262 | #[stable(feature = "rust1", since = "1.0.0")] |
1263 | trait RcEqIdent<T: ?Sized + PartialEq> { | |
1264 | fn eq(&self, other: &Rc<T>) -> bool; | |
1265 | fn ne(&self, other: &Rc<T>) -> bool; | |
1266 | } | |
1267 | ||
1268 | #[stable(feature = "rust1", since = "1.0.0")] | |
1269 | impl<T: ?Sized + PartialEq> RcEqIdent<T> for Rc<T> { | |
1270 | #[inline] | |
1271 | default fn eq(&self, other: &Rc<T>) -> bool { | |
1272 | **self == **other | |
1273 | } | |
1274 | ||
1275 | #[inline] | |
1276 | default fn ne(&self, other: &Rc<T>) -> bool { | |
1277 | **self != **other | |
1278 | } | |
1279 | } | |
1280 | ||
f9f354fc XL |
1281 | // Hack to allow specializing on `Eq` even though `Eq` has a method. |
1282 | #[rustc_unsafe_specialization_marker] | |
1283 | pub(crate) trait MarkerEq: PartialEq<Self> {} | |
1284 | ||
1285 | impl<T: Eq> MarkerEq for T {} | |
1286 | ||
48663c56 XL |
1287 | /// We're doing this specialization here, and not as a more general optimization on `&T`, because it |
1288 | /// would otherwise add a cost to all equality checks on refs. We assume that `Rc`s are used to | |
1289 | /// store large values, that are slow to clone, but also heavy to check for equality, causing this | |
1290 | /// cost to pay off more easily. It's also more likely to have two `Rc` clones, that point to | |
1291 | /// the same value, than two `&T`s. | |
e74abb32 XL |
1292 | /// |
1293 | /// We can only do this when `T: Eq` as a `PartialEq` might be deliberately irreflexive. | |
0731742a | 1294 | #[stable(feature = "rust1", since = "1.0.0")] |
f9f354fc | 1295 | impl<T: ?Sized + MarkerEq> RcEqIdent<T> for Rc<T> { |
0731742a XL |
1296 | #[inline] |
1297 | fn eq(&self, other: &Rc<T>) -> bool { | |
1298 | Rc::ptr_eq(self, other) || **self == **other | |
1299 | } | |
1300 | ||
1301 | #[inline] | |
1302 | fn ne(&self, other: &Rc<T>) -> bool { | |
1303 | !Rc::ptr_eq(self, other) && **self != **other | |
1304 | } | |
1305 | } | |
1306 | ||
85aaf69f | 1307 | #[stable(feature = "rust1", since = "1.0.0")] |
62682a34 | 1308 | impl<T: ?Sized + PartialEq> PartialEq for Rc<T> { |
9e0c209e | 1309 | /// Equality for two `Rc`s. |
1a4d82fc | 1310 | /// |
e74abb32 XL |
1311 | /// Two `Rc`s are equal if their inner values are equal, even if they are |
1312 | /// stored in different allocation. | |
1a4d82fc | 1313 | /// |
e74abb32 XL |
1314 | /// If `T` also implements `Eq` (implying reflexivity of equality), |
1315 | /// two `Rc`s that point to the same allocation are | |
0731742a XL |
1316 | /// always equal. |
1317 | /// | |
1a4d82fc JJ |
1318 | /// # Examples |
1319 | /// | |
1320 | /// ``` | |
1321 | /// use std::rc::Rc; | |
1322 | /// | |
85aaf69f | 1323 | /// let five = Rc::new(5); |
1a4d82fc | 1324 | /// |
9e0c209e | 1325 | /// assert!(five == Rc::new(5)); |
1a4d82fc | 1326 | /// ``` |
0731742a | 1327 | #[inline] |
b039eaaf | 1328 | fn eq(&self, other: &Rc<T>) -> bool { |
0731742a | 1329 | RcEqIdent::eq(self, other) |
b039eaaf | 1330 | } |
1a4d82fc | 1331 | |
9e0c209e | 1332 | /// Inequality for two `Rc`s. |
1a4d82fc | 1333 | /// |
9e0c209e | 1334 | /// Two `Rc`s are unequal if their inner values are unequal. |
1a4d82fc | 1335 | /// |
e74abb32 XL |
1336 | /// If `T` also implements `Eq` (implying reflexivity of equality), |
1337 | /// two `Rc`s that point to the same allocation are | |
0731742a XL |
1338 | /// never unequal. |
1339 | /// | |
1a4d82fc JJ |
1340 | /// # Examples |
1341 | /// | |
1342 | /// ``` | |
1343 | /// use std::rc::Rc; | |
1344 | /// | |
85aaf69f | 1345 | /// let five = Rc::new(5); |
1a4d82fc | 1346 | /// |
9e0c209e | 1347 | /// assert!(five != Rc::new(6)); |
1a4d82fc | 1348 | /// ``` |
0731742a | 1349 | #[inline] |
b039eaaf | 1350 | fn ne(&self, other: &Rc<T>) -> bool { |
0731742a | 1351 | RcEqIdent::ne(self, other) |
b039eaaf | 1352 | } |
1a4d82fc JJ |
1353 | } |
1354 | ||
85aaf69f | 1355 | #[stable(feature = "rust1", since = "1.0.0")] |
62682a34 | 1356 | impl<T: ?Sized + Eq> Eq for Rc<T> {} |
1a4d82fc | 1357 | |
85aaf69f | 1358 | #[stable(feature = "rust1", since = "1.0.0")] |
62682a34 | 1359 | impl<T: ?Sized + PartialOrd> PartialOrd for Rc<T> { |
9e0c209e | 1360 | /// Partial comparison for two `Rc`s. |
1a4d82fc JJ |
1361 | /// |
1362 | /// The two are compared by calling `partial_cmp()` on their inner values. | |
1363 | /// | |
1364 | /// # Examples | |
1365 | /// | |
1366 | /// ``` | |
1367 | /// use std::rc::Rc; | |
9e0c209e | 1368 | /// use std::cmp::Ordering; |
1a4d82fc | 1369 | /// |
85aaf69f | 1370 | /// let five = Rc::new(5); |
1a4d82fc | 1371 | /// |
9e0c209e | 1372 | /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&Rc::new(6))); |
1a4d82fc JJ |
1373 | /// ``` |
1374 | #[inline(always)] | |
1375 | fn partial_cmp(&self, other: &Rc<T>) -> Option<Ordering> { | |
1376 | (**self).partial_cmp(&**other) | |
1377 | } | |
1378 | ||
9e0c209e | 1379 | /// Less-than comparison for two `Rc`s. |
1a4d82fc JJ |
1380 | /// |
1381 | /// The two are compared by calling `<` on their inner values. | |
1382 | /// | |
1383 | /// # Examples | |
1384 | /// | |
1385 | /// ``` | |
1386 | /// use std::rc::Rc; | |
1387 | /// | |
85aaf69f | 1388 | /// let five = Rc::new(5); |
1a4d82fc | 1389 | /// |
9e0c209e | 1390 | /// assert!(five < Rc::new(6)); |
1a4d82fc JJ |
1391 | /// ``` |
1392 | #[inline(always)] | |
b039eaaf SL |
1393 | fn lt(&self, other: &Rc<T>) -> bool { |
1394 | **self < **other | |
1395 | } | |
1a4d82fc | 1396 | |
9e0c209e | 1397 | /// 'Less than or equal to' comparison for two `Rc`s. |
1a4d82fc JJ |
1398 | /// |
1399 | /// The two are compared by calling `<=` on their inner values. | |
1400 | /// | |
1401 | /// # Examples | |
1402 | /// | |
1403 | /// ``` | |
1404 | /// use std::rc::Rc; | |
1405 | /// | |
85aaf69f | 1406 | /// let five = Rc::new(5); |
1a4d82fc | 1407 | /// |
9e0c209e | 1408 | /// assert!(five <= Rc::new(5)); |
1a4d82fc JJ |
1409 | /// ``` |
1410 | #[inline(always)] | |
b039eaaf SL |
1411 | fn le(&self, other: &Rc<T>) -> bool { |
1412 | **self <= **other | |
1413 | } | |
1a4d82fc | 1414 | |
9e0c209e | 1415 | /// Greater-than comparison for two `Rc`s. |
1a4d82fc JJ |
1416 | /// |
1417 | /// The two are compared by calling `>` on their inner values. | |
1418 | /// | |
1419 | /// # Examples | |
1420 | /// | |
1421 | /// ``` | |
1422 | /// use std::rc::Rc; | |
1423 | /// | |
85aaf69f | 1424 | /// let five = Rc::new(5); |
1a4d82fc | 1425 | /// |
9e0c209e | 1426 | /// assert!(five > Rc::new(4)); |
1a4d82fc JJ |
1427 | /// ``` |
1428 | #[inline(always)] | |
b039eaaf SL |
1429 | fn gt(&self, other: &Rc<T>) -> bool { |
1430 | **self > **other | |
1431 | } | |
1a4d82fc | 1432 | |
9e0c209e | 1433 | /// 'Greater than or equal to' comparison for two `Rc`s. |
1a4d82fc JJ |
1434 | /// |
1435 | /// The two are compared by calling `>=` on their inner values. | |
1436 | /// | |
1437 | /// # Examples | |
1438 | /// | |
1439 | /// ``` | |
1440 | /// use std::rc::Rc; | |
1441 | /// | |
85aaf69f | 1442 | /// let five = Rc::new(5); |
1a4d82fc | 1443 | /// |
9e0c209e | 1444 | /// assert!(five >= Rc::new(5)); |
1a4d82fc JJ |
1445 | /// ``` |
1446 | #[inline(always)] | |
b039eaaf SL |
1447 | fn ge(&self, other: &Rc<T>) -> bool { |
1448 | **self >= **other | |
1449 | } | |
1a4d82fc JJ |
1450 | } |
1451 | ||
85aaf69f | 1452 | #[stable(feature = "rust1", since = "1.0.0")] |
62682a34 | 1453 | impl<T: ?Sized + Ord> Ord for Rc<T> { |
9e0c209e | 1454 | /// Comparison for two `Rc`s. |
1a4d82fc JJ |
1455 | /// |
1456 | /// The two are compared by calling `cmp()` on their inner values. | |
1457 | /// | |
1458 | /// # Examples | |
1459 | /// | |
1460 | /// ``` | |
1461 | /// use std::rc::Rc; | |
9e0c209e | 1462 | /// use std::cmp::Ordering; |
1a4d82fc | 1463 | /// |
85aaf69f | 1464 | /// let five = Rc::new(5); |
1a4d82fc | 1465 | /// |
9e0c209e | 1466 | /// assert_eq!(Ordering::Less, five.cmp(&Rc::new(6))); |
1a4d82fc JJ |
1467 | /// ``` |
1468 | #[inline] | |
b039eaaf SL |
1469 | fn cmp(&self, other: &Rc<T>) -> Ordering { |
1470 | (**self).cmp(&**other) | |
1471 | } | |
1a4d82fc JJ |
1472 | } |
1473 | ||
d9579d0f | 1474 | #[stable(feature = "rust1", since = "1.0.0")] |
92a42be0 | 1475 | impl<T: ?Sized + Hash> Hash for Rc<T> { |
d9579d0f AL |
1476 | fn hash<H: Hasher>(&self, state: &mut H) { |
1477 | (**self).hash(state); | |
1478 | } | |
1479 | } | |
1a4d82fc | 1480 | |
d9579d0f | 1481 | #[stable(feature = "rust1", since = "1.0.0")] |
92a42be0 | 1482 | impl<T: ?Sized + fmt::Display> fmt::Display for Rc<T> { |
9fa01778 | 1483 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
d9579d0f AL |
1484 | fmt::Display::fmt(&**self, f) |
1485 | } | |
1486 | } | |
1a4d82fc | 1487 | |
d9579d0f | 1488 | #[stable(feature = "rust1", since = "1.0.0")] |
92a42be0 | 1489 | impl<T: ?Sized + fmt::Debug> fmt::Debug for Rc<T> { |
9fa01778 | 1490 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
d9579d0f AL |
1491 | fmt::Debug::fmt(&**self, f) |
1492 | } | |
1493 | } | |
1a4d82fc | 1494 | |
9346a6ac | 1495 | #[stable(feature = "rust1", since = "1.0.0")] |
7453a54e | 1496 | impl<T: ?Sized> fmt::Pointer for Rc<T> { |
9fa01778 | 1497 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
ff7c6d11 | 1498 | fmt::Pointer::fmt(&(&**self as *const T), f) |
9346a6ac AL |
1499 | } |
1500 | } | |
1501 | ||
92a42be0 SL |
1502 | #[stable(feature = "from_for_ptrs", since = "1.6.0")] |
1503 | impl<T> From<T> for Rc<T> { | |
1504 | fn from(t: T) -> Self { | |
1505 | Rc::new(t) | |
1506 | } | |
1507 | } | |
1508 | ||
3b2f2976 | 1509 | #[stable(feature = "shared_from_slice", since = "1.21.0")] |
532ac7d7 | 1510 | impl<T: Clone> From<&[T]> for Rc<[T]> { |
3b2f2976 XL |
1511 | #[inline] |
1512 | fn from(v: &[T]) -> Rc<[T]> { | |
1513 | <Self as RcFromSlice<T>>::from_slice(v) | |
1514 | } | |
1515 | } | |
1516 | ||
1517 | #[stable(feature = "shared_from_slice", since = "1.21.0")] | |
532ac7d7 | 1518 | impl From<&str> for Rc<str> { |
3b2f2976 XL |
1519 | #[inline] |
1520 | fn from(v: &str) -> Rc<str> { | |
ff7c6d11 XL |
1521 | let rc = Rc::<[u8]>::from(v.as_bytes()); |
1522 | unsafe { Rc::from_raw(Rc::into_raw(rc) as *const str) } | |
3b2f2976 XL |
1523 | } |
1524 | } | |
1525 | ||
1526 | #[stable(feature = "shared_from_slice", since = "1.21.0")] | |
1527 | impl From<String> for Rc<str> { | |
1528 | #[inline] | |
1529 | fn from(v: String) -> Rc<str> { | |
1530 | Rc::from(&v[..]) | |
1531 | } | |
1532 | } | |
1533 | ||
1534 | #[stable(feature = "shared_from_slice", since = "1.21.0")] | |
1535 | impl<T: ?Sized> From<Box<T>> for Rc<T> { | |
1536 | #[inline] | |
1537 | fn from(v: Box<T>) -> Rc<T> { | |
1538 | Rc::from_box(v) | |
1539 | } | |
1540 | } | |
1541 | ||
1542 | #[stable(feature = "shared_from_slice", since = "1.21.0")] | |
1543 | impl<T> From<Vec<T>> for Rc<[T]> { | |
1544 | #[inline] | |
1545 | fn from(mut v: Vec<T>) -> Rc<[T]> { | |
1546 | unsafe { | |
1547 | let rc = Rc::copy_from_slice(&v); | |
1548 | ||
1549 | // Allow the Vec to free its memory, but not destroy its contents | |
1550 | v.set_len(0); | |
1551 | ||
1552 | rc | |
1553 | } | |
1554 | } | |
1555 | } | |
1556 | ||
f9f354fc XL |
1557 | #[stable(feature = "shared_from_cow", since = "1.45.0")] |
1558 | impl<'a, B> From<Cow<'a, B>> for Rc<B> | |
1559 | where | |
1560 | B: ToOwned + ?Sized, | |
1561 | Rc<B>: From<&'a B> + From<B::Owned>, | |
1562 | { | |
1563 | #[inline] | |
1564 | fn from(cow: Cow<'a, B>) -> Rc<B> { | |
1565 | match cow { | |
1566 | Cow::Borrowed(s) => Rc::from(s), | |
1567 | Cow::Owned(s) => Rc::from(s), | |
1568 | } | |
1569 | } | |
1570 | } | |
1571 | ||
74b04a01 | 1572 | #[stable(feature = "boxed_slice_try_from", since = "1.43.0")] |
3dfed10e | 1573 | impl<T, const N: usize> TryFrom<Rc<[T]>> for Rc<[T; N]> { |
416331ca XL |
1574 | type Error = Rc<[T]>; |
1575 | ||
1576 | fn try_from(boxed_slice: Rc<[T]>) -> Result<Self, Self::Error> { | |
1577 | if boxed_slice.len() == N { | |
1578 | Ok(unsafe { Rc::from_raw(Rc::into_raw(boxed_slice) as *mut [T; N]) }) | |
1579 | } else { | |
1580 | Err(boxed_slice) | |
1581 | } | |
1582 | } | |
1583 | } | |
1584 | ||
1585 | #[stable(feature = "shared_from_iter", since = "1.37.0")] | |
1586 | impl<T> iter::FromIterator<T> for Rc<[T]> { | |
1587 | /// Takes each element in the `Iterator` and collects it into an `Rc<[T]>`. | |
1588 | /// | |
1589 | /// # Performance characteristics | |
1590 | /// | |
1591 | /// ## The general case | |
1592 | /// | |
1593 | /// In the general case, collecting into `Rc<[T]>` is done by first | |
1594 | /// collecting into a `Vec<T>`. That is, when writing the following: | |
1595 | /// | |
1596 | /// ```rust | |
1597 | /// # use std::rc::Rc; | |
1598 | /// let evens: Rc<[u8]> = (0..10).filter(|&x| x % 2 == 0).collect(); | |
1599 | /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]); | |
1600 | /// ``` | |
1601 | /// | |
1602 | /// this behaves as if we wrote: | |
1603 | /// | |
1604 | /// ```rust | |
1605 | /// # use std::rc::Rc; | |
1606 | /// let evens: Rc<[u8]> = (0..10).filter(|&x| x % 2 == 0) | |
1607 | /// .collect::<Vec<_>>() // The first set of allocations happens here. | |
1608 | /// .into(); // A second allocation for `Rc<[T]>` happens here. | |
1609 | /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]); | |
1610 | /// ``` | |
1611 | /// | |
1612 | /// This will allocate as many times as needed for constructing the `Vec<T>` | |
1613 | /// and then it will allocate once for turning the `Vec<T>` into the `Rc<[T]>`. | |
1614 | /// | |
1615 | /// ## Iterators of known length | |
1616 | /// | |
1617 | /// When your `Iterator` implements `TrustedLen` and is of an exact size, | |
1618 | /// a single allocation will be made for the `Rc<[T]>`. For example: | |
1619 | /// | |
1620 | /// ```rust | |
1621 | /// # use std::rc::Rc; | |
1622 | /// let evens: Rc<[u8]> = (0..10).collect(); // Just a single allocation happens here. | |
1623 | /// # assert_eq!(&*evens, &*(0..10).collect::<Vec<_>>()); | |
1624 | /// ``` | |
1625 | fn from_iter<I: iter::IntoIterator<Item = T>>(iter: I) -> Self { | |
f9f354fc | 1626 | ToRcSlice::to_rc_slice(iter.into_iter()) |
416331ca XL |
1627 | } |
1628 | } | |
1629 | ||
1630 | /// Specialization trait used for collecting into `Rc<[T]>`. | |
f9f354fc XL |
1631 | trait ToRcSlice<T>: Iterator<Item = T> + Sized { |
1632 | fn to_rc_slice(self) -> Rc<[T]>; | |
416331ca XL |
1633 | } |
1634 | ||
f9f354fc XL |
1635 | impl<T, I: Iterator<Item = T>> ToRcSlice<T> for I { |
1636 | default fn to_rc_slice(self) -> Rc<[T]> { | |
1637 | self.collect::<Vec<T>>().into() | |
416331ca XL |
1638 | } |
1639 | } | |
1640 | ||
f9f354fc XL |
1641 | impl<T, I: iter::TrustedLen<Item = T>> ToRcSlice<T> for I { |
1642 | fn to_rc_slice(self) -> Rc<[T]> { | |
416331ca | 1643 | // This is the case for a `TrustedLen` iterator. |
f9f354fc | 1644 | let (low, high) = self.size_hint(); |
416331ca XL |
1645 | if let Some(high) = high { |
1646 | debug_assert_eq!( | |
dfeec247 XL |
1647 | low, |
1648 | high, | |
416331ca XL |
1649 | "TrustedLen iterator's size hint is not exact: {:?}", |
1650 | (low, high) | |
1651 | ); | |
1652 | ||
1653 | unsafe { | |
1654 | // SAFETY: We need to ensure that the iterator has an exact length and we have. | |
f9f354fc | 1655 | Rc::from_iter_exact(self, low) |
416331ca XL |
1656 | } |
1657 | } else { | |
1658 | // Fall back to normal implementation. | |
f9f354fc | 1659 | self.collect::<Vec<T>>().into() |
416331ca XL |
1660 | } |
1661 | } | |
1662 | } | |
1663 | ||
cc61c64b | 1664 | /// `Weak` is a version of [`Rc`] that holds a non-owning reference to the |
e74abb32 | 1665 | /// managed allocation. The allocation is accessed by calling [`upgrade`] on the `Weak` |
cc61c64b | 1666 | /// pointer, which returns an [`Option`]`<`[`Rc`]`<T>>`. |
9e0c209e | 1667 | /// |
cc61c64b | 1668 | /// Since a `Weak` reference does not count towards ownership, it will not |
e74abb32 XL |
1669 | /// prevent the value stored in the allocation from being dropped, and `Weak` itself makes no |
1670 | /// guarantees about the value still being present. Thus it may return [`None`] | |
1671 | /// when [`upgrade`]d. Note however that a `Weak` reference *does* prevent the allocation | |
1672 | /// itself (the backing store) from being deallocated. | |
9e0c209e | 1673 | /// |
e74abb32 XL |
1674 | /// A `Weak` pointer is useful for keeping a temporary reference to the allocation |
1675 | /// managed by [`Rc`] without preventing its inner value from being dropped. It is also used to | |
1676 | /// prevent circular references between [`Rc`] pointers, since mutual owning references | |
3b2f2976 | 1677 | /// would never allow either [`Rc`] to be dropped. For example, a tree could |
cc61c64b XL |
1678 | /// have strong [`Rc`] pointers from parent nodes to children, and `Weak` |
1679 | /// pointers from children back to their parents. | |
1a4d82fc | 1680 | /// |
cc61c64b | 1681 | /// The typical way to obtain a `Weak` pointer is to call [`Rc::downgrade`]. |
1a4d82fc | 1682 | /// |
3dfed10e | 1683 | /// [`upgrade`]: Weak::upgrade |
e9174d1e | 1684 | #[stable(feature = "rc_weak", since = "1.4.0")] |
d9579d0f | 1685 | pub struct Weak<T: ?Sized> { |
8faf50e0 XL |
1686 | // This is a `NonNull` to allow optimizing the size of this type in enums, |
1687 | // but it is not necessarily a valid pointer. | |
1688 | // `Weak::new` sets this to `usize::MAX` so that it doesn’t need | |
1689 | // to allocate space on the heap. That's not a value a real pointer | |
1690 | // will ever have because RcBox has alignment at least 2. | |
f035d41b | 1691 | // This is only possible when `T: Sized`; unsized `T` never dangle. |
2c00a5a8 | 1692 | ptr: NonNull<RcBox<T>>, |
d9579d0f | 1693 | } |
1a4d82fc | 1694 | |
7453a54e | 1695 | #[stable(feature = "rc_weak", since = "1.4.0")] |
d9579d0f | 1696 | impl<T: ?Sized> !marker::Send for Weak<T> {} |
7453a54e | 1697 | #[stable(feature = "rc_weak", since = "1.4.0")] |
d9579d0f | 1698 | impl<T: ?Sized> !marker::Sync for Weak<T> {} |
85aaf69f | 1699 | |
92a42be0 SL |
1700 | #[unstable(feature = "coerce_unsized", issue = "27732")] |
1701 | impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {} | |
c1a9b12d | 1702 | |
dfeec247 | 1703 | #[unstable(feature = "dispatch_from_dyn", issue = "none")] |
a1dfa0c6 XL |
1704 | impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Weak<U>> for Weak<T> {} |
1705 | ||
a7813a04 | 1706 | impl<T> Weak<T> { |
8faf50e0 | 1707 | /// Constructs a new `Weak<T>`, without allocating any memory. |
0731742a | 1708 | /// Calling [`upgrade`] on the return value always gives [`None`]. |
a7813a04 | 1709 | /// |
3dfed10e | 1710 | /// [`upgrade`]: Weak::upgrade |
a7813a04 XL |
1711 | /// |
1712 | /// # Examples | |
1713 | /// | |
1714 | /// ``` | |
1715 | /// use std::rc::Weak; | |
1716 | /// | |
1717 | /// let empty: Weak<i64> = Weak::new(); | |
9e0c209e | 1718 | /// assert!(empty.upgrade().is_none()); |
a7813a04 XL |
1719 | /// ``` |
1720 | #[stable(feature = "downgraded_weak", since = "1.10.0")] | |
1721 | pub fn new() -> Weak<T> { | |
dfeec247 | 1722 | Weak { ptr: NonNull::new(usize::MAX as *mut RcBox<T>).expect("MAX is not 0") } |
a7813a04 | 1723 | } |
dc9dc135 XL |
1724 | |
1725 | /// Returns a raw pointer to the object `T` pointed to by this `Weak<T>`. | |
1726 | /// | |
ba9703b0 XL |
1727 | /// The pointer is valid only if there are some strong references. The pointer may be dangling, |
1728 | /// unaligned or even [`null`] otherwise. | |
dc9dc135 XL |
1729 | /// |
1730 | /// # Examples | |
1731 | /// | |
1732 | /// ``` | |
416331ca | 1733 | /// use std::rc::Rc; |
dc9dc135 XL |
1734 | /// use std::ptr; |
1735 | /// | |
1736 | /// let strong = Rc::new("hello".to_owned()); | |
1737 | /// let weak = Rc::downgrade(&strong); | |
1738 | /// // Both point to the same object | |
ba9703b0 | 1739 | /// assert!(ptr::eq(&*strong, weak.as_ptr())); |
dc9dc135 | 1740 | /// // The strong here keeps it alive, so we can still access the object. |
ba9703b0 | 1741 | /// assert_eq!("hello", unsafe { &*weak.as_ptr() }); |
dc9dc135 XL |
1742 | /// |
1743 | /// drop(strong); | |
ba9703b0 | 1744 | /// // But not any more. We can do weak.as_ptr(), but accessing the pointer would lead to |
dc9dc135 | 1745 | /// // undefined behaviour. |
ba9703b0 | 1746 | /// // assert_eq!("hello", unsafe { &*weak.as_ptr() }); |
dc9dc135 XL |
1747 | /// ``` |
1748 | /// | |
3dfed10e | 1749 | /// [`null`]: core::ptr::null |
f035d41b | 1750 | #[stable(feature = "rc_as_ptr", since = "1.45.0")] |
ba9703b0 | 1751 | pub fn as_ptr(&self) -> *const T { |
f035d41b XL |
1752 | let ptr: *mut RcBox<T> = NonNull::as_ptr(self.ptr); |
1753 | ||
1754 | // SAFETY: we must offset the pointer manually, and said pointer may be | |
1755 | // a dangling weak (usize::MAX) if T is sized. data_offset is safe to call, | |
1756 | // because we know that a pointer to unsized T was derived from a real | |
1757 | // unsized T, as dangling weaks are only created for sized T. wrapping_offset | |
1758 | // is used so that we can use the same code path for the non-dangling | |
1759 | // unsized case and the potentially dangling sized case. | |
1760 | unsafe { | |
1761 | let offset = data_offset(ptr as *mut T); | |
1762 | set_data_ptr(ptr as *mut T, (ptr as *mut u8).wrapping_offset(offset)) | |
1763 | } | |
dc9dc135 XL |
1764 | } |
1765 | ||
1766 | /// Consumes the `Weak<T>` and turns it into a raw pointer. | |
1767 | /// | |
3dfed10e XL |
1768 | /// This converts the weak pointer into a raw pointer, while still preserving the ownership of |
1769 | /// one weak reference (the weak count is not modified by this operation). It can be turned | |
1770 | /// back into the `Weak<T>` with [`from_raw`]. | |
dc9dc135 XL |
1771 | /// |
1772 | /// The same restrictions of accessing the target of the pointer as with | |
ba9703b0 | 1773 | /// [`as_ptr`] apply. |
dc9dc135 XL |
1774 | /// |
1775 | /// # Examples | |
1776 | /// | |
1777 | /// ``` | |
dc9dc135 XL |
1778 | /// use std::rc::{Rc, Weak}; |
1779 | /// | |
1780 | /// let strong = Rc::new("hello".to_owned()); | |
1781 | /// let weak = Rc::downgrade(&strong); | |
416331ca | 1782 | /// let raw = weak.into_raw(); |
dc9dc135 XL |
1783 | /// |
1784 | /// assert_eq!(1, Rc::weak_count(&strong)); | |
1785 | /// assert_eq!("hello", unsafe { &*raw }); | |
1786 | /// | |
1787 | /// drop(unsafe { Weak::from_raw(raw) }); | |
1788 | /// assert_eq!(0, Rc::weak_count(&strong)); | |
1789 | /// ``` | |
1790 | /// | |
3dfed10e XL |
1791 | /// [`from_raw`]: Weak::from_raw |
1792 | /// [`as_ptr`]: Weak::as_ptr | |
f9f354fc | 1793 | #[stable(feature = "weak_into_raw", since = "1.45.0")] |
416331ca | 1794 | pub fn into_raw(self) -> *const T { |
ba9703b0 | 1795 | let result = self.as_ptr(); |
416331ca | 1796 | mem::forget(self); |
dc9dc135 XL |
1797 | result |
1798 | } | |
1799 | ||
1800 | /// Converts a raw pointer previously created by [`into_raw`] back into `Weak<T>`. | |
1801 | /// | |
1802 | /// This can be used to safely get a strong reference (by calling [`upgrade`] | |
1803 | /// later) or to deallocate the weak count by dropping the `Weak<T>`. | |
1804 | /// | |
3dfed10e XL |
1805 | /// It takes ownership of one weak reference (with the exception of pointers created by [`new`], |
1806 | /// as these don't own anything; the method still works on them). | |
dc9dc135 XL |
1807 | /// |
1808 | /// # Safety | |
1809 | /// | |
3dfed10e XL |
1810 | /// The pointer must have originated from the [`into_raw`] and must still own its potential |
1811 | /// weak reference. | |
60c5eb7d | 1812 | /// |
3dfed10e XL |
1813 | /// It is allowed for the strong count to be 0 at the time of calling this. Nevertheless, this |
1814 | /// takes ownership of one weak reference currently represented as a raw pointer (the weak | |
1815 | /// count is not modified by this operation) and therefore it must be paired with a previous | |
1816 | /// call to [`into_raw`]. | |
dc9dc135 XL |
1817 | /// |
1818 | /// # Examples | |
1819 | /// | |
1820 | /// ``` | |
dc9dc135 XL |
1821 | /// use std::rc::{Rc, Weak}; |
1822 | /// | |
1823 | /// let strong = Rc::new("hello".to_owned()); | |
1824 | /// | |
416331ca XL |
1825 | /// let raw_1 = Rc::downgrade(&strong).into_raw(); |
1826 | /// let raw_2 = Rc::downgrade(&strong).into_raw(); | |
dc9dc135 XL |
1827 | /// |
1828 | /// assert_eq!(2, Rc::weak_count(&strong)); | |
1829 | /// | |
416331ca | 1830 | /// assert_eq!("hello", &*unsafe { Weak::from_raw(raw_1) }.upgrade().unwrap()); |
dc9dc135 XL |
1831 | /// assert_eq!(1, Rc::weak_count(&strong)); |
1832 | /// | |
1833 | /// drop(strong); | |
1834 | /// | |
1835 | /// // Decrement the last weak count. | |
416331ca | 1836 | /// assert!(unsafe { Weak::from_raw(raw_2) }.upgrade().is_none()); |
dc9dc135 XL |
1837 | /// ``` |
1838 | /// | |
3dfed10e XL |
1839 | /// [`into_raw`]: Weak::into_raw |
1840 | /// [`upgrade`]: Weak::upgrade | |
1841 | /// [`new`]: Weak::new | |
f9f354fc | 1842 | #[stable(feature = "weak_into_raw", since = "1.45.0")] |
dc9dc135 XL |
1843 | pub unsafe fn from_raw(ptr: *const T) -> Self { |
1844 | if ptr.is_null() { | |
1845 | Self::new() | |
1846 | } else { | |
1847 | // See Rc::from_raw for details | |
f035d41b XL |
1848 | unsafe { |
1849 | let offset = data_offset(ptr); | |
1850 | let fake_ptr = ptr as *mut RcBox<T>; | |
1851 | let ptr = set_data_ptr(fake_ptr, (ptr as *mut u8).offset(-offset)); | |
1852 | Weak { ptr: NonNull::new(ptr).expect("Invalid pointer passed to from_raw") } | |
1853 | } | |
dc9dc135 XL |
1854 | } |
1855 | } | |
a7813a04 XL |
1856 | } |
1857 | ||
8faf50e0 XL |
1858 | pub(crate) fn is_dangling<T: ?Sized>(ptr: NonNull<T>) -> bool { |
1859 | let address = ptr.as_ptr() as *mut () as usize; | |
1860 | address == usize::MAX | |
1861 | } | |
1862 | ||
1b1a35ee XL |
1863 | /// Helper type to allow accessing the reference counts without |
1864 | /// making any assertions about the data field. | |
1865 | struct WeakInner<'a> { | |
1866 | weak: &'a Cell<usize>, | |
1867 | strong: &'a Cell<usize>, | |
1868 | } | |
1869 | ||
d9579d0f | 1870 | impl<T: ?Sized> Weak<T> { |
e74abb32 XL |
1871 | /// Attempts to upgrade the `Weak` pointer to an [`Rc`], delaying |
1872 | /// dropping of the inner value if successful. | |
d9579d0f | 1873 | /// |
e74abb32 | 1874 | /// Returns [`None`] if the inner value has since been dropped. |
d9579d0f | 1875 | /// |
d9579d0f AL |
1876 | /// # Examples |
1877 | /// | |
1878 | /// ``` | |
d9579d0f AL |
1879 | /// use std::rc::Rc; |
1880 | /// | |
1881 | /// let five = Rc::new(5); | |
1882 | /// | |
e9174d1e | 1883 | /// let weak_five = Rc::downgrade(&five); |
d9579d0f AL |
1884 | /// |
1885 | /// let strong_five: Option<Rc<_>> = weak_five.upgrade(); | |
9e0c209e SL |
1886 | /// assert!(strong_five.is_some()); |
1887 | /// | |
1888 | /// // Destroy all strong pointers. | |
1889 | /// drop(strong_five); | |
1890 | /// drop(five); | |
1891 | /// | |
1892 | /// assert!(weak_five.upgrade().is_none()); | |
d9579d0f | 1893 | /// ``` |
e9174d1e | 1894 | #[stable(feature = "rc_weak", since = "1.4.0")] |
d9579d0f | 1895 | pub fn upgrade(&self) -> Option<Rc<T>> { |
8faf50e0 XL |
1896 | let inner = self.inner()?; |
1897 | if inner.strong() == 0 { | |
d9579d0f AL |
1898 | None |
1899 | } else { | |
8faf50e0 | 1900 | inner.inc_strong(); |
416331ca | 1901 | Some(Rc::from_inner(self.ptr)) |
d9579d0f AL |
1902 | } |
1903 | } | |
8faf50e0 | 1904 | |
e74abb32 | 1905 | /// Gets the number of strong (`Rc`) pointers pointing to this allocation. |
9fa01778 XL |
1906 | /// |
1907 | /// If `self` was created using [`Weak::new`], this will return 0. | |
60c5eb7d | 1908 | #[stable(feature = "weak_counts", since = "1.41.0")] |
9fa01778 | 1909 | pub fn strong_count(&self) -> usize { |
dfeec247 | 1910 | if let Some(inner) = self.inner() { inner.strong() } else { 0 } |
9fa01778 XL |
1911 | } |
1912 | ||
e74abb32 | 1913 | /// Gets the number of `Weak` pointers pointing to this allocation. |
9fa01778 | 1914 | /// |
60c5eb7d XL |
1915 | /// If no strong pointers remain, this will return zero. |
1916 | #[stable(feature = "weak_counts", since = "1.41.0")] | |
1917 | pub fn weak_count(&self) -> usize { | |
dfeec247 XL |
1918 | self.inner() |
1919 | .map(|inner| { | |
1920 | if inner.strong() > 0 { | |
1921 | inner.weak() - 1 // subtract the implicit weak ptr | |
1922 | } else { | |
1923 | 0 | |
1924 | } | |
1925 | }) | |
1926 | .unwrap_or(0) | |
9fa01778 XL |
1927 | } |
1928 | ||
1b1a35ee | 1929 | /// Returns `None` when the pointer is dangling and there is no allocated `RcBox`, |
9fa01778 | 1930 | /// (i.e., when this `Weak` was created by `Weak::new`). |
8faf50e0 | 1931 | #[inline] |
1b1a35ee XL |
1932 | fn inner(&self) -> Option<WeakInner<'_>> { |
1933 | if is_dangling(self.ptr) { | |
1934 | None | |
1935 | } else { | |
1936 | // We are careful to *not* create a reference covering the "data" field, as | |
1937 | // the field may be mutated concurrently (for example, if the last `Rc` | |
1938 | // is dropped, the data field will be dropped in-place). | |
1939 | Some(unsafe { | |
1940 | let ptr = self.ptr.as_ptr(); | |
1941 | WeakInner { strong: &(*ptr).strong, weak: &(*ptr).weak } | |
1942 | }) | |
1943 | } | |
8faf50e0 | 1944 | } |
0731742a | 1945 | |
e74abb32 XL |
1946 | /// Returns `true` if the two `Weak`s point to the same allocation (similar to |
1947 | /// [`ptr::eq`]), or if both don't point to any allocation | |
e1599b0c | 1948 | /// (because they were created with `Weak::new()`). |
0731742a XL |
1949 | /// |
1950 | /// # Notes | |
1951 | /// | |
1952 | /// Since this compares pointers it means that `Weak::new()` will equal each | |
e74abb32 | 1953 | /// other, even though they don't point to any allocation. |
0731742a XL |
1954 | /// |
1955 | /// # Examples | |
1956 | /// | |
1957 | /// ``` | |
dc9dc135 | 1958 | /// use std::rc::Rc; |
0731742a XL |
1959 | /// |
1960 | /// let first_rc = Rc::new(5); | |
1961 | /// let first = Rc::downgrade(&first_rc); | |
1962 | /// let second = Rc::downgrade(&first_rc); | |
1963 | /// | |
dc9dc135 | 1964 | /// assert!(first.ptr_eq(&second)); |
0731742a XL |
1965 | /// |
1966 | /// let third_rc = Rc::new(5); | |
1967 | /// let third = Rc::downgrade(&third_rc); | |
1968 | /// | |
dc9dc135 | 1969 | /// assert!(!first.ptr_eq(&third)); |
0731742a XL |
1970 | /// ``` |
1971 | /// | |
1972 | /// Comparing `Weak::new`. | |
1973 | /// | |
1974 | /// ``` | |
0731742a XL |
1975 | /// use std::rc::{Rc, Weak}; |
1976 | /// | |
1977 | /// let first = Weak::new(); | |
1978 | /// let second = Weak::new(); | |
dc9dc135 | 1979 | /// assert!(first.ptr_eq(&second)); |
0731742a XL |
1980 | /// |
1981 | /// let third_rc = Rc::new(()); | |
1982 | /// let third = Rc::downgrade(&third_rc); | |
dc9dc135 | 1983 | /// assert!(!first.ptr_eq(&third)); |
0731742a | 1984 | /// ``` |
e74abb32 | 1985 | /// |
3dfed10e | 1986 | /// [`ptr::eq`]: core::ptr::eq |
0731742a | 1987 | #[inline] |
e1599b0c | 1988 | #[stable(feature = "weak_ptr_eq", since = "1.39.0")] |
dc9dc135 XL |
1989 | pub fn ptr_eq(&self, other: &Self) -> bool { |
1990 | self.ptr.as_ptr() == other.ptr.as_ptr() | |
0731742a | 1991 | } |
d9579d0f AL |
1992 | } |
1993 | ||
7453a54e | 1994 | #[stable(feature = "rc_weak", since = "1.4.0")] |
d9579d0f | 1995 | impl<T: ?Sized> Drop for Weak<T> { |
9e0c209e | 1996 | /// Drops the `Weak` pointer. |
d9579d0f | 1997 | /// |
d9579d0f AL |
1998 | /// # Examples |
1999 | /// | |
2000 | /// ``` | |
7cac9316 | 2001 | /// use std::rc::{Rc, Weak}; |
d9579d0f | 2002 | /// |
9e0c209e | 2003 | /// struct Foo; |
d9579d0f | 2004 | /// |
9e0c209e SL |
2005 | /// impl Drop for Foo { |
2006 | /// fn drop(&mut self) { | |
2007 | /// println!("dropped!"); | |
2008 | /// } | |
d9579d0f | 2009 | /// } |
d9579d0f | 2010 | /// |
9e0c209e SL |
2011 | /// let foo = Rc::new(Foo); |
2012 | /// let weak_foo = Rc::downgrade(&foo); | |
7cac9316 | 2013 | /// let other_weak_foo = Weak::clone(&weak_foo); |
9e0c209e SL |
2014 | /// |
2015 | /// drop(weak_foo); // Doesn't print anything | |
2016 | /// drop(foo); // Prints "dropped!" | |
d9579d0f | 2017 | /// |
9e0c209e | 2018 | /// assert!(other_weak_foo.upgrade().is_none()); |
d9579d0f AL |
2019 | /// ``` |
2020 | fn drop(&mut self) { | |
1b1a35ee XL |
2021 | let inner = if let Some(inner) = self.inner() { inner } else { return }; |
2022 | ||
2023 | inner.dec_weak(); | |
2024 | // the weak count starts at 1, and will only go to zero if all | |
2025 | // the strong pointers have disappeared. | |
2026 | if inner.weak() == 0 { | |
2027 | unsafe { | |
2028 | Global.dealloc(self.ptr.cast(), Layout::for_value(self.ptr.as_ref())); | |
d9579d0f AL |
2029 | } |
2030 | } | |
2031 | } | |
2032 | } | |
2033 | ||
e9174d1e | 2034 | #[stable(feature = "rc_weak", since = "1.4.0")] |
d9579d0f | 2035 | impl<T: ?Sized> Clone for Weak<T> { |
e74abb32 | 2036 | /// Makes a clone of the `Weak` pointer that points to the same allocation. |
d9579d0f AL |
2037 | /// |
2038 | /// # Examples | |
2039 | /// | |
2040 | /// ``` | |
7cac9316 | 2041 | /// use std::rc::{Rc, Weak}; |
d9579d0f | 2042 | /// |
e9174d1e | 2043 | /// let weak_five = Rc::downgrade(&Rc::new(5)); |
d9579d0f | 2044 | /// |
0bf4aa26 | 2045 | /// let _ = Weak::clone(&weak_five); |
d9579d0f AL |
2046 | /// ``` |
2047 | #[inline] | |
2048 | fn clone(&self) -> Weak<T> { | |
8faf50e0 XL |
2049 | if let Some(inner) = self.inner() { |
2050 | inner.inc_weak() | |
2051 | } | |
54a0048b | 2052 | Weak { ptr: self.ptr } |
d9579d0f AL |
2053 | } |
2054 | } | |
1a4d82fc | 2055 | |
7453a54e | 2056 | #[stable(feature = "rc_weak", since = "1.4.0")] |
92a42be0 | 2057 | impl<T: ?Sized + fmt::Debug> fmt::Debug for Weak<T> { |
9fa01778 | 2058 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
d9579d0f AL |
2059 | write!(f, "(Weak)") |
2060 | } | |
2061 | } | |
1a4d82fc | 2062 | |
a7813a04 XL |
2063 | #[stable(feature = "downgraded_weak", since = "1.10.0")] |
2064 | impl<T> Default for Weak<T> { | |
cc61c64b | 2065 | /// Constructs a new `Weak<T>`, allocating memory for `T` without initializing |
0731742a | 2066 | /// it. Calling [`upgrade`] on the return value always gives [`None`]. |
9e0c209e | 2067 | /// |
3dfed10e XL |
2068 | /// [`None`]: Option |
2069 | /// [`upgrade`]: Weak::upgrade | |
9e0c209e SL |
2070 | /// |
2071 | /// # Examples | |
2072 | /// | |
2073 | /// ``` | |
2074 | /// use std::rc::Weak; | |
2075 | /// | |
2076 | /// let empty: Weak<i64> = Default::default(); | |
2077 | /// assert!(empty.upgrade().is_none()); | |
2078 | /// ``` | |
a7813a04 XL |
2079 | fn default() -> Weak<T> { |
2080 | Weak::new() | |
9cc50fc6 SL |
2081 | } |
2082 | } | |
2083 | ||
8faf50e0 | 2084 | // NOTE: We checked_add here to deal with mem::forget safely. In particular |
c1a9b12d SL |
2085 | // if you mem::forget Rcs (or Weaks), the ref-count can overflow, and then |
2086 | // you can free the allocation while outstanding Rcs (or Weaks) exist. | |
2087 | // We abort because this is such a degenerate scenario that we don't care about | |
2088 | // what happens -- no real program should ever experience this. | |
2089 | // | |
2090 | // This should have negligible overhead since you don't actually need to | |
2091 | // clone these much in Rust thanks to ownership and move-semantics. | |
2092 | ||
d9579d0f | 2093 | #[doc(hidden)] |
1b1a35ee XL |
2094 | trait RcInnerPtr { |
2095 | fn weak_ref(&self) -> &Cell<usize>; | |
2096 | fn strong_ref(&self) -> &Cell<usize>; | |
d9579d0f AL |
2097 | |
2098 | #[inline] | |
b039eaaf | 2099 | fn strong(&self) -> usize { |
1b1a35ee | 2100 | self.strong_ref().get() |
b039eaaf | 2101 | } |
d9579d0f AL |
2102 | |
2103 | #[inline] | |
c1a9b12d | 2104 | fn inc_strong(&self) { |
416331ca XL |
2105 | let strong = self.strong(); |
2106 | ||
b7449926 XL |
2107 | // We want to abort on overflow instead of dropping the value. |
2108 | // The reference count will never be zero when this is called; | |
2109 | // nevertheless, we insert an abort here to hint LLVM at | |
2110 | // an otherwise missed optimization. | |
f035d41b XL |
2111 | if strong == 0 || strong == usize::MAX { |
2112 | abort(); | |
b7449926 | 2113 | } |
1b1a35ee | 2114 | self.strong_ref().set(strong + 1); |
c1a9b12d | 2115 | } |
d9579d0f AL |
2116 | |
2117 | #[inline] | |
b039eaaf | 2118 | fn dec_strong(&self) { |
1b1a35ee | 2119 | self.strong_ref().set(self.strong() - 1); |
b039eaaf | 2120 | } |
d9579d0f AL |
2121 | |
2122 | #[inline] | |
b039eaaf | 2123 | fn weak(&self) -> usize { |
1b1a35ee | 2124 | self.weak_ref().get() |
b039eaaf | 2125 | } |
d9579d0f AL |
2126 | |
2127 | #[inline] | |
c1a9b12d | 2128 | fn inc_weak(&self) { |
416331ca XL |
2129 | let weak = self.weak(); |
2130 | ||
b7449926 XL |
2131 | // We want to abort on overflow instead of dropping the value. |
2132 | // The reference count will never be zero when this is called; | |
2133 | // nevertheless, we insert an abort here to hint LLVM at | |
2134 | // an otherwise missed optimization. | |
f035d41b XL |
2135 | if weak == 0 || weak == usize::MAX { |
2136 | abort(); | |
b7449926 | 2137 | } |
1b1a35ee | 2138 | self.weak_ref().set(weak + 1); |
c1a9b12d | 2139 | } |
d9579d0f AL |
2140 | |
2141 | #[inline] | |
b039eaaf | 2142 | fn dec_weak(&self) { |
1b1a35ee | 2143 | self.weak_ref().set(self.weak() - 1); |
b039eaaf | 2144 | } |
d9579d0f | 2145 | } |
1a4d82fc | 2146 | |
1b1a35ee | 2147 | impl<T: ?Sized> RcInnerPtr for RcBox<T> { |
d9579d0f | 2148 | #[inline(always)] |
1b1a35ee XL |
2149 | fn weak_ref(&self) -> &Cell<usize> { |
2150 | &self.weak | |
2151 | } | |
2152 | ||
2153 | #[inline(always)] | |
2154 | fn strong_ref(&self) -> &Cell<usize> { | |
2155 | &self.strong | |
85aaf69f | 2156 | } |
1a4d82fc JJ |
2157 | } |
2158 | ||
1b1a35ee | 2159 | impl<'a> RcInnerPtr for WeakInner<'a> { |
d9579d0f | 2160 | #[inline(always)] |
1b1a35ee XL |
2161 | fn weak_ref(&self) -> &Cell<usize> { |
2162 | self.weak | |
2163 | } | |
2164 | ||
2165 | #[inline(always)] | |
2166 | fn strong_ref(&self) -> &Cell<usize> { | |
2167 | self.strong | |
85aaf69f | 2168 | } |
1a4d82fc JJ |
2169 | } |
2170 | ||
92a42be0 | 2171 | #[stable(feature = "rust1", since = "1.0.0")] |
e9174d1e | 2172 | impl<T: ?Sized> borrow::Borrow<T> for Rc<T> { |
b039eaaf SL |
2173 | fn borrow(&self) -> &T { |
2174 | &**self | |
2175 | } | |
2176 | } | |
2177 | ||
2178 | #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")] | |
2179 | impl<T: ?Sized> AsRef<T> for Rc<T> { | |
2180 | fn as_ref(&self) -> &T { | |
2181 | &**self | |
2182 | } | |
e9174d1e | 2183 | } |
b7449926 | 2184 | |
0731742a | 2185 | #[stable(feature = "pin", since = "1.33.0")] |
dfeec247 | 2186 | impl<T: ?Sized> Unpin for Rc<T> {} |
dc9dc135 | 2187 | |
3dfed10e | 2188 | /// Get the offset within an `RcBox` for |
f035d41b XL |
2189 | /// a payload of type described by a pointer. |
2190 | /// | |
2191 | /// # Safety | |
2192 | /// | |
2193 | /// This has the same safety requirements as `align_of_val_raw`. In effect: | |
2194 | /// | |
2195 | /// - This function is safe for any argument if `T` is sized, and | |
2196 | /// - if `T` is unsized, the pointer must have appropriate pointer metadata | |
3dfed10e | 2197 | /// acquired from the real instance that you are getting this offset for. |
dc9dc135 | 2198 | unsafe fn data_offset<T: ?Sized>(ptr: *const T) -> isize { |
416331ca | 2199 | // Align the unsized value to the end of the `RcBox`. |
dc9dc135 | 2200 | // Because it is ?Sized, it will always be the last field in memory. |
dfeec247 XL |
2201 | // Note: This is a detail of the current implementation of the compiler, |
2202 | // and is not a guaranteed language detail. Do not rely on it outside of std. | |
f035d41b | 2203 | unsafe { data_offset_align(align_of_val_raw(ptr)) } |
416331ca XL |
2204 | } |
2205 | ||
2206 | #[inline] | |
2207 | fn data_offset_align(align: usize) -> isize { | |
dc9dc135 XL |
2208 | let layout = Layout::new::<RcBox<()>>(); |
2209 | (layout.size() + layout.padding_needed_for(align)) as isize | |
2210 | } |