1 //! Single-threaded reference-counting pointers. 'Rc' stands for 'Reference
2 //! Counted'.
3 //!
4 //! The type [`Rc<T>`][`Rc`] provides shared ownership of a value of type `T`,
5 //! allocated in the heap. Invoking [`clone`][clone] on [`Rc`] produces a new
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.
9 //!
10 //! Shared references in Rust disallow mutation by default, and [`Rc`]
11 //! is no exception: you cannot generally obtain a mutable reference to
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].
15 //!
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`]
18 //! does not implement [`Send`]. As a result, the Rust compiler
19 //! will check *at compile time* that you are not sending [`Rc`]s between
20 //! threads. If you need multi-threaded, atomic reference counting, use
21 //! [`sync::Arc`][arc].
22 //!
23 //! The [`downgrade`][downgrade] method can be used to create a non-owning
24 //! [`Weak`] pointer. A [`Weak`] pointer can be [`upgrade`][upgrade]d
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.
29 //!
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
33 //! children back to their parents.
34 //!
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
37 //! clashes with `T`'s methods, the methods of [`Rc<T>`][`Rc`] itself are associated
38 //! functions, called using [fully qualified syntax]:
39 //!
40 //! ```
41 //! use std::rc::Rc;
42 //!
43 //! let my_rc = Rc::new(());
44 //! let my_weak = Rc::downgrade(&my_rc);
45 //! ```
46 //!
47 //! `Rc<T>`'s implementations of traits like `Clone` may also be called using
48 //! fully qualified syntax. Some people prefer to use fully qualified syntax,
49 //! while others prefer using method-call syntax.
50 //!
51 //! ```
52 //! use std::rc::Rc;
53 //!
54 //! let rc = Rc::new(());
55 //! // Method-call syntax
56 //! let rc2 = rc.clone();
57 //! // Fully qualified syntax
58 //! let rc3 = Rc::clone(&rc);
59 //! ```
60 //!
61 //! [`Weak<T>`][`Weak`] does not auto-dereference to `T`, because the inner value may have
62 //! already been dropped.
63 //!
64 //! # Cloning references
65 //!
66 //! Creating a new reference to the same allocation as an existing reference counted pointer
67 //! is done using the `Clone` trait implemented for [`Rc<T>`][`Rc`] and [`Weak<T>`][`Weak`].
68 //!
69 //! ```
70 //! use std::rc::Rc;
71 //!
72 //! let foo = Rc::new(vec![1.0, 2.0, 3.0]);
73 //! // The two syntaxes below are equivalent.
74 //! let a = foo.clone();
75 //! let b = Rc::clone(&foo);
76 //! // a and b both point to the same memory location as foo.
77 //! ```
78 //!
79 //! The `Rc::clone(&from)` syntax is the most idiomatic because it conveys more explicitly
80 //! the meaning of the code. In the example above, this syntax makes it easier to see that
81 //! this code is creating a new reference rather than copying the whole content of foo.
82 //!
83 //! # Examples
84 //!
85 //! Consider a scenario where a set of `Gadget`s are owned by a given `Owner`.
86 //! We want to have our `Gadget`s point to their `Owner`. We can't do this with
87 //! unique ownership, because more than one gadget may belong to the same
88 //! `Owner`. [`Rc`] allows us to share an `Owner` between multiple `Gadget`s,
89 //! and have the `Owner` remain allocated as long as any `Gadget` points at it.
90 //!
91 //! ```
92 //! use std::rc::Rc;
93 //!
94 //! struct Owner {
95 //! name: String,
96 //! // ...other fields
97 //! }
98 //!
99 //! struct Gadget {
100 //! id: i32,
101 //! owner: Rc<Owner>,
102 //! // ...other fields
103 //! }
104 //!
105 //! fn main() {
106 //! // Create a reference-counted `Owner`.
107 //! let gadget_owner: Rc<Owner> = Rc::new(
108 //! Owner {
109 //! name: "Gadget Man".to_string(),
110 //! }
111 //! );
112 //!
113 //! // Create `Gadget`s belonging to `gadget_owner`. Cloning the `Rc<Owner>`
114 //! // gives us a new pointer to the same `Owner` allocation, incrementing
115 //! // the reference count in the process.
116 //! let gadget1 = Gadget {
117 //! id: 1,
118 //! owner: Rc::clone(&gadget_owner),
119 //! };
120 //! let gadget2 = Gadget {
121 //! id: 2,
122 //! owner: Rc::clone(&gadget_owner),
123 //! };
124 //!
125 //! // Dispose of our local variable `gadget_owner`.
126 //! drop(gadget_owner);
127 //!
128 //! // Despite dropping `gadget_owner`, we're still able to print out the name
129 //! // of the `Owner` of the `Gadget`s. This is because we've only dropped a
130 //! // single `Rc<Owner>`, not the `Owner` it points to. As long as there are
131 //! // other `Rc<Owner>` pointing at the same `Owner` allocation, it will remain
132 //! // live. The field projection `gadget1.owner.name` works because
133 //! // `Rc<Owner>` automatically dereferences to `Owner`.
134 //! println!("Gadget {} owned by {}", gadget1.id, gadget1.owner.name);
135 //! println!("Gadget {} owned by {}", gadget2.id, gadget2.owner.name);
136 //!
137 //! // At the end of the function, `gadget1` and `gadget2` are destroyed, and
138 //! // with them the last counted references to our `Owner`. Gadget Man now
139 //! // gets destroyed as well.
140 //! }
141 //! ```
142 //!
143 //! If our requirements change, and we also need to be able to traverse from
144 //! `Owner` to `Gadget`, we will run into problems. An [`Rc`] pointer from `Owner`
145 //! to `Gadget` introduces a cycle. This means that their
146 //! reference counts can never reach 0, and the allocation will never be destroyed:
147 //! a memory leak. In order to get around this, we can use [`Weak`]
148 //! pointers.
149 //!
150 //! Rust actually makes it somewhat difficult to produce this loop in the first
151 //! place. In order to end up with two values that point at each other, one of
152 //! them needs to be mutable. This is difficult because [`Rc`] enforces
153 //! memory safety by only giving out shared references to the value it wraps,
154 //! and these don't allow direct mutation. We need to wrap the part of the
155 //! value we wish to mutate in a [`RefCell`], which provides *interior
156 //! mutability*: a method to achieve mutability through a shared reference.
157 //! [`RefCell`] enforces Rust's borrowing rules at runtime.
158 //!
159 //! ```
160 //! use std::rc::Rc;
161 //! use std::rc::Weak;
162 //! use std::cell::RefCell;
163 //!
164 //! struct Owner {
165 //! name: String,
166 //! gadgets: RefCell<Vec<Weak<Gadget>>>,
167 //! // ...other fields
168 //! }
169 //!
170 //! struct Gadget {
171 //! id: i32,
172 //! owner: Rc<Owner>,
173 //! // ...other fields
174 //! }
175 //!
176 //! fn main() {
177 //! // Create a reference-counted `Owner`. Note that we've put the `Owner`'s
178 //! // vector of `Gadget`s inside a `RefCell` so that we can mutate it through
179 //! // a shared reference.
180 //! let gadget_owner: Rc<Owner> = Rc::new(
181 //! Owner {
182 //! name: "Gadget Man".to_string(),
183 //! gadgets: RefCell::new(vec![]),
184 //! }
185 //! );
186 //!
187 //! // Create `Gadget`s belonging to `gadget_owner`, as before.
188 //! let gadget1 = Rc::new(
189 //! Gadget {
190 //! id: 1,
191 //! owner: Rc::clone(&gadget_owner),
192 //! }
193 //! );
194 //! let gadget2 = Rc::new(
195 //! Gadget {
196 //! id: 2,
197 //! owner: Rc::clone(&gadget_owner),
198 //! }
199 //! );
200 //!
201 //! // Add the `Gadget`s to their `Owner`.
202 //! {
203 //! let mut gadgets = gadget_owner.gadgets.borrow_mut();
204 //! gadgets.push(Rc::downgrade(&gadget1));
205 //! gadgets.push(Rc::downgrade(&gadget2));
206 //!
207 //! // `RefCell` dynamic borrow ends here.
208 //! }
209 //!
210 //! // Iterate over our `Gadget`s, printing their details out.
211 //! for gadget_weak in gadget_owner.gadgets.borrow().iter() {
212 //!
213 //! // `gadget_weak` is a `Weak<Gadget>`. Since `Weak` pointers can't
214 //! // guarantee the allocation still exists, we need to call
215 //! // `upgrade`, which returns an `Option<Rc<Gadget>>`.
216 //! //
217 //! // In this case we know the allocation still exists, so we simply
218 //! // `unwrap` the `Option`. In a more complicated program, you might
219 //! // need graceful error handling for a `None` result.
220 //!
221 //! let gadget = gadget_weak.upgrade().unwrap();
222 //! println!("Gadget {} owned by {}", gadget.id, gadget.owner.name);
223 //! }
224 //!
225 //! // At the end of the function, `gadget_owner`, `gadget1`, and `gadget2`
226 //! // are destroyed. There are now no strong (`Rc`) pointers to the
227 //! // gadgets, so they are destroyed. This zeroes the reference count on
228 //! // Gadget Man, so he gets destroyed as well.
229 //! }
230 //! ```
231 //!
232 //! [clone]: Clone::clone
233 //! [`Cell`]: core::cell::Cell
234 //! [`RefCell`]: core::cell::RefCell
235 //! [arc]: crate::sync::Arc
236 //! [`Deref`]: core::ops::Deref
237 //! [downgrade]: Rc::downgrade
238 //! [upgrade]: Weak::upgrade
239 //! [mutability]: core::cell#introducing-mutability-inside-of-something-immutable
240 //! [fully qualified syntax]: https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#fully-qualified-syntax-for-disambiguation-calling-methods-with-the-same-name
241
242 #![stable(feature = "rust1", since = "1.0.0")]
243
244 #[cfg(not(test))]
245 use crate::boxed::Box;
246 #[cfg(test)]
247 use std::boxed::Box;
248
249 use core::any::Any;
250 use core::borrow;
251 use core::cell::Cell;
252 use core::cmp::Ordering;
253 use core::fmt;
254 use core::hash::{Hash, Hasher};
255 use core::intrinsics::abort;
256 #[cfg(not(no_global_oom_handling))]
257 use core::iter;
258 use core::marker::{PhantomData, Unsize};
259 #[cfg(not(no_global_oom_handling))]
260 use core::mem::size_of_val;
261 use core::mem::{self, align_of_val_raw, forget, ManuallyDrop};
262 use core::ops::{CoerceUnsized, Deref, DerefMut, DispatchFromDyn, Receiver};
263 use core::panic::{RefUnwindSafe, UnwindSafe};
264 #[cfg(not(no_global_oom_handling))]
265 use core::pin::Pin;
266 use core::ptr::{self, drop_in_place, NonNull};
267 #[cfg(not(no_global_oom_handling))]
268 use core::slice::from_raw_parts_mut;
269
270 #[cfg(not(no_global_oom_handling))]
271 use crate::alloc::handle_alloc_error;
272 #[cfg(not(no_global_oom_handling))]
273 use crate::alloc::WriteCloneIntoRaw;
274 use crate::alloc::{AllocError, Allocator, Global, Layout};
275 use crate::borrow::{Cow, ToOwned};
276 #[cfg(not(no_global_oom_handling))]
277 use crate::string::String;
278 #[cfg(not(no_global_oom_handling))]
279 use crate::vec::Vec;
280
281 #[cfg(test)]
282 mod tests;
283
284 // This is repr(C) to future-proof against possible field-reordering, which
285 // would interfere with otherwise safe [into|from]_raw() of transmutable
286 // inner types.
287 #[repr(C)]
288 struct RcBox<T: ?Sized> {
289 strong: Cell<usize>,
290 weak: Cell<usize>,
291 value: T,
292 }
293
294 /// Calculate layout for `RcBox<T>` using the inner value's layout
rcbox_layout_for_value_layout(layout: Layout) -> Layout295 fn rcbox_layout_for_value_layout(layout: Layout) -> Layout {
296 // Calculate layout using the given value layout.
297 // Previously, layout was calculated on the expression
298 // `&*(ptr as *const RcBox<T>)`, but this created a misaligned
299 // reference (see #54908).
300 Layout::new::<RcBox<()>>().extend(layout).unwrap().0.pad_to_align()
301 }
302
303 /// A single-threaded reference-counting pointer. 'Rc' stands for 'Reference
304 /// Counted'.
305 ///
306 /// See the [module-level documentation](./index.html) for more details.
307 ///
308 /// The inherent methods of `Rc` are all associated functions, which means
309 /// that you have to call them as e.g., [`Rc::get_mut(&mut value)`][get_mut] instead of
310 /// `value.get_mut()`. This avoids conflicts with methods of the inner type `T`.
311 ///
312 /// [get_mut]: Rc::get_mut
313 #[cfg_attr(not(test), rustc_diagnostic_item = "Rc")]
314 #[stable(feature = "rust1", since = "1.0.0")]
315 #[rustc_insignificant_dtor]
316 pub struct Rc<T: ?Sized> {
317 ptr: NonNull<RcBox<T>>,
318 phantom: PhantomData<RcBox<T>>,
319 }
320
321 #[stable(feature = "rust1", since = "1.0.0")]
322 impl<T: ?Sized> !Send for Rc<T> {}
323
324 // Note that this negative impl isn't strictly necessary for correctness,
325 // as `Rc` transitively contains a `Cell`, which is itself `!Sync`.
326 // However, given how important `Rc`'s `!Sync`-ness is,
327 // having an explicit negative impl is nice for documentation purposes
328 // and results in nicer error messages.
329 #[stable(feature = "rust1", since = "1.0.0")]
330 impl<T: ?Sized> !Sync for Rc<T> {}
331
332 #[stable(feature = "catch_unwind", since = "1.9.0")]
333 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for Rc<T> {}
334 #[stable(feature = "rc_ref_unwind_safe", since = "1.58.0")]
335 impl<T: RefUnwindSafe + ?Sized> RefUnwindSafe for Rc<T> {}
336
337 #[unstable(feature = "coerce_unsized", issue = "18598")]
338 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Rc<U>> for Rc<T> {}
339
340 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
341 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Rc<U>> for Rc<T> {}
342
343 impl<T: ?Sized> Rc<T> {
344 #[inline(always)]
inner(&self) -> &RcBox<T>345 fn inner(&self) -> &RcBox<T> {
346 // This unsafety is ok because while this Rc is alive we're guaranteed
347 // that the inner pointer is valid.
348 unsafe { self.ptr.as_ref() }
349 }
350
from_inner(ptr: NonNull<RcBox<T>>) -> Self351 unsafe fn from_inner(ptr: NonNull<RcBox<T>>) -> Self {
352 Self { ptr, phantom: PhantomData }
353 }
354
from_ptr(ptr: *mut RcBox<T>) -> Self355 unsafe fn from_ptr(ptr: *mut RcBox<T>) -> Self {
356 unsafe { Self::from_inner(NonNull::new_unchecked(ptr)) }
357 }
358 }
359
360 impl<T> Rc<T> {
361 /// Constructs a new `Rc<T>`.
362 ///
363 /// # Examples
364 ///
365 /// ```
366 /// use std::rc::Rc;
367 ///
368 /// let five = Rc::new(5);
369 /// ```
370 #[cfg(not(no_global_oom_handling))]
371 #[stable(feature = "rust1", since = "1.0.0")]
new(value: T) -> Rc<T>372 pub fn new(value: T) -> Rc<T> {
373 // There is an implicit weak pointer owned by all the strong
374 // pointers, which ensures that the weak destructor never frees
375 // the allocation while the strong destructor is running, even
376 // if the weak pointer is stored inside the strong one.
377 unsafe {
378 Self::from_inner(
379 Box::leak(Box::new(RcBox { strong: Cell::new(1), weak: Cell::new(1), value }))
380 .into(),
381 )
382 }
383 }
384
385 /// Constructs a new `Rc<T>` while giving you a `Weak<T>` to the allocation,
386 /// to allow you to construct a `T` which holds a weak pointer to itself.
387 ///
388 /// Generally, a structure circularly referencing itself, either directly or
389 /// indirectly, should not hold a strong reference to itself to prevent a memory leak.
390 /// Using this function, you get access to the weak pointer during the
391 /// initialization of `T`, before the `Rc<T>` is created, such that you can
392 /// clone and store it inside the `T`.
393 ///
394 /// `new_cyclic` first allocates the managed allocation for the `Rc<T>`,
395 /// then calls your closure, giving it a `Weak<T>` to this allocation,
396 /// and only afterwards completes the construction of the `Rc<T>` by placing
397 /// the `T` returned from your closure into the allocation.
398 ///
399 /// Since the new `Rc<T>` is not fully-constructed until `Rc<T>::new_cyclic`
400 /// returns, calling [`upgrade`] on the weak reference inside your closure will
401 /// fail and result in a `None` value.
402 ///
403 /// # Panics
404 ///
405 /// If `data_fn` panics, the panic is propagated to the caller, and the
406 /// temporary [`Weak<T>`] is dropped normally.
407 ///
408 /// # Examples
409 ///
410 /// ```
411 /// # #![allow(dead_code)]
412 /// use std::rc::{Rc, Weak};
413 ///
414 /// struct Gadget {
415 /// me: Weak<Gadget>,
416 /// }
417 ///
418 /// impl Gadget {
419 /// /// Construct a reference counted Gadget.
420 /// fn new() -> Rc<Self> {
421 /// // `me` is a `Weak<Gadget>` pointing at the new allocation of the
422 /// // `Rc` we're constructing.
423 /// Rc::new_cyclic(|me| {
424 /// // Create the actual struct here.
425 /// Gadget { me: me.clone() }
426 /// })
427 /// }
428 ///
429 /// /// Return a reference counted pointer to Self.
430 /// fn me(&self) -> Rc<Self> {
431 /// self.me.upgrade().unwrap()
432 /// }
433 /// }
434 /// ```
435 /// [`upgrade`]: Weak::upgrade
436 #[cfg(not(no_global_oom_handling))]
437 #[stable(feature = "arc_new_cyclic", since = "1.60.0")]
new_cyclic<F>(data_fn: F) -> Rc<T> where F: FnOnce(&Weak<T>) -> T,438 pub fn new_cyclic<F>(data_fn: F) -> Rc<T>
439 where
440 F: FnOnce(&Weak<T>) -> T,
441 {
442 // Construct the inner in the "uninitialized" state with a single
443 // weak reference.
444 let uninit_ptr: NonNull<_> = Box::leak(Box::new(RcBox {
445 strong: Cell::new(0),
446 weak: Cell::new(1),
447 value: mem::MaybeUninit::<T>::uninit(),
448 }))
449 .into();
450
451 let init_ptr: NonNull<RcBox<T>> = uninit_ptr.cast();
452
453 let weak = Weak { ptr: init_ptr };
454
455 // It's important we don't give up ownership of the weak pointer, or
456 // else the memory might be freed by the time `data_fn` returns. If
457 // we really wanted to pass ownership, we could create an additional
458 // weak pointer for ourselves, but this would result in additional
459 // updates to the weak reference count which might not be necessary
460 // otherwise.
461 let data = data_fn(&weak);
462
463 let strong = unsafe {
464 let inner = init_ptr.as_ptr();
465 ptr::write(ptr::addr_of_mut!((*inner).value), data);
466
467 let prev_value = (*inner).strong.get();
468 debug_assert_eq!(prev_value, 0, "No prior strong references should exist");
469 (*inner).strong.set(1);
470
471 Rc::from_inner(init_ptr)
472 };
473
474 // Strong references should collectively own a shared weak reference,
475 // so don't run the destructor for our old weak reference.
476 mem::forget(weak);
477 strong
478 }
479
480 /// Constructs a new `Rc` with uninitialized contents.
481 ///
482 /// # Examples
483 ///
484 /// ```
485 /// #![feature(new_uninit)]
486 /// #![feature(get_mut_unchecked)]
487 ///
488 /// use std::rc::Rc;
489 ///
490 /// let mut five = Rc::<u32>::new_uninit();
491 ///
492 /// // Deferred initialization:
493 /// Rc::get_mut(&mut five).unwrap().write(5);
494 ///
495 /// let five = unsafe { five.assume_init() };
496 ///
497 /// assert_eq!(*five, 5)
498 /// ```
499 #[cfg(not(no_global_oom_handling))]
500 #[unstable(feature = "new_uninit", issue = "63291")]
501 #[must_use]
new_uninit() -> Rc<mem::MaybeUninit<T>>502 pub fn new_uninit() -> Rc<mem::MaybeUninit<T>> {
503 unsafe {
504 Rc::from_ptr(Rc::allocate_for_layout(
505 Layout::new::<T>(),
506 |layout| Global.allocate(layout),
507 |mem| mem as *mut RcBox<mem::MaybeUninit<T>>,
508 ))
509 }
510 }
511
512 /// Constructs a new `Rc` with uninitialized contents, with the memory
513 /// being filled with `0` bytes.
514 ///
515 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and
516 /// incorrect usage of this method.
517 ///
518 /// # Examples
519 ///
520 /// ```
521 /// #![feature(new_uninit)]
522 ///
523 /// use std::rc::Rc;
524 ///
525 /// let zero = Rc::<u32>::new_zeroed();
526 /// let zero = unsafe { zero.assume_init() };
527 ///
528 /// assert_eq!(*zero, 0)
529 /// ```
530 ///
531 /// [zeroed]: mem::MaybeUninit::zeroed
532 #[cfg(not(no_global_oom_handling))]
533 #[unstable(feature = "new_uninit", issue = "63291")]
534 #[must_use]
new_zeroed() -> Rc<mem::MaybeUninit<T>>535 pub fn new_zeroed() -> Rc<mem::MaybeUninit<T>> {
536 unsafe {
537 Rc::from_ptr(Rc::allocate_for_layout(
538 Layout::new::<T>(),
539 |layout| Global.allocate_zeroed(layout),
540 |mem| mem as *mut RcBox<mem::MaybeUninit<T>>,
541 ))
542 }
543 }
544
545 /// Constructs a new `Rc<T>`, returning an error if the allocation fails
546 ///
547 /// # Examples
548 ///
549 /// ```
550 /// #![feature(allocator_api)]
551 /// use std::rc::Rc;
552 ///
553 /// let five = Rc::try_new(5);
554 /// # Ok::<(), std::alloc::AllocError>(())
555 /// ```
556 #[unstable(feature = "allocator_api", issue = "32838")]
try_new(value: T) -> Result<Rc<T>, AllocError>557 pub fn try_new(value: T) -> Result<Rc<T>, AllocError> {
558 // There is an implicit weak pointer owned by all the strong
559 // pointers, which ensures that the weak destructor never frees
560 // the allocation while the strong destructor is running, even
561 // if the weak pointer is stored inside the strong one.
562 unsafe {
563 Ok(Self::from_inner(
564 Box::leak(Box::try_new(RcBox { strong: Cell::new(1), weak: Cell::new(1), value })?)
565 .into(),
566 ))
567 }
568 }
569
570 /// Constructs a new `Rc` with uninitialized contents, returning an error if the allocation fails
571 ///
572 /// # Examples
573 ///
574 /// ```
575 /// #![feature(allocator_api, new_uninit)]
576 /// #![feature(get_mut_unchecked)]
577 ///
578 /// use std::rc::Rc;
579 ///
580 /// let mut five = Rc::<u32>::try_new_uninit()?;
581 ///
582 /// // Deferred initialization:
583 /// Rc::get_mut(&mut five).unwrap().write(5);
584 ///
585 /// let five = unsafe { five.assume_init() };
586 ///
587 /// assert_eq!(*five, 5);
588 /// # Ok::<(), std::alloc::AllocError>(())
589 /// ```
590 #[unstable(feature = "allocator_api", issue = "32838")]
591 // #[unstable(feature = "new_uninit", issue = "63291")]
try_new_uninit() -> Result<Rc<mem::MaybeUninit<T>>, AllocError>592 pub fn try_new_uninit() -> Result<Rc<mem::MaybeUninit<T>>, AllocError> {
593 unsafe {
594 Ok(Rc::from_ptr(Rc::try_allocate_for_layout(
595 Layout::new::<T>(),
596 |layout| Global.allocate(layout),
597 |mem| mem as *mut RcBox<mem::MaybeUninit<T>>,
598 )?))
599 }
600 }
601
602 /// Constructs a new `Rc` with uninitialized contents, with the memory
603 /// being filled with `0` bytes, returning an error if the allocation fails
604 ///
605 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and
606 /// incorrect usage of this method.
607 ///
608 /// # Examples
609 ///
610 /// ```
611 /// #![feature(allocator_api, new_uninit)]
612 ///
613 /// use std::rc::Rc;
614 ///
615 /// let zero = Rc::<u32>::try_new_zeroed()?;
616 /// let zero = unsafe { zero.assume_init() };
617 ///
618 /// assert_eq!(*zero, 0);
619 /// # Ok::<(), std::alloc::AllocError>(())
620 /// ```
621 ///
622 /// [zeroed]: mem::MaybeUninit::zeroed
623 #[unstable(feature = "allocator_api", issue = "32838")]
624 //#[unstable(feature = "new_uninit", issue = "63291")]
try_new_zeroed() -> Result<Rc<mem::MaybeUninit<T>>, AllocError>625 pub fn try_new_zeroed() -> Result<Rc<mem::MaybeUninit<T>>, AllocError> {
626 unsafe {
627 Ok(Rc::from_ptr(Rc::try_allocate_for_layout(
628 Layout::new::<T>(),
629 |layout| Global.allocate_zeroed(layout),
630 |mem| mem as *mut RcBox<mem::MaybeUninit<T>>,
631 )?))
632 }
633 }
634 /// Constructs a new `Pin<Rc<T>>`. If `T` does not implement `Unpin`, then
635 /// `value` will be pinned in memory and unable to be moved.
636 #[cfg(not(no_global_oom_handling))]
637 #[stable(feature = "pin", since = "1.33.0")]
638 #[must_use]
pin(value: T) -> Pin<Rc<T>>639 pub fn pin(value: T) -> Pin<Rc<T>> {
640 unsafe { Pin::new_unchecked(Rc::new(value)) }
641 }
642
643 /// Returns the inner value, if the `Rc` has exactly one strong reference.
644 ///
645 /// Otherwise, an [`Err`] is returned with the same `Rc` that was
646 /// passed in.
647 ///
648 /// This will succeed even if there are outstanding weak references.
649 ///
650 /// # Examples
651 ///
652 /// ```
653 /// use std::rc::Rc;
654 ///
655 /// let x = Rc::new(3);
656 /// assert_eq!(Rc::try_unwrap(x), Ok(3));
657 ///
658 /// let x = Rc::new(4);
659 /// let _y = Rc::clone(&x);
660 /// assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4);
661 /// ```
662 #[inline]
663 #[stable(feature = "rc_unique", since = "1.4.0")]
try_unwrap(this: Self) -> Result<T, Self>664 pub fn try_unwrap(this: Self) -> Result<T, Self> {
665 if Rc::strong_count(&this) == 1 {
666 unsafe {
667 let val = ptr::read(&*this); // copy the contained object
668
669 // Indicate to Weaks that they can't be promoted by decrementing
670 // the strong count, and then remove the implicit "strong weak"
671 // pointer while also handling drop logic by just crafting a
672 // fake Weak.
673 this.inner().dec_strong();
674 let _weak = Weak { ptr: this.ptr };
675 forget(this);
676 Ok(val)
677 }
678 } else {
679 Err(this)
680 }
681 }
682
683 /// Returns the inner value, if the `Rc` has exactly one strong reference.
684 ///
685 /// Otherwise, [`None`] is returned and the `Rc` is dropped.
686 ///
687 /// This will succeed even if there are outstanding weak references.
688 ///
689 /// If `Rc::into_inner` is called on every clone of this `Rc`,
690 /// it is guaranteed that exactly one of the calls returns the inner value.
691 /// This means in particular that the inner value is not dropped.
692 ///
693 /// This is equivalent to `Rc::try_unwrap(this).ok()`. (Note that these are not equivalent for
694 /// [`Arc`](crate::sync::Arc), due to race conditions that do not apply to `Rc`.)
695 #[inline]
696 #[stable(feature = "rc_into_inner", since = "1.70.0")]
into_inner(this: Self) -> Option<T>697 pub fn into_inner(this: Self) -> Option<T> {
698 Rc::try_unwrap(this).ok()
699 }
700 }
701
702 impl<T> Rc<[T]> {
703 /// Constructs a new reference-counted slice with uninitialized contents.
704 ///
705 /// # Examples
706 ///
707 /// ```
708 /// #![feature(new_uninit)]
709 /// #![feature(get_mut_unchecked)]
710 ///
711 /// use std::rc::Rc;
712 ///
713 /// let mut values = Rc::<[u32]>::new_uninit_slice(3);
714 ///
715 /// // Deferred initialization:
716 /// let data = Rc::get_mut(&mut values).unwrap();
717 /// data[0].write(1);
718 /// data[1].write(2);
719 /// data[2].write(3);
720 ///
721 /// let values = unsafe { values.assume_init() };
722 ///
723 /// assert_eq!(*values, [1, 2, 3])
724 /// ```
725 #[cfg(not(no_global_oom_handling))]
726 #[unstable(feature = "new_uninit", issue = "63291")]
727 #[must_use]
new_uninit_slice(len: usize) -> Rc<[mem::MaybeUninit<T>]>728 pub fn new_uninit_slice(len: usize) -> Rc<[mem::MaybeUninit<T>]> {
729 unsafe { Rc::from_ptr(Rc::allocate_for_slice(len)) }
730 }
731
732 /// Constructs a new reference-counted slice with uninitialized contents, with the memory being
733 /// filled with `0` bytes.
734 ///
735 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and
736 /// incorrect usage of this method.
737 ///
738 /// # Examples
739 ///
740 /// ```
741 /// #![feature(new_uninit)]
742 ///
743 /// use std::rc::Rc;
744 ///
745 /// let values = Rc::<[u32]>::new_zeroed_slice(3);
746 /// let values = unsafe { values.assume_init() };
747 ///
748 /// assert_eq!(*values, [0, 0, 0])
749 /// ```
750 ///
751 /// [zeroed]: mem::MaybeUninit::zeroed
752 #[cfg(not(no_global_oom_handling))]
753 #[unstable(feature = "new_uninit", issue = "63291")]
754 #[must_use]
new_zeroed_slice(len: usize) -> Rc<[mem::MaybeUninit<T>]>755 pub fn new_zeroed_slice(len: usize) -> Rc<[mem::MaybeUninit<T>]> {
756 unsafe {
757 Rc::from_ptr(Rc::allocate_for_layout(
758 Layout::array::<T>(len).unwrap(),
759 |layout| Global.allocate_zeroed(layout),
760 |mem| {
761 ptr::slice_from_raw_parts_mut(mem as *mut T, len)
762 as *mut RcBox<[mem::MaybeUninit<T>]>
763 },
764 ))
765 }
766 }
767 }
768
769 impl<T> Rc<mem::MaybeUninit<T>> {
770 /// Converts to `Rc<T>`.
771 ///
772 /// # Safety
773 ///
774 /// As with [`MaybeUninit::assume_init`],
775 /// it is up to the caller to guarantee that the inner value
776 /// really is in an initialized state.
777 /// Calling this when the content is not yet fully initialized
778 /// causes immediate undefined behavior.
779 ///
780 /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
781 ///
782 /// # Examples
783 ///
784 /// ```
785 /// #![feature(new_uninit)]
786 /// #![feature(get_mut_unchecked)]
787 ///
788 /// use std::rc::Rc;
789 ///
790 /// let mut five = Rc::<u32>::new_uninit();
791 ///
792 /// // Deferred initialization:
793 /// Rc::get_mut(&mut five).unwrap().write(5);
794 ///
795 /// let five = unsafe { five.assume_init() };
796 ///
797 /// assert_eq!(*five, 5)
798 /// ```
799 #[unstable(feature = "new_uninit", issue = "63291")]
800 #[inline]
assume_init(self) -> Rc<T>801 pub unsafe fn assume_init(self) -> Rc<T> {
802 unsafe { Rc::from_inner(mem::ManuallyDrop::new(self).ptr.cast()) }
803 }
804 }
805
806 impl<T> Rc<[mem::MaybeUninit<T>]> {
807 /// Converts to `Rc<[T]>`.
808 ///
809 /// # Safety
810 ///
811 /// As with [`MaybeUninit::assume_init`],
812 /// it is up to the caller to guarantee that the inner value
813 /// really is in an initialized state.
814 /// Calling this when the content is not yet fully initialized
815 /// causes immediate undefined behavior.
816 ///
817 /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
818 ///
819 /// # Examples
820 ///
821 /// ```
822 /// #![feature(new_uninit)]
823 /// #![feature(get_mut_unchecked)]
824 ///
825 /// use std::rc::Rc;
826 ///
827 /// let mut values = Rc::<[u32]>::new_uninit_slice(3);
828 ///
829 /// // Deferred initialization:
830 /// let data = Rc::get_mut(&mut values).unwrap();
831 /// data[0].write(1);
832 /// data[1].write(2);
833 /// data[2].write(3);
834 ///
835 /// let values = unsafe { values.assume_init() };
836 ///
837 /// assert_eq!(*values, [1, 2, 3])
838 /// ```
839 #[unstable(feature = "new_uninit", issue = "63291")]
840 #[inline]
assume_init(self) -> Rc<[T]>841 pub unsafe fn assume_init(self) -> Rc<[T]> {
842 unsafe { Rc::from_ptr(mem::ManuallyDrop::new(self).ptr.as_ptr() as _) }
843 }
844 }
845
846 impl<T: ?Sized> Rc<T> {
847 /// Consumes the `Rc`, returning the wrapped pointer.
848 ///
849 /// To avoid a memory leak the pointer must be converted back to an `Rc` using
850 /// [`Rc::from_raw`].
851 ///
852 /// # Examples
853 ///
854 /// ```
855 /// use std::rc::Rc;
856 ///
857 /// let x = Rc::new("hello".to_owned());
858 /// let x_ptr = Rc::into_raw(x);
859 /// assert_eq!(unsafe { &*x_ptr }, "hello");
860 /// ```
861 #[stable(feature = "rc_raw", since = "1.17.0")]
into_raw(this: Self) -> *const T862 pub fn into_raw(this: Self) -> *const T {
863 let ptr = Self::as_ptr(&this);
864 mem::forget(this);
865 ptr
866 }
867
868 /// Provides a raw pointer to the data.
869 ///
870 /// The counts are not affected in any way and the `Rc` is not consumed. The pointer is valid
871 /// for as long there are strong counts in the `Rc`.
872 ///
873 /// # Examples
874 ///
875 /// ```
876 /// use std::rc::Rc;
877 ///
878 /// let x = Rc::new("hello".to_owned());
879 /// let y = Rc::clone(&x);
880 /// let x_ptr = Rc::as_ptr(&x);
881 /// assert_eq!(x_ptr, Rc::as_ptr(&y));
882 /// assert_eq!(unsafe { &*x_ptr }, "hello");
883 /// ```
884 #[stable(feature = "weak_into_raw", since = "1.45.0")]
as_ptr(this: &Self) -> *const T885 pub fn as_ptr(this: &Self) -> *const T {
886 let ptr: *mut RcBox<T> = NonNull::as_ptr(this.ptr);
887
888 // SAFETY: This cannot go through Deref::deref or Rc::inner because
889 // this is required to retain raw/mut provenance such that e.g. `get_mut` can
890 // write through the pointer after the Rc is recovered through `from_raw`.
891 unsafe { ptr::addr_of_mut!((*ptr).value) }
892 }
893
894 /// Constructs an `Rc<T>` from a raw pointer.
895 ///
896 /// The raw pointer must have been previously returned by a call to
897 /// [`Rc<U>::into_raw`][into_raw] where `U` must have the same size
898 /// and alignment as `T`. This is trivially true if `U` is `T`.
899 /// Note that if `U` is not `T` but has the same size and alignment, this is
900 /// basically like transmuting references of different types. See
901 /// [`mem::transmute`] for more information on what
902 /// restrictions apply in this case.
903 ///
904 /// The user of `from_raw` has to make sure a specific value of `T` is only
905 /// dropped once.
906 ///
907 /// This function is unsafe because improper use may lead to memory unsafety,
908 /// even if the returned `Rc<T>` is never accessed.
909 ///
910 /// [into_raw]: Rc::into_raw
911 ///
912 /// # Examples
913 ///
914 /// ```
915 /// use std::rc::Rc;
916 ///
917 /// let x = Rc::new("hello".to_owned());
918 /// let x_ptr = Rc::into_raw(x);
919 ///
920 /// unsafe {
921 /// // Convert back to an `Rc` to prevent leak.
922 /// let x = Rc::from_raw(x_ptr);
923 /// assert_eq!(&*x, "hello");
924 ///
925 /// // Further calls to `Rc::from_raw(x_ptr)` would be memory-unsafe.
926 /// }
927 ///
928 /// // The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling!
929 /// ```
930 #[stable(feature = "rc_raw", since = "1.17.0")]
from_raw(ptr: *const T) -> Self931 pub unsafe fn from_raw(ptr: *const T) -> Self {
932 let offset = unsafe { data_offset(ptr) };
933
934 // Reverse the offset to find the original RcBox.
935 let rc_ptr = unsafe { ptr.byte_sub(offset) as *mut RcBox<T> };
936
937 unsafe { Self::from_ptr(rc_ptr) }
938 }
939
940 /// Creates a new [`Weak`] pointer to this allocation.
941 ///
942 /// # Examples
943 ///
944 /// ```
945 /// use std::rc::Rc;
946 ///
947 /// let five = Rc::new(5);
948 ///
949 /// let weak_five = Rc::downgrade(&five);
950 /// ```
951 #[must_use = "this returns a new `Weak` pointer, \
952 without modifying the original `Rc`"]
953 #[stable(feature = "rc_weak", since = "1.4.0")]
downgrade(this: &Self) -> Weak<T>954 pub fn downgrade(this: &Self) -> Weak<T> {
955 this.inner().inc_weak();
956 // Make sure we do not create a dangling Weak
957 debug_assert!(!is_dangling(this.ptr.as_ptr()));
958 Weak { ptr: this.ptr }
959 }
960
961 /// Gets the number of [`Weak`] pointers to this allocation.
962 ///
963 /// # Examples
964 ///
965 /// ```
966 /// use std::rc::Rc;
967 ///
968 /// let five = Rc::new(5);
969 /// let _weak_five = Rc::downgrade(&five);
970 ///
971 /// assert_eq!(1, Rc::weak_count(&five));
972 /// ```
973 #[inline]
974 #[stable(feature = "rc_counts", since = "1.15.0")]
weak_count(this: &Self) -> usize975 pub fn weak_count(this: &Self) -> usize {
976 this.inner().weak() - 1
977 }
978
979 /// Gets the number of strong (`Rc`) pointers to this allocation.
980 ///
981 /// # Examples
982 ///
983 /// ```
984 /// use std::rc::Rc;
985 ///
986 /// let five = Rc::new(5);
987 /// let _also_five = Rc::clone(&five);
988 ///
989 /// assert_eq!(2, Rc::strong_count(&five));
990 /// ```
991 #[inline]
992 #[stable(feature = "rc_counts", since = "1.15.0")]
strong_count(this: &Self) -> usize993 pub fn strong_count(this: &Self) -> usize {
994 this.inner().strong()
995 }
996
997 /// Increments the strong reference count on the `Rc<T>` associated with the
998 /// provided pointer by one.
999 ///
1000 /// # Safety
1001 ///
1002 /// The pointer must have been obtained through `Rc::into_raw`, and the
1003 /// associated `Rc` instance must be valid (i.e. the strong count must be at
1004 /// least 1) for the duration of this method.
1005 ///
1006 /// # Examples
1007 ///
1008 /// ```
1009 /// use std::rc::Rc;
1010 ///
1011 /// let five = Rc::new(5);
1012 ///
1013 /// unsafe {
1014 /// let ptr = Rc::into_raw(five);
1015 /// Rc::increment_strong_count(ptr);
1016 ///
1017 /// let five = Rc::from_raw(ptr);
1018 /// assert_eq!(2, Rc::strong_count(&five));
1019 /// }
1020 /// ```
1021 #[inline]
1022 #[stable(feature = "rc_mutate_strong_count", since = "1.53.0")]
increment_strong_count(ptr: *const T)1023 pub unsafe fn increment_strong_count(ptr: *const T) {
1024 // Retain Rc, but don't touch refcount by wrapping in ManuallyDrop
1025 let rc = unsafe { mem::ManuallyDrop::new(Rc::<T>::from_raw(ptr)) };
1026 // Now increase refcount, but don't drop new refcount either
1027 let _rc_clone: mem::ManuallyDrop<_> = rc.clone();
1028 }
1029
1030 /// Decrements the strong reference count on the `Rc<T>` associated with the
1031 /// provided pointer by one.
1032 ///
1033 /// # Safety
1034 ///
1035 /// The pointer must have been obtained through `Rc::into_raw`, and the
1036 /// associated `Rc` instance must be valid (i.e. the strong count must be at
1037 /// least 1) when invoking this method. This method can be used to release
1038 /// the final `Rc` and backing storage, but **should not** be called after
1039 /// the final `Rc` has been released.
1040 ///
1041 /// # Examples
1042 ///
1043 /// ```
1044 /// use std::rc::Rc;
1045 ///
1046 /// let five = Rc::new(5);
1047 ///
1048 /// unsafe {
1049 /// let ptr = Rc::into_raw(five);
1050 /// Rc::increment_strong_count(ptr);
1051 ///
1052 /// let five = Rc::from_raw(ptr);
1053 /// assert_eq!(2, Rc::strong_count(&five));
1054 /// Rc::decrement_strong_count(ptr);
1055 /// assert_eq!(1, Rc::strong_count(&five));
1056 /// }
1057 /// ```
1058 #[inline]
1059 #[stable(feature = "rc_mutate_strong_count", since = "1.53.0")]
decrement_strong_count(ptr: *const T)1060 pub unsafe fn decrement_strong_count(ptr: *const T) {
1061 unsafe { drop(Rc::from_raw(ptr)) };
1062 }
1063
1064 /// Returns `true` if there are no other `Rc` or [`Weak`] pointers to
1065 /// this allocation.
1066 #[inline]
is_unique(this: &Self) -> bool1067 fn is_unique(this: &Self) -> bool {
1068 Rc::weak_count(this) == 0 && Rc::strong_count(this) == 1
1069 }
1070
1071 /// Returns a mutable reference into the given `Rc`, if there are
1072 /// no other `Rc` or [`Weak`] pointers to the same allocation.
1073 ///
1074 /// Returns [`None`] otherwise, because it is not safe to
1075 /// mutate a shared value.
1076 ///
1077 /// See also [`make_mut`][make_mut], which will [`clone`][clone]
1078 /// the inner value when there are other `Rc` pointers.
1079 ///
1080 /// [make_mut]: Rc::make_mut
1081 /// [clone]: Clone::clone
1082 ///
1083 /// # Examples
1084 ///
1085 /// ```
1086 /// use std::rc::Rc;
1087 ///
1088 /// let mut x = Rc::new(3);
1089 /// *Rc::get_mut(&mut x).unwrap() = 4;
1090 /// assert_eq!(*x, 4);
1091 ///
1092 /// let _y = Rc::clone(&x);
1093 /// assert!(Rc::get_mut(&mut x).is_none());
1094 /// ```
1095 #[inline]
1096 #[stable(feature = "rc_unique", since = "1.4.0")]
get_mut(this: &mut Self) -> Option<&mut T>1097 pub fn get_mut(this: &mut Self) -> Option<&mut T> {
1098 if Rc::is_unique(this) { unsafe { Some(Rc::get_mut_unchecked(this)) } } else { None }
1099 }
1100
1101 /// Returns a mutable reference into the given `Rc`,
1102 /// without any check.
1103 ///
1104 /// See also [`get_mut`], which is safe and does appropriate checks.
1105 ///
1106 /// [`get_mut`]: Rc::get_mut
1107 ///
1108 /// # Safety
1109 ///
1110 /// If any other `Rc` or [`Weak`] pointers to the same allocation exist, then
1111 /// they must not be dereferenced or have active borrows for the duration
1112 /// of the returned borrow, and their inner type must be exactly the same as the
1113 /// inner type of this Rc (including lifetimes). This is trivially the case if no
1114 /// such pointers exist, for example immediately after `Rc::new`.
1115 ///
1116 /// # Examples
1117 ///
1118 /// ```
1119 /// #![feature(get_mut_unchecked)]
1120 ///
1121 /// use std::rc::Rc;
1122 ///
1123 /// let mut x = Rc::new(String::new());
1124 /// unsafe {
1125 /// Rc::get_mut_unchecked(&mut x).push_str("foo")
1126 /// }
1127 /// assert_eq!(*x, "foo");
1128 /// ```
1129 /// Other `Rc` pointers to the same allocation must be to the same type.
1130 /// ```no_run
1131 /// #![feature(get_mut_unchecked)]
1132 ///
1133 /// use std::rc::Rc;
1134 ///
1135 /// let x: Rc<str> = Rc::from("Hello, world!");
1136 /// let mut y: Rc<[u8]> = x.clone().into();
1137 /// unsafe {
1138 /// // this is Undefined Behavior, because x's inner type is str, not [u8]
1139 /// Rc::get_mut_unchecked(&mut y).fill(0xff); // 0xff is invalid in UTF-8
1140 /// }
1141 /// println!("{}", &*x); // Invalid UTF-8 in a str
1142 /// ```
1143 /// Other `Rc` pointers to the same allocation must be to the exact same type, including lifetimes.
1144 /// ```no_run
1145 /// #![feature(get_mut_unchecked)]
1146 ///
1147 /// use std::rc::Rc;
1148 ///
1149 /// let x: Rc<&str> = Rc::new("Hello, world!");
1150 /// {
1151 /// let s = String::from("Oh, no!");
1152 /// let mut y: Rc<&str> = x.clone().into();
1153 /// unsafe {
1154 /// // this is Undefined Behavior, because x's inner type
1155 /// // is &'long str, not &'short str
1156 /// *Rc::get_mut_unchecked(&mut y) = &s;
1157 /// }
1158 /// }
1159 /// println!("{}", &*x); // Use-after-free
1160 /// ```
1161 #[inline]
1162 #[unstable(feature = "get_mut_unchecked", issue = "63292")]
get_mut_unchecked(this: &mut Self) -> &mut T1163 pub unsafe fn get_mut_unchecked(this: &mut Self) -> &mut T {
1164 // We are careful to *not* create a reference covering the "count" fields, as
1165 // this would conflict with accesses to the reference counts (e.g. by `Weak`).
1166 unsafe { &mut (*this.ptr.as_ptr()).value }
1167 }
1168
1169 #[inline]
1170 #[stable(feature = "ptr_eq", since = "1.17.0")]
1171 /// Returns `true` if the two `Rc`s point to the same allocation in a vein similar to
1172 /// [`ptr::eq`]. This function ignores the metadata of `dyn Trait` pointers.
1173 ///
1174 /// # Examples
1175 ///
1176 /// ```
1177 /// use std::rc::Rc;
1178 ///
1179 /// let five = Rc::new(5);
1180 /// let same_five = Rc::clone(&five);
1181 /// let other_five = Rc::new(5);
1182 ///
1183 /// assert!(Rc::ptr_eq(&five, &same_five));
1184 /// assert!(!Rc::ptr_eq(&five, &other_five));
1185 /// ```
ptr_eq(this: &Self, other: &Self) -> bool1186 pub fn ptr_eq(this: &Self, other: &Self) -> bool {
1187 this.ptr.as_ptr() as *const () == other.ptr.as_ptr() as *const ()
1188 }
1189 }
1190
1191 impl<T: Clone> Rc<T> {
1192 /// Makes a mutable reference into the given `Rc`.
1193 ///
1194 /// If there are other `Rc` pointers to the same allocation, then `make_mut` will
1195 /// [`clone`] the inner value to a new allocation to ensure unique ownership. This is also
1196 /// referred to as clone-on-write.
1197 ///
1198 /// However, if there are no other `Rc` pointers to this allocation, but some [`Weak`]
1199 /// pointers, then the [`Weak`] pointers will be disassociated and the inner value will not
1200 /// be cloned.
1201 ///
1202 /// See also [`get_mut`], which will fail rather than cloning the inner value
1203 /// or disassociating [`Weak`] pointers.
1204 ///
1205 /// [`clone`]: Clone::clone
1206 /// [`get_mut`]: Rc::get_mut
1207 ///
1208 /// # Examples
1209 ///
1210 /// ```
1211 /// use std::rc::Rc;
1212 ///
1213 /// let mut data = Rc::new(5);
1214 ///
1215 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
1216 /// let mut other_data = Rc::clone(&data); // Won't clone inner data
1217 /// *Rc::make_mut(&mut data) += 1; // Clones inner data
1218 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
1219 /// *Rc::make_mut(&mut other_data) *= 2; // Won't clone anything
1220 ///
1221 /// // Now `data` and `other_data` point to different allocations.
1222 /// assert_eq!(*data, 8);
1223 /// assert_eq!(*other_data, 12);
1224 /// ```
1225 ///
1226 /// [`Weak`] pointers will be disassociated:
1227 ///
1228 /// ```
1229 /// use std::rc::Rc;
1230 ///
1231 /// let mut data = Rc::new(75);
1232 /// let weak = Rc::downgrade(&data);
1233 ///
1234 /// assert!(75 == *data);
1235 /// assert!(75 == *weak.upgrade().unwrap());
1236 ///
1237 /// *Rc::make_mut(&mut data) += 1;
1238 ///
1239 /// assert!(76 == *data);
1240 /// assert!(weak.upgrade().is_none());
1241 /// ```
1242 #[cfg(not(no_global_oom_handling))]
1243 #[inline]
1244 #[stable(feature = "rc_unique", since = "1.4.0")]
make_mut(this: &mut Self) -> &mut T1245 pub fn make_mut(this: &mut Self) -> &mut T {
1246 if Rc::strong_count(this) != 1 {
1247 // Gotta clone the data, there are other Rcs.
1248 // Pre-allocate memory to allow writing the cloned value directly.
1249 let mut rc = Self::new_uninit();
1250 unsafe {
1251 let data = Rc::get_mut_unchecked(&mut rc);
1252 (**this).write_clone_into_raw(data.as_mut_ptr());
1253 *this = rc.assume_init();
1254 }
1255 } else if Rc::weak_count(this) != 0 {
1256 // Can just steal the data, all that's left is Weaks
1257 let mut rc = Self::new_uninit();
1258 unsafe {
1259 let data = Rc::get_mut_unchecked(&mut rc);
1260 data.as_mut_ptr().copy_from_nonoverlapping(&**this, 1);
1261
1262 this.inner().dec_strong();
1263 // Remove implicit strong-weak ref (no need to craft a fake
1264 // Weak here -- we know other Weaks can clean up for us)
1265 this.inner().dec_weak();
1266 ptr::write(this, rc.assume_init());
1267 }
1268 }
1269 // This unsafety is ok because we're guaranteed that the pointer
1270 // returned is the *only* pointer that will ever be returned to T. Our
1271 // reference count is guaranteed to be 1 at this point, and we required
1272 // the `Rc<T>` itself to be `mut`, so we're returning the only possible
1273 // reference to the allocation.
1274 unsafe { &mut this.ptr.as_mut().value }
1275 }
1276
1277 /// If we have the only reference to `T` then unwrap it. Otherwise, clone `T` and return the
1278 /// clone.
1279 ///
1280 /// Assuming `rc_t` is of type `Rc<T>`, this function is functionally equivalent to
1281 /// `(*rc_t).clone()`, but will avoid cloning the inner value where possible.
1282 ///
1283 /// # Examples
1284 ///
1285 /// ```
1286 /// #![feature(arc_unwrap_or_clone)]
1287 /// # use std::{ptr, rc::Rc};
1288 /// let inner = String::from("test");
1289 /// let ptr = inner.as_ptr();
1290 ///
1291 /// let rc = Rc::new(inner);
1292 /// let inner = Rc::unwrap_or_clone(rc);
1293 /// // The inner value was not cloned
1294 /// assert!(ptr::eq(ptr, inner.as_ptr()));
1295 ///
1296 /// let rc = Rc::new(inner);
1297 /// let rc2 = rc.clone();
1298 /// let inner = Rc::unwrap_or_clone(rc);
1299 /// // Because there were 2 references, we had to clone the inner value.
1300 /// assert!(!ptr::eq(ptr, inner.as_ptr()));
1301 /// // `rc2` is the last reference, so when we unwrap it we get back
1302 /// // the original `String`.
1303 /// let inner = Rc::unwrap_or_clone(rc2);
1304 /// assert!(ptr::eq(ptr, inner.as_ptr()));
1305 /// ```
1306 #[inline]
1307 #[unstable(feature = "arc_unwrap_or_clone", issue = "93610")]
unwrap_or_clone(this: Self) -> T1308 pub fn unwrap_or_clone(this: Self) -> T {
1309 Rc::try_unwrap(this).unwrap_or_else(|rc| (*rc).clone())
1310 }
1311 }
1312
1313 impl Rc<dyn Any> {
1314 /// Attempt to downcast the `Rc<dyn Any>` to a concrete type.
1315 ///
1316 /// # Examples
1317 ///
1318 /// ```
1319 /// use std::any::Any;
1320 /// use std::rc::Rc;
1321 ///
1322 /// fn print_if_string(value: Rc<dyn Any>) {
1323 /// if let Ok(string) = value.downcast::<String>() {
1324 /// println!("String ({}): {}", string.len(), string);
1325 /// }
1326 /// }
1327 ///
1328 /// let my_string = "Hello World".to_string();
1329 /// print_if_string(Rc::new(my_string));
1330 /// print_if_string(Rc::new(0i8));
1331 /// ```
1332 #[inline]
1333 #[stable(feature = "rc_downcast", since = "1.29.0")]
downcast<T: Any>(self) -> Result<Rc<T>, Rc<dyn Any>>1334 pub fn downcast<T: Any>(self) -> Result<Rc<T>, Rc<dyn Any>> {
1335 if (*self).is::<T>() {
1336 unsafe {
1337 let ptr = self.ptr.cast::<RcBox<T>>();
1338 forget(self);
1339 Ok(Rc::from_inner(ptr))
1340 }
1341 } else {
1342 Err(self)
1343 }
1344 }
1345
1346 /// Downcasts the `Rc<dyn Any>` to a concrete type.
1347 ///
1348 /// For a safe alternative see [`downcast`].
1349 ///
1350 /// # Examples
1351 ///
1352 /// ```
1353 /// #![feature(downcast_unchecked)]
1354 ///
1355 /// use std::any::Any;
1356 /// use std::rc::Rc;
1357 ///
1358 /// let x: Rc<dyn Any> = Rc::new(1_usize);
1359 ///
1360 /// unsafe {
1361 /// assert_eq!(*x.downcast_unchecked::<usize>(), 1);
1362 /// }
1363 /// ```
1364 ///
1365 /// # Safety
1366 ///
1367 /// The contained value must be of type `T`. Calling this method
1368 /// with the incorrect type is *undefined behavior*.
1369 ///
1370 ///
1371 /// [`downcast`]: Self::downcast
1372 #[inline]
1373 #[unstable(feature = "downcast_unchecked", issue = "90850")]
downcast_unchecked<T: Any>(self) -> Rc<T>1374 pub unsafe fn downcast_unchecked<T: Any>(self) -> Rc<T> {
1375 unsafe {
1376 let ptr = self.ptr.cast::<RcBox<T>>();
1377 mem::forget(self);
1378 Rc::from_inner(ptr)
1379 }
1380 }
1381 }
1382
1383 impl<T: ?Sized> Rc<T> {
1384 /// Allocates an `RcBox<T>` with sufficient space for
1385 /// a possibly-unsized inner value where the value has the layout provided.
1386 ///
1387 /// The function `mem_to_rcbox` is called with the data pointer
1388 /// and must return back a (potentially fat)-pointer for the `RcBox<T>`.
1389 #[cfg(not(no_global_oom_handling))]
allocate_for_layout( value_layout: Layout, allocate: impl FnOnce(Layout) -> Result<NonNull<[u8]>, AllocError>, mem_to_rcbox: impl FnOnce(*mut u8) -> *mut RcBox<T>, ) -> *mut RcBox<T>1390 unsafe fn allocate_for_layout(
1391 value_layout: Layout,
1392 allocate: impl FnOnce(Layout) -> Result<NonNull<[u8]>, AllocError>,
1393 mem_to_rcbox: impl FnOnce(*mut u8) -> *mut RcBox<T>,
1394 ) -> *mut RcBox<T> {
1395 let layout = rcbox_layout_for_value_layout(value_layout);
1396 unsafe {
1397 Rc::try_allocate_for_layout(value_layout, allocate, mem_to_rcbox)
1398 .unwrap_or_else(|_| handle_alloc_error(layout))
1399 }
1400 }
1401
1402 /// Allocates an `RcBox<T>` with sufficient space for
1403 /// a possibly-unsized inner value where the value has the layout provided,
1404 /// returning an error if allocation fails.
1405 ///
1406 /// The function `mem_to_rcbox` is called with the data pointer
1407 /// and must return back a (potentially fat)-pointer for the `RcBox<T>`.
1408 #[inline]
try_allocate_for_layout( value_layout: Layout, allocate: impl FnOnce(Layout) -> Result<NonNull<[u8]>, AllocError>, mem_to_rcbox: impl FnOnce(*mut u8) -> *mut RcBox<T>, ) -> Result<*mut RcBox<T>, AllocError>1409 unsafe fn try_allocate_for_layout(
1410 value_layout: Layout,
1411 allocate: impl FnOnce(Layout) -> Result<NonNull<[u8]>, AllocError>,
1412 mem_to_rcbox: impl FnOnce(*mut u8) -> *mut RcBox<T>,
1413 ) -> Result<*mut RcBox<T>, AllocError> {
1414 let layout = rcbox_layout_for_value_layout(value_layout);
1415
1416 // Allocate for the layout.
1417 let ptr = allocate(layout)?;
1418
1419 // Initialize the RcBox
1420 let inner = mem_to_rcbox(ptr.as_non_null_ptr().as_ptr());
1421 unsafe {
1422 debug_assert_eq!(Layout::for_value(&*inner), layout);
1423
1424 ptr::write(&mut (*inner).strong, Cell::new(1));
1425 ptr::write(&mut (*inner).weak, Cell::new(1));
1426 }
1427
1428 Ok(inner)
1429 }
1430
1431 /// Allocates an `RcBox<T>` with sufficient space for an unsized inner value
1432 #[cfg(not(no_global_oom_handling))]
allocate_for_ptr(ptr: *const T) -> *mut RcBox<T>1433 unsafe fn allocate_for_ptr(ptr: *const T) -> *mut RcBox<T> {
1434 // Allocate for the `RcBox<T>` using the given value.
1435 unsafe {
1436 Self::allocate_for_layout(
1437 Layout::for_value(&*ptr),
1438 |layout| Global.allocate(layout),
1439 |mem| mem.with_metadata_of(ptr as *const RcBox<T>),
1440 )
1441 }
1442 }
1443
1444 #[cfg(not(no_global_oom_handling))]
from_box(src: Box<T>) -> Rc<T>1445 fn from_box(src: Box<T>) -> Rc<T> {
1446 unsafe {
1447 let value_size = size_of_val(&*src);
1448 let ptr = Self::allocate_for_ptr(&*src);
1449
1450 // Copy value as bytes
1451 ptr::copy_nonoverlapping(
1452 &*src as *const T as *const u8,
1453 &mut (*ptr).value as *mut _ as *mut u8,
1454 value_size,
1455 );
1456
1457 // Free the allocation without dropping its contents
1458 let src = Box::from_raw(Box::into_raw(src) as *mut mem::ManuallyDrop<T>);
1459 drop(src);
1460
1461 Self::from_ptr(ptr)
1462 }
1463 }
1464 }
1465
1466 impl<T> Rc<[T]> {
1467 /// Allocates an `RcBox<[T]>` with the given length.
1468 #[cfg(not(no_global_oom_handling))]
allocate_for_slice(len: usize) -> *mut RcBox<[T]>1469 unsafe fn allocate_for_slice(len: usize) -> *mut RcBox<[T]> {
1470 unsafe {
1471 Self::allocate_for_layout(
1472 Layout::array::<T>(len).unwrap(),
1473 |layout| Global.allocate(layout),
1474 |mem| ptr::slice_from_raw_parts_mut(mem as *mut T, len) as *mut RcBox<[T]>,
1475 )
1476 }
1477 }
1478
1479 /// Copy elements from slice into newly allocated `Rc<[T]>`
1480 ///
1481 /// Unsafe because the caller must either take ownership or bind `T: Copy`
1482 #[cfg(not(no_global_oom_handling))]
copy_from_slice(v: &[T]) -> Rc<[T]>1483 unsafe fn copy_from_slice(v: &[T]) -> Rc<[T]> {
1484 unsafe {
1485 let ptr = Self::allocate_for_slice(v.len());
1486 ptr::copy_nonoverlapping(v.as_ptr(), &mut (*ptr).value as *mut [T] as *mut T, v.len());
1487 Self::from_ptr(ptr)
1488 }
1489 }
1490
1491 /// Constructs an `Rc<[T]>` from an iterator known to be of a certain size.
1492 ///
1493 /// Behavior is undefined should the size be wrong.
1494 #[cfg(not(no_global_oom_handling))]
from_iter_exact(iter: impl Iterator<Item = T>, len: usize) -> Rc<[T]>1495 unsafe fn from_iter_exact(iter: impl Iterator<Item = T>, len: usize) -> Rc<[T]> {
1496 // Panic guard while cloning T elements.
1497 // In the event of a panic, elements that have been written
1498 // into the new RcBox will be dropped, then the memory freed.
1499 struct Guard<T> {
1500 mem: NonNull<u8>,
1501 elems: *mut T,
1502 layout: Layout,
1503 n_elems: usize,
1504 }
1505
1506 impl<T> Drop for Guard<T> {
1507 fn drop(&mut self) {
1508 unsafe {
1509 let slice = from_raw_parts_mut(self.elems, self.n_elems);
1510 ptr::drop_in_place(slice);
1511
1512 Global.deallocate(self.mem, self.layout);
1513 }
1514 }
1515 }
1516
1517 unsafe {
1518 let ptr = Self::allocate_for_slice(len);
1519
1520 let mem = ptr as *mut _ as *mut u8;
1521 let layout = Layout::for_value(&*ptr);
1522
1523 // Pointer to first element
1524 let elems = &mut (*ptr).value as *mut [T] as *mut T;
1525
1526 let mut guard = Guard { mem: NonNull::new_unchecked(mem), elems, layout, n_elems: 0 };
1527
1528 for (i, item) in iter.enumerate() {
1529 ptr::write(elems.add(i), item);
1530 guard.n_elems += 1;
1531 }
1532
1533 // All clear. Forget the guard so it doesn't free the new RcBox.
1534 forget(guard);
1535
1536 Self::from_ptr(ptr)
1537 }
1538 }
1539 }
1540
1541 /// Specialization trait used for `From<&[T]>`.
1542 trait RcFromSlice<T> {
from_slice(slice: &[T]) -> Self1543 fn from_slice(slice: &[T]) -> Self;
1544 }
1545
1546 #[cfg(not(no_global_oom_handling))]
1547 impl<T: Clone> RcFromSlice<T> for Rc<[T]> {
1548 #[inline]
from_slice(v: &[T]) -> Self1549 default fn from_slice(v: &[T]) -> Self {
1550 unsafe { Self::from_iter_exact(v.iter().cloned(), v.len()) }
1551 }
1552 }
1553
1554 #[cfg(not(no_global_oom_handling))]
1555 impl<T: Copy> RcFromSlice<T> for Rc<[T]> {
1556 #[inline]
from_slice(v: &[T]) -> Self1557 fn from_slice(v: &[T]) -> Self {
1558 unsafe { Rc::copy_from_slice(v) }
1559 }
1560 }
1561
1562 #[stable(feature = "rust1", since = "1.0.0")]
1563 impl<T: ?Sized> Deref for Rc<T> {
1564 type Target = T;
1565
1566 #[inline(always)]
deref(&self) -> &T1567 fn deref(&self) -> &T {
1568 &self.inner().value
1569 }
1570 }
1571
1572 #[unstable(feature = "receiver_trait", issue = "none")]
1573 impl<T: ?Sized> Receiver for Rc<T> {}
1574
1575 #[stable(feature = "rust1", since = "1.0.0")]
1576 unsafe impl<#[may_dangle] T: ?Sized> Drop for Rc<T> {
1577 /// Drops the `Rc`.
1578 ///
1579 /// This will decrement the strong reference count. If the strong reference
1580 /// count reaches zero then the only other references (if any) are
1581 /// [`Weak`], so we `drop` the inner value.
1582 ///
1583 /// # Examples
1584 ///
1585 /// ```
1586 /// use std::rc::Rc;
1587 ///
1588 /// struct Foo;
1589 ///
1590 /// impl Drop for Foo {
1591 /// fn drop(&mut self) {
1592 /// println!("dropped!");
1593 /// }
1594 /// }
1595 ///
1596 /// let foo = Rc::new(Foo);
1597 /// let foo2 = Rc::clone(&foo);
1598 ///
1599 /// drop(foo); // Doesn't print anything
1600 /// drop(foo2); // Prints "dropped!"
1601 /// ```
drop(&mut self)1602 fn drop(&mut self) {
1603 unsafe {
1604 self.inner().dec_strong();
1605 if self.inner().strong() == 0 {
1606 // destroy the contained object
1607 ptr::drop_in_place(Self::get_mut_unchecked(self));
1608
1609 // remove the implicit "strong weak" pointer now that we've
1610 // destroyed the contents.
1611 self.inner().dec_weak();
1612
1613 if self.inner().weak() == 0 {
1614 Global.deallocate(self.ptr.cast(), Layout::for_value(self.ptr.as_ref()));
1615 }
1616 }
1617 }
1618 }
1619 }
1620
1621 #[stable(feature = "rust1", since = "1.0.0")]
1622 impl<T: ?Sized> Clone for Rc<T> {
1623 /// Makes a clone of the `Rc` pointer.
1624 ///
1625 /// This creates another pointer to the same allocation, increasing the
1626 /// strong reference count.
1627 ///
1628 /// # Examples
1629 ///
1630 /// ```
1631 /// use std::rc::Rc;
1632 ///
1633 /// let five = Rc::new(5);
1634 ///
1635 /// let _ = Rc::clone(&five);
1636 /// ```
1637 #[inline]
clone(&self) -> Rc<T>1638 fn clone(&self) -> Rc<T> {
1639 unsafe {
1640 self.inner().inc_strong();
1641 Self::from_inner(self.ptr)
1642 }
1643 }
1644 }
1645
1646 #[cfg(not(no_global_oom_handling))]
1647 #[stable(feature = "rust1", since = "1.0.0")]
1648 impl<T: Default> Default for Rc<T> {
1649 /// Creates a new `Rc<T>`, with the `Default` value for `T`.
1650 ///
1651 /// # Examples
1652 ///
1653 /// ```
1654 /// use std::rc::Rc;
1655 ///
1656 /// let x: Rc<i32> = Default::default();
1657 /// assert_eq!(*x, 0);
1658 /// ```
1659 #[inline]
default() -> Rc<T>1660 fn default() -> Rc<T> {
1661 Rc::new(Default::default())
1662 }
1663 }
1664
1665 #[stable(feature = "rust1", since = "1.0.0")]
1666 trait RcEqIdent<T: ?Sized + PartialEq> {
eq(&self, other: &Rc<T>) -> bool1667 fn eq(&self, other: &Rc<T>) -> bool;
ne(&self, other: &Rc<T>) -> bool1668 fn ne(&self, other: &Rc<T>) -> bool;
1669 }
1670
1671 #[stable(feature = "rust1", since = "1.0.0")]
1672 impl<T: ?Sized + PartialEq> RcEqIdent<T> for Rc<T> {
1673 #[inline]
eq(&self, other: &Rc<T>) -> bool1674 default fn eq(&self, other: &Rc<T>) -> bool {
1675 **self == **other
1676 }
1677
1678 #[inline]
ne(&self, other: &Rc<T>) -> bool1679 default fn ne(&self, other: &Rc<T>) -> bool {
1680 **self != **other
1681 }
1682 }
1683
1684 // Hack to allow specializing on `Eq` even though `Eq` has a method.
1685 #[rustc_unsafe_specialization_marker]
1686 pub(crate) trait MarkerEq: PartialEq<Self> {}
1687
1688 impl<T: Eq> MarkerEq for T {}
1689
1690 /// We're doing this specialization here, and not as a more general optimization on `&T`, because it
1691 /// would otherwise add a cost to all equality checks on refs. We assume that `Rc`s are used to
1692 /// store large values, that are slow to clone, but also heavy to check for equality, causing this
1693 /// cost to pay off more easily. It's also more likely to have two `Rc` clones, that point to
1694 /// the same value, than two `&T`s.
1695 ///
1696 /// We can only do this when `T: Eq` as a `PartialEq` might be deliberately irreflexive.
1697 #[stable(feature = "rust1", since = "1.0.0")]
1698 impl<T: ?Sized + MarkerEq> RcEqIdent<T> for Rc<T> {
1699 #[inline]
eq(&self, other: &Rc<T>) -> bool1700 fn eq(&self, other: &Rc<T>) -> bool {
1701 Rc::ptr_eq(self, other) || **self == **other
1702 }
1703
1704 #[inline]
ne(&self, other: &Rc<T>) -> bool1705 fn ne(&self, other: &Rc<T>) -> bool {
1706 !Rc::ptr_eq(self, other) && **self != **other
1707 }
1708 }
1709
1710 #[stable(feature = "rust1", since = "1.0.0")]
1711 impl<T: ?Sized + PartialEq> PartialEq for Rc<T> {
1712 /// Equality for two `Rc`s.
1713 ///
1714 /// Two `Rc`s are equal if their inner values are equal, even if they are
1715 /// stored in different allocation.
1716 ///
1717 /// If `T` also implements `Eq` (implying reflexivity of equality),
1718 /// two `Rc`s that point to the same allocation are
1719 /// always equal.
1720 ///
1721 /// # Examples
1722 ///
1723 /// ```
1724 /// use std::rc::Rc;
1725 ///
1726 /// let five = Rc::new(5);
1727 ///
1728 /// assert!(five == Rc::new(5));
1729 /// ```
1730 #[inline]
eq(&self, other: &Rc<T>) -> bool1731 fn eq(&self, other: &Rc<T>) -> bool {
1732 RcEqIdent::eq(self, other)
1733 }
1734
1735 /// Inequality for two `Rc`s.
1736 ///
1737 /// Two `Rc`s are not equal if their inner values are not equal.
1738 ///
1739 /// If `T` also implements `Eq` (implying reflexivity of equality),
1740 /// two `Rc`s that point to the same allocation are
1741 /// always equal.
1742 ///
1743 /// # Examples
1744 ///
1745 /// ```
1746 /// use std::rc::Rc;
1747 ///
1748 /// let five = Rc::new(5);
1749 ///
1750 /// assert!(five != Rc::new(6));
1751 /// ```
1752 #[inline]
ne(&self, other: &Rc<T>) -> bool1753 fn ne(&self, other: &Rc<T>) -> bool {
1754 RcEqIdent::ne(self, other)
1755 }
1756 }
1757
1758 #[stable(feature = "rust1", since = "1.0.0")]
1759 impl<T: ?Sized + Eq> Eq for Rc<T> {}
1760
1761 #[stable(feature = "rust1", since = "1.0.0")]
1762 impl<T: ?Sized + PartialOrd> PartialOrd for Rc<T> {
1763 /// Partial comparison for two `Rc`s.
1764 ///
1765 /// The two are compared by calling `partial_cmp()` on their inner values.
1766 ///
1767 /// # Examples
1768 ///
1769 /// ```
1770 /// use std::rc::Rc;
1771 /// use std::cmp::Ordering;
1772 ///
1773 /// let five = Rc::new(5);
1774 ///
1775 /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&Rc::new(6)));
1776 /// ```
1777 #[inline(always)]
partial_cmp(&self, other: &Rc<T>) -> Option<Ordering>1778 fn partial_cmp(&self, other: &Rc<T>) -> Option<Ordering> {
1779 (**self).partial_cmp(&**other)
1780 }
1781
1782 /// Less-than comparison for two `Rc`s.
1783 ///
1784 /// The two are compared by calling `<` on their inner values.
1785 ///
1786 /// # Examples
1787 ///
1788 /// ```
1789 /// use std::rc::Rc;
1790 ///
1791 /// let five = Rc::new(5);
1792 ///
1793 /// assert!(five < Rc::new(6));
1794 /// ```
1795 #[inline(always)]
lt(&self, other: &Rc<T>) -> bool1796 fn lt(&self, other: &Rc<T>) -> bool {
1797 **self < **other
1798 }
1799
1800 /// 'Less than or equal to' comparison for two `Rc`s.
1801 ///
1802 /// The two are compared by calling `<=` on their inner values.
1803 ///
1804 /// # Examples
1805 ///
1806 /// ```
1807 /// use std::rc::Rc;
1808 ///
1809 /// let five = Rc::new(5);
1810 ///
1811 /// assert!(five <= Rc::new(5));
1812 /// ```
1813 #[inline(always)]
le(&self, other: &Rc<T>) -> bool1814 fn le(&self, other: &Rc<T>) -> bool {
1815 **self <= **other
1816 }
1817
1818 /// Greater-than comparison for two `Rc`s.
1819 ///
1820 /// The two are compared by calling `>` on their inner values.
1821 ///
1822 /// # Examples
1823 ///
1824 /// ```
1825 /// use std::rc::Rc;
1826 ///
1827 /// let five = Rc::new(5);
1828 ///
1829 /// assert!(five > Rc::new(4));
1830 /// ```
1831 #[inline(always)]
gt(&self, other: &Rc<T>) -> bool1832 fn gt(&self, other: &Rc<T>) -> bool {
1833 **self > **other
1834 }
1835
1836 /// 'Greater than or equal to' comparison for two `Rc`s.
1837 ///
1838 /// The two are compared by calling `>=` on their inner values.
1839 ///
1840 /// # Examples
1841 ///
1842 /// ```
1843 /// use std::rc::Rc;
1844 ///
1845 /// let five = Rc::new(5);
1846 ///
1847 /// assert!(five >= Rc::new(5));
1848 /// ```
1849 #[inline(always)]
ge(&self, other: &Rc<T>) -> bool1850 fn ge(&self, other: &Rc<T>) -> bool {
1851 **self >= **other
1852 }
1853 }
1854
1855 #[stable(feature = "rust1", since = "1.0.0")]
1856 impl<T: ?Sized + Ord> Ord for Rc<T> {
1857 /// Comparison for two `Rc`s.
1858 ///
1859 /// The two are compared by calling `cmp()` on their inner values.
1860 ///
1861 /// # Examples
1862 ///
1863 /// ```
1864 /// use std::rc::Rc;
1865 /// use std::cmp::Ordering;
1866 ///
1867 /// let five = Rc::new(5);
1868 ///
1869 /// assert_eq!(Ordering::Less, five.cmp(&Rc::new(6)));
1870 /// ```
1871 #[inline]
cmp(&self, other: &Rc<T>) -> Ordering1872 fn cmp(&self, other: &Rc<T>) -> Ordering {
1873 (**self).cmp(&**other)
1874 }
1875 }
1876
1877 #[stable(feature = "rust1", since = "1.0.0")]
1878 impl<T: ?Sized + Hash> Hash for Rc<T> {
hash<H: Hasher>(&self, state: &mut H)1879 fn hash<H: Hasher>(&self, state: &mut H) {
1880 (**self).hash(state);
1881 }
1882 }
1883
1884 #[stable(feature = "rust1", since = "1.0.0")]
1885 impl<T: ?Sized + fmt::Display> fmt::Display for Rc<T> {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result1886 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1887 fmt::Display::fmt(&**self, f)
1888 }
1889 }
1890
1891 #[stable(feature = "rust1", since = "1.0.0")]
1892 impl<T: ?Sized + fmt::Debug> fmt::Debug for Rc<T> {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result1893 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1894 fmt::Debug::fmt(&**self, f)
1895 }
1896 }
1897
1898 #[stable(feature = "rust1", since = "1.0.0")]
1899 impl<T: ?Sized> fmt::Pointer for Rc<T> {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result1900 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1901 fmt::Pointer::fmt(&(&**self as *const T), f)
1902 }
1903 }
1904
1905 #[cfg(not(no_global_oom_handling))]
1906 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
1907 impl<T> From<T> for Rc<T> {
1908 /// Converts a generic type `T` into an `Rc<T>`
1909 ///
1910 /// The conversion allocates on the heap and moves `t`
1911 /// from the stack into it.
1912 ///
1913 /// # Example
1914 /// ```rust
1915 /// # use std::rc::Rc;
1916 /// let x = 5;
1917 /// let rc = Rc::new(5);
1918 ///
1919 /// assert_eq!(Rc::from(x), rc);
1920 /// ```
from(t: T) -> Self1921 fn from(t: T) -> Self {
1922 Rc::new(t)
1923 }
1924 }
1925
1926 #[cfg(not(no_global_oom_handling))]
1927 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1928 impl<T: Clone> From<&[T]> for Rc<[T]> {
1929 /// Allocate a reference-counted slice and fill it by cloning `v`'s items.
1930 ///
1931 /// # Example
1932 ///
1933 /// ```
1934 /// # use std::rc::Rc;
1935 /// let original: &[i32] = &[1, 2, 3];
1936 /// let shared: Rc<[i32]> = Rc::from(original);
1937 /// assert_eq!(&[1, 2, 3], &shared[..]);
1938 /// ```
1939 #[inline]
from(v: &[T]) -> Rc<[T]>1940 fn from(v: &[T]) -> Rc<[T]> {
1941 <Self as RcFromSlice<T>>::from_slice(v)
1942 }
1943 }
1944
1945 #[cfg(not(no_global_oom_handling))]
1946 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1947 impl From<&str> for Rc<str> {
1948 /// Allocate a reference-counted string slice and copy `v` into it.
1949 ///
1950 /// # Example
1951 ///
1952 /// ```
1953 /// # use std::rc::Rc;
1954 /// let shared: Rc<str> = Rc::from("statue");
1955 /// assert_eq!("statue", &shared[..]);
1956 /// ```
1957 #[inline]
from(v: &str) -> Rc<str>1958 fn from(v: &str) -> Rc<str> {
1959 let rc = Rc::<[u8]>::from(v.as_bytes());
1960 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const str) }
1961 }
1962 }
1963
1964 #[cfg(not(no_global_oom_handling))]
1965 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1966 impl From<String> for Rc<str> {
1967 /// Allocate a reference-counted string slice and copy `v` into it.
1968 ///
1969 /// # Example
1970 ///
1971 /// ```
1972 /// # use std::rc::Rc;
1973 /// let original: String = "statue".to_owned();
1974 /// let shared: Rc<str> = Rc::from(original);
1975 /// assert_eq!("statue", &shared[..]);
1976 /// ```
1977 #[inline]
from(v: String) -> Rc<str>1978 fn from(v: String) -> Rc<str> {
1979 Rc::from(&v[..])
1980 }
1981 }
1982
1983 #[cfg(not(no_global_oom_handling))]
1984 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1985 impl<T: ?Sized> From<Box<T>> for Rc<T> {
1986 /// Move a boxed object to a new, reference counted, allocation.
1987 ///
1988 /// # Example
1989 ///
1990 /// ```
1991 /// # use std::rc::Rc;
1992 /// let original: Box<i32> = Box::new(1);
1993 /// let shared: Rc<i32> = Rc::from(original);
1994 /// assert_eq!(1, *shared);
1995 /// ```
1996 #[inline]
from(v: Box<T>) -> Rc<T>1997 fn from(v: Box<T>) -> Rc<T> {
1998 Rc::from_box(v)
1999 }
2000 }
2001
2002 #[cfg(not(no_global_oom_handling))]
2003 #[stable(feature = "shared_from_slice", since = "1.21.0")]
2004 impl<T> From<Vec<T>> for Rc<[T]> {
2005 /// Allocate a reference-counted slice and move `v`'s items into it.
2006 ///
2007 /// # Example
2008 ///
2009 /// ```
2010 /// # use std::rc::Rc;
2011 /// let original: Box<Vec<i32>> = Box::new(vec![1, 2, 3]);
2012 /// let shared: Rc<Vec<i32>> = Rc::from(original);
2013 /// assert_eq!(vec![1, 2, 3], *shared);
2014 /// ```
2015 #[inline]
from(mut v: Vec<T>) -> Rc<[T]>2016 fn from(mut v: Vec<T>) -> Rc<[T]> {
2017 unsafe {
2018 let rc = Rc::copy_from_slice(&v);
2019 // Allow the Vec to free its memory, but not destroy its contents
2020 v.set_len(0);
2021 rc
2022 }
2023 }
2024 }
2025
2026 #[stable(feature = "shared_from_cow", since = "1.45.0")]
2027 impl<'a, B> From<Cow<'a, B>> for Rc<B>
2028 where
2029 B: ToOwned + ?Sized,
2030 Rc<B>: From<&'a B> + From<B::Owned>,
2031 {
2032 /// Create a reference-counted pointer from
2033 /// a clone-on-write pointer by copying its content.
2034 ///
2035 /// # Example
2036 ///
2037 /// ```rust
2038 /// # use std::rc::Rc;
2039 /// # use std::borrow::Cow;
2040 /// let cow: Cow<'_, str> = Cow::Borrowed("eggplant");
2041 /// let shared: Rc<str> = Rc::from(cow);
2042 /// assert_eq!("eggplant", &shared[..]);
2043 /// ```
2044 #[inline]
from(cow: Cow<'a, B>) -> Rc<B>2045 fn from(cow: Cow<'a, B>) -> Rc<B> {
2046 match cow {
2047 Cow::Borrowed(s) => Rc::from(s),
2048 Cow::Owned(s) => Rc::from(s),
2049 }
2050 }
2051 }
2052
2053 #[stable(feature = "shared_from_str", since = "1.62.0")]
2054 impl From<Rc<str>> for Rc<[u8]> {
2055 /// Converts a reference-counted string slice into a byte slice.
2056 ///
2057 /// # Example
2058 ///
2059 /// ```
2060 /// # use std::rc::Rc;
2061 /// let string: Rc<str> = Rc::from("eggplant");
2062 /// let bytes: Rc<[u8]> = Rc::from(string);
2063 /// assert_eq!("eggplant".as_bytes(), bytes.as_ref());
2064 /// ```
2065 #[inline]
from(rc: Rc<str>) -> Self2066 fn from(rc: Rc<str>) -> Self {
2067 // SAFETY: `str` has the same layout as `[u8]`.
2068 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const [u8]) }
2069 }
2070 }
2071
2072 #[stable(feature = "boxed_slice_try_from", since = "1.43.0")]
2073 impl<T, const N: usize> TryFrom<Rc<[T]>> for Rc<[T; N]> {
2074 type Error = Rc<[T]>;
2075
try_from(boxed_slice: Rc<[T]>) -> Result<Self, Self::Error>2076 fn try_from(boxed_slice: Rc<[T]>) -> Result<Self, Self::Error> {
2077 if boxed_slice.len() == N {
2078 Ok(unsafe { Rc::from_raw(Rc::into_raw(boxed_slice) as *mut [T; N]) })
2079 } else {
2080 Err(boxed_slice)
2081 }
2082 }
2083 }
2084
2085 #[cfg(not(no_global_oom_handling))]
2086 #[stable(feature = "shared_from_iter", since = "1.37.0")]
2087 impl<T> FromIterator<T> for Rc<[T]> {
2088 /// Takes each element in the `Iterator` and collects it into an `Rc<[T]>`.
2089 ///
2090 /// # Performance characteristics
2091 ///
2092 /// ## The general case
2093 ///
2094 /// In the general case, collecting into `Rc<[T]>` is done by first
2095 /// collecting into a `Vec<T>`. That is, when writing the following:
2096 ///
2097 /// ```rust
2098 /// # use std::rc::Rc;
2099 /// let evens: Rc<[u8]> = (0..10).filter(|&x| x % 2 == 0).collect();
2100 /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]);
2101 /// ```
2102 ///
2103 /// this behaves as if we wrote:
2104 ///
2105 /// ```rust
2106 /// # use std::rc::Rc;
2107 /// let evens: Rc<[u8]> = (0..10).filter(|&x| x % 2 == 0)
2108 /// .collect::<Vec<_>>() // The first set of allocations happens here.
2109 /// .into(); // A second allocation for `Rc<[T]>` happens here.
2110 /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]);
2111 /// ```
2112 ///
2113 /// This will allocate as many times as needed for constructing the `Vec<T>`
2114 /// and then it will allocate once for turning the `Vec<T>` into the `Rc<[T]>`.
2115 ///
2116 /// ## Iterators of known length
2117 ///
2118 /// When your `Iterator` implements `TrustedLen` and is of an exact size,
2119 /// a single allocation will be made for the `Rc<[T]>`. For example:
2120 ///
2121 /// ```rust
2122 /// # use std::rc::Rc;
2123 /// let evens: Rc<[u8]> = (0..10).collect(); // Just a single allocation happens here.
2124 /// # assert_eq!(&*evens, &*(0..10).collect::<Vec<_>>());
2125 /// ```
from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self2126 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
2127 ToRcSlice::to_rc_slice(iter.into_iter())
2128 }
2129 }
2130
2131 /// Specialization trait used for collecting into `Rc<[T]>`.
2132 #[cfg(not(no_global_oom_handling))]
2133 trait ToRcSlice<T>: Iterator<Item = T> + Sized {
to_rc_slice(self) -> Rc<[T]>2134 fn to_rc_slice(self) -> Rc<[T]>;
2135 }
2136
2137 #[cfg(not(no_global_oom_handling))]
2138 impl<T, I: Iterator<Item = T>> ToRcSlice<T> for I {
to_rc_slice(self) -> Rc<[T]>2139 default fn to_rc_slice(self) -> Rc<[T]> {
2140 self.collect::<Vec<T>>().into()
2141 }
2142 }
2143
2144 #[cfg(not(no_global_oom_handling))]
2145 impl<T, I: iter::TrustedLen<Item = T>> ToRcSlice<T> for I {
to_rc_slice(self) -> Rc<[T]>2146 fn to_rc_slice(self) -> Rc<[T]> {
2147 // This is the case for a `TrustedLen` iterator.
2148 let (low, high) = self.size_hint();
2149 if let Some(high) = high {
2150 debug_assert_eq!(
2151 low,
2152 high,
2153 "TrustedLen iterator's size hint is not exact: {:?}",
2154 (low, high)
2155 );
2156
2157 unsafe {
2158 // SAFETY: We need to ensure that the iterator has an exact length and we have.
2159 Rc::from_iter_exact(self, low)
2160 }
2161 } else {
2162 // TrustedLen contract guarantees that `upper_bound == None` implies an iterator
2163 // length exceeding `usize::MAX`.
2164 // The default implementation would collect into a vec which would panic.
2165 // Thus we panic here immediately without invoking `Vec` code.
2166 panic!("capacity overflow");
2167 }
2168 }
2169 }
2170
2171 /// `Weak` is a version of [`Rc`] that holds a non-owning reference to the
2172 /// managed allocation. The allocation is accessed by calling [`upgrade`] on the `Weak`
2173 /// pointer, which returns an <code>[Option]<[Rc]\<T>></code>.
2174 ///
2175 /// Since a `Weak` reference does not count towards ownership, it will not
2176 /// prevent the value stored in the allocation from being dropped, and `Weak` itself makes no
2177 /// guarantees about the value still being present. Thus it may return [`None`]
2178 /// when [`upgrade`]d. Note however that a `Weak` reference *does* prevent the allocation
2179 /// itself (the backing store) from being deallocated.
2180 ///
2181 /// A `Weak` pointer is useful for keeping a temporary reference to the allocation
2182 /// managed by [`Rc`] without preventing its inner value from being dropped. It is also used to
2183 /// prevent circular references between [`Rc`] pointers, since mutual owning references
2184 /// would never allow either [`Rc`] to be dropped. For example, a tree could
2185 /// have strong [`Rc`] pointers from parent nodes to children, and `Weak`
2186 /// pointers from children back to their parents.
2187 ///
2188 /// The typical way to obtain a `Weak` pointer is to call [`Rc::downgrade`].
2189 ///
2190 /// [`upgrade`]: Weak::upgrade
2191 #[stable(feature = "rc_weak", since = "1.4.0")]
2192 pub struct Weak<T: ?Sized> {
2193 // This is a `NonNull` to allow optimizing the size of this type in enums,
2194 // but it is not necessarily a valid pointer.
2195 // `Weak::new` sets this to `usize::MAX` so that it doesn’t need
2196 // to allocate space on the heap. That's not a value a real pointer
2197 // will ever have because RcBox has alignment at least 2.
2198 // This is only possible when `T: Sized`; unsized `T` never dangle.
2199 ptr: NonNull<RcBox<T>>,
2200 }
2201
2202 #[stable(feature = "rc_weak", since = "1.4.0")]
2203 impl<T: ?Sized> !Send for Weak<T> {}
2204 #[stable(feature = "rc_weak", since = "1.4.0")]
2205 impl<T: ?Sized> !Sync for Weak<T> {}
2206
2207 #[unstable(feature = "coerce_unsized", issue = "18598")]
2208 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {}
2209
2210 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
2211 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Weak<U>> for Weak<T> {}
2212
2213 impl<T> Weak<T> {
2214 /// Constructs a new `Weak<T>`, without allocating any memory.
2215 /// Calling [`upgrade`] on the return value always gives [`None`].
2216 ///
2217 /// [`upgrade`]: Weak::upgrade
2218 ///
2219 /// # Examples
2220 ///
2221 /// ```
2222 /// use std::rc::Weak;
2223 ///
2224 /// let empty: Weak<i64> = Weak::new();
2225 /// assert!(empty.upgrade().is_none());
2226 /// ```
2227 #[stable(feature = "downgraded_weak", since = "1.10.0")]
2228 #[rustc_const_unstable(feature = "const_weak_new", issue = "95091", reason = "recently added")]
2229 #[must_use]
new() -> Weak<T>2230 pub const fn new() -> Weak<T> {
2231 Weak { ptr: unsafe { NonNull::new_unchecked(ptr::invalid_mut::<RcBox<T>>(usize::MAX)) } }
2232 }
2233 }
2234
is_dangling<T: ?Sized>(ptr: *mut T) -> bool2235 pub(crate) fn is_dangling<T: ?Sized>(ptr: *mut T) -> bool {
2236 (ptr as *mut ()).addr() == usize::MAX
2237 }
2238
2239 /// Helper type to allow accessing the reference counts without
2240 /// making any assertions about the data field.
2241 struct WeakInner<'a> {
2242 weak: &'a Cell<usize>,
2243 strong: &'a Cell<usize>,
2244 }
2245
2246 impl<T: ?Sized> Weak<T> {
2247 /// Returns a raw pointer to the object `T` pointed to by this `Weak<T>`.
2248 ///
2249 /// The pointer is valid only if there are some strong references. The pointer may be dangling,
2250 /// unaligned or even [`null`] otherwise.
2251 ///
2252 /// # Examples
2253 ///
2254 /// ```
2255 /// use std::rc::Rc;
2256 /// use std::ptr;
2257 ///
2258 /// let strong = Rc::new("hello".to_owned());
2259 /// let weak = Rc::downgrade(&strong);
2260 /// // Both point to the same object
2261 /// assert!(ptr::eq(&*strong, weak.as_ptr()));
2262 /// // The strong here keeps it alive, so we can still access the object.
2263 /// assert_eq!("hello", unsafe { &*weak.as_ptr() });
2264 ///
2265 /// drop(strong);
2266 /// // But not any more. We can do weak.as_ptr(), but accessing the pointer would lead to
2267 /// // undefined behaviour.
2268 /// // assert_eq!("hello", unsafe { &*weak.as_ptr() });
2269 /// ```
2270 ///
2271 /// [`null`]: ptr::null
2272 #[must_use]
2273 #[stable(feature = "rc_as_ptr", since = "1.45.0")]
as_ptr(&self) -> *const T2274 pub fn as_ptr(&self) -> *const T {
2275 let ptr: *mut RcBox<T> = NonNull::as_ptr(self.ptr);
2276
2277 if is_dangling(ptr) {
2278 // If the pointer is dangling, we return the sentinel directly. This cannot be
2279 // a valid payload address, as the payload is at least as aligned as RcBox (usize).
2280 ptr as *const T
2281 } else {
2282 // SAFETY: if is_dangling returns false, then the pointer is dereferenceable.
2283 // The payload may be dropped at this point, and we have to maintain provenance,
2284 // so use raw pointer manipulation.
2285 unsafe { ptr::addr_of_mut!((*ptr).value) }
2286 }
2287 }
2288
2289 /// Consumes the `Weak<T>` and turns it into a raw pointer.
2290 ///
2291 /// This converts the weak pointer into a raw pointer, while still preserving the ownership of
2292 /// one weak reference (the weak count is not modified by this operation). It can be turned
2293 /// back into the `Weak<T>` with [`from_raw`].
2294 ///
2295 /// The same restrictions of accessing the target of the pointer as with
2296 /// [`as_ptr`] apply.
2297 ///
2298 /// # Examples
2299 ///
2300 /// ```
2301 /// use std::rc::{Rc, Weak};
2302 ///
2303 /// let strong = Rc::new("hello".to_owned());
2304 /// let weak = Rc::downgrade(&strong);
2305 /// let raw = weak.into_raw();
2306 ///
2307 /// assert_eq!(1, Rc::weak_count(&strong));
2308 /// assert_eq!("hello", unsafe { &*raw });
2309 ///
2310 /// drop(unsafe { Weak::from_raw(raw) });
2311 /// assert_eq!(0, Rc::weak_count(&strong));
2312 /// ```
2313 ///
2314 /// [`from_raw`]: Weak::from_raw
2315 /// [`as_ptr`]: Weak::as_ptr
2316 #[must_use = "`self` will be dropped if the result is not used"]
2317 #[stable(feature = "weak_into_raw", since = "1.45.0")]
into_raw(self) -> *const T2318 pub fn into_raw(self) -> *const T {
2319 let result = self.as_ptr();
2320 mem::forget(self);
2321 result
2322 }
2323
2324 /// Converts a raw pointer previously created by [`into_raw`] back into `Weak<T>`.
2325 ///
2326 /// This can be used to safely get a strong reference (by calling [`upgrade`]
2327 /// later) or to deallocate the weak count by dropping the `Weak<T>`.
2328 ///
2329 /// It takes ownership of one weak reference (with the exception of pointers created by [`new`],
2330 /// as these don't own anything; the method still works on them).
2331 ///
2332 /// # Safety
2333 ///
2334 /// The pointer must have originated from the [`into_raw`] and must still own its potential
2335 /// weak reference.
2336 ///
2337 /// It is allowed for the strong count to be 0 at the time of calling this. Nevertheless, this
2338 /// takes ownership of one weak reference currently represented as a raw pointer (the weak
2339 /// count is not modified by this operation) and therefore it must be paired with a previous
2340 /// call to [`into_raw`].
2341 ///
2342 /// # Examples
2343 ///
2344 /// ```
2345 /// use std::rc::{Rc, Weak};
2346 ///
2347 /// let strong = Rc::new("hello".to_owned());
2348 ///
2349 /// let raw_1 = Rc::downgrade(&strong).into_raw();
2350 /// let raw_2 = Rc::downgrade(&strong).into_raw();
2351 ///
2352 /// assert_eq!(2, Rc::weak_count(&strong));
2353 ///
2354 /// assert_eq!("hello", &*unsafe { Weak::from_raw(raw_1) }.upgrade().unwrap());
2355 /// assert_eq!(1, Rc::weak_count(&strong));
2356 ///
2357 /// drop(strong);
2358 ///
2359 /// // Decrement the last weak count.
2360 /// assert!(unsafe { Weak::from_raw(raw_2) }.upgrade().is_none());
2361 /// ```
2362 ///
2363 /// [`into_raw`]: Weak::into_raw
2364 /// [`upgrade`]: Weak::upgrade
2365 /// [`new`]: Weak::new
2366 #[stable(feature = "weak_into_raw", since = "1.45.0")]
from_raw(ptr: *const T) -> Self2367 pub unsafe fn from_raw(ptr: *const T) -> Self {
2368 // See Weak::as_ptr for context on how the input pointer is derived.
2369
2370 let ptr = if is_dangling(ptr as *mut T) {
2371 // This is a dangling Weak.
2372 ptr as *mut RcBox<T>
2373 } else {
2374 // Otherwise, we're guaranteed the pointer came from a nondangling Weak.
2375 // SAFETY: data_offset is safe to call, as ptr references a real (potentially dropped) T.
2376 let offset = unsafe { data_offset(ptr) };
2377 // Thus, we reverse the offset to get the whole RcBox.
2378 // SAFETY: the pointer originated from a Weak, so this offset is safe.
2379 unsafe { ptr.byte_sub(offset) as *mut RcBox<T> }
2380 };
2381
2382 // SAFETY: we now have recovered the original Weak pointer, so can create the Weak.
2383 Weak { ptr: unsafe { NonNull::new_unchecked(ptr) } }
2384 }
2385
2386 /// Attempts to upgrade the `Weak` pointer to an [`Rc`], delaying
2387 /// dropping of the inner value if successful.
2388 ///
2389 /// Returns [`None`] if the inner value has since been dropped.
2390 ///
2391 /// # Examples
2392 ///
2393 /// ```
2394 /// use std::rc::Rc;
2395 ///
2396 /// let five = Rc::new(5);
2397 ///
2398 /// let weak_five = Rc::downgrade(&five);
2399 ///
2400 /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
2401 /// assert!(strong_five.is_some());
2402 ///
2403 /// // Destroy all strong pointers.
2404 /// drop(strong_five);
2405 /// drop(five);
2406 ///
2407 /// assert!(weak_five.upgrade().is_none());
2408 /// ```
2409 #[must_use = "this returns a new `Rc`, \
2410 without modifying the original weak pointer"]
2411 #[stable(feature = "rc_weak", since = "1.4.0")]
upgrade(&self) -> Option<Rc<T>>2412 pub fn upgrade(&self) -> Option<Rc<T>> {
2413 let inner = self.inner()?;
2414
2415 if inner.strong() == 0 {
2416 None
2417 } else {
2418 unsafe {
2419 inner.inc_strong();
2420 Some(Rc::from_inner(self.ptr))
2421 }
2422 }
2423 }
2424
2425 /// Gets the number of strong (`Rc`) pointers pointing to this allocation.
2426 ///
2427 /// If `self` was created using [`Weak::new`], this will return 0.
2428 #[must_use]
2429 #[stable(feature = "weak_counts", since = "1.41.0")]
strong_count(&self) -> usize2430 pub fn strong_count(&self) -> usize {
2431 if let Some(inner) = self.inner() { inner.strong() } else { 0 }
2432 }
2433
2434 /// Gets the number of `Weak` pointers pointing to this allocation.
2435 ///
2436 /// If no strong pointers remain, this will return zero.
2437 #[must_use]
2438 #[stable(feature = "weak_counts", since = "1.41.0")]
weak_count(&self) -> usize2439 pub fn weak_count(&self) -> usize {
2440 self.inner()
2441 .map(|inner| {
2442 if inner.strong() > 0 {
2443 inner.weak() - 1 // subtract the implicit weak ptr
2444 } else {
2445 0
2446 }
2447 })
2448 .unwrap_or(0)
2449 }
2450
2451 /// Returns `None` when the pointer is dangling and there is no allocated `RcBox`,
2452 /// (i.e., when this `Weak` was created by `Weak::new`).
2453 #[inline]
inner(&self) -> Option<WeakInner<'_>>2454 fn inner(&self) -> Option<WeakInner<'_>> {
2455 if is_dangling(self.ptr.as_ptr()) {
2456 None
2457 } else {
2458 // We are careful to *not* create a reference covering the "data" field, as
2459 // the field may be mutated concurrently (for example, if the last `Rc`
2460 // is dropped, the data field will be dropped in-place).
2461 Some(unsafe {
2462 let ptr = self.ptr.as_ptr();
2463 WeakInner { strong: &(*ptr).strong, weak: &(*ptr).weak }
2464 })
2465 }
2466 }
2467
2468 /// Returns `true` if the two `Weak`s point to the same allocation similar to [`ptr::eq`], or if
2469 /// both don't point to any allocation (because they were created with `Weak::new()`). However,
2470 /// this function ignores the metadata of `dyn Trait` pointers.
2471 ///
2472 /// # Notes
2473 ///
2474 /// Since this compares pointers it means that `Weak::new()` will equal each
2475 /// other, even though they don't point to any allocation.
2476 ///
2477 /// # Examples
2478 ///
2479 /// ```
2480 /// use std::rc::Rc;
2481 ///
2482 /// let first_rc = Rc::new(5);
2483 /// let first = Rc::downgrade(&first_rc);
2484 /// let second = Rc::downgrade(&first_rc);
2485 ///
2486 /// assert!(first.ptr_eq(&second));
2487 ///
2488 /// let third_rc = Rc::new(5);
2489 /// let third = Rc::downgrade(&third_rc);
2490 ///
2491 /// assert!(!first.ptr_eq(&third));
2492 /// ```
2493 ///
2494 /// Comparing `Weak::new`.
2495 ///
2496 /// ```
2497 /// use std::rc::{Rc, Weak};
2498 ///
2499 /// let first = Weak::new();
2500 /// let second = Weak::new();
2501 /// assert!(first.ptr_eq(&second));
2502 ///
2503 /// let third_rc = Rc::new(());
2504 /// let third = Rc::downgrade(&third_rc);
2505 /// assert!(!first.ptr_eq(&third));
2506 /// ```
2507 #[inline]
2508 #[must_use]
2509 #[stable(feature = "weak_ptr_eq", since = "1.39.0")]
ptr_eq(&self, other: &Self) -> bool2510 pub fn ptr_eq(&self, other: &Self) -> bool {
2511 ptr::eq(self.ptr.as_ptr() as *const (), other.ptr.as_ptr() as *const ())
2512 }
2513 }
2514
2515 #[stable(feature = "rc_weak", since = "1.4.0")]
2516 unsafe impl<#[may_dangle] T: ?Sized> Drop for Weak<T> {
2517 /// Drops the `Weak` pointer.
2518 ///
2519 /// # Examples
2520 ///
2521 /// ```
2522 /// use std::rc::{Rc, Weak};
2523 ///
2524 /// struct Foo;
2525 ///
2526 /// impl Drop for Foo {
2527 /// fn drop(&mut self) {
2528 /// println!("dropped!");
2529 /// }
2530 /// }
2531 ///
2532 /// let foo = Rc::new(Foo);
2533 /// let weak_foo = Rc::downgrade(&foo);
2534 /// let other_weak_foo = Weak::clone(&weak_foo);
2535 ///
2536 /// drop(weak_foo); // Doesn't print anything
2537 /// drop(foo); // Prints "dropped!"
2538 ///
2539 /// assert!(other_weak_foo.upgrade().is_none());
2540 /// ```
drop(&mut self)2541 fn drop(&mut self) {
2542 let inner = if let Some(inner) = self.inner() { inner } else { return };
2543
2544 inner.dec_weak();
2545 // the weak count starts at 1, and will only go to zero if all
2546 // the strong pointers have disappeared.
2547 if inner.weak() == 0 {
2548 unsafe {
2549 Global.deallocate(self.ptr.cast(), Layout::for_value_raw(self.ptr.as_ptr()));
2550 }
2551 }
2552 }
2553 }
2554
2555 #[stable(feature = "rc_weak", since = "1.4.0")]
2556 impl<T: ?Sized> Clone for Weak<T> {
2557 /// Makes a clone of the `Weak` pointer that points to the same allocation.
2558 ///
2559 /// # Examples
2560 ///
2561 /// ```
2562 /// use std::rc::{Rc, Weak};
2563 ///
2564 /// let weak_five = Rc::downgrade(&Rc::new(5));
2565 ///
2566 /// let _ = Weak::clone(&weak_five);
2567 /// ```
2568 #[inline]
clone(&self) -> Weak<T>2569 fn clone(&self) -> Weak<T> {
2570 if let Some(inner) = self.inner() {
2571 inner.inc_weak()
2572 }
2573 Weak { ptr: self.ptr }
2574 }
2575 }
2576
2577 #[stable(feature = "rc_weak", since = "1.4.0")]
2578 impl<T: ?Sized> fmt::Debug for Weak<T> {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result2579 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2580 write!(f, "(Weak)")
2581 }
2582 }
2583
2584 #[stable(feature = "downgraded_weak", since = "1.10.0")]
2585 impl<T> Default for Weak<T> {
2586 /// Constructs a new `Weak<T>`, without allocating any memory.
2587 /// Calling [`upgrade`] on the return value always gives [`None`].
2588 ///
2589 /// [`upgrade`]: Weak::upgrade
2590 ///
2591 /// # Examples
2592 ///
2593 /// ```
2594 /// use std::rc::Weak;
2595 ///
2596 /// let empty: Weak<i64> = Default::default();
2597 /// assert!(empty.upgrade().is_none());
2598 /// ```
default() -> Weak<T>2599 fn default() -> Weak<T> {
2600 Weak::new()
2601 }
2602 }
2603
2604 // NOTE: We checked_add here to deal with mem::forget safely. In particular
2605 // if you mem::forget Rcs (or Weaks), the ref-count can overflow, and then
2606 // you can free the allocation while outstanding Rcs (or Weaks) exist.
2607 // We abort because this is such a degenerate scenario that we don't care about
2608 // what happens -- no real program should ever experience this.
2609 //
2610 // This should have negligible overhead since you don't actually need to
2611 // clone these much in Rust thanks to ownership and move-semantics.
2612
2613 #[doc(hidden)]
2614 trait RcInnerPtr {
weak_ref(&self) -> &Cell<usize>2615 fn weak_ref(&self) -> &Cell<usize>;
strong_ref(&self) -> &Cell<usize>2616 fn strong_ref(&self) -> &Cell<usize>;
2617
2618 #[inline]
strong(&self) -> usize2619 fn strong(&self) -> usize {
2620 self.strong_ref().get()
2621 }
2622
2623 #[inline]
inc_strong(&self)2624 fn inc_strong(&self) {
2625 let strong = self.strong();
2626
2627 // We insert an `assume` here to hint LLVM at an otherwise
2628 // missed optimization.
2629 // SAFETY: The reference count will never be zero when this is
2630 // called.
2631 unsafe {
2632 core::intrinsics::assume(strong != 0);
2633 }
2634
2635 let strong = strong.wrapping_add(1);
2636 self.strong_ref().set(strong);
2637
2638 // We want to abort on overflow instead of dropping the value.
2639 // Checking for overflow after the store instead of before
2640 // allows for slightly better code generation.
2641 if core::intrinsics::unlikely(strong == 0) {
2642 abort();
2643 }
2644 }
2645
2646 #[inline]
dec_strong(&self)2647 fn dec_strong(&self) {
2648 self.strong_ref().set(self.strong() - 1);
2649 }
2650
2651 #[inline]
weak(&self) -> usize2652 fn weak(&self) -> usize {
2653 self.weak_ref().get()
2654 }
2655
2656 #[inline]
inc_weak(&self)2657 fn inc_weak(&self) {
2658 let weak = self.weak();
2659
2660 // We insert an `assume` here to hint LLVM at an otherwise
2661 // missed optimization.
2662 // SAFETY: The reference count will never be zero when this is
2663 // called.
2664 unsafe {
2665 core::intrinsics::assume(weak != 0);
2666 }
2667
2668 let weak = weak.wrapping_add(1);
2669 self.weak_ref().set(weak);
2670
2671 // We want to abort on overflow instead of dropping the value.
2672 // Checking for overflow after the store instead of before
2673 // allows for slightly better code generation.
2674 if core::intrinsics::unlikely(weak == 0) {
2675 abort();
2676 }
2677 }
2678
2679 #[inline]
dec_weak(&self)2680 fn dec_weak(&self) {
2681 self.weak_ref().set(self.weak() - 1);
2682 }
2683 }
2684
2685 impl<T: ?Sized> RcInnerPtr for RcBox<T> {
2686 #[inline(always)]
weak_ref(&self) -> &Cell<usize>2687 fn weak_ref(&self) -> &Cell<usize> {
2688 &self.weak
2689 }
2690
2691 #[inline(always)]
strong_ref(&self) -> &Cell<usize>2692 fn strong_ref(&self) -> &Cell<usize> {
2693 &self.strong
2694 }
2695 }
2696
2697 impl<'a> RcInnerPtr for WeakInner<'a> {
2698 #[inline(always)]
weak_ref(&self) -> &Cell<usize>2699 fn weak_ref(&self) -> &Cell<usize> {
2700 self.weak
2701 }
2702
2703 #[inline(always)]
strong_ref(&self) -> &Cell<usize>2704 fn strong_ref(&self) -> &Cell<usize> {
2705 self.strong
2706 }
2707 }
2708
2709 #[stable(feature = "rust1", since = "1.0.0")]
2710 impl<T: ?Sized> borrow::Borrow<T> for Rc<T> {
borrow(&self) -> &T2711 fn borrow(&self) -> &T {
2712 &**self
2713 }
2714 }
2715
2716 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
2717 impl<T: ?Sized> AsRef<T> for Rc<T> {
as_ref(&self) -> &T2718 fn as_ref(&self) -> &T {
2719 &**self
2720 }
2721 }
2722
2723 #[stable(feature = "pin", since = "1.33.0")]
2724 impl<T: ?Sized> Unpin for Rc<T> {}
2725
2726 /// Get the offset within an `RcBox` for the payload behind a pointer.
2727 ///
2728 /// # Safety
2729 ///
2730 /// The pointer must point to (and have valid metadata for) a previously
2731 /// valid instance of T, but the T is allowed to be dropped.
data_offset<T: ?Sized>(ptr: *const T) -> usize2732 unsafe fn data_offset<T: ?Sized>(ptr: *const T) -> usize {
2733 // Align the unsized value to the end of the RcBox.
2734 // Because RcBox is repr(C), it will always be the last field in memory.
2735 // SAFETY: since the only unsized types possible are slices, trait objects,
2736 // and extern types, the input safety requirement is currently enough to
2737 // satisfy the requirements of align_of_val_raw; this is an implementation
2738 // detail of the language that must not be relied upon outside of std.
2739 unsafe { data_offset_align(align_of_val_raw(ptr)) }
2740 }
2741
2742 #[inline]
data_offset_align(align: usize) -> usize2743 fn data_offset_align(align: usize) -> usize {
2744 let layout = Layout::new::<RcBox<()>>();
2745 layout.size() + layout.padding_needed_for(align)
2746 }
2747
2748 /// A uniquely owned `Rc`
2749 ///
2750 /// This represents an `Rc` that is known to be uniquely owned -- that is, have exactly one strong
2751 /// reference. Multiple weak pointers can be created, but attempts to upgrade those to strong
2752 /// references will fail unless the `UniqueRc` they point to has been converted into a regular `Rc`.
2753 ///
2754 /// Because they are uniquely owned, the contents of a `UniqueRc` can be freely mutated. A common
2755 /// use case is to have an object be mutable during its initialization phase but then have it become
2756 /// immutable and converted to a normal `Rc`.
2757 ///
2758 /// This can be used as a flexible way to create cyclic data structures, as in the example below.
2759 ///
2760 /// ```
2761 /// #![feature(unique_rc_arc)]
2762 /// use std::rc::{Rc, Weak, UniqueRc};
2763 ///
2764 /// struct Gadget {
2765 /// #[allow(dead_code)]
2766 /// me: Weak<Gadget>,
2767 /// }
2768 ///
2769 /// fn create_gadget() -> Option<Rc<Gadget>> {
2770 /// let mut rc = UniqueRc::new(Gadget {
2771 /// me: Weak::new(),
2772 /// });
2773 /// rc.me = UniqueRc::downgrade(&rc);
2774 /// Some(UniqueRc::into_rc(rc))
2775 /// }
2776 ///
2777 /// create_gadget().unwrap();
2778 /// ```
2779 ///
2780 /// An advantage of using `UniqueRc` over [`Rc::new_cyclic`] to build cyclic data structures is that
2781 /// [`Rc::new_cyclic`]'s `data_fn` parameter cannot be async or return a [`Result`]. As shown in the
2782 /// previous example, `UniqueRc` allows for more flexibility in the construction of cyclic data,
2783 /// including fallible or async constructors.
2784 #[unstable(feature = "unique_rc_arc", issue = "112566")]
2785 #[derive(Debug)]
2786 pub struct UniqueRc<T> {
2787 ptr: NonNull<RcBox<T>>,
2788 phantom: PhantomData<RcBox<T>>,
2789 }
2790
2791 impl<T> UniqueRc<T> {
2792 /// Creates a new `UniqueRc`
2793 ///
2794 /// Weak references to this `UniqueRc` can be created with [`UniqueRc::downgrade`]. Upgrading
2795 /// these weak references will fail before the `UniqueRc` has been converted into an [`Rc`].
2796 /// After converting the `UniqueRc` into an [`Rc`], any weak references created beforehand will
2797 /// point to the new [`Rc`].
2798 #[cfg(not(no_global_oom_handling))]
2799 #[unstable(feature = "unique_rc_arc", issue = "112566")]
new(value: T) -> Self2800 pub fn new(value: T) -> Self {
2801 Self {
2802 ptr: Box::leak(Box::new(RcBox {
2803 strong: Cell::new(0),
2804 // keep one weak reference so if all the weak pointers that are created are dropped
2805 // the UniqueRc still stays valid.
2806 weak: Cell::new(1),
2807 value,
2808 }))
2809 .into(),
2810 phantom: PhantomData,
2811 }
2812 }
2813
2814 /// Creates a new weak reference to the `UniqueRc`
2815 ///
2816 /// Attempting to upgrade this weak reference will fail before the `UniqueRc` has been converted
2817 /// to a [`Rc`] using [`UniqueRc::into_rc`].
2818 #[unstable(feature = "unique_rc_arc", issue = "112566")]
downgrade(this: &Self) -> Weak<T>2819 pub fn downgrade(this: &Self) -> Weak<T> {
2820 // SAFETY: This pointer was allocated at creation time and we guarantee that we only have
2821 // one strong reference before converting to a regular Rc.
2822 unsafe {
2823 this.ptr.as_ref().inc_weak();
2824 }
2825 Weak { ptr: this.ptr }
2826 }
2827
2828 /// Converts the `UniqueRc` into a regular [`Rc`]
2829 ///
2830 /// This consumes the `UniqueRc` and returns a regular [`Rc`] that contains the `value` that
2831 /// is passed to `into_rc`.
2832 ///
2833 /// Any weak references created before this method is called can now be upgraded to strong
2834 /// references.
2835 #[unstable(feature = "unique_rc_arc", issue = "112566")]
into_rc(this: Self) -> Rc<T>2836 pub fn into_rc(this: Self) -> Rc<T> {
2837 let mut this = ManuallyDrop::new(this);
2838 // SAFETY: This pointer was allocated at creation time so we know it is valid.
2839 unsafe {
2840 // Convert our weak reference into a strong reference
2841 this.ptr.as_mut().strong.set(1);
2842 Rc::from_inner(this.ptr)
2843 }
2844 }
2845 }
2846
2847 #[unstable(feature = "unique_rc_arc", issue = "112566")]
2848 impl<T> Deref for UniqueRc<T> {
2849 type Target = T;
2850
deref(&self) -> &T2851 fn deref(&self) -> &T {
2852 // SAFETY: This pointer was allocated at creation time so we know it is valid.
2853 unsafe { &self.ptr.as_ref().value }
2854 }
2855 }
2856
2857 #[unstable(feature = "unique_rc_arc", issue = "112566")]
2858 impl<T> DerefMut for UniqueRc<T> {
deref_mut(&mut self) -> &mut T2859 fn deref_mut(&mut self) -> &mut T {
2860 // SAFETY: This pointer was allocated at creation time so we know it is valid. We know we
2861 // have unique ownership and therefore it's safe to make a mutable reference because
2862 // `UniqueRc` owns the only strong reference to itself.
2863 unsafe { &mut (*self.ptr.as_ptr()).value }
2864 }
2865 }
2866
2867 #[unstable(feature = "unique_rc_arc", issue = "112566")]
2868 unsafe impl<#[may_dangle] T> Drop for UniqueRc<T> {
drop(&mut self)2869 fn drop(&mut self) {
2870 unsafe {
2871 // destroy the contained object
2872 drop_in_place(DerefMut::deref_mut(self));
2873
2874 // remove the implicit "strong weak" pointer now that we've destroyed the contents.
2875 self.ptr.as_ref().dec_weak();
2876
2877 if self.ptr.as_ref().weak() == 0 {
2878 Global.deallocate(self.ptr.cast(), Layout::for_value(self.ptr.as_ref()));
2879 }
2880 }
2881 }
2882 }
2883