1 //! Single-threaded reference-counting pointers. 'Rc' stands for 'Reference
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 value in the heap. When the last [`Rc`] pointer to a
7 //! given value is destroyed, the pointed-to value is also destroyed.
9 //! Shared references in Rust disallow mutation by default, and [`Rc`]
10 //! is no exception: you cannot generally obtain a mutable reference to
11 //! something inside an [`Rc`]. If you need mutability, put a [`Cell`]
12 //! or [`RefCell`] inside the [`Rc`]; see [an example of mutability
13 //! inside an Rc][mutability].
15 //! [`Rc`] uses non-atomic reference counting. This means that overhead is very
16 //! low, but an [`Rc`] cannot be sent between threads, and consequently [`Rc`]
17 //! does not implement [`Send`][send]. As a result, the Rust compiler
18 //! will check *at compile time* that you are not sending [`Rc`]s between
19 //! threads. If you need multi-threaded, atomic reference counting, use
20 //! [`sync::Arc`][arc].
22 //! The [`downgrade`][downgrade] method can be used to create a non-owning
23 //! [`Weak`] pointer. A [`Weak`] pointer can be [`upgrade`][upgrade]d
24 //! to an [`Rc`], but this will return [`None`] if the value has
25 //! already been dropped.
27 //! A cycle between [`Rc`] pointers will never be deallocated. For this reason,
28 //! [`Weak`] is used to break cycles. For example, a tree could have strong
29 //! [`Rc`] pointers from parent nodes to children, and [`Weak`] pointers from
30 //! children back to their parents.
32 //! `Rc<T>` automatically dereferences to `T` (via the [`Deref`] trait),
33 //! so you can call `T`'s methods on a value of type [`Rc<T>`][`Rc`]. To avoid name
34 //! clashes with `T`'s methods, the methods of [`Rc<T>`][`Rc`] itself are associated
35 //! functions, called using function-like syntax:
39 //! let my_rc = Rc::new(());
41 //! Rc::downgrade(&my_rc);
44 //! [`Weak<T>`][`Weak`] does not auto-dereference to `T`, because the value may have
45 //! already been destroyed.
47 //! # Cloning references
49 //! Creating a new reference from an existing reference counted pointer is done using the
50 //! `Clone` trait implemented for [`Rc<T>`][`Rc`] and [`Weak<T>`][`Weak`].
54 //! let foo = Rc::new(vec![1.0, 2.0, 3.0]);
55 //! // The two syntaxes below are equivalent.
56 //! let a = foo.clone();
57 //! let b = Rc::clone(&foo);
58 //! // a and b both point to the same memory location as foo.
61 //! The `Rc::clone(&from)` syntax is the most idiomatic because it conveys more explicitly
62 //! the meaning of the code. In the example above, this syntax makes it easier to see that
63 //! this code is creating a new reference rather than copying the whole content of foo.
67 //! Consider a scenario where a set of `Gadget`s are owned by a given `Owner`.
68 //! We want to have our `Gadget`s point to their `Owner`. We can't do this with
69 //! unique ownership, because more than one gadget may belong to the same
70 //! `Owner`. [`Rc`] allows us to share an `Owner` between multiple `Gadget`s,
71 //! and have the `Owner` remain allocated as long as any `Gadget` points at it.
78 //! // ...other fields
84 //! // ...other fields
88 //! // Create a reference-counted `Owner`.
89 //! let gadget_owner: Rc<Owner> = Rc::new(
91 //! name: "Gadget Man".to_string(),
95 //! // Create `Gadget`s belonging to `gadget_owner`. Cloning the `Rc<Owner>`
96 //! // value gives us a new pointer to the same `Owner` value, incrementing
97 //! // the reference count in the process.
98 //! let gadget1 = Gadget {
100 //! owner: Rc::clone(&gadget_owner),
102 //! let gadget2 = Gadget {
104 //! owner: Rc::clone(&gadget_owner),
107 //! // Dispose of our local variable `gadget_owner`.
108 //! drop(gadget_owner);
110 //! // Despite dropping `gadget_owner`, we're still able to print out the name
111 //! // of the `Owner` of the `Gadget`s. This is because we've only dropped a
112 //! // single `Rc<Owner>`, not the `Owner` it points to. As long as there are
113 //! // other `Rc<Owner>` values pointing at the same `Owner`, it will remain
114 //! // allocated. The field projection `gadget1.owner.name` works because
115 //! // `Rc<Owner>` automatically dereferences to `Owner`.
116 //! println!("Gadget {} owned by {}", gadget1.id, gadget1.owner.name);
117 //! println!("Gadget {} owned by {}", gadget2.id, gadget2.owner.name);
119 //! // At the end of the function, `gadget1` and `gadget2` are destroyed, and
120 //! // with them the last counted references to our `Owner`. Gadget Man now
121 //! // gets destroyed as well.
125 //! If our requirements change, and we also need to be able to traverse from
126 //! `Owner` to `Gadget`, we will run into problems. An [`Rc`] pointer from `Owner`
127 //! to `Gadget` introduces a cycle between the values. This means that their
128 //! reference counts can never reach 0, and the values will remain allocated
129 //! forever: a memory leak. In order to get around this, we can use [`Weak`]
132 //! Rust actually makes it somewhat difficult to produce this loop in the first
133 //! place. In order to end up with two values that point at each other, one of
134 //! them needs to be mutable. This is difficult because [`Rc`] enforces
135 //! memory safety by only giving out shared references to the value it wraps,
136 //! and these don't allow direct mutation. We need to wrap the part of the
137 //! value we wish to mutate in a [`RefCell`], which provides *interior
138 //! mutability*: a method to achieve mutability through a shared reference.
139 //! [`RefCell`] enforces Rust's borrowing rules at runtime.
143 //! use std::rc::Weak;
144 //! use std::cell::RefCell;
148 //! gadgets: RefCell<Vec<Weak<Gadget>>>,
149 //! // ...other fields
154 //! owner: Rc<Owner>,
155 //! // ...other fields
159 //! // Create a reference-counted `Owner`. Note that we've put the `Owner`'s
160 //! // vector of `Gadget`s inside a `RefCell` so that we can mutate it through
161 //! // a shared reference.
162 //! let gadget_owner: Rc<Owner> = Rc::new(
164 //! name: "Gadget Man".to_string(),
165 //! gadgets: RefCell::new(vec![]),
169 //! // Create `Gadget`s belonging to `gadget_owner`, as before.
170 //! let gadget1 = Rc::new(
173 //! owner: Rc::clone(&gadget_owner),
176 //! let gadget2 = Rc::new(
179 //! owner: Rc::clone(&gadget_owner),
183 //! // Add the `Gadget`s to their `Owner`.
185 //! let mut gadgets = gadget_owner.gadgets.borrow_mut();
186 //! gadgets.push(Rc::downgrade(&gadget1));
187 //! gadgets.push(Rc::downgrade(&gadget2));
189 //! // `RefCell` dynamic borrow ends here.
192 //! // Iterate over our `Gadget`s, printing their details out.
193 //! for gadget_weak in gadget_owner.gadgets.borrow().iter() {
195 //! // `gadget_weak` is a `Weak<Gadget>`. Since `Weak` pointers can't
196 //! // guarantee the value is still allocated, we need to call
197 //! // `upgrade`, which returns an `Option<Rc<Gadget>>`.
199 //! // In this case we know the value still exists, so we simply
200 //! // `unwrap` the `Option`. In a more complicated program, you might
201 //! // need graceful error handling for a `None` result.
203 //! let gadget = gadget_weak.upgrade().unwrap();
204 //! println!("Gadget {} owned by {}", gadget.id, gadget.owner.name);
207 //! // At the end of the function, `gadget_owner`, `gadget1`, and `gadget2`
208 //! // are destroyed. There are now no strong (`Rc`) pointers to the
209 //! // gadgets, so they are destroyed. This zeroes the reference count on
210 //! // Gadget Man, so he gets destroyed as well.
214 //! [`Rc`]: struct.Rc.html
215 //! [`Weak`]: struct.Weak.html
216 //! [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
217 //! [`Cell`]: ../../std/cell/struct.Cell.html
218 //! [`RefCell`]: ../../std/cell/struct.RefCell.html
219 //! [send]: ../../std/marker/trait.Send.html
220 //! [arc]: ../../std/sync/struct.Arc.html
221 //! [`Deref`]: ../../std/ops/trait.Deref.html
222 //! [downgrade]: struct.Rc.html#method.downgrade
223 //! [upgrade]: struct.Weak.html#method.upgrade
224 //! [`None`]: ../../std/option/enum.Option.html#variant.None
225 //! [mutability]: ../../std/cell/index.html#introducing-mutability-inside-of-something-immutable
227 #![stable(feature = "rust1", since = "1.0.0")]
230 use crate::boxed::Box;
235 use core::array::LengthAtMost32;
237 use core::cell::Cell;
238 use core::cmp::Ordering;
240 use core::hash::{Hash, Hasher};
241 use core::intrinsics::abort;
243 use core::marker::{self, Unpin, Unsize, PhantomData};
244 use core::mem::{self, align_of, align_of_val, forget, size_of_val};
245 use core::ops::{Deref, Receiver, CoerceUnsized, DispatchFromDyn};
247 use core::ptr::{self, NonNull};
248 use core::slice::{self, from_raw_parts_mut};
249 use core::convert::{From, TryFrom};
252 use crate::alloc::{Global, Alloc, Layout, box_free, handle_alloc_error};
253 use crate::string::String;
259 struct RcBox<T: ?Sized> {
265 /// A single-threaded reference-counting pointer. 'Rc' stands for 'Reference
268 /// See the [module-level documentation](./index.html) for more details.
270 /// The inherent methods of `Rc` are all associated functions, which means
271 /// that you have to call them as e.g., [`Rc::get_mut(&mut value)`][get_mut] instead of
272 /// `value.get_mut()`. This avoids conflicts with methods of the inner
275 /// [get_mut]: #method.get_mut
276 #[cfg_attr(not(test), lang = "rc")]
277 #[stable(feature = "rust1", since = "1.0.0")]
278 pub struct Rc<T: ?Sized> {
279 ptr: NonNull<RcBox<T>>,
280 phantom: PhantomData<T>,
283 #[stable(feature = "rust1", since = "1.0.0")]
284 impl<T: ?Sized> !marker::Send for Rc<T> {}
285 #[stable(feature = "rust1", since = "1.0.0")]
286 impl<T: ?Sized> !marker::Sync for Rc<T> {}
288 #[unstable(feature = "coerce_unsized", issue = "27732")]
289 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Rc<U>> for Rc<T> {}
291 #[unstable(feature = "dispatch_from_dyn", issue = "0")]
292 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Rc<U>> for Rc<T> {}
294 impl<T: ?Sized> Rc<T> {
295 fn from_inner(ptr: NonNull<RcBox<T>>) -> Self {
298 phantom: PhantomData,
302 unsafe fn from_ptr(ptr: *mut RcBox<T>) -> Self {
303 Self::from_inner(NonNull::new_unchecked(ptr))
308 /// Constructs a new `Rc<T>`.
315 /// let five = Rc::new(5);
317 #[stable(feature = "rust1", since = "1.0.0")]
318 pub fn new(value: T) -> Rc<T> {
319 // There is an implicit weak pointer owned by all the strong
320 // pointers, which ensures that the weak destructor never frees
321 // the allocation while the strong destructor is running, even
322 // if the weak pointer is stored inside the strong one.
323 Self::from_inner(Box::into_raw_non_null(box RcBox {
324 strong: Cell::new(1),
330 /// Constructs a new `Rc` with uninitialized contents.
335 /// #![feature(new_uninit)]
336 /// #![feature(get_mut_unchecked)]
340 /// let mut five = Rc::<u32>::new_uninit();
342 /// let five = unsafe {
343 /// // Deferred initialization:
344 /// Rc::get_mut_unchecked(&mut five).as_mut_ptr().write(5);
346 /// five.assume_init()
349 /// assert_eq!(*five, 5)
351 #[unstable(feature = "new_uninit", issue = "63291")]
352 pub fn new_uninit() -> Rc<mem::MaybeUninit<T>> {
354 Rc::from_ptr(Rc::allocate_for_layout(
356 |mem| mem as *mut RcBox<mem::MaybeUninit<T>>,
361 /// Constructs a new `Pin<Rc<T>>`. If `T` does not implement `Unpin`, then
362 /// `value` will be pinned in memory and unable to be moved.
363 #[stable(feature = "pin", since = "1.33.0")]
364 pub fn pin(value: T) -> Pin<Rc<T>> {
365 unsafe { Pin::new_unchecked(Rc::new(value)) }
368 /// Returns the contained value, if the `Rc` has exactly one strong reference.
370 /// Otherwise, an [`Err`][result] is returned with the same `Rc` that was
373 /// This will succeed even if there are outstanding weak references.
375 /// [result]: ../../std/result/enum.Result.html
382 /// let x = Rc::new(3);
383 /// assert_eq!(Rc::try_unwrap(x), Ok(3));
385 /// let x = Rc::new(4);
386 /// let _y = Rc::clone(&x);
387 /// assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4);
390 #[stable(feature = "rc_unique", since = "1.4.0")]
391 pub fn try_unwrap(this: Self) -> Result<T, Self> {
392 if Rc::strong_count(&this) == 1 {
394 let val = ptr::read(&*this); // copy the contained object
396 // Indicate to Weaks that they can't be promoted by decrementing
397 // the strong count, and then remove the implicit "strong weak"
398 // pointer while also handling drop logic by just crafting a
401 let _weak = Weak { ptr: this.ptr };
412 /// Constructs a new reference-counted slice with uninitialized contents.
417 /// #![feature(new_uninit)]
418 /// #![feature(get_mut_unchecked)]
422 /// let mut values = Rc::<[u32]>::new_uninit_slice(3);
424 /// let values = unsafe {
425 /// // Deferred initialization:
426 /// Rc::get_mut_unchecked(&mut values)[0].as_mut_ptr().write(1);
427 /// Rc::get_mut_unchecked(&mut values)[1].as_mut_ptr().write(2);
428 /// Rc::get_mut_unchecked(&mut values)[2].as_mut_ptr().write(3);
430 /// values.assume_init()
433 /// assert_eq!(*values, [1, 2, 3])
435 #[unstable(feature = "new_uninit", issue = "63291")]
436 pub fn new_uninit_slice(len: usize) -> Rc<[mem::MaybeUninit<T>]> {
438 Rc::from_ptr(Rc::allocate_for_slice(len))
443 impl<T> Rc<mem::MaybeUninit<T>> {
444 /// Converts to `Rc<T>`.
448 /// As with [`MaybeUninit::assume_init`],
449 /// it is up to the caller to guarantee that the value
450 /// really is in an initialized state.
451 /// Calling this when the content is not yet fully initialized
452 /// causes immediate undefined behavior.
454 /// [`MaybeUninit::assume_init`]: ../../std/mem/union.MaybeUninit.html#method.assume_init
459 /// #![feature(new_uninit)]
460 /// #![feature(get_mut_unchecked)]
464 /// let mut five = Rc::<u32>::new_uninit();
466 /// let five = unsafe {
467 /// // Deferred initialization:
468 /// Rc::get_mut_unchecked(&mut five).as_mut_ptr().write(5);
470 /// five.assume_init()
473 /// assert_eq!(*five, 5)
475 #[unstable(feature = "new_uninit", issue = "63291")]
477 pub unsafe fn assume_init(self) -> Rc<T> {
478 Rc::from_inner(mem::ManuallyDrop::new(self).ptr.cast())
482 impl<T> Rc<[mem::MaybeUninit<T>]> {
483 /// Converts to `Rc<[T]>`.
487 /// As with [`MaybeUninit::assume_init`],
488 /// it is up to the caller to guarantee that the value
489 /// really is in an initialized state.
490 /// Calling this when the content is not yet fully initialized
491 /// causes immediate undefined behavior.
493 /// [`MaybeUninit::assume_init`]: ../../std/mem/union.MaybeUninit.html#method.assume_init
498 /// #![feature(new_uninit)]
499 /// #![feature(get_mut_unchecked)]
503 /// let mut values = Rc::<[u32]>::new_uninit_slice(3);
505 /// let values = unsafe {
506 /// // Deferred initialization:
507 /// Rc::get_mut_unchecked(&mut values)[0].as_mut_ptr().write(1);
508 /// Rc::get_mut_unchecked(&mut values)[1].as_mut_ptr().write(2);
509 /// Rc::get_mut_unchecked(&mut values)[2].as_mut_ptr().write(3);
511 /// values.assume_init()
514 /// assert_eq!(*values, [1, 2, 3])
516 #[unstable(feature = "new_uninit", issue = "63291")]
518 pub unsafe fn assume_init(self) -> Rc<[T]> {
519 Rc::from_ptr(mem::ManuallyDrop::new(self).ptr.as_ptr() as _)
523 impl<T: ?Sized> Rc<T> {
524 /// Consumes the `Rc`, returning the wrapped pointer.
526 /// To avoid a memory leak the pointer must be converted back to an `Rc` using
527 /// [`Rc::from_raw`][from_raw].
529 /// [from_raw]: struct.Rc.html#method.from_raw
536 /// let x = Rc::new("hello".to_owned());
537 /// let x_ptr = Rc::into_raw(x);
538 /// assert_eq!(unsafe { &*x_ptr }, "hello");
540 #[stable(feature = "rc_raw", since = "1.17.0")]
541 pub fn into_raw(this: Self) -> *const T {
542 let ptr: *const T = &*this;
547 /// Constructs an `Rc` from a raw pointer.
549 /// The raw pointer must have been previously returned by a call to a
550 /// [`Rc::into_raw`][into_raw].
552 /// This function is unsafe because improper use may lead to memory problems. For example, a
553 /// double-free may occur if the function is called twice on the same raw pointer.
555 /// [into_raw]: struct.Rc.html#method.into_raw
562 /// let x = Rc::new("hello".to_owned());
563 /// let x_ptr = Rc::into_raw(x);
566 /// // Convert back to an `Rc` to prevent leak.
567 /// let x = Rc::from_raw(x_ptr);
568 /// assert_eq!(&*x, "hello");
570 /// // Further calls to `Rc::from_raw(x_ptr)` would be memory-unsafe.
573 /// // The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling!
575 #[stable(feature = "rc_raw", since = "1.17.0")]
576 pub unsafe fn from_raw(ptr: *const T) -> Self {
577 let offset = data_offset(ptr);
579 // Reverse the offset to find the original RcBox.
580 let fake_ptr = ptr as *mut RcBox<T>;
581 let rc_ptr = set_data_ptr(fake_ptr, (ptr as *mut u8).offset(-offset));
583 Self::from_ptr(rc_ptr)
586 /// Consumes the `Rc`, returning the wrapped pointer as `NonNull<T>`.
591 /// #![feature(rc_into_raw_non_null)]
595 /// let x = Rc::new("hello".to_owned());
596 /// let ptr = Rc::into_raw_non_null(x);
597 /// let deref = unsafe { ptr.as_ref() };
598 /// assert_eq!(deref, "hello");
600 #[unstable(feature = "rc_into_raw_non_null", issue = "47336")]
602 pub fn into_raw_non_null(this: Self) -> NonNull<T> {
603 // safe because Rc guarantees its pointer is non-null
604 unsafe { NonNull::new_unchecked(Rc::into_raw(this) as *mut _) }
607 /// Creates a new [`Weak`][weak] pointer to this value.
609 /// [weak]: struct.Weak.html
616 /// let five = Rc::new(5);
618 /// let weak_five = Rc::downgrade(&five);
620 #[stable(feature = "rc_weak", since = "1.4.0")]
621 pub fn downgrade(this: &Self) -> Weak<T> {
623 // Make sure we do not create a dangling Weak
624 debug_assert!(!is_dangling(this.ptr));
625 Weak { ptr: this.ptr }
628 /// Gets the number of [`Weak`][weak] pointers to this value.
630 /// [weak]: struct.Weak.html
637 /// let five = Rc::new(5);
638 /// let _weak_five = Rc::downgrade(&five);
640 /// assert_eq!(1, Rc::weak_count(&five));
643 #[stable(feature = "rc_counts", since = "1.15.0")]
644 pub fn weak_count(this: &Self) -> usize {
648 /// Gets the number of strong (`Rc`) pointers to this value.
655 /// let five = Rc::new(5);
656 /// let _also_five = Rc::clone(&five);
658 /// assert_eq!(2, Rc::strong_count(&five));
661 #[stable(feature = "rc_counts", since = "1.15.0")]
662 pub fn strong_count(this: &Self) -> usize {
666 /// Returns `true` if there are no other `Rc` or [`Weak`][weak] pointers to
667 /// this inner value.
669 /// [weak]: struct.Weak.html
671 fn is_unique(this: &Self) -> bool {
672 Rc::weak_count(this) == 0 && Rc::strong_count(this) == 1
675 /// Returns a mutable reference to the inner value, if there are
676 /// no other `Rc` or [`Weak`][weak] pointers to the same value.
678 /// Returns [`None`] otherwise, because it is not safe to
679 /// mutate a shared value.
681 /// See also [`make_mut`][make_mut], which will [`clone`][clone]
682 /// the inner value when it's shared.
684 /// [weak]: struct.Weak.html
685 /// [`None`]: ../../std/option/enum.Option.html#variant.None
686 /// [make_mut]: struct.Rc.html#method.make_mut
687 /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
694 /// let mut x = Rc::new(3);
695 /// *Rc::get_mut(&mut x).unwrap() = 4;
696 /// assert_eq!(*x, 4);
698 /// let _y = Rc::clone(&x);
699 /// assert!(Rc::get_mut(&mut x).is_none());
702 #[stable(feature = "rc_unique", since = "1.4.0")]
703 pub fn get_mut(this: &mut Self) -> Option<&mut T> {
704 if Rc::is_unique(this) {
706 Some(Rc::get_mut_unchecked(this))
713 /// Returns a mutable reference to the inner value,
714 /// without any check.
716 /// See also [`get_mut`], which is safe and does appropriate checks.
718 /// [`get_mut`]: struct.Rc.html#method.get_mut
722 /// Any other `Rc` or [`Weak`] pointers to the same value must not be dereferenced
723 /// for the duration of the returned borrow.
724 /// This is trivially the case if no such pointers exist,
725 /// for example immediately after `Rc::new`.
730 /// #![feature(get_mut_unchecked)]
734 /// let mut x = Rc::new(String::new());
736 /// Rc::get_mut_unchecked(&mut x).push_str("foo")
738 /// assert_eq!(*x, "foo");
741 #[unstable(feature = "get_mut_unchecked", issue = "63292")]
742 pub unsafe fn get_mut_unchecked(this: &mut Self) -> &mut T {
743 &mut this.ptr.as_mut().value
747 #[stable(feature = "ptr_eq", since = "1.17.0")]
748 /// Returns `true` if the two `Rc`s point to the same value (not
749 /// just values that compare as equal).
756 /// let five = Rc::new(5);
757 /// let same_five = Rc::clone(&five);
758 /// let other_five = Rc::new(5);
760 /// assert!(Rc::ptr_eq(&five, &same_five));
761 /// assert!(!Rc::ptr_eq(&five, &other_five));
763 pub fn ptr_eq(this: &Self, other: &Self) -> bool {
764 this.ptr.as_ptr() == other.ptr.as_ptr()
768 impl<T: Clone> Rc<T> {
769 /// Makes a mutable reference into the given `Rc`.
771 /// If there are other `Rc` pointers to the same value, then `make_mut` will
772 /// [`clone`] the inner value to ensure unique ownership. This is also
773 /// referred to as clone-on-write.
775 /// If there are no other `Rc` pointers to this value, then [`Weak`]
776 /// pointers to this value will be disassociated.
778 /// See also [`get_mut`], which will fail rather than cloning.
780 /// [`Weak`]: struct.Weak.html
781 /// [`clone`]: ../../std/clone/trait.Clone.html#tymethod.clone
782 /// [`get_mut`]: struct.Rc.html#method.get_mut
789 /// let mut data = Rc::new(5);
791 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
792 /// let mut other_data = Rc::clone(&data); // Won't clone inner data
793 /// *Rc::make_mut(&mut data) += 1; // Clones inner data
794 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
795 /// *Rc::make_mut(&mut other_data) *= 2; // Won't clone anything
797 /// // Now `data` and `other_data` point to different values.
798 /// assert_eq!(*data, 8);
799 /// assert_eq!(*other_data, 12);
802 /// [`Weak`] pointers will be disassociated:
807 /// let mut data = Rc::new(75);
808 /// let weak = Rc::downgrade(&data);
810 /// assert!(75 == *data);
811 /// assert!(75 == *weak.upgrade().unwrap());
813 /// *Rc::make_mut(&mut data) += 1;
815 /// assert!(76 == *data);
816 /// assert!(weak.upgrade().is_none());
819 #[stable(feature = "rc_unique", since = "1.4.0")]
820 pub fn make_mut(this: &mut Self) -> &mut T {
821 if Rc::strong_count(this) != 1 {
822 // Gotta clone the data, there are other Rcs
823 *this = Rc::new((**this).clone())
824 } else if Rc::weak_count(this) != 0 {
825 // Can just steal the data, all that's left is Weaks
827 let mut swap = Rc::new(ptr::read(&this.ptr.as_ref().value));
828 mem::swap(this, &mut swap);
830 // Remove implicit strong-weak ref (no need to craft a fake
831 // Weak here -- we know other Weaks can clean up for us)
836 // This unsafety is ok because we're guaranteed that the pointer
837 // returned is the *only* pointer that will ever be returned to T. Our
838 // reference count is guaranteed to be 1 at this point, and we required
839 // the `Rc<T>` itself to be `mut`, so we're returning the only possible
840 // reference to the inner value.
842 &mut this.ptr.as_mut().value
849 #[stable(feature = "rc_downcast", since = "1.29.0")]
850 /// Attempt to downcast the `Rc<dyn Any>` to a concrete type.
855 /// use std::any::Any;
858 /// fn print_if_string(value: Rc<dyn Any>) {
859 /// if let Ok(string) = value.downcast::<String>() {
860 /// println!("String ({}): {}", string.len(), string);
864 /// let my_string = "Hello World".to_string();
865 /// print_if_string(Rc::new(my_string));
866 /// print_if_string(Rc::new(0i8));
868 pub fn downcast<T: Any>(self) -> Result<Rc<T>, Rc<dyn Any>> {
869 if (*self).is::<T>() {
870 let ptr = self.ptr.cast::<RcBox<T>>();
872 Ok(Rc::from_inner(ptr))
879 impl<T: ?Sized> Rc<T> {
880 /// Allocates an `RcBox<T>` with sufficient space for
881 /// a possibly-unsized value where the value has the layout provided.
883 /// The function `mem_to_rcbox` is called with the data pointer
884 /// and must return back a (potentially fat)-pointer for the `RcBox<T>`.
885 unsafe fn allocate_for_layout(
886 value_layout: Layout,
887 mem_to_rcbox: impl FnOnce(*mut u8) -> *mut RcBox<T>
889 // Calculate layout using the given value layout.
890 // Previously, layout was calculated on the expression
891 // `&*(ptr as *const RcBox<T>)`, but this created a misaligned
892 // reference (see #54908).
893 let layout = Layout::new::<RcBox<()>>()
894 .extend(value_layout).unwrap().0
895 .pad_to_align().unwrap();
897 // Allocate for the layout.
898 let mem = Global.alloc(layout)
899 .unwrap_or_else(|_| handle_alloc_error(layout));
901 // Initialize the RcBox
902 let inner = mem_to_rcbox(mem.as_ptr());
903 debug_assert_eq!(Layout::for_value(&*inner), layout);
905 ptr::write(&mut (*inner).strong, Cell::new(1));
906 ptr::write(&mut (*inner).weak, Cell::new(1));
911 /// Allocates an `RcBox<T>` with sufficient space for an unsized value
912 unsafe fn allocate_for_ptr(ptr: *const T) -> *mut RcBox<T> {
913 // Allocate for the `RcBox<T>` using the given value.
914 Self::allocate_for_layout(
915 Layout::for_value(&*ptr),
916 |mem| set_data_ptr(ptr as *mut T, mem) as *mut RcBox<T>,
920 fn from_box(v: Box<T>) -> Rc<T> {
922 let box_unique = Box::into_unique(v);
923 let bptr = box_unique.as_ptr();
925 let value_size = size_of_val(&*bptr);
926 let ptr = Self::allocate_for_ptr(bptr);
928 // Copy value as bytes
929 ptr::copy_nonoverlapping(
930 bptr as *const T as *const u8,
931 &mut (*ptr).value as *mut _ as *mut u8,
934 // Free the allocation without dropping its contents
935 box_free(box_unique);
943 /// Allocates an `RcBox<[T]>` with the given length.
944 unsafe fn allocate_for_slice(len: usize) -> *mut RcBox<[T]> {
945 Self::allocate_for_layout(
946 Layout::array::<T>(len).unwrap(),
947 |mem| ptr::slice_from_raw_parts_mut(mem as *mut T, len) as *mut RcBox<[T]>,
952 /// Sets the data pointer of a `?Sized` raw pointer.
954 /// For a slice/trait object, this sets the `data` field and leaves the rest
955 /// unchanged. For a sized raw pointer, this simply sets the pointer.
956 unsafe fn set_data_ptr<T: ?Sized, U>(mut ptr: *mut T, data: *mut U) -> *mut T {
957 ptr::write(&mut ptr as *mut _ as *mut *mut u8, data as *mut u8);
962 /// Copy elements from slice into newly allocated Rc<[T]>
964 /// Unsafe because the caller must either take ownership or bind `T: Copy`
965 unsafe fn copy_from_slice(v: &[T]) -> Rc<[T]> {
966 let ptr = Self::allocate_for_slice(v.len());
968 ptr::copy_nonoverlapping(
970 &mut (*ptr).value as *mut [T] as *mut T,
976 /// Constructs an `Rc<[T]>` from an iterator known to be of a certain size.
978 /// Behavior is undefined should the size be wrong.
979 unsafe fn from_iter_exact(iter: impl iter::Iterator<Item = T>, len: usize) -> Rc<[T]> {
980 // Panic guard while cloning T elements.
981 // In the event of a panic, elements that have been written
982 // into the new RcBox will be dropped, then the memory freed.
990 impl<T> Drop for Guard<T> {
993 let slice = from_raw_parts_mut(self.elems, self.n_elems);
994 ptr::drop_in_place(slice);
996 Global.dealloc(self.mem, self.layout);
1001 let ptr = Self::allocate_for_slice(len);
1003 let mem = ptr as *mut _ as *mut u8;
1004 let layout = Layout::for_value(&*ptr);
1006 // Pointer to first element
1007 let elems = &mut (*ptr).value as *mut [T] as *mut T;
1009 let mut guard = Guard {
1010 mem: NonNull::new_unchecked(mem),
1016 for (i, item) in iter.enumerate() {
1017 ptr::write(elems.add(i), item);
1021 // All clear. Forget the guard so it doesn't free the new RcBox.
1028 /// Specialization trait used for `From<&[T]>`.
1029 trait RcFromSlice<T> {
1030 fn from_slice(slice: &[T]) -> Self;
1033 impl<T: Clone> RcFromSlice<T> for Rc<[T]> {
1035 default fn from_slice(v: &[T]) -> Self {
1037 Self::from_iter_exact(v.iter().cloned(), v.len())
1042 impl<T: Copy> RcFromSlice<T> for Rc<[T]> {
1044 fn from_slice(v: &[T]) -> Self {
1045 unsafe { Rc::copy_from_slice(v) }
1049 #[stable(feature = "rust1", since = "1.0.0")]
1050 impl<T: ?Sized> Deref for Rc<T> {
1054 fn deref(&self) -> &T {
1059 #[unstable(feature = "receiver_trait", issue = "0")]
1060 impl<T: ?Sized> Receiver for Rc<T> {}
1062 #[stable(feature = "rust1", since = "1.0.0")]
1063 unsafe impl<#[may_dangle] T: ?Sized> Drop for Rc<T> {
1066 /// This will decrement the strong reference count. If the strong reference
1067 /// count reaches zero then the only other references (if any) are
1068 /// [`Weak`], so we `drop` the inner value.
1073 /// use std::rc::Rc;
1077 /// impl Drop for Foo {
1078 /// fn drop(&mut self) {
1079 /// println!("dropped!");
1083 /// let foo = Rc::new(Foo);
1084 /// let foo2 = Rc::clone(&foo);
1086 /// drop(foo); // Doesn't print anything
1087 /// drop(foo2); // Prints "dropped!"
1090 /// [`Weak`]: ../../std/rc/struct.Weak.html
1091 fn drop(&mut self) {
1094 if self.strong() == 0 {
1095 // destroy the contained object
1096 ptr::drop_in_place(self.ptr.as_mut());
1098 // remove the implicit "strong weak" pointer now that we've
1099 // destroyed the contents.
1102 if self.weak() == 0 {
1103 Global.dealloc(self.ptr.cast(), Layout::for_value(self.ptr.as_ref()));
1110 #[stable(feature = "rust1", since = "1.0.0")]
1111 impl<T: ?Sized> Clone for Rc<T> {
1112 /// Makes a clone of the `Rc` pointer.
1114 /// This creates another pointer to the same inner value, increasing the
1115 /// strong reference count.
1120 /// use std::rc::Rc;
1122 /// let five = Rc::new(5);
1124 /// let _ = Rc::clone(&five);
1127 fn clone(&self) -> Rc<T> {
1129 Self::from_inner(self.ptr)
1133 #[stable(feature = "rust1", since = "1.0.0")]
1134 impl<T: Default> Default for Rc<T> {
1135 /// Creates a new `Rc<T>`, with the `Default` value for `T`.
1140 /// use std::rc::Rc;
1142 /// let x: Rc<i32> = Default::default();
1143 /// assert_eq!(*x, 0);
1146 fn default() -> Rc<T> {
1147 Rc::new(Default::default())
1151 #[stable(feature = "rust1", since = "1.0.0")]
1152 trait RcEqIdent<T: ?Sized + PartialEq> {
1153 fn eq(&self, other: &Rc<T>) -> bool;
1154 fn ne(&self, other: &Rc<T>) -> bool;
1157 #[stable(feature = "rust1", since = "1.0.0")]
1158 impl<T: ?Sized + PartialEq> RcEqIdent<T> for Rc<T> {
1160 default fn eq(&self, other: &Rc<T>) -> bool {
1165 default fn ne(&self, other: &Rc<T>) -> bool {
1170 /// We're doing this specialization here, and not as a more general optimization on `&T`, because it
1171 /// would otherwise add a cost to all equality checks on refs. We assume that `Rc`s are used to
1172 /// store large values, that are slow to clone, but also heavy to check for equality, causing this
1173 /// cost to pay off more easily. It's also more likely to have two `Rc` clones, that point to
1174 /// the same value, than two `&T`s.
1175 #[stable(feature = "rust1", since = "1.0.0")]
1176 impl<T: ?Sized + Eq> RcEqIdent<T> for Rc<T> {
1178 fn eq(&self, other: &Rc<T>) -> bool {
1179 Rc::ptr_eq(self, other) || **self == **other
1183 fn ne(&self, other: &Rc<T>) -> bool {
1184 !Rc::ptr_eq(self, other) && **self != **other
1188 #[stable(feature = "rust1", since = "1.0.0")]
1189 impl<T: ?Sized + PartialEq> PartialEq for Rc<T> {
1190 /// Equality for two `Rc`s.
1192 /// Two `Rc`s are equal if their inner values are equal.
1194 /// If `T` also implements `Eq`, two `Rc`s that point to the same value are
1200 /// use std::rc::Rc;
1202 /// let five = Rc::new(5);
1204 /// assert!(five == Rc::new(5));
1207 fn eq(&self, other: &Rc<T>) -> bool {
1208 RcEqIdent::eq(self, other)
1211 /// Inequality for two `Rc`s.
1213 /// Two `Rc`s are unequal if their inner values are unequal.
1215 /// If `T` also implements `Eq`, two `Rc`s that point to the same value are
1221 /// use std::rc::Rc;
1223 /// let five = Rc::new(5);
1225 /// assert!(five != Rc::new(6));
1228 fn ne(&self, other: &Rc<T>) -> bool {
1229 RcEqIdent::ne(self, other)
1233 #[stable(feature = "rust1", since = "1.0.0")]
1234 impl<T: ?Sized + Eq> Eq for Rc<T> {}
1236 #[stable(feature = "rust1", since = "1.0.0")]
1237 impl<T: ?Sized + PartialOrd> PartialOrd for Rc<T> {
1238 /// Partial comparison for two `Rc`s.
1240 /// The two are compared by calling `partial_cmp()` on their inner values.
1245 /// use std::rc::Rc;
1246 /// use std::cmp::Ordering;
1248 /// let five = Rc::new(5);
1250 /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&Rc::new(6)));
1253 fn partial_cmp(&self, other: &Rc<T>) -> Option<Ordering> {
1254 (**self).partial_cmp(&**other)
1257 /// Less-than comparison for two `Rc`s.
1259 /// The two are compared by calling `<` on their inner values.
1264 /// use std::rc::Rc;
1266 /// let five = Rc::new(5);
1268 /// assert!(five < Rc::new(6));
1271 fn lt(&self, other: &Rc<T>) -> bool {
1275 /// 'Less than or equal to' comparison for two `Rc`s.
1277 /// The two are compared by calling `<=` on their inner values.
1282 /// use std::rc::Rc;
1284 /// let five = Rc::new(5);
1286 /// assert!(five <= Rc::new(5));
1289 fn le(&self, other: &Rc<T>) -> bool {
1293 /// Greater-than comparison for two `Rc`s.
1295 /// The two are compared by calling `>` on their inner values.
1300 /// use std::rc::Rc;
1302 /// let five = Rc::new(5);
1304 /// assert!(five > Rc::new(4));
1307 fn gt(&self, other: &Rc<T>) -> bool {
1311 /// 'Greater than or equal to' comparison for two `Rc`s.
1313 /// The two are compared by calling `>=` on their inner values.
1318 /// use std::rc::Rc;
1320 /// let five = Rc::new(5);
1322 /// assert!(five >= Rc::new(5));
1325 fn ge(&self, other: &Rc<T>) -> bool {
1330 #[stable(feature = "rust1", since = "1.0.0")]
1331 impl<T: ?Sized + Ord> Ord for Rc<T> {
1332 /// Comparison for two `Rc`s.
1334 /// The two are compared by calling `cmp()` on their inner values.
1339 /// use std::rc::Rc;
1340 /// use std::cmp::Ordering;
1342 /// let five = Rc::new(5);
1344 /// assert_eq!(Ordering::Less, five.cmp(&Rc::new(6)));
1347 fn cmp(&self, other: &Rc<T>) -> Ordering {
1348 (**self).cmp(&**other)
1352 #[stable(feature = "rust1", since = "1.0.0")]
1353 impl<T: ?Sized + Hash> Hash for Rc<T> {
1354 fn hash<H: Hasher>(&self, state: &mut H) {
1355 (**self).hash(state);
1359 #[stable(feature = "rust1", since = "1.0.0")]
1360 impl<T: ?Sized + fmt::Display> fmt::Display for Rc<T> {
1361 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1362 fmt::Display::fmt(&**self, f)
1366 #[stable(feature = "rust1", since = "1.0.0")]
1367 impl<T: ?Sized + fmt::Debug> fmt::Debug for Rc<T> {
1368 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1369 fmt::Debug::fmt(&**self, f)
1373 #[stable(feature = "rust1", since = "1.0.0")]
1374 impl<T: ?Sized> fmt::Pointer for Rc<T> {
1375 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1376 fmt::Pointer::fmt(&(&**self as *const T), f)
1380 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
1381 impl<T> From<T> for Rc<T> {
1382 fn from(t: T) -> Self {
1387 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1388 impl<T: Clone> From<&[T]> for Rc<[T]> {
1390 fn from(v: &[T]) -> Rc<[T]> {
1391 <Self as RcFromSlice<T>>::from_slice(v)
1395 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1396 impl From<&str> for Rc<str> {
1398 fn from(v: &str) -> Rc<str> {
1399 let rc = Rc::<[u8]>::from(v.as_bytes());
1400 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const str) }
1404 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1405 impl From<String> for Rc<str> {
1407 fn from(v: String) -> Rc<str> {
1412 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1413 impl<T: ?Sized> From<Box<T>> for Rc<T> {
1415 fn from(v: Box<T>) -> Rc<T> {
1420 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1421 impl<T> From<Vec<T>> for Rc<[T]> {
1423 fn from(mut v: Vec<T>) -> Rc<[T]> {
1425 let rc = Rc::copy_from_slice(&v);
1427 // Allow the Vec to free its memory, but not destroy its contents
1435 #[unstable(feature = "boxed_slice_try_from", issue = "0")]
1436 impl<T, const N: usize> TryFrom<Rc<[T]>> for Rc<[T; N]>
1438 [T; N]: LengthAtMost32,
1440 type Error = Rc<[T]>;
1442 fn try_from(boxed_slice: Rc<[T]>) -> Result<Self, Self::Error> {
1443 if boxed_slice.len() == N {
1444 Ok(unsafe { Rc::from_raw(Rc::into_raw(boxed_slice) as *mut [T; N]) })
1451 #[stable(feature = "shared_from_iter", since = "1.37.0")]
1452 impl<T> iter::FromIterator<T> for Rc<[T]> {
1453 /// Takes each element in the `Iterator` and collects it into an `Rc<[T]>`.
1455 /// # Performance characteristics
1457 /// ## The general case
1459 /// In the general case, collecting into `Rc<[T]>` is done by first
1460 /// collecting into a `Vec<T>`. That is, when writing the following:
1463 /// # use std::rc::Rc;
1464 /// let evens: Rc<[u8]> = (0..10).filter(|&x| x % 2 == 0).collect();
1465 /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]);
1468 /// this behaves as if we wrote:
1471 /// # use std::rc::Rc;
1472 /// let evens: Rc<[u8]> = (0..10).filter(|&x| x % 2 == 0)
1473 /// .collect::<Vec<_>>() // The first set of allocations happens here.
1474 /// .into(); // A second allocation for `Rc<[T]>` happens here.
1475 /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]);
1478 /// This will allocate as many times as needed for constructing the `Vec<T>`
1479 /// and then it will allocate once for turning the `Vec<T>` into the `Rc<[T]>`.
1481 /// ## Iterators of known length
1483 /// When your `Iterator` implements `TrustedLen` and is of an exact size,
1484 /// a single allocation will be made for the `Rc<[T]>`. For example:
1487 /// # use std::rc::Rc;
1488 /// let evens: Rc<[u8]> = (0..10).collect(); // Just a single allocation happens here.
1489 /// # assert_eq!(&*evens, &*(0..10).collect::<Vec<_>>());
1491 fn from_iter<I: iter::IntoIterator<Item = T>>(iter: I) -> Self {
1492 RcFromIter::from_iter(iter.into_iter())
1496 /// Specialization trait used for collecting into `Rc<[T]>`.
1497 trait RcFromIter<T, I> {
1498 fn from_iter(iter: I) -> Self;
1501 impl<T, I: Iterator<Item = T>> RcFromIter<T, I> for Rc<[T]> {
1502 default fn from_iter(iter: I) -> Self {
1503 iter.collect::<Vec<T>>().into()
1507 impl<T, I: iter::TrustedLen<Item = T>> RcFromIter<T, I> for Rc<[T]> {
1508 default fn from_iter(iter: I) -> Self {
1509 // This is the case for a `TrustedLen` iterator.
1510 let (low, high) = iter.size_hint();
1511 if let Some(high) = high {
1514 "TrustedLen iterator's size hint is not exact: {:?}",
1519 // SAFETY: We need to ensure that the iterator has an exact length and we have.
1520 Rc::from_iter_exact(iter, low)
1523 // Fall back to normal implementation.
1524 iter.collect::<Vec<T>>().into()
1529 impl<'a, T: 'a + Clone> RcFromIter<&'a T, slice::Iter<'a, T>> for Rc<[T]> {
1530 fn from_iter(iter: slice::Iter<'a, T>) -> Self {
1531 // Delegate to `impl<T: Clone> From<&[T]> for Rc<[T]>`.
1533 // In the case that `T: Copy`, we get to use `ptr::copy_nonoverlapping`
1534 // which is even more performant.
1536 // In the fall-back case we have `T: Clone`. This is still better
1537 // than the `TrustedLen` implementation as slices have a known length
1538 // and so we get to avoid calling `size_hint` and avoid the branching.
1539 iter.as_slice().into()
1543 /// `Weak` is a version of [`Rc`] that holds a non-owning reference to the
1544 /// managed value. The value is accessed by calling [`upgrade`] on the `Weak`
1545 /// pointer, which returns an [`Option`]`<`[`Rc`]`<T>>`.
1547 /// Since a `Weak` reference does not count towards ownership, it will not
1548 /// prevent the inner value from being dropped, and `Weak` itself makes no
1549 /// guarantees about the value still being present and may return [`None`]
1550 /// when [`upgrade`]d.
1552 /// A `Weak` pointer is useful for keeping a temporary reference to the value
1553 /// within [`Rc`] without extending its lifetime. It is also used to prevent
1554 /// circular references between [`Rc`] pointers, since mutual owning references
1555 /// would never allow either [`Rc`] to be dropped. For example, a tree could
1556 /// have strong [`Rc`] pointers from parent nodes to children, and `Weak`
1557 /// pointers from children back to their parents.
1559 /// The typical way to obtain a `Weak` pointer is to call [`Rc::downgrade`].
1561 /// [`Rc`]: struct.Rc.html
1562 /// [`Rc::downgrade`]: struct.Rc.html#method.downgrade
1563 /// [`upgrade`]: struct.Weak.html#method.upgrade
1564 /// [`Option`]: ../../std/option/enum.Option.html
1565 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1566 #[stable(feature = "rc_weak", since = "1.4.0")]
1567 pub struct Weak<T: ?Sized> {
1568 // This is a `NonNull` to allow optimizing the size of this type in enums,
1569 // but it is not necessarily a valid pointer.
1570 // `Weak::new` sets this to `usize::MAX` so that it doesn’t need
1571 // to allocate space on the heap. That's not a value a real pointer
1572 // will ever have because RcBox has alignment at least 2.
1573 ptr: NonNull<RcBox<T>>,
1576 #[stable(feature = "rc_weak", since = "1.4.0")]
1577 impl<T: ?Sized> !marker::Send for Weak<T> {}
1578 #[stable(feature = "rc_weak", since = "1.4.0")]
1579 impl<T: ?Sized> !marker::Sync for Weak<T> {}
1581 #[unstable(feature = "coerce_unsized", issue = "27732")]
1582 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {}
1584 #[unstable(feature = "dispatch_from_dyn", issue = "0")]
1585 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Weak<U>> for Weak<T> {}
1588 /// Constructs a new `Weak<T>`, without allocating any memory.
1589 /// Calling [`upgrade`] on the return value always gives [`None`].
1591 /// [`upgrade`]: #method.upgrade
1592 /// [`None`]: ../../std/option/enum.Option.html
1597 /// use std::rc::Weak;
1599 /// let empty: Weak<i64> = Weak::new();
1600 /// assert!(empty.upgrade().is_none());
1602 #[stable(feature = "downgraded_weak", since = "1.10.0")]
1603 pub fn new() -> Weak<T> {
1605 ptr: NonNull::new(usize::MAX as *mut RcBox<T>).expect("MAX is not 0"),
1609 /// Returns a raw pointer to the object `T` pointed to by this `Weak<T>`.
1611 /// It is up to the caller to ensure that the object is still alive when accessing it through
1614 /// The pointer may be [`null`] or be dangling in case the object has already been destroyed.
1619 /// #![feature(weak_into_raw)]
1621 /// use std::rc::Rc;
1624 /// let strong = Rc::new("hello".to_owned());
1625 /// let weak = Rc::downgrade(&strong);
1626 /// // Both point to the same object
1627 /// assert!(ptr::eq(&*strong, weak.as_raw()));
1628 /// // The strong here keeps it alive, so we can still access the object.
1629 /// assert_eq!("hello", unsafe { &*weak.as_raw() });
1632 /// // But not any more. We can do weak.as_raw(), but accessing the pointer would lead to
1633 /// // undefined behaviour.
1634 /// // assert_eq!("hello", unsafe { &*weak.as_raw() });
1637 /// [`null`]: ../../std/ptr/fn.null.html
1638 #[unstable(feature = "weak_into_raw", issue = "60728")]
1639 pub fn as_raw(&self) -> *const T {
1640 match self.inner() {
1641 None => ptr::null(),
1643 let offset = data_offset_sized::<T>();
1644 let ptr = inner as *const RcBox<T>;
1645 // Note: while the pointer we create may already point to dropped value, the
1646 // allocation still lives (it must hold the weak point as long as we are alive).
1647 // Therefore, the offset is OK to do, it won't get out of the allocation.
1648 let ptr = unsafe { (ptr as *const u8).offset(offset) };
1654 /// Consumes the `Weak<T>` and turns it into a raw pointer.
1656 /// This converts the weak pointer into a raw pointer, preserving the original weak count. It
1657 /// can be turned back into the `Weak<T>` with [`from_raw`].
1659 /// The same restrictions of accessing the target of the pointer as with
1660 /// [`as_raw`] apply.
1665 /// #![feature(weak_into_raw)]
1667 /// use std::rc::{Rc, Weak};
1669 /// let strong = Rc::new("hello".to_owned());
1670 /// let weak = Rc::downgrade(&strong);
1671 /// let raw = weak.into_raw();
1673 /// assert_eq!(1, Rc::weak_count(&strong));
1674 /// assert_eq!("hello", unsafe { &*raw });
1676 /// drop(unsafe { Weak::from_raw(raw) });
1677 /// assert_eq!(0, Rc::weak_count(&strong));
1680 /// [`from_raw`]: struct.Weak.html#method.from_raw
1681 /// [`as_raw`]: struct.Weak.html#method.as_raw
1682 #[unstable(feature = "weak_into_raw", issue = "60728")]
1683 pub fn into_raw(self) -> *const T {
1684 let result = self.as_raw();
1689 /// Converts a raw pointer previously created by [`into_raw`] back into `Weak<T>`.
1691 /// This can be used to safely get a strong reference (by calling [`upgrade`]
1692 /// later) or to deallocate the weak count by dropping the `Weak<T>`.
1694 /// It takes ownership of one weak count. In case a [`null`] is passed, a dangling [`Weak`] is
1699 /// The pointer must represent one valid weak count. In other words, it must point to `T` which
1700 /// is or *was* managed by an [`Rc`] and the weak count of that [`Rc`] must not have reached
1701 /// 0. It is allowed for the strong count to be 0.
1706 /// #![feature(weak_into_raw)]
1708 /// use std::rc::{Rc, Weak};
1710 /// let strong = Rc::new("hello".to_owned());
1712 /// let raw_1 = Rc::downgrade(&strong).into_raw();
1713 /// let raw_2 = Rc::downgrade(&strong).into_raw();
1715 /// assert_eq!(2, Rc::weak_count(&strong));
1717 /// assert_eq!("hello", &*unsafe { Weak::from_raw(raw_1) }.upgrade().unwrap());
1718 /// assert_eq!(1, Rc::weak_count(&strong));
1722 /// // Decrement the last weak count.
1723 /// assert!(unsafe { Weak::from_raw(raw_2) }.upgrade().is_none());
1726 /// [`null`]: ../../std/ptr/fn.null.html
1727 /// [`into_raw`]: struct.Weak.html#method.into_raw
1728 /// [`upgrade`]: struct.Weak.html#method.upgrade
1729 /// [`Rc`]: struct.Rc.html
1730 /// [`Weak`]: struct.Weak.html
1731 #[unstable(feature = "weak_into_raw", issue = "60728")]
1732 pub unsafe fn from_raw(ptr: *const T) -> Self {
1736 // See Rc::from_raw for details
1737 let offset = data_offset(ptr);
1738 let fake_ptr = ptr as *mut RcBox<T>;
1739 let ptr = set_data_ptr(fake_ptr, (ptr as *mut u8).offset(-offset));
1741 ptr: NonNull::new(ptr).expect("Invalid pointer passed to from_raw"),
1747 pub(crate) fn is_dangling<T: ?Sized>(ptr: NonNull<T>) -> bool {
1748 let address = ptr.as_ptr() as *mut () as usize;
1749 address == usize::MAX
1752 impl<T: ?Sized> Weak<T> {
1753 /// Attempts to upgrade the `Weak` pointer to an [`Rc`], extending
1754 /// the lifetime of the value if successful.
1756 /// Returns [`None`] if the value has since been dropped.
1758 /// [`Rc`]: struct.Rc.html
1759 /// [`None`]: ../../std/option/enum.Option.html
1764 /// use std::rc::Rc;
1766 /// let five = Rc::new(5);
1768 /// let weak_five = Rc::downgrade(&five);
1770 /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
1771 /// assert!(strong_five.is_some());
1773 /// // Destroy all strong pointers.
1774 /// drop(strong_five);
1777 /// assert!(weak_five.upgrade().is_none());
1779 #[stable(feature = "rc_weak", since = "1.4.0")]
1780 pub fn upgrade(&self) -> Option<Rc<T>> {
1781 let inner = self.inner()?;
1782 if inner.strong() == 0 {
1786 Some(Rc::from_inner(self.ptr))
1790 /// Gets the number of strong (`Rc`) pointers pointing to this value.
1792 /// If `self` was created using [`Weak::new`], this will return 0.
1794 /// [`Weak::new`]: #method.new
1795 #[unstable(feature = "weak_counts", issue = "57977")]
1796 pub fn strong_count(&self) -> usize {
1797 if let Some(inner) = self.inner() {
1804 /// Gets the number of `Weak` pointers pointing to this value.
1806 /// If `self` was created using [`Weak::new`], this will return `None`. If
1807 /// not, the returned value is at least 1, since `self` still points to the
1810 /// [`Weak::new`]: #method.new
1811 #[unstable(feature = "weak_counts", issue = "57977")]
1812 pub fn weak_count(&self) -> Option<usize> {
1813 self.inner().map(|inner| {
1814 if inner.strong() > 0 {
1815 inner.weak() - 1 // subtract the implicit weak ptr
1822 /// Returns `None` when the pointer is dangling and there is no allocated `RcBox`
1823 /// (i.e., when this `Weak` was created by `Weak::new`).
1825 fn inner(&self) -> Option<&RcBox<T>> {
1826 if is_dangling(self.ptr) {
1829 Some(unsafe { self.ptr.as_ref() })
1833 /// Returns `true` if the two `Weak`s point to the same value (not just
1834 /// values that compare as equal), or if both don't point to any value
1835 /// (because they were created with `Weak::new()`).
1839 /// Since this compares pointers it means that `Weak::new()` will equal each
1840 /// other, even though they don't point to any value.
1845 /// use std::rc::Rc;
1847 /// let first_rc = Rc::new(5);
1848 /// let first = Rc::downgrade(&first_rc);
1849 /// let second = Rc::downgrade(&first_rc);
1851 /// assert!(first.ptr_eq(&second));
1853 /// let third_rc = Rc::new(5);
1854 /// let third = Rc::downgrade(&third_rc);
1856 /// assert!(!first.ptr_eq(&third));
1859 /// Comparing `Weak::new`.
1862 /// use std::rc::{Rc, Weak};
1864 /// let first = Weak::new();
1865 /// let second = Weak::new();
1866 /// assert!(first.ptr_eq(&second));
1868 /// let third_rc = Rc::new(());
1869 /// let third = Rc::downgrade(&third_rc);
1870 /// assert!(!first.ptr_eq(&third));
1873 #[stable(feature = "weak_ptr_eq", since = "1.39.0")]
1874 pub fn ptr_eq(&self, other: &Self) -> bool {
1875 self.ptr.as_ptr() == other.ptr.as_ptr()
1879 #[stable(feature = "rc_weak", since = "1.4.0")]
1880 impl<T: ?Sized> Drop for Weak<T> {
1881 /// Drops the `Weak` pointer.
1886 /// use std::rc::{Rc, Weak};
1890 /// impl Drop for Foo {
1891 /// fn drop(&mut self) {
1892 /// println!("dropped!");
1896 /// let foo = Rc::new(Foo);
1897 /// let weak_foo = Rc::downgrade(&foo);
1898 /// let other_weak_foo = Weak::clone(&weak_foo);
1900 /// drop(weak_foo); // Doesn't print anything
1901 /// drop(foo); // Prints "dropped!"
1903 /// assert!(other_weak_foo.upgrade().is_none());
1905 fn drop(&mut self) {
1906 if let Some(inner) = self.inner() {
1908 // the weak count starts at 1, and will only go to zero if all
1909 // the strong pointers have disappeared.
1910 if inner.weak() == 0 {
1912 Global.dealloc(self.ptr.cast(), Layout::for_value(self.ptr.as_ref()));
1919 #[stable(feature = "rc_weak", since = "1.4.0")]
1920 impl<T: ?Sized> Clone for Weak<T> {
1921 /// Makes a clone of the `Weak` pointer that points to the same value.
1926 /// use std::rc::{Rc, Weak};
1928 /// let weak_five = Rc::downgrade(&Rc::new(5));
1930 /// let _ = Weak::clone(&weak_five);
1933 fn clone(&self) -> Weak<T> {
1934 if let Some(inner) = self.inner() {
1937 Weak { ptr: self.ptr }
1941 #[stable(feature = "rc_weak", since = "1.4.0")]
1942 impl<T: ?Sized + fmt::Debug> fmt::Debug for Weak<T> {
1943 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1948 #[stable(feature = "downgraded_weak", since = "1.10.0")]
1949 impl<T> Default for Weak<T> {
1950 /// Constructs a new `Weak<T>`, allocating memory for `T` without initializing
1951 /// it. Calling [`upgrade`] on the return value always gives [`None`].
1953 /// [`None`]: ../../std/option/enum.Option.html
1954 /// [`upgrade`]: ../../std/rc/struct.Weak.html#method.upgrade
1959 /// use std::rc::Weak;
1961 /// let empty: Weak<i64> = Default::default();
1962 /// assert!(empty.upgrade().is_none());
1964 fn default() -> Weak<T> {
1969 // NOTE: We checked_add here to deal with mem::forget safely. In particular
1970 // if you mem::forget Rcs (or Weaks), the ref-count can overflow, and then
1971 // you can free the allocation while outstanding Rcs (or Weaks) exist.
1972 // We abort because this is such a degenerate scenario that we don't care about
1973 // what happens -- no real program should ever experience this.
1975 // This should have negligible overhead since you don't actually need to
1976 // clone these much in Rust thanks to ownership and move-semantics.
1979 trait RcBoxPtr<T: ?Sized> {
1980 fn inner(&self) -> &RcBox<T>;
1983 fn strong(&self) -> usize {
1984 self.inner().strong.get()
1988 fn inc_strong(&self) {
1989 let strong = self.strong();
1991 // We want to abort on overflow instead of dropping the value.
1992 // The reference count will never be zero when this is called;
1993 // nevertheless, we insert an abort here to hint LLVM at
1994 // an otherwise missed optimization.
1995 if strong == 0 || strong == usize::max_value() {
1998 self.inner().strong.set(strong + 1);
2002 fn dec_strong(&self) {
2003 self.inner().strong.set(self.strong() - 1);
2007 fn weak(&self) -> usize {
2008 self.inner().weak.get()
2012 fn inc_weak(&self) {
2013 let weak = self.weak();
2015 // We want to abort on overflow instead of dropping the value.
2016 // The reference count will never be zero when this is called;
2017 // nevertheless, we insert an abort here to hint LLVM at
2018 // an otherwise missed optimization.
2019 if weak == 0 || weak == usize::max_value() {
2022 self.inner().weak.set(weak + 1);
2026 fn dec_weak(&self) {
2027 self.inner().weak.set(self.weak() - 1);
2031 impl<T: ?Sized> RcBoxPtr<T> for Rc<T> {
2033 fn inner(&self) -> &RcBox<T> {
2040 impl<T: ?Sized> RcBoxPtr<T> for RcBox<T> {
2042 fn inner(&self) -> &RcBox<T> {
2047 #[stable(feature = "rust1", since = "1.0.0")]
2048 impl<T: ?Sized> borrow::Borrow<T> for Rc<T> {
2049 fn borrow(&self) -> &T {
2054 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
2055 impl<T: ?Sized> AsRef<T> for Rc<T> {
2056 fn as_ref(&self) -> &T {
2061 #[stable(feature = "pin", since = "1.33.0")]
2062 impl<T: ?Sized> Unpin for Rc<T> { }
2064 unsafe fn data_offset<T: ?Sized>(ptr: *const T) -> isize {
2065 // Align the unsized value to the end of the `RcBox`.
2066 // Because it is ?Sized, it will always be the last field in memory.
2067 data_offset_align(align_of_val(&*ptr))
2070 /// Computes the offset of the data field within `RcBox`.
2072 /// Unlike [`data_offset`], this doesn't need the pointer, but it works only on `T: Sized`.
2073 fn data_offset_sized<T>() -> isize {
2074 data_offset_align(align_of::<T>())
2078 fn data_offset_align(align: usize) -> isize {
2079 let layout = Layout::new::<RcBox<()>>();
2080 (layout.size() + layout.padding_needed_for(align)) as isize