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 /// Construct 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>> {
353 let layout = Layout::new::<RcBox<mem::MaybeUninit<T>>>();
355 let mut ptr = Global.alloc(layout)
356 .unwrap_or_else(|_| handle_alloc_error(layout))
357 .cast::<RcBox<mem::MaybeUninit<T>>>();
358 ptr::write(&mut ptr.as_mut().strong, Cell::new(1));
359 ptr::write(&mut ptr.as_mut().weak, Cell::new(1));
362 phantom: PhantomData,
367 /// Constructs a new `Pin<Rc<T>>`. If `T` does not implement `Unpin`, then
368 /// `value` will be pinned in memory and unable to be moved.
369 #[stable(feature = "pin", since = "1.33.0")]
370 pub fn pin(value: T) -> Pin<Rc<T>> {
371 unsafe { Pin::new_unchecked(Rc::new(value)) }
374 /// Returns the contained value, if the `Rc` has exactly one strong reference.
376 /// Otherwise, an [`Err`][result] is returned with the same `Rc` that was
379 /// This will succeed even if there are outstanding weak references.
381 /// [result]: ../../std/result/enum.Result.html
388 /// let x = Rc::new(3);
389 /// assert_eq!(Rc::try_unwrap(x), Ok(3));
391 /// let x = Rc::new(4);
392 /// let _y = Rc::clone(&x);
393 /// assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4);
396 #[stable(feature = "rc_unique", since = "1.4.0")]
397 pub fn try_unwrap(this: Self) -> Result<T, Self> {
398 if Rc::strong_count(&this) == 1 {
400 let val = ptr::read(&*this); // copy the contained object
402 // Indicate to Weaks that they can't be promoted by decrementing
403 // the strong count, and then remove the implicit "strong weak"
404 // pointer while also handling drop logic by just crafting a
407 let _weak = Weak { ptr: this.ptr };
418 /// Construct a new reference-counted slice with uninitialized contents.
423 /// #![feature(new_uninit)]
424 /// #![feature(get_mut_unchecked)]
428 /// let mut values = Rc::<[u32]>::new_uninit_slice(3);
430 /// let values = unsafe {
431 /// // Deferred initialization:
432 /// Rc::get_mut_unchecked(&mut values)[0].as_mut_ptr().write(1);
433 /// Rc::get_mut_unchecked(&mut values)[1].as_mut_ptr().write(2);
434 /// Rc::get_mut_unchecked(&mut values)[2].as_mut_ptr().write(3);
436 /// values.assume_init()
439 /// assert_eq!(*values, [1, 2, 3])
441 #[unstable(feature = "new_uninit", issue = "63291")]
442 pub fn new_uninit_slice(len: usize) -> Rc<[mem::MaybeUninit<T>]> {
443 let data_layout = Layout::array::<mem::MaybeUninit<T>>(len).unwrap();
444 let (layout, offset) = Layout::new::<RcBox<()>>().extend(data_layout).unwrap();
446 let allocated_ptr = Global.alloc(layout)
447 .unwrap_or_else(|_| handle_alloc_error(layout))
449 let data_ptr = allocated_ptr.add(offset) as *mut mem::MaybeUninit<T>;
450 let slice: *mut [mem::MaybeUninit<T>] = from_raw_parts_mut(data_ptr, len);
451 let wide_ptr = slice as *mut RcBox<[mem::MaybeUninit<T>]>;
452 let wide_ptr = set_data_ptr(wide_ptr, allocated_ptr);
453 ptr::write(&mut (*wide_ptr).strong, Cell::new(1));
454 ptr::write(&mut (*wide_ptr).weak, Cell::new(1));
456 ptr: NonNull::new_unchecked(wide_ptr),
457 phantom: PhantomData,
463 impl<T> Rc<mem::MaybeUninit<T>> {
464 /// Convert to `Rc<T>`.
468 /// As with [`MaybeUninit::assume_init`],
469 /// it is up to the caller to guarantee that the value
470 /// really is in an initialized state.
471 /// Calling this when the content is not yet fully initialized
472 /// causes immediate undefined behavior.
474 /// [`MaybeUninit::assume_init`]: ../../std/mem/union.MaybeUninit.html#method.assume_init
479 /// #![feature(new_uninit)]
480 /// #![feature(get_mut_unchecked)]
484 /// let mut five = Rc::<u32>::new_uninit();
486 /// let five = unsafe {
487 /// // Deferred initialization:
488 /// Rc::get_mut_unchecked(&mut five).as_mut_ptr().write(5);
490 /// five.assume_init()
493 /// assert_eq!(*five, 5)
495 #[unstable(feature = "new_uninit", issue = "63291")]
497 pub unsafe fn assume_init(self) -> Rc<T> {
499 ptr: mem::ManuallyDrop::new(self).ptr.cast(),
500 phantom: PhantomData,
505 impl<T> Rc<[mem::MaybeUninit<T>]> {
506 /// Convert to `Rc<[T]>`.
510 /// As with [`MaybeUninit::assume_init`],
511 /// it is up to the caller to guarantee that the value
512 /// really is in an initialized state.
513 /// Calling this when the content is not yet fully initialized
514 /// causes immediate undefined behavior.
516 /// [`MaybeUninit::assume_init`]: ../../std/mem/union.MaybeUninit.html#method.assume_init
521 /// #![feature(new_uninit)]
522 /// #![feature(get_mut_unchecked)]
526 /// let mut values = Rc::<[u32]>::new_uninit_slice(3);
528 /// let values = unsafe {
529 /// // Deferred initialization:
530 /// Rc::get_mut_unchecked(&mut values)[0].as_mut_ptr().write(1);
531 /// Rc::get_mut_unchecked(&mut values)[1].as_mut_ptr().write(2);
532 /// Rc::get_mut_unchecked(&mut values)[2].as_mut_ptr().write(3);
534 /// values.assume_init()
537 /// assert_eq!(*values, [1, 2, 3])
539 #[unstable(feature = "new_uninit", issue = "63291")]
541 pub unsafe fn assume_init(self) -> Rc<[T]> {
543 ptr: NonNull::new_unchecked(mem::ManuallyDrop::new(self).ptr.as_ptr() as _),
544 phantom: PhantomData,
549 impl<T: ?Sized> Rc<T> {
550 /// Consumes the `Rc`, returning the wrapped pointer.
552 /// To avoid a memory leak the pointer must be converted back to an `Rc` using
553 /// [`Rc::from_raw`][from_raw].
555 /// [from_raw]: struct.Rc.html#method.from_raw
562 /// let x = Rc::new("hello".to_owned());
563 /// let x_ptr = Rc::into_raw(x);
564 /// assert_eq!(unsafe { &*x_ptr }, "hello");
566 #[stable(feature = "rc_raw", since = "1.17.0")]
567 pub fn into_raw(this: Self) -> *const T {
568 let ptr: *const T = &*this;
573 /// Constructs an `Rc` from a raw pointer.
575 /// The raw pointer must have been previously returned by a call to a
576 /// [`Rc::into_raw`][into_raw].
578 /// This function is unsafe because improper use may lead to memory problems. For example, a
579 /// double-free may occur if the function is called twice on the same raw pointer.
581 /// [into_raw]: struct.Rc.html#method.into_raw
588 /// let x = Rc::new("hello".to_owned());
589 /// let x_ptr = Rc::into_raw(x);
592 /// // Convert back to an `Rc` to prevent leak.
593 /// let x = Rc::from_raw(x_ptr);
594 /// assert_eq!(&*x, "hello");
596 /// // Further calls to `Rc::from_raw(x_ptr)` would be memory unsafe.
599 /// // The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling!
601 #[stable(feature = "rc_raw", since = "1.17.0")]
602 pub unsafe fn from_raw(ptr: *const T) -> Self {
603 let offset = data_offset(ptr);
605 // Reverse the offset to find the original RcBox.
606 let fake_ptr = ptr as *mut RcBox<T>;
607 let rc_ptr = set_data_ptr(fake_ptr, (ptr as *mut u8).offset(-offset));
609 Self::from_ptr(rc_ptr)
612 /// Consumes the `Rc`, returning the wrapped pointer as `NonNull<T>`.
617 /// #![feature(rc_into_raw_non_null)]
621 /// let x = Rc::new("hello".to_owned());
622 /// let ptr = Rc::into_raw_non_null(x);
623 /// let deref = unsafe { ptr.as_ref() };
624 /// assert_eq!(deref, "hello");
626 #[unstable(feature = "rc_into_raw_non_null", issue = "47336")]
628 pub fn into_raw_non_null(this: Self) -> NonNull<T> {
629 // safe because Rc guarantees its pointer is non-null
630 unsafe { NonNull::new_unchecked(Rc::into_raw(this) as *mut _) }
633 /// Creates a new [`Weak`][weak] pointer to this value.
635 /// [weak]: struct.Weak.html
642 /// let five = Rc::new(5);
644 /// let weak_five = Rc::downgrade(&five);
646 #[stable(feature = "rc_weak", since = "1.4.0")]
647 pub fn downgrade(this: &Self) -> Weak<T> {
649 // Make sure we do not create a dangling Weak
650 debug_assert!(!is_dangling(this.ptr));
651 Weak { ptr: this.ptr }
654 /// Gets the number of [`Weak`][weak] pointers to this value.
656 /// [weak]: struct.Weak.html
663 /// let five = Rc::new(5);
664 /// let _weak_five = Rc::downgrade(&five);
666 /// assert_eq!(1, Rc::weak_count(&five));
669 #[stable(feature = "rc_counts", since = "1.15.0")]
670 pub fn weak_count(this: &Self) -> usize {
674 /// Gets the number of strong (`Rc`) pointers to this value.
681 /// let five = Rc::new(5);
682 /// let _also_five = Rc::clone(&five);
684 /// assert_eq!(2, Rc::strong_count(&five));
687 #[stable(feature = "rc_counts", since = "1.15.0")]
688 pub fn strong_count(this: &Self) -> usize {
692 /// Returns `true` if there are no other `Rc` or [`Weak`][weak] pointers to
693 /// this inner value.
695 /// [weak]: struct.Weak.html
697 fn is_unique(this: &Self) -> bool {
698 Rc::weak_count(this) == 0 && Rc::strong_count(this) == 1
701 /// Returns a mutable reference to the inner value, if there are
702 /// no other `Rc` or [`Weak`][weak] pointers to the same value.
704 /// Returns [`None`] otherwise, because it is not safe to
705 /// mutate a shared value.
707 /// See also [`make_mut`][make_mut], which will [`clone`][clone]
708 /// the inner value when it's shared.
710 /// [weak]: struct.Weak.html
711 /// [`None`]: ../../std/option/enum.Option.html#variant.None
712 /// [make_mut]: struct.Rc.html#method.make_mut
713 /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
720 /// let mut x = Rc::new(3);
721 /// *Rc::get_mut(&mut x).unwrap() = 4;
722 /// assert_eq!(*x, 4);
724 /// let _y = Rc::clone(&x);
725 /// assert!(Rc::get_mut(&mut x).is_none());
728 #[stable(feature = "rc_unique", since = "1.4.0")]
729 pub fn get_mut(this: &mut Self) -> Option<&mut T> {
730 if Rc::is_unique(this) {
732 Some(Rc::get_mut_unchecked(this))
739 /// Returns a mutable reference to the inner value,
740 /// without any check.
742 /// See also [`get_mut`], which is safe and does appropriate checks.
744 /// [`get_mut`]: struct.Rc.html#method.get_mut
748 /// There must be no other `Rc` or [`Weak`] pointers to the same value.
749 /// This is the case for example immediately after `Rc::new`.
754 /// #![feature(get_mut_unchecked)]
758 /// let mut x = Rc::new(String::new());
760 /// Rc::get_mut_unchecked(&mut x).push_str("foo")
762 /// assert_eq!(*x, "foo");
765 #[unstable(feature = "get_mut_unchecked", issue = "63292")]
766 pub unsafe fn get_mut_unchecked(this: &mut Self) -> &mut T {
767 &mut this.ptr.as_mut().value
771 #[stable(feature = "ptr_eq", since = "1.17.0")]
772 /// Returns `true` if the two `Rc`s point to the same value (not
773 /// just values that compare as equal).
780 /// let five = Rc::new(5);
781 /// let same_five = Rc::clone(&five);
782 /// let other_five = Rc::new(5);
784 /// assert!(Rc::ptr_eq(&five, &same_five));
785 /// assert!(!Rc::ptr_eq(&five, &other_five));
787 pub fn ptr_eq(this: &Self, other: &Self) -> bool {
788 this.ptr.as_ptr() == other.ptr.as_ptr()
792 impl<T: Clone> Rc<T> {
793 /// Makes a mutable reference into the given `Rc`.
795 /// If there are other `Rc` pointers to the same value, then `make_mut` will
796 /// [`clone`] the inner value to ensure unique ownership. This is also
797 /// referred to as clone-on-write.
799 /// If there are no other `Rc` pointers to this value, then [`Weak`]
800 /// pointers to this value will be dissassociated.
802 /// See also [`get_mut`], which will fail rather than cloning.
804 /// [`Weak`]: struct.Weak.html
805 /// [`clone`]: ../../std/clone/trait.Clone.html#tymethod.clone
806 /// [`get_mut`]: struct.Rc.html#method.get_mut
813 /// let mut data = Rc::new(5);
815 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
816 /// let mut other_data = Rc::clone(&data); // Won't clone inner data
817 /// *Rc::make_mut(&mut data) += 1; // Clones inner data
818 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
819 /// *Rc::make_mut(&mut other_data) *= 2; // Won't clone anything
821 /// // Now `data` and `other_data` point to different values.
822 /// assert_eq!(*data, 8);
823 /// assert_eq!(*other_data, 12);
826 /// [`Weak`] pointers will be dissassociated:
831 /// let mut data = Rc::new(75);
832 /// let weak = Rc::downgrade(&data);
834 /// assert!(75 == *data);
835 /// assert!(75 == *weak.upgrade().unwrap());
837 /// *Rc::make_mut(&mut data) += 1;
839 /// assert!(76 == *data);
840 /// assert!(weak.upgrade().is_none());
843 #[stable(feature = "rc_unique", since = "1.4.0")]
844 pub fn make_mut(this: &mut Self) -> &mut T {
845 if Rc::strong_count(this) != 1 {
846 // Gotta clone the data, there are other Rcs
847 *this = Rc::new((**this).clone())
848 } else if Rc::weak_count(this) != 0 {
849 // Can just steal the data, all that's left is Weaks
851 let mut swap = Rc::new(ptr::read(&this.ptr.as_ref().value));
852 mem::swap(this, &mut swap);
854 // Remove implicit strong-weak ref (no need to craft a fake
855 // Weak here -- we know other Weaks can clean up for us)
860 // This unsafety is ok because we're guaranteed that the pointer
861 // returned is the *only* pointer that will ever be returned to T. Our
862 // reference count is guaranteed to be 1 at this point, and we required
863 // the `Rc<T>` itself to be `mut`, so we're returning the only possible
864 // reference to the inner value.
866 &mut this.ptr.as_mut().value
873 #[stable(feature = "rc_downcast", since = "1.29.0")]
874 /// Attempt to downcast the `Rc<dyn Any>` to a concrete type.
879 /// use std::any::Any;
882 /// fn print_if_string(value: Rc<dyn Any>) {
883 /// if let Ok(string) = value.downcast::<String>() {
884 /// println!("String ({}): {}", string.len(), string);
889 /// let my_string = "Hello World".to_string();
890 /// print_if_string(Rc::new(my_string));
891 /// print_if_string(Rc::new(0i8));
894 pub fn downcast<T: Any>(self) -> Result<Rc<T>, Rc<dyn Any>> {
895 if (*self).is::<T>() {
896 let ptr = self.ptr.cast::<RcBox<T>>();
898 Ok(Rc::from_inner(ptr))
905 impl<T: ?Sized> Rc<T> {
906 /// Allocates an `RcBox<T>` with sufficient space for
907 /// an unsized value where the value has the layout provided.
909 /// The function `mem_to_rcbox` is called with the data pointer
910 /// and must return back a (potentially fat)-pointer for the `RcBox<T>`.
911 unsafe fn allocate_for_unsized(
912 value_layout: Layout,
913 mem_to_rcbox: impl FnOnce(*mut u8) -> *mut RcBox<T>
915 // Calculate layout using the given value layout.
916 // Previously, layout was calculated on the expression
917 // `&*(ptr as *const RcBox<T>)`, but this created a misaligned
918 // reference (see #54908).
919 let layout = Layout::new::<RcBox<()>>()
920 .extend(value_layout).unwrap().0
921 .pad_to_align().unwrap();
923 // Allocate for the layout.
924 let mem = Global.alloc(layout)
925 .unwrap_or_else(|_| handle_alloc_error(layout));
927 // Initialize the RcBox
928 let inner = mem_to_rcbox(mem.as_ptr());
929 debug_assert_eq!(Layout::for_value(&*inner), layout);
931 ptr::write(&mut (*inner).strong, Cell::new(1));
932 ptr::write(&mut (*inner).weak, Cell::new(1));
937 /// Allocates an `RcBox<T>` with sufficient space for an unsized value
938 unsafe fn allocate_for_ptr(ptr: *const T) -> *mut RcBox<T> {
939 // Allocate for the `RcBox<T>` using the given value.
940 Self::allocate_for_unsized(
941 Layout::for_value(&*ptr),
942 |mem| set_data_ptr(ptr as *mut T, mem) as *mut RcBox<T>,
946 fn from_box(v: Box<T>) -> Rc<T> {
948 let box_unique = Box::into_unique(v);
949 let bptr = box_unique.as_ptr();
951 let value_size = size_of_val(&*bptr);
952 let ptr = Self::allocate_for_ptr(bptr);
954 // Copy value as bytes
955 ptr::copy_nonoverlapping(
956 bptr as *const T as *const u8,
957 &mut (*ptr).value as *mut _ as *mut u8,
960 // Free the allocation without dropping its contents
961 box_free(box_unique);
969 /// Allocates an `RcBox<[T]>` with the given length.
970 unsafe fn allocate_for_slice(len: usize) -> *mut RcBox<[T]> {
971 Self::allocate_for_unsized(
972 Layout::array::<T>(len).unwrap(),
973 |mem| ptr::slice_from_raw_parts_mut(mem as *mut T, len) as *mut RcBox<[T]>,
978 /// Sets the data pointer of a `?Sized` raw pointer.
980 /// For a slice/trait object, this sets the `data` field and leaves the rest
981 /// unchanged. For a sized raw pointer, this simply sets the pointer.
982 unsafe fn set_data_ptr<T: ?Sized, U>(mut ptr: *mut T, data: *mut U) -> *mut T {
983 ptr::write(&mut ptr as *mut _ as *mut *mut u8, data as *mut u8);
988 /// Copy elements from slice into newly allocated Rc<[T]>
990 /// Unsafe because the caller must either take ownership or bind `T: Copy`
991 unsafe fn copy_from_slice(v: &[T]) -> Rc<[T]> {
992 let ptr = Self::allocate_for_slice(v.len());
994 ptr::copy_nonoverlapping(
996 &mut (*ptr).value as *mut [T] as *mut T,
1002 /// Constructs an `Rc<[T]>` from an iterator known to be of a certain size.
1004 /// Behavior is undefined should the size be wrong.
1005 unsafe fn from_iter_exact(iter: impl iter::Iterator<Item = T>, len: usize) -> Rc<[T]> {
1006 // Panic guard while cloning T elements.
1007 // In the event of a panic, elements that have been written
1008 // into the new RcBox will be dropped, then the memory freed.
1016 impl<T> Drop for Guard<T> {
1017 fn drop(&mut self) {
1019 let slice = from_raw_parts_mut(self.elems, self.n_elems);
1020 ptr::drop_in_place(slice);
1022 Global.dealloc(self.mem, self.layout);
1027 let ptr = Self::allocate_for_slice(len);
1029 let mem = ptr as *mut _ as *mut u8;
1030 let layout = Layout::for_value(&*ptr);
1032 // Pointer to first element
1033 let elems = &mut (*ptr).value as *mut [T] as *mut T;
1035 let mut guard = Guard {
1036 mem: NonNull::new_unchecked(mem),
1042 for (i, item) in iter.enumerate() {
1043 ptr::write(elems.add(i), item);
1047 // All clear. Forget the guard so it doesn't free the new RcBox.
1054 /// Specialization trait used for `From<&[T]>`.
1055 trait RcFromSlice<T> {
1056 fn from_slice(slice: &[T]) -> Self;
1059 impl<T: Clone> RcFromSlice<T> for Rc<[T]> {
1061 default fn from_slice(v: &[T]) -> Self {
1063 Self::from_iter_exact(v.iter().cloned(), v.len())
1068 impl<T: Copy> RcFromSlice<T> for Rc<[T]> {
1070 fn from_slice(v: &[T]) -> Self {
1071 unsafe { Rc::copy_from_slice(v) }
1075 #[stable(feature = "rust1", since = "1.0.0")]
1076 impl<T: ?Sized> Deref for Rc<T> {
1080 fn deref(&self) -> &T {
1085 #[unstable(feature = "receiver_trait", issue = "0")]
1086 impl<T: ?Sized> Receiver for Rc<T> {}
1088 #[stable(feature = "rust1", since = "1.0.0")]
1089 unsafe impl<#[may_dangle] T: ?Sized> Drop for Rc<T> {
1092 /// This will decrement the strong reference count. If the strong reference
1093 /// count reaches zero then the only other references (if any) are
1094 /// [`Weak`], so we `drop` the inner value.
1099 /// use std::rc::Rc;
1103 /// impl Drop for Foo {
1104 /// fn drop(&mut self) {
1105 /// println!("dropped!");
1109 /// let foo = Rc::new(Foo);
1110 /// let foo2 = Rc::clone(&foo);
1112 /// drop(foo); // Doesn't print anything
1113 /// drop(foo2); // Prints "dropped!"
1116 /// [`Weak`]: ../../std/rc/struct.Weak.html
1117 fn drop(&mut self) {
1120 if self.strong() == 0 {
1121 // destroy the contained object
1122 ptr::drop_in_place(self.ptr.as_mut());
1124 // remove the implicit "strong weak" pointer now that we've
1125 // destroyed the contents.
1128 if self.weak() == 0 {
1129 Global.dealloc(self.ptr.cast(), Layout::for_value(self.ptr.as_ref()));
1136 #[stable(feature = "rust1", since = "1.0.0")]
1137 impl<T: ?Sized> Clone for Rc<T> {
1138 /// Makes a clone of the `Rc` pointer.
1140 /// This creates another pointer to the same inner value, increasing the
1141 /// strong reference count.
1146 /// use std::rc::Rc;
1148 /// let five = Rc::new(5);
1150 /// let _ = Rc::clone(&five);
1153 fn clone(&self) -> Rc<T> {
1155 Self::from_inner(self.ptr)
1159 #[stable(feature = "rust1", since = "1.0.0")]
1160 impl<T: Default> Default for Rc<T> {
1161 /// Creates a new `Rc<T>`, with the `Default` value for `T`.
1166 /// use std::rc::Rc;
1168 /// let x: Rc<i32> = Default::default();
1169 /// assert_eq!(*x, 0);
1172 fn default() -> Rc<T> {
1173 Rc::new(Default::default())
1177 #[stable(feature = "rust1", since = "1.0.0")]
1178 trait RcEqIdent<T: ?Sized + PartialEq> {
1179 fn eq(&self, other: &Rc<T>) -> bool;
1180 fn ne(&self, other: &Rc<T>) -> bool;
1183 #[stable(feature = "rust1", since = "1.0.0")]
1184 impl<T: ?Sized + PartialEq> RcEqIdent<T> for Rc<T> {
1186 default fn eq(&self, other: &Rc<T>) -> bool {
1191 default fn ne(&self, other: &Rc<T>) -> bool {
1196 /// We're doing this specialization here, and not as a more general optimization on `&T`, because it
1197 /// would otherwise add a cost to all equality checks on refs. We assume that `Rc`s are used to
1198 /// store large values, that are slow to clone, but also heavy to check for equality, causing this
1199 /// cost to pay off more easily. It's also more likely to have two `Rc` clones, that point to
1200 /// the same value, than two `&T`s.
1201 #[stable(feature = "rust1", since = "1.0.0")]
1202 impl<T: ?Sized + Eq> RcEqIdent<T> for Rc<T> {
1204 fn eq(&self, other: &Rc<T>) -> bool {
1205 Rc::ptr_eq(self, other) || **self == **other
1209 fn ne(&self, other: &Rc<T>) -> bool {
1210 !Rc::ptr_eq(self, other) && **self != **other
1214 #[stable(feature = "rust1", since = "1.0.0")]
1215 impl<T: ?Sized + PartialEq> PartialEq for Rc<T> {
1216 /// Equality for two `Rc`s.
1218 /// Two `Rc`s are equal if their inner values are equal.
1220 /// If `T` also implements `Eq`, two `Rc`s that point to the same value are
1226 /// use std::rc::Rc;
1228 /// let five = Rc::new(5);
1230 /// assert!(five == Rc::new(5));
1233 fn eq(&self, other: &Rc<T>) -> bool {
1234 RcEqIdent::eq(self, other)
1237 /// Inequality for two `Rc`s.
1239 /// Two `Rc`s are unequal if their inner values are unequal.
1241 /// If `T` also implements `Eq`, two `Rc`s that point to the same value are
1247 /// use std::rc::Rc;
1249 /// let five = Rc::new(5);
1251 /// assert!(five != Rc::new(6));
1254 fn ne(&self, other: &Rc<T>) -> bool {
1255 RcEqIdent::ne(self, other)
1259 #[stable(feature = "rust1", since = "1.0.0")]
1260 impl<T: ?Sized + Eq> Eq for Rc<T> {}
1262 #[stable(feature = "rust1", since = "1.0.0")]
1263 impl<T: ?Sized + PartialOrd> PartialOrd for Rc<T> {
1264 /// Partial comparison for two `Rc`s.
1266 /// The two are compared by calling `partial_cmp()` on their inner values.
1271 /// use std::rc::Rc;
1272 /// use std::cmp::Ordering;
1274 /// let five = Rc::new(5);
1276 /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&Rc::new(6)));
1279 fn partial_cmp(&self, other: &Rc<T>) -> Option<Ordering> {
1280 (**self).partial_cmp(&**other)
1283 /// Less-than comparison for two `Rc`s.
1285 /// The two are compared by calling `<` on their inner values.
1290 /// use std::rc::Rc;
1292 /// let five = Rc::new(5);
1294 /// assert!(five < Rc::new(6));
1297 fn lt(&self, other: &Rc<T>) -> bool {
1301 /// 'Less than or equal to' comparison for two `Rc`s.
1303 /// The two are compared by calling `<=` on their inner values.
1308 /// use std::rc::Rc;
1310 /// let five = Rc::new(5);
1312 /// assert!(five <= Rc::new(5));
1315 fn le(&self, other: &Rc<T>) -> bool {
1319 /// Greater-than comparison for two `Rc`s.
1321 /// The two are compared by calling `>` on their inner values.
1326 /// use std::rc::Rc;
1328 /// let five = Rc::new(5);
1330 /// assert!(five > Rc::new(4));
1333 fn gt(&self, other: &Rc<T>) -> bool {
1337 /// 'Greater than or equal to' comparison for two `Rc`s.
1339 /// The two are compared by calling `>=` on their inner values.
1344 /// use std::rc::Rc;
1346 /// let five = Rc::new(5);
1348 /// assert!(five >= Rc::new(5));
1351 fn ge(&self, other: &Rc<T>) -> bool {
1356 #[stable(feature = "rust1", since = "1.0.0")]
1357 impl<T: ?Sized + Ord> Ord for Rc<T> {
1358 /// Comparison for two `Rc`s.
1360 /// The two are compared by calling `cmp()` on their inner values.
1365 /// use std::rc::Rc;
1366 /// use std::cmp::Ordering;
1368 /// let five = Rc::new(5);
1370 /// assert_eq!(Ordering::Less, five.cmp(&Rc::new(6)));
1373 fn cmp(&self, other: &Rc<T>) -> Ordering {
1374 (**self).cmp(&**other)
1378 #[stable(feature = "rust1", since = "1.0.0")]
1379 impl<T: ?Sized + Hash> Hash for Rc<T> {
1380 fn hash<H: Hasher>(&self, state: &mut H) {
1381 (**self).hash(state);
1385 #[stable(feature = "rust1", since = "1.0.0")]
1386 impl<T: ?Sized + fmt::Display> fmt::Display for Rc<T> {
1387 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1388 fmt::Display::fmt(&**self, f)
1392 #[stable(feature = "rust1", since = "1.0.0")]
1393 impl<T: ?Sized + fmt::Debug> fmt::Debug for Rc<T> {
1394 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1395 fmt::Debug::fmt(&**self, f)
1399 #[stable(feature = "rust1", since = "1.0.0")]
1400 impl<T: ?Sized> fmt::Pointer for Rc<T> {
1401 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1402 fmt::Pointer::fmt(&(&**self as *const T), f)
1406 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
1407 impl<T> From<T> for Rc<T> {
1408 fn from(t: T) -> Self {
1413 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1414 impl<T: Clone> From<&[T]> for Rc<[T]> {
1416 fn from(v: &[T]) -> Rc<[T]> {
1417 <Self as RcFromSlice<T>>::from_slice(v)
1421 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1422 impl From<&str> for Rc<str> {
1424 fn from(v: &str) -> Rc<str> {
1425 let rc = Rc::<[u8]>::from(v.as_bytes());
1426 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const str) }
1430 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1431 impl From<String> for Rc<str> {
1433 fn from(v: String) -> Rc<str> {
1438 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1439 impl<T: ?Sized> From<Box<T>> for Rc<T> {
1441 fn from(v: Box<T>) -> Rc<T> {
1446 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1447 impl<T> From<Vec<T>> for Rc<[T]> {
1449 fn from(mut v: Vec<T>) -> Rc<[T]> {
1451 let rc = Rc::copy_from_slice(&v);
1453 // Allow the Vec to free its memory, but not destroy its contents
1461 #[unstable(feature = "boxed_slice_try_from", issue = "0")]
1462 impl<T, const N: usize> TryFrom<Rc<[T]>> for Rc<[T; N]>
1464 [T; N]: LengthAtMost32,
1466 type Error = Rc<[T]>;
1468 fn try_from(boxed_slice: Rc<[T]>) -> Result<Self, Self::Error> {
1469 if boxed_slice.len() == N {
1470 Ok(unsafe { Rc::from_raw(Rc::into_raw(boxed_slice) as *mut [T; N]) })
1477 #[stable(feature = "shared_from_iter", since = "1.37.0")]
1478 impl<T> iter::FromIterator<T> for Rc<[T]> {
1479 /// Takes each element in the `Iterator` and collects it into an `Rc<[T]>`.
1481 /// # Performance characteristics
1483 /// ## The general case
1485 /// In the general case, collecting into `Rc<[T]>` is done by first
1486 /// collecting into a `Vec<T>`. That is, when writing the following:
1489 /// # use std::rc::Rc;
1490 /// let evens: Rc<[u8]> = (0..10).filter(|&x| x % 2 == 0).collect();
1491 /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]);
1494 /// this behaves as if we wrote:
1497 /// # use std::rc::Rc;
1498 /// let evens: Rc<[u8]> = (0..10).filter(|&x| x % 2 == 0)
1499 /// .collect::<Vec<_>>() // The first set of allocations happens here.
1500 /// .into(); // A second allocation for `Rc<[T]>` happens here.
1501 /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]);
1504 /// This will allocate as many times as needed for constructing the `Vec<T>`
1505 /// and then it will allocate once for turning the `Vec<T>` into the `Rc<[T]>`.
1507 /// ## Iterators of known length
1509 /// When your `Iterator` implements `TrustedLen` and is of an exact size,
1510 /// a single allocation will be made for the `Rc<[T]>`. For example:
1513 /// # use std::rc::Rc;
1514 /// let evens: Rc<[u8]> = (0..10).collect(); // Just a single allocation happens here.
1515 /// # assert_eq!(&*evens, &*(0..10).collect::<Vec<_>>());
1517 fn from_iter<I: iter::IntoIterator<Item = T>>(iter: I) -> Self {
1518 RcFromIter::from_iter(iter.into_iter())
1522 /// Specialization trait used for collecting into `Rc<[T]>`.
1523 trait RcFromIter<T, I> {
1524 fn from_iter(iter: I) -> Self;
1527 impl<T, I: Iterator<Item = T>> RcFromIter<T, I> for Rc<[T]> {
1528 default fn from_iter(iter: I) -> Self {
1529 iter.collect::<Vec<T>>().into()
1533 impl<T, I: iter::TrustedLen<Item = T>> RcFromIter<T, I> for Rc<[T]> {
1534 default fn from_iter(iter: I) -> Self {
1535 // This is the case for a `TrustedLen` iterator.
1536 let (low, high) = iter.size_hint();
1537 if let Some(high) = high {
1540 "TrustedLen iterator's size hint is not exact: {:?}",
1545 // SAFETY: We need to ensure that the iterator has an exact length and we have.
1546 Rc::from_iter_exact(iter, low)
1549 // Fall back to normal implementation.
1550 iter.collect::<Vec<T>>().into()
1555 impl<'a, T: 'a + Clone> RcFromIter<&'a T, slice::Iter<'a, T>> for Rc<[T]> {
1556 fn from_iter(iter: slice::Iter<'a, T>) -> Self {
1557 // Delegate to `impl<T: Clone> From<&[T]> for Rc<[T]>`.
1559 // In the case that `T: Copy`, we get to use `ptr::copy_nonoverlapping`
1560 // which is even more performant.
1562 // In the fall-back case we have `T: Clone`. This is still better
1563 // than the `TrustedLen` implementation as slices have a known length
1564 // and so we get to avoid calling `size_hint` and avoid the branching.
1565 iter.as_slice().into()
1569 /// `Weak` is a version of [`Rc`] that holds a non-owning reference to the
1570 /// managed value. The value is accessed by calling [`upgrade`] on the `Weak`
1571 /// pointer, which returns an [`Option`]`<`[`Rc`]`<T>>`.
1573 /// Since a `Weak` reference does not count towards ownership, it will not
1574 /// prevent the inner value from being dropped, and `Weak` itself makes no
1575 /// guarantees about the value still being present and may return [`None`]
1576 /// when [`upgrade`]d.
1578 /// A `Weak` pointer is useful for keeping a temporary reference to the value
1579 /// within [`Rc`] without extending its lifetime. It is also used to prevent
1580 /// circular references between [`Rc`] pointers, since mutual owning references
1581 /// would never allow either [`Rc`] to be dropped. For example, a tree could
1582 /// have strong [`Rc`] pointers from parent nodes to children, and `Weak`
1583 /// pointers from children back to their parents.
1585 /// The typical way to obtain a `Weak` pointer is to call [`Rc::downgrade`].
1587 /// [`Rc`]: struct.Rc.html
1588 /// [`Rc::downgrade`]: struct.Rc.html#method.downgrade
1589 /// [`upgrade`]: struct.Weak.html#method.upgrade
1590 /// [`Option`]: ../../std/option/enum.Option.html
1591 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1592 #[stable(feature = "rc_weak", since = "1.4.0")]
1593 pub struct Weak<T: ?Sized> {
1594 // This is a `NonNull` to allow optimizing the size of this type in enums,
1595 // but it is not necessarily a valid pointer.
1596 // `Weak::new` sets this to `usize::MAX` so that it doesn’t need
1597 // to allocate space on the heap. That's not a value a real pointer
1598 // will ever have because RcBox has alignment at least 2.
1599 ptr: NonNull<RcBox<T>>,
1602 #[stable(feature = "rc_weak", since = "1.4.0")]
1603 impl<T: ?Sized> !marker::Send for Weak<T> {}
1604 #[stable(feature = "rc_weak", since = "1.4.0")]
1605 impl<T: ?Sized> !marker::Sync for Weak<T> {}
1607 #[unstable(feature = "coerce_unsized", issue = "27732")]
1608 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {}
1610 #[unstable(feature = "dispatch_from_dyn", issue = "0")]
1611 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Weak<U>> for Weak<T> {}
1614 /// Constructs a new `Weak<T>`, without allocating any memory.
1615 /// Calling [`upgrade`] on the return value always gives [`None`].
1617 /// [`upgrade`]: #method.upgrade
1618 /// [`None`]: ../../std/option/enum.Option.html
1623 /// use std::rc::Weak;
1625 /// let empty: Weak<i64> = Weak::new();
1626 /// assert!(empty.upgrade().is_none());
1628 #[stable(feature = "downgraded_weak", since = "1.10.0")]
1629 pub fn new() -> Weak<T> {
1631 ptr: NonNull::new(usize::MAX as *mut RcBox<T>).expect("MAX is not 0"),
1635 /// Returns a raw pointer to the object `T` pointed to by this `Weak<T>`.
1637 /// It is up to the caller to ensure that the object is still alive when accessing it through
1640 /// The pointer may be [`null`] or be dangling in case the object has already been destroyed.
1645 /// #![feature(weak_into_raw)]
1647 /// use std::rc::Rc;
1650 /// let strong = Rc::new("hello".to_owned());
1651 /// let weak = Rc::downgrade(&strong);
1652 /// // Both point to the same object
1653 /// assert!(ptr::eq(&*strong, weak.as_raw()));
1654 /// // The strong here keeps it alive, so we can still access the object.
1655 /// assert_eq!("hello", unsafe { &*weak.as_raw() });
1658 /// // But not any more. We can do weak.as_raw(), but accessing the pointer would lead to
1659 /// // undefined behaviour.
1660 /// // assert_eq!("hello", unsafe { &*weak.as_raw() });
1663 /// [`null`]: ../../std/ptr/fn.null.html
1664 #[unstable(feature = "weak_into_raw", issue = "60728")]
1665 pub fn as_raw(&self) -> *const T {
1666 match self.inner() {
1667 None => ptr::null(),
1669 let offset = data_offset_sized::<T>();
1670 let ptr = inner as *const RcBox<T>;
1671 // Note: while the pointer we create may already point to dropped value, the
1672 // allocation still lives (it must hold the weak point as long as we are alive).
1673 // Therefore, the offset is OK to do, it won't get out of the allocation.
1674 let ptr = unsafe { (ptr as *const u8).offset(offset) };
1680 /// Consumes the `Weak<T>` and turns it into a raw pointer.
1682 /// This converts the weak pointer into a raw pointer, preserving the original weak count. It
1683 /// can be turned back into the `Weak<T>` with [`from_raw`].
1685 /// The same restrictions of accessing the target of the pointer as with
1686 /// [`as_raw`] apply.
1691 /// #![feature(weak_into_raw)]
1693 /// use std::rc::{Rc, Weak};
1695 /// let strong = Rc::new("hello".to_owned());
1696 /// let weak = Rc::downgrade(&strong);
1697 /// let raw = weak.into_raw();
1699 /// assert_eq!(1, Rc::weak_count(&strong));
1700 /// assert_eq!("hello", unsafe { &*raw });
1702 /// drop(unsafe { Weak::from_raw(raw) });
1703 /// assert_eq!(0, Rc::weak_count(&strong));
1706 /// [`from_raw`]: struct.Weak.html#method.from_raw
1707 /// [`as_raw`]: struct.Weak.html#method.as_raw
1708 #[unstable(feature = "weak_into_raw", issue = "60728")]
1709 pub fn into_raw(self) -> *const T {
1710 let result = self.as_raw();
1715 /// Converts a raw pointer previously created by [`into_raw`] back into `Weak<T>`.
1717 /// This can be used to safely get a strong reference (by calling [`upgrade`]
1718 /// later) or to deallocate the weak count by dropping the `Weak<T>`.
1720 /// It takes ownership of one weak count. In case a [`null`] is passed, a dangling [`Weak`] is
1725 /// The pointer must represent one valid weak count. In other words, it must point to `T` which
1726 /// is or *was* managed by an [`Rc`] and the weak count of that [`Rc`] must not have reached
1727 /// 0. It is allowed for the strong count to be 0.
1732 /// #![feature(weak_into_raw)]
1734 /// use std::rc::{Rc, Weak};
1736 /// let strong = Rc::new("hello".to_owned());
1738 /// let raw_1 = Rc::downgrade(&strong).into_raw();
1739 /// let raw_2 = Rc::downgrade(&strong).into_raw();
1741 /// assert_eq!(2, Rc::weak_count(&strong));
1743 /// assert_eq!("hello", &*unsafe { Weak::from_raw(raw_1) }.upgrade().unwrap());
1744 /// assert_eq!(1, Rc::weak_count(&strong));
1748 /// // Decrement the last weak count.
1749 /// assert!(unsafe { Weak::from_raw(raw_2) }.upgrade().is_none());
1752 /// [`null`]: ../../std/ptr/fn.null.html
1753 /// [`into_raw`]: struct.Weak.html#method.into_raw
1754 /// [`upgrade`]: struct.Weak.html#method.upgrade
1755 /// [`Rc`]: struct.Rc.html
1756 /// [`Weak`]: struct.Weak.html
1757 #[unstable(feature = "weak_into_raw", issue = "60728")]
1758 pub unsafe fn from_raw(ptr: *const T) -> Self {
1762 // See Rc::from_raw for details
1763 let offset = data_offset(ptr);
1764 let fake_ptr = ptr as *mut RcBox<T>;
1765 let ptr = set_data_ptr(fake_ptr, (ptr as *mut u8).offset(-offset));
1767 ptr: NonNull::new(ptr).expect("Invalid pointer passed to from_raw"),
1773 pub(crate) fn is_dangling<T: ?Sized>(ptr: NonNull<T>) -> bool {
1774 let address = ptr.as_ptr() as *mut () as usize;
1775 address == usize::MAX
1778 impl<T: ?Sized> Weak<T> {
1779 /// Attempts to upgrade the `Weak` pointer to an [`Rc`], extending
1780 /// the lifetime of the value if successful.
1782 /// Returns [`None`] if the value has since been dropped.
1784 /// [`Rc`]: struct.Rc.html
1785 /// [`None`]: ../../std/option/enum.Option.html
1790 /// use std::rc::Rc;
1792 /// let five = Rc::new(5);
1794 /// let weak_five = Rc::downgrade(&five);
1796 /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
1797 /// assert!(strong_five.is_some());
1799 /// // Destroy all strong pointers.
1800 /// drop(strong_five);
1803 /// assert!(weak_five.upgrade().is_none());
1805 #[stable(feature = "rc_weak", since = "1.4.0")]
1806 pub fn upgrade(&self) -> Option<Rc<T>> {
1807 let inner = self.inner()?;
1808 if inner.strong() == 0 {
1812 Some(Rc::from_inner(self.ptr))
1816 /// Gets the number of strong (`Rc`) pointers pointing to this value.
1818 /// If `self` was created using [`Weak::new`], this will return 0.
1820 /// [`Weak::new`]: #method.new
1821 #[unstable(feature = "weak_counts", issue = "57977")]
1822 pub fn strong_count(&self) -> usize {
1823 if let Some(inner) = self.inner() {
1830 /// Gets the number of `Weak` pointers pointing to this value.
1832 /// If `self` was created using [`Weak::new`], this will return `None`. If
1833 /// not, the returned value is at least 1, since `self` still points to the
1836 /// [`Weak::new`]: #method.new
1837 #[unstable(feature = "weak_counts", issue = "57977")]
1838 pub fn weak_count(&self) -> Option<usize> {
1839 self.inner().map(|inner| {
1840 if inner.strong() > 0 {
1841 inner.weak() - 1 // subtract the implicit weak ptr
1848 /// Returns `None` when the pointer is dangling and there is no allocated `RcBox`
1849 /// (i.e., when this `Weak` was created by `Weak::new`).
1851 fn inner(&self) -> Option<&RcBox<T>> {
1852 if is_dangling(self.ptr) {
1855 Some(unsafe { self.ptr.as_ref() })
1859 /// Returns `true` if the two `Weak`s point to the same value (not just values
1860 /// that compare as equal).
1864 /// Since this compares pointers it means that `Weak::new()` will equal each
1865 /// other, even though they don't point to any value.
1870 /// #![feature(weak_ptr_eq)]
1871 /// use std::rc::Rc;
1873 /// let first_rc = Rc::new(5);
1874 /// let first = Rc::downgrade(&first_rc);
1875 /// let second = Rc::downgrade(&first_rc);
1877 /// assert!(first.ptr_eq(&second));
1879 /// let third_rc = Rc::new(5);
1880 /// let third = Rc::downgrade(&third_rc);
1882 /// assert!(!first.ptr_eq(&third));
1885 /// Comparing `Weak::new`.
1888 /// #![feature(weak_ptr_eq)]
1889 /// use std::rc::{Rc, Weak};
1891 /// let first = Weak::new();
1892 /// let second = Weak::new();
1893 /// assert!(first.ptr_eq(&second));
1895 /// let third_rc = Rc::new(());
1896 /// let third = Rc::downgrade(&third_rc);
1897 /// assert!(!first.ptr_eq(&third));
1900 #[unstable(feature = "weak_ptr_eq", issue = "55981")]
1901 pub fn ptr_eq(&self, other: &Self) -> bool {
1902 self.ptr.as_ptr() == other.ptr.as_ptr()
1906 #[stable(feature = "rc_weak", since = "1.4.0")]
1907 impl<T: ?Sized> Drop for Weak<T> {
1908 /// Drops the `Weak` pointer.
1913 /// use std::rc::{Rc, Weak};
1917 /// impl Drop for Foo {
1918 /// fn drop(&mut self) {
1919 /// println!("dropped!");
1923 /// let foo = Rc::new(Foo);
1924 /// let weak_foo = Rc::downgrade(&foo);
1925 /// let other_weak_foo = Weak::clone(&weak_foo);
1927 /// drop(weak_foo); // Doesn't print anything
1928 /// drop(foo); // Prints "dropped!"
1930 /// assert!(other_weak_foo.upgrade().is_none());
1932 fn drop(&mut self) {
1933 if let Some(inner) = self.inner() {
1935 // the weak count starts at 1, and will only go to zero if all
1936 // the strong pointers have disappeared.
1937 if inner.weak() == 0 {
1939 Global.dealloc(self.ptr.cast(), Layout::for_value(self.ptr.as_ref()));
1946 #[stable(feature = "rc_weak", since = "1.4.0")]
1947 impl<T: ?Sized> Clone for Weak<T> {
1948 /// Makes a clone of the `Weak` pointer that points to the same value.
1953 /// use std::rc::{Rc, Weak};
1955 /// let weak_five = Rc::downgrade(&Rc::new(5));
1957 /// let _ = Weak::clone(&weak_five);
1960 fn clone(&self) -> Weak<T> {
1961 if let Some(inner) = self.inner() {
1964 Weak { ptr: self.ptr }
1968 #[stable(feature = "rc_weak", since = "1.4.0")]
1969 impl<T: ?Sized + fmt::Debug> fmt::Debug for Weak<T> {
1970 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1975 #[stable(feature = "downgraded_weak", since = "1.10.0")]
1976 impl<T> Default for Weak<T> {
1977 /// Constructs a new `Weak<T>`, allocating memory for `T` without initializing
1978 /// it. Calling [`upgrade`] on the return value always gives [`None`].
1980 /// [`None`]: ../../std/option/enum.Option.html
1981 /// [`upgrade`]: ../../std/rc/struct.Weak.html#method.upgrade
1986 /// use std::rc::Weak;
1988 /// let empty: Weak<i64> = Default::default();
1989 /// assert!(empty.upgrade().is_none());
1991 fn default() -> Weak<T> {
1996 // NOTE: We checked_add here to deal with mem::forget safely. In particular
1997 // if you mem::forget Rcs (or Weaks), the ref-count can overflow, and then
1998 // you can free the allocation while outstanding Rcs (or Weaks) exist.
1999 // We abort because this is such a degenerate scenario that we don't care about
2000 // what happens -- no real program should ever experience this.
2002 // This should have negligible overhead since you don't actually need to
2003 // clone these much in Rust thanks to ownership and move-semantics.
2006 trait RcBoxPtr<T: ?Sized> {
2007 fn inner(&self) -> &RcBox<T>;
2010 fn strong(&self) -> usize {
2011 self.inner().strong.get()
2015 fn inc_strong(&self) {
2016 let strong = self.strong();
2018 // We want to abort on overflow instead of dropping the value.
2019 // The reference count will never be zero when this is called;
2020 // nevertheless, we insert an abort here to hint LLVM at
2021 // an otherwise missed optimization.
2022 if strong == 0 || strong == usize::max_value() {
2025 self.inner().strong.set(strong + 1);
2029 fn dec_strong(&self) {
2030 self.inner().strong.set(self.strong() - 1);
2034 fn weak(&self) -> usize {
2035 self.inner().weak.get()
2039 fn inc_weak(&self) {
2040 let weak = self.weak();
2042 // We want to abort on overflow instead of dropping the value.
2043 // The reference count will never be zero when this is called;
2044 // nevertheless, we insert an abort here to hint LLVM at
2045 // an otherwise missed optimization.
2046 if weak == 0 || weak == usize::max_value() {
2049 self.inner().weak.set(weak + 1);
2053 fn dec_weak(&self) {
2054 self.inner().weak.set(self.weak() - 1);
2058 impl<T: ?Sized> RcBoxPtr<T> for Rc<T> {
2060 fn inner(&self) -> &RcBox<T> {
2067 impl<T: ?Sized> RcBoxPtr<T> for RcBox<T> {
2069 fn inner(&self) -> &RcBox<T> {
2074 #[stable(feature = "rust1", since = "1.0.0")]
2075 impl<T: ?Sized> borrow::Borrow<T> for Rc<T> {
2076 fn borrow(&self) -> &T {
2081 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
2082 impl<T: ?Sized> AsRef<T> for Rc<T> {
2083 fn as_ref(&self) -> &T {
2088 #[stable(feature = "pin", since = "1.33.0")]
2089 impl<T: ?Sized> Unpin for Rc<T> { }
2091 unsafe fn data_offset<T: ?Sized>(ptr: *const T) -> isize {
2092 // Align the unsized value to the end of the `RcBox`.
2093 // Because it is ?Sized, it will always be the last field in memory.
2094 data_offset_align(align_of_val(&*ptr))
2097 /// Computes the offset of the data field within `RcBox`.
2099 /// Unlike [`data_offset`], this doesn't need the pointer, but it works only on `T: Sized`.
2100 fn data_offset_sized<T>() -> isize {
2101 data_offset_align(align_of::<T>())
2105 fn data_offset_align(align: usize) -> isize {
2106 let layout = Layout::new::<RcBox<()>>();
2107 (layout.size() + layout.padding_needed_for(align)) as isize