1 // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
13 //! Single-threaded reference-counting pointers. 'Rc' stands for 'Reference
16 //! The type [`Rc<T>`][`Rc`] provides shared ownership of a value of type `T`,
17 //! allocated in the heap. Invoking [`clone`][clone] on [`Rc`] produces a new
18 //! pointer to the same value in the heap. When the last [`Rc`] pointer to a
19 //! given value is destroyed, the pointed-to value is also destroyed.
21 //! Shared references in Rust disallow mutation by default, and [`Rc`]
22 //! is no exception: you cannot generally obtain a mutable reference to
23 //! something inside an [`Rc`]. If you need mutability, put a [`Cell`]
24 //! or [`RefCell`] inside the [`Rc`]; see [an example of mutability
25 //! inside an Rc][mutability].
27 //! [`Rc`] uses non-atomic reference counting. This means that overhead is very
28 //! low, but an [`Rc`] cannot be sent between threads, and consequently [`Rc`]
29 //! does not implement [`Send`][send]. As a result, the Rust compiler
30 //! will check *at compile time* that you are not sending [`Rc`]s between
31 //! threads. If you need multi-threaded, atomic reference counting, use
32 //! [`sync::Arc`][arc].
34 //! The [`downgrade`][downgrade] method can be used to create a non-owning
35 //! [`Weak`] pointer. A [`Weak`] pointer can be [`upgrade`][upgrade]d
36 //! to an [`Rc`], but this will return [`None`] if the value has
37 //! already been dropped.
39 //! A cycle between [`Rc`] pointers will never be deallocated. For this reason,
40 //! [`Weak`] is used to break cycles. For example, a tree could have strong
41 //! [`Rc`] pointers from parent nodes to children, and [`Weak`] pointers from
42 //! children back to their parents.
44 //! `Rc<T>` automatically dereferences to `T` (via the [`Deref`] trait),
45 //! so you can call `T`'s methods on a value of type [`Rc<T>`][`Rc`]. To avoid name
46 //! clashes with `T`'s methods, the methods of [`Rc<T>`][`Rc`] itself are associated
47 //! functions, called using function-like syntax:
51 //! let my_rc = Rc::new(());
53 //! Rc::downgrade(&my_rc);
56 //! [`Weak<T>`][`Weak`] does not auto-dereference to `T`, because the value may have
57 //! already been destroyed.
59 //! # Cloning references
61 //! Creating a new reference from an existing reference counted pointer is done using the
62 //! `Clone` trait implemented for [`Rc<T>`][`Rc`] and [`Weak<T>`][`Weak`].
66 //! let foo = Rc::new(vec![1.0, 2.0, 3.0]);
67 //! // The two syntaxes below are equivalent.
68 //! let a = foo.clone();
69 //! let b = Rc::clone(&foo);
70 //! // a and b both point to the same memory location as foo.
73 //! The `Rc::clone(&from)` syntax is the most idiomatic because it conveys more explicitly
74 //! the meaning of the code. In the example above, this syntax makes it easier to see that
75 //! this code is creating a new reference rather than copying the whole content of foo.
79 //! Consider a scenario where a set of `Gadget`s are owned by a given `Owner`.
80 //! We want to have our `Gadget`s point to their `Owner`. We can't do this with
81 //! unique ownership, because more than one gadget may belong to the same
82 //! `Owner`. [`Rc`] allows us to share an `Owner` between multiple `Gadget`s,
83 //! and have the `Owner` remain allocated as long as any `Gadget` points at it.
90 //! // ...other fields
96 //! // ...other fields
100 //! // Create a reference-counted `Owner`.
101 //! let gadget_owner: Rc<Owner> = Rc::new(
103 //! name: "Gadget Man".to_string(),
107 //! // Create `Gadget`s belonging to `gadget_owner`. Cloning the `Rc<Owner>`
108 //! // value gives us a new pointer to the same `Owner` value, incrementing
109 //! // the reference count in the process.
110 //! let gadget1 = Gadget {
112 //! owner: Rc::clone(&gadget_owner),
114 //! let gadget2 = Gadget {
116 //! owner: Rc::clone(&gadget_owner),
119 //! // Dispose of our local variable `gadget_owner`.
120 //! drop(gadget_owner);
122 //! // Despite dropping `gadget_owner`, we're still able to print out the name
123 //! // of the `Owner` of the `Gadget`s. This is because we've only dropped a
124 //! // single `Rc<Owner>`, not the `Owner` it points to. As long as there are
125 //! // other `Rc<Owner>` values pointing at the same `Owner`, it will remain
126 //! // allocated. The field projection `gadget1.owner.name` works because
127 //! // `Rc<Owner>` automatically dereferences to `Owner`.
128 //! println!("Gadget {} owned by {}", gadget1.id, gadget1.owner.name);
129 //! println!("Gadget {} owned by {}", gadget2.id, gadget2.owner.name);
131 //! // At the end of the function, `gadget1` and `gadget2` are destroyed, and
132 //! // with them the last counted references to our `Owner`. Gadget Man now
133 //! // gets destroyed as well.
137 //! If our requirements change, and we also need to be able to traverse from
138 //! `Owner` to `Gadget`, we will run into problems. An [`Rc`] pointer from `Owner`
139 //! to `Gadget` introduces a cycle between the values. This means that their
140 //! reference counts can never reach 0, and the values will remain allocated
141 //! forever: a memory leak. In order to get around this, we can use [`Weak`]
144 //! Rust actually makes it somewhat difficult to produce this loop in the first
145 //! place. In order to end up with two values that point at each other, one of
146 //! them needs to be mutable. This is difficult because [`Rc`] enforces
147 //! memory safety by only giving out shared references to the value it wraps,
148 //! and these don't allow direct mutation. We need to wrap the part of the
149 //! value we wish to mutate in a [`RefCell`], which provides *interior
150 //! mutability*: a method to achieve mutability through a shared reference.
151 //! [`RefCell`] enforces Rust's borrowing rules at runtime.
155 //! use std::rc::Weak;
156 //! use std::cell::RefCell;
160 //! gadgets: RefCell<Vec<Weak<Gadget>>>,
161 //! // ...other fields
166 //! owner: Rc<Owner>,
167 //! // ...other fields
171 //! // Create a reference-counted `Owner`. Note that we've put the `Owner`'s
172 //! // vector of `Gadget`s inside a `RefCell` so that we can mutate it through
173 //! // a shared reference.
174 //! let gadget_owner: Rc<Owner> = Rc::new(
176 //! name: "Gadget Man".to_string(),
177 //! gadgets: RefCell::new(vec![]),
181 //! // Create `Gadget`s belonging to `gadget_owner`, as before.
182 //! let gadget1 = Rc::new(
185 //! owner: Rc::clone(&gadget_owner),
188 //! let gadget2 = Rc::new(
191 //! owner: Rc::clone(&gadget_owner),
195 //! // Add the `Gadget`s to their `Owner`.
197 //! let mut gadgets = gadget_owner.gadgets.borrow_mut();
198 //! gadgets.push(Rc::downgrade(&gadget1));
199 //! gadgets.push(Rc::downgrade(&gadget2));
201 //! // `RefCell` dynamic borrow ends here.
204 //! // Iterate over our `Gadget`s, printing their details out.
205 //! for gadget_weak in gadget_owner.gadgets.borrow().iter() {
207 //! // `gadget_weak` is a `Weak<Gadget>`. Since `Weak` pointers can't
208 //! // guarantee the value is still allocated, we need to call
209 //! // `upgrade`, which returns an `Option<Rc<Gadget>>`.
211 //! // In this case we know the value still exists, so we simply
212 //! // `unwrap` the `Option`. In a more complicated program, you might
213 //! // need graceful error handling for a `None` result.
215 //! let gadget = gadget_weak.upgrade().unwrap();
216 //! println!("Gadget {} owned by {}", gadget.id, gadget.owner.name);
219 //! // At the end of the function, `gadget_owner`, `gadget1`, and `gadget2`
220 //! // are destroyed. There are now no strong (`Rc`) pointers to the
221 //! // gadgets, so they are destroyed. This zeroes the reference count on
222 //! // Gadget Man, so he gets destroyed as well.
226 //! [`Rc`]: struct.Rc.html
227 //! [`Weak`]: struct.Weak.html
228 //! [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
229 //! [`Cell`]: ../../std/cell/struct.Cell.html
230 //! [`RefCell`]: ../../std/cell/struct.RefCell.html
231 //! [send]: ../../std/marker/trait.Send.html
232 //! [arc]: ../../std/sync/struct.Arc.html
233 //! [`Deref`]: ../../std/ops/trait.Deref.html
234 //! [downgrade]: struct.Rc.html#method.downgrade
235 //! [upgrade]: struct.Weak.html#method.upgrade
236 //! [`None`]: ../../std/option/enum.Option.html#variant.None
237 //! [mutability]: ../../std/cell/index.html#introducing-mutability-inside-of-something-immutable
239 #![stable(feature = "rust1", since = "1.0.0")]
248 use core::cell::Cell;
249 use core::cmp::Ordering;
251 use core::hash::{Hash, Hasher};
252 use core::intrinsics::abort;
254 use core::marker::{Unpin, Unsize, PhantomData};
255 use core::mem::{self, align_of_val, forget, size_of_val};
256 use core::ops::Deref;
257 use core::ops::{CoerceUnsized, DispatchFromDyn};
259 use core::ptr::{self, NonNull};
260 use core::convert::From;
263 use alloc::{Global, Alloc, Layout, box_free, handle_alloc_error};
267 struct RcBox<T: ?Sized> {
273 /// A single-threaded reference-counting pointer. 'Rc' stands for 'Reference
276 /// See the [module-level documentation](./index.html) for more details.
278 /// The inherent methods of `Rc` are all associated functions, which means
279 /// that you have to call them as e.g. [`Rc::get_mut(&mut value)`][get_mut] instead of
280 /// `value.get_mut()`. This avoids conflicts with methods of the inner
283 /// [get_mut]: #method.get_mut
284 #[cfg_attr(not(test), lang = "rc")]
285 #[stable(feature = "rust1", since = "1.0.0")]
286 pub struct Rc<T: ?Sized> {
287 ptr: NonNull<RcBox<T>>,
288 phantom: PhantomData<T>,
291 #[stable(feature = "rust1", since = "1.0.0")]
292 impl<T: ?Sized> !marker::Send for Rc<T> {}
293 #[stable(feature = "rust1", since = "1.0.0")]
294 impl<T: ?Sized> !marker::Sync for Rc<T> {}
296 #[unstable(feature = "coerce_unsized", issue = "27732")]
297 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Rc<U>> for Rc<T> {}
299 #[unstable(feature = "dispatch_from_dyn", issue = "0")]
300 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Rc<U>> for Rc<T> {}
303 /// Constructs a new `Rc<T>`.
310 /// let five = Rc::new(5);
312 #[stable(feature = "rust1", since = "1.0.0")]
313 pub fn new(value: T) -> Rc<T> {
315 // there is an implicit weak pointer owned by all the strong
316 // pointers, which ensures that the weak destructor never frees
317 // the allocation while the strong destructor is running, even
318 // if the weak pointer is stored inside the strong one.
319 ptr: Box::into_raw_non_null(box RcBox {
320 strong: Cell::new(1),
324 phantom: PhantomData,
328 #[unstable(feature = "pin", issue = "49150")]
329 pub fn pinned(value: T) -> Pin<Rc<T>> {
330 unsafe { Pin::new_unchecked(Rc::new(value)) }
333 /// Returns the contained value, if the `Rc` has exactly one strong reference.
335 /// Otherwise, an [`Err`][result] is returned with the same `Rc` that was
338 /// This will succeed even if there are outstanding weak references.
340 /// [result]: ../../std/result/enum.Result.html
347 /// let x = Rc::new(3);
348 /// assert_eq!(Rc::try_unwrap(x), Ok(3));
350 /// let x = Rc::new(4);
351 /// let _y = Rc::clone(&x);
352 /// assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4);
355 #[stable(feature = "rc_unique", since = "1.4.0")]
356 pub fn try_unwrap(this: Self) -> Result<T, Self> {
357 if Rc::strong_count(&this) == 1 {
359 let val = ptr::read(&*this); // copy the contained object
361 // Indicate to Weaks that they can't be promoted by decrementing
362 // the strong count, and then remove the implicit "strong weak"
363 // pointer while also handling drop logic by just crafting a
366 let _weak = Weak { ptr: this.ptr };
376 impl<T: ?Sized> Rc<T> {
377 /// Consumes the `Rc`, returning the wrapped pointer.
379 /// To avoid a memory leak the pointer must be converted back to an `Rc` using
380 /// [`Rc::from_raw`][from_raw].
382 /// [from_raw]: struct.Rc.html#method.from_raw
389 /// let x = Rc::new(10);
390 /// let x_ptr = Rc::into_raw(x);
391 /// assert_eq!(unsafe { *x_ptr }, 10);
393 #[stable(feature = "rc_raw", since = "1.17.0")]
394 pub fn into_raw(this: Self) -> *const T {
395 let ptr: *const T = &*this;
400 /// Constructs an `Rc` from a raw pointer.
402 /// The raw pointer must have been previously returned by a call to a
403 /// [`Rc::into_raw`][into_raw].
405 /// This function is unsafe because improper use may lead to memory problems. For example, a
406 /// double-free may occur if the function is called twice on the same raw pointer.
408 /// [into_raw]: struct.Rc.html#method.into_raw
415 /// let x = Rc::new(10);
416 /// let x_ptr = Rc::into_raw(x);
419 /// // Convert back to an `Rc` to prevent leak.
420 /// let x = Rc::from_raw(x_ptr);
421 /// assert_eq!(*x, 10);
423 /// // Further calls to `Rc::from_raw(x_ptr)` would be memory unsafe.
426 /// // The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling!
428 #[stable(feature = "rc_raw", since = "1.17.0")]
429 pub unsafe fn from_raw(ptr: *const T) -> Self {
430 // Align the unsized value to the end of the RcBox.
431 // Because it is ?Sized, it will always be the last field in memory.
432 let align = align_of_val(&*ptr);
433 let layout = Layout::new::<RcBox<()>>();
434 let offset = (layout.size() + layout.padding_needed_for(align)) as isize;
436 // Reverse the offset to find the original RcBox.
437 let fake_ptr = ptr as *mut RcBox<T>;
438 let rc_ptr = set_data_ptr(fake_ptr, (ptr as *mut u8).offset(-offset));
441 ptr: NonNull::new_unchecked(rc_ptr),
442 phantom: PhantomData,
446 /// Creates a new [`Weak`][weak] pointer to this value.
448 /// [weak]: struct.Weak.html
455 /// let five = Rc::new(5);
457 /// let weak_five = Rc::downgrade(&five);
459 #[stable(feature = "rc_weak", since = "1.4.0")]
460 pub fn downgrade(this: &Self) -> Weak<T> {
462 // Make sure we do not create a dangling Weak
463 debug_assert!(!is_dangling(this.ptr));
464 Weak { ptr: this.ptr }
467 /// Gets the number of [`Weak`][weak] pointers to this value.
469 /// [weak]: struct.Weak.html
476 /// let five = Rc::new(5);
477 /// let _weak_five = Rc::downgrade(&five);
479 /// assert_eq!(1, Rc::weak_count(&five));
482 #[stable(feature = "rc_counts", since = "1.15.0")]
483 pub fn weak_count(this: &Self) -> usize {
487 /// Gets the number of strong (`Rc`) pointers to this value.
494 /// let five = Rc::new(5);
495 /// let _also_five = Rc::clone(&five);
497 /// assert_eq!(2, Rc::strong_count(&five));
500 #[stable(feature = "rc_counts", since = "1.15.0")]
501 pub fn strong_count(this: &Self) -> usize {
505 /// Returns true if there are no other `Rc` or [`Weak`][weak] pointers to
506 /// this inner value.
508 /// [weak]: struct.Weak.html
510 fn is_unique(this: &Self) -> bool {
511 Rc::weak_count(this) == 0 && Rc::strong_count(this) == 1
514 /// Returns a mutable reference to the inner value, if there are
515 /// no other `Rc` or [`Weak`][weak] pointers to the same value.
517 /// Returns [`None`] otherwise, because it is not safe to
518 /// mutate a shared value.
520 /// See also [`make_mut`][make_mut], which will [`clone`][clone]
521 /// the inner value when it's shared.
523 /// [weak]: struct.Weak.html
524 /// [`None`]: ../../std/option/enum.Option.html#variant.None
525 /// [make_mut]: struct.Rc.html#method.make_mut
526 /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
533 /// let mut x = Rc::new(3);
534 /// *Rc::get_mut(&mut x).unwrap() = 4;
535 /// assert_eq!(*x, 4);
537 /// let _y = Rc::clone(&x);
538 /// assert!(Rc::get_mut(&mut x).is_none());
541 #[stable(feature = "rc_unique", since = "1.4.0")]
542 pub fn get_mut(this: &mut Self) -> Option<&mut T> {
543 if Rc::is_unique(this) {
545 Some(&mut this.ptr.as_mut().value)
553 #[stable(feature = "ptr_eq", since = "1.17.0")]
554 /// Returns true if the two `Rc`s point to the same value (not
555 /// just values that compare as equal).
562 /// let five = Rc::new(5);
563 /// let same_five = Rc::clone(&five);
564 /// let other_five = Rc::new(5);
566 /// assert!(Rc::ptr_eq(&five, &same_five));
567 /// assert!(!Rc::ptr_eq(&five, &other_five));
569 pub fn ptr_eq(this: &Self, other: &Self) -> bool {
570 this.ptr.as_ptr() == other.ptr.as_ptr()
574 impl<T: Clone> Rc<T> {
575 /// Makes a mutable reference into the given `Rc`.
577 /// If there are other `Rc` or [`Weak`][weak] pointers to the same value,
578 /// then `make_mut` will invoke [`clone`][clone] on the inner value to
579 /// ensure unique ownership. This is also referred to as clone-on-write.
581 /// See also [`get_mut`][get_mut], which will fail rather than cloning.
583 /// [weak]: struct.Weak.html
584 /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
585 /// [get_mut]: struct.Rc.html#method.get_mut
592 /// let mut data = Rc::new(5);
594 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
595 /// let mut other_data = Rc::clone(&data); // Won't clone inner data
596 /// *Rc::make_mut(&mut data) += 1; // Clones inner data
597 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
598 /// *Rc::make_mut(&mut other_data) *= 2; // Won't clone anything
600 /// // Now `data` and `other_data` point to different values.
601 /// assert_eq!(*data, 8);
602 /// assert_eq!(*other_data, 12);
605 #[stable(feature = "rc_unique", since = "1.4.0")]
606 pub fn make_mut(this: &mut Self) -> &mut T {
607 if Rc::strong_count(this) != 1 {
608 // Gotta clone the data, there are other Rcs
609 *this = Rc::new((**this).clone())
610 } else if Rc::weak_count(this) != 0 {
611 // Can just steal the data, all that's left is Weaks
613 let mut swap = Rc::new(ptr::read(&this.ptr.as_ref().value));
614 mem::swap(this, &mut swap);
616 // Remove implicit strong-weak ref (no need to craft a fake
617 // Weak here -- we know other Weaks can clean up for us)
622 // This unsafety is ok because we're guaranteed that the pointer
623 // returned is the *only* pointer that will ever be returned to T. Our
624 // reference count is guaranteed to be 1 at this point, and we required
625 // the `Rc<T>` itself to be `mut`, so we're returning the only possible
626 // reference to the inner value.
628 &mut this.ptr.as_mut().value
635 #[stable(feature = "rc_downcast", since = "1.29.0")]
636 /// Attempt to downcast the `Rc<dyn Any>` to a concrete type.
641 /// use std::any::Any;
644 /// fn print_if_string(value: Rc<dyn Any>) {
645 /// if let Ok(string) = value.downcast::<String>() {
646 /// println!("String ({}): {}", string.len(), string);
651 /// let my_string = "Hello World".to_string();
652 /// print_if_string(Rc::new(my_string));
653 /// print_if_string(Rc::new(0i8));
656 pub fn downcast<T: Any>(self) -> Result<Rc<T>, Rc<dyn Any>> {
657 if (*self).is::<T>() {
658 let ptr = self.ptr.cast::<RcBox<T>>();
660 Ok(Rc { ptr, phantom: PhantomData })
667 impl<T: ?Sized> Rc<T> {
668 // Allocates an `RcBox<T>` with sufficient space for an unsized value
669 unsafe fn allocate_for_ptr(ptr: *const T) -> *mut RcBox<T> {
670 // Calculate layout using the given value.
671 // Previously, layout was calculated on the expression
672 // `&*(ptr as *const RcBox<T>)`, but this created a misaligned
673 // reference (see #54908).
674 let layout = Layout::new::<RcBox<()>>()
675 .extend(Layout::for_value(&*ptr)).unwrap().0
676 .pad_to_align().unwrap();
678 let mem = Global.alloc(layout)
679 .unwrap_or_else(|_| handle_alloc_error(layout));
681 // Initialize the RcBox
682 let inner = set_data_ptr(ptr as *mut T, mem.as_ptr() as *mut u8) as *mut RcBox<T>;
683 debug_assert_eq!(Layout::for_value(&*inner), layout);
685 ptr::write(&mut (*inner).strong, Cell::new(1));
686 ptr::write(&mut (*inner).weak, Cell::new(1));
691 fn from_box(v: Box<T>) -> Rc<T> {
693 let box_unique = Box::into_unique(v);
694 let bptr = box_unique.as_ptr();
696 let value_size = size_of_val(&*bptr);
697 let ptr = Self::allocate_for_ptr(bptr);
699 // Copy value as bytes
700 ptr::copy_nonoverlapping(
701 bptr as *const T as *const u8,
702 &mut (*ptr).value as *mut _ as *mut u8,
705 // Free the allocation without dropping its contents
706 box_free(box_unique);
708 Rc { ptr: NonNull::new_unchecked(ptr), phantom: PhantomData }
713 // Sets the data pointer of a `?Sized` raw pointer.
715 // For a slice/trait object, this sets the `data` field and leaves the rest
716 // unchanged. For a sized raw pointer, this simply sets the pointer.
717 unsafe fn set_data_ptr<T: ?Sized, U>(mut ptr: *mut T, data: *mut U) -> *mut T {
718 ptr::write(&mut ptr as *mut _ as *mut *mut u8, data as *mut u8);
723 // Copy elements from slice into newly allocated Rc<[T]>
725 // Unsafe because the caller must either take ownership or bind `T: Copy`
726 unsafe fn copy_from_slice(v: &[T]) -> Rc<[T]> {
727 let v_ptr = v as *const [T];
728 let ptr = Self::allocate_for_ptr(v_ptr);
730 ptr::copy_nonoverlapping(
732 &mut (*ptr).value as *mut [T] as *mut T,
735 Rc { ptr: NonNull::new_unchecked(ptr), phantom: PhantomData }
739 trait RcFromSlice<T> {
740 fn from_slice(slice: &[T]) -> Self;
743 impl<T: Clone> RcFromSlice<T> for Rc<[T]> {
745 default fn from_slice(v: &[T]) -> Self {
746 // Panic guard while cloning T elements.
747 // In the event of a panic, elements that have been written
748 // into the new RcBox will be dropped, then the memory freed.
756 impl<T> Drop for Guard<T> {
758 use core::slice::from_raw_parts_mut;
761 let slice = from_raw_parts_mut(self.elems, self.n_elems);
762 ptr::drop_in_place(slice);
764 Global.dealloc(self.mem, self.layout.clone());
770 let v_ptr = v as *const [T];
771 let ptr = Self::allocate_for_ptr(v_ptr);
773 let mem = ptr as *mut _ as *mut u8;
774 let layout = Layout::for_value(&*ptr);
776 // Pointer to first element
777 let elems = &mut (*ptr).value as *mut [T] as *mut T;
779 let mut guard = Guard{
780 mem: NonNull::new_unchecked(mem),
786 for (i, item) in v.iter().enumerate() {
787 ptr::write(elems.add(i), item.clone());
791 // All clear. Forget the guard so it doesn't free the new RcBox.
794 Rc { ptr: NonNull::new_unchecked(ptr), phantom: PhantomData }
799 impl<T: Copy> RcFromSlice<T> for Rc<[T]> {
801 fn from_slice(v: &[T]) -> Self {
802 unsafe { Rc::copy_from_slice(v) }
806 #[stable(feature = "rust1", since = "1.0.0")]
807 impl<T: ?Sized> Deref for Rc<T> {
811 fn deref(&self) -> &T {
816 #[stable(feature = "rust1", since = "1.0.0")]
817 unsafe impl<#[may_dangle] T: ?Sized> Drop for Rc<T> {
820 /// This will decrement the strong reference count. If the strong reference
821 /// count reaches zero then the only other references (if any) are
822 /// [`Weak`], so we `drop` the inner value.
831 /// impl Drop for Foo {
832 /// fn drop(&mut self) {
833 /// println!("dropped!");
837 /// let foo = Rc::new(Foo);
838 /// let foo2 = Rc::clone(&foo);
840 /// drop(foo); // Doesn't print anything
841 /// drop(foo2); // Prints "dropped!"
846 if self.strong() == 0 {
847 // destroy the contained object
848 ptr::drop_in_place(self.ptr.as_mut());
850 // remove the implicit "strong weak" pointer now that we've
851 // destroyed the contents.
854 if self.weak() == 0 {
855 Global.dealloc(self.ptr.cast(), Layout::for_value(self.ptr.as_ref()));
862 #[stable(feature = "rust1", since = "1.0.0")]
863 impl<T: ?Sized> Clone for Rc<T> {
864 /// Makes a clone of the `Rc` pointer.
866 /// This creates another pointer to the same inner value, increasing the
867 /// strong reference count.
874 /// let five = Rc::new(5);
876 /// let _ = Rc::clone(&five);
879 fn clone(&self) -> Rc<T> {
881 Rc { ptr: self.ptr, phantom: PhantomData }
885 #[stable(feature = "rust1", since = "1.0.0")]
886 impl<T: Default> Default for Rc<T> {
887 /// Creates a new `Rc<T>`, with the `Default` value for `T`.
894 /// let x: Rc<i32> = Default::default();
895 /// assert_eq!(*x, 0);
898 fn default() -> Rc<T> {
899 Rc::new(Default::default())
903 #[stable(feature = "rust1", since = "1.0.0")]
904 impl<T: ?Sized + PartialEq> PartialEq for Rc<T> {
905 /// Equality for two `Rc`s.
907 /// Two `Rc`s are equal if their inner values are equal.
914 /// let five = Rc::new(5);
916 /// assert!(five == Rc::new(5));
919 fn eq(&self, other: &Rc<T>) -> bool {
923 /// Inequality for two `Rc`s.
925 /// Two `Rc`s are unequal if their inner values are unequal.
932 /// let five = Rc::new(5);
934 /// assert!(five != Rc::new(6));
937 fn ne(&self, other: &Rc<T>) -> bool {
942 #[stable(feature = "rust1", since = "1.0.0")]
943 impl<T: ?Sized + Eq> Eq for Rc<T> {}
945 #[stable(feature = "rust1", since = "1.0.0")]
946 impl<T: ?Sized + PartialOrd> PartialOrd for Rc<T> {
947 /// Partial comparison for two `Rc`s.
949 /// The two are compared by calling `partial_cmp()` on their inner values.
955 /// use std::cmp::Ordering;
957 /// let five = Rc::new(5);
959 /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&Rc::new(6)));
962 fn partial_cmp(&self, other: &Rc<T>) -> Option<Ordering> {
963 (**self).partial_cmp(&**other)
966 /// Less-than comparison for two `Rc`s.
968 /// The two are compared by calling `<` on their inner values.
975 /// let five = Rc::new(5);
977 /// assert!(five < Rc::new(6));
980 fn lt(&self, other: &Rc<T>) -> bool {
984 /// 'Less than or equal to' comparison for two `Rc`s.
986 /// The two are compared by calling `<=` on their inner values.
993 /// let five = Rc::new(5);
995 /// assert!(five <= Rc::new(5));
998 fn le(&self, other: &Rc<T>) -> bool {
1002 /// Greater-than comparison for two `Rc`s.
1004 /// The two are compared by calling `>` on their inner values.
1009 /// use std::rc::Rc;
1011 /// let five = Rc::new(5);
1013 /// assert!(five > Rc::new(4));
1016 fn gt(&self, other: &Rc<T>) -> bool {
1020 /// 'Greater than or equal to' comparison for two `Rc`s.
1022 /// The two are compared by calling `>=` on their inner values.
1027 /// use std::rc::Rc;
1029 /// let five = Rc::new(5);
1031 /// assert!(five >= Rc::new(5));
1034 fn ge(&self, other: &Rc<T>) -> bool {
1039 #[stable(feature = "rust1", since = "1.0.0")]
1040 impl<T: ?Sized + Ord> Ord for Rc<T> {
1041 /// Comparison for two `Rc`s.
1043 /// The two are compared by calling `cmp()` on their inner values.
1048 /// use std::rc::Rc;
1049 /// use std::cmp::Ordering;
1051 /// let five = Rc::new(5);
1053 /// assert_eq!(Ordering::Less, five.cmp(&Rc::new(6)));
1056 fn cmp(&self, other: &Rc<T>) -> Ordering {
1057 (**self).cmp(&**other)
1061 #[stable(feature = "rust1", since = "1.0.0")]
1062 impl<T: ?Sized + Hash> Hash for Rc<T> {
1063 fn hash<H: Hasher>(&self, state: &mut H) {
1064 (**self).hash(state);
1068 #[stable(feature = "rust1", since = "1.0.0")]
1069 impl<T: ?Sized + fmt::Display> fmt::Display for Rc<T> {
1070 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1071 fmt::Display::fmt(&**self, f)
1075 #[stable(feature = "rust1", since = "1.0.0")]
1076 impl<T: ?Sized + fmt::Debug> fmt::Debug for Rc<T> {
1077 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1078 fmt::Debug::fmt(&**self, f)
1082 #[stable(feature = "rust1", since = "1.0.0")]
1083 impl<T: ?Sized> fmt::Pointer for Rc<T> {
1084 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1085 fmt::Pointer::fmt(&(&**self as *const T), f)
1089 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
1090 impl<T> From<T> for Rc<T> {
1091 fn from(t: T) -> Self {
1096 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1097 impl<'a, T: Clone> From<&'a [T]> for Rc<[T]> {
1099 fn from(v: &[T]) -> Rc<[T]> {
1100 <Self as RcFromSlice<T>>::from_slice(v)
1104 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1105 impl<'a> From<&'a str> for Rc<str> {
1107 fn from(v: &str) -> Rc<str> {
1108 let rc = Rc::<[u8]>::from(v.as_bytes());
1109 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const str) }
1113 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1114 impl From<String> for Rc<str> {
1116 fn from(v: String) -> Rc<str> {
1121 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1122 impl<T: ?Sized> From<Box<T>> for Rc<T> {
1124 fn from(v: Box<T>) -> Rc<T> {
1129 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1130 impl<T> From<Vec<T>> for Rc<[T]> {
1132 fn from(mut v: Vec<T>) -> Rc<[T]> {
1134 let rc = Rc::copy_from_slice(&v);
1136 // Allow the Vec to free its memory, but not destroy its contents
1144 /// `Weak` is a version of [`Rc`] that holds a non-owning reference to the
1145 /// managed value. The value is accessed by calling [`upgrade`] on the `Weak`
1146 /// pointer, which returns an [`Option`]`<`[`Rc`]`<T>>`.
1148 /// Since a `Weak` reference does not count towards ownership, it will not
1149 /// prevent the inner value from being dropped, and `Weak` itself makes no
1150 /// guarantees about the value still being present and may return [`None`]
1151 /// when [`upgrade`]d.
1153 /// A `Weak` pointer is useful for keeping a temporary reference to the value
1154 /// within [`Rc`] without extending its lifetime. It is also used to prevent
1155 /// circular references between [`Rc`] pointers, since mutual owning references
1156 /// would never allow either [`Rc`] to be dropped. For example, a tree could
1157 /// have strong [`Rc`] pointers from parent nodes to children, and `Weak`
1158 /// pointers from children back to their parents.
1160 /// The typical way to obtain a `Weak` pointer is to call [`Rc::downgrade`].
1162 /// [`Rc`]: struct.Rc.html
1163 /// [`Rc::downgrade`]: struct.Rc.html#method.downgrade
1164 /// [`upgrade`]: struct.Weak.html#method.upgrade
1165 /// [`Option`]: ../../std/option/enum.Option.html
1166 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1167 #[stable(feature = "rc_weak", since = "1.4.0")]
1168 pub struct Weak<T: ?Sized> {
1169 // This is a `NonNull` to allow optimizing the size of this type in enums,
1170 // but it is not necessarily a valid pointer.
1171 // `Weak::new` sets this to `usize::MAX` so that it doesn’t need
1172 // to allocate space on the heap. That's not a value a real pointer
1173 // will ever have because RcBox has alignment at least 2.
1174 ptr: NonNull<RcBox<T>>,
1177 #[stable(feature = "rc_weak", since = "1.4.0")]
1178 impl<T: ?Sized> !marker::Send for Weak<T> {}
1179 #[stable(feature = "rc_weak", since = "1.4.0")]
1180 impl<T: ?Sized> !marker::Sync for Weak<T> {}
1182 #[unstable(feature = "coerce_unsized", issue = "27732")]
1183 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {}
1185 #[unstable(feature = "dispatch_from_dyn", issue = "0")]
1186 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Weak<U>> for Weak<T> {}
1189 /// Constructs a new `Weak<T>`, without allocating any memory.
1190 /// Calling [`upgrade`][Weak::upgrade] on the return value always gives [`None`].
1192 /// [`None`]: ../../std/option/enum.Option.html
1197 /// use std::rc::Weak;
1199 /// let empty: Weak<i64> = Weak::new();
1200 /// assert!(empty.upgrade().is_none());
1202 #[stable(feature = "downgraded_weak", since = "1.10.0")]
1203 pub fn new() -> Weak<T> {
1205 ptr: NonNull::new(usize::MAX as *mut RcBox<T>).expect("MAX is not 0"),
1210 pub(crate) fn is_dangling<T: ?Sized>(ptr: NonNull<T>) -> bool {
1211 let address = ptr.as_ptr() as *mut () as usize;
1212 address == usize::MAX
1215 impl<T: ?Sized> Weak<T> {
1216 /// Attempts to upgrade the `Weak` pointer to an [`Rc`], extending
1217 /// the lifetime of the value if successful.
1219 /// Returns [`None`] if the value has since been dropped.
1221 /// [`Rc`]: struct.Rc.html
1222 /// [`None`]: ../../std/option/enum.Option.html
1227 /// use std::rc::Rc;
1229 /// let five = Rc::new(5);
1231 /// let weak_five = Rc::downgrade(&five);
1233 /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
1234 /// assert!(strong_five.is_some());
1236 /// // Destroy all strong pointers.
1237 /// drop(strong_five);
1240 /// assert!(weak_five.upgrade().is_none());
1242 #[stable(feature = "rc_weak", since = "1.4.0")]
1243 pub fn upgrade(&self) -> Option<Rc<T>> {
1244 let inner = self.inner()?;
1245 if inner.strong() == 0 {
1249 Some(Rc { ptr: self.ptr, phantom: PhantomData })
1253 /// Return `None` when the pointer is dangling and there is no allocated `RcBox`,
1254 /// i.e. this `Weak` was created by `Weak::new`
1256 fn inner(&self) -> Option<&RcBox<T>> {
1257 if is_dangling(self.ptr) {
1260 Some(unsafe { self.ptr.as_ref() })
1265 #[stable(feature = "rc_weak", since = "1.4.0")]
1266 impl<T: ?Sized> Drop for Weak<T> {
1267 /// Drops the `Weak` pointer.
1272 /// use std::rc::{Rc, Weak};
1276 /// impl Drop for Foo {
1277 /// fn drop(&mut self) {
1278 /// println!("dropped!");
1282 /// let foo = Rc::new(Foo);
1283 /// let weak_foo = Rc::downgrade(&foo);
1284 /// let other_weak_foo = Weak::clone(&weak_foo);
1286 /// drop(weak_foo); // Doesn't print anything
1287 /// drop(foo); // Prints "dropped!"
1289 /// assert!(other_weak_foo.upgrade().is_none());
1291 fn drop(&mut self) {
1292 if let Some(inner) = self.inner() {
1294 // the weak count starts at 1, and will only go to zero if all
1295 // the strong pointers have disappeared.
1296 if inner.weak() == 0 {
1298 Global.dealloc(self.ptr.cast(), Layout::for_value(self.ptr.as_ref()));
1305 #[stable(feature = "rc_weak", since = "1.4.0")]
1306 impl<T: ?Sized> Clone for Weak<T> {
1307 /// Makes a clone of the `Weak` pointer that points to the same value.
1312 /// use std::rc::{Rc, Weak};
1314 /// let weak_five = Rc::downgrade(&Rc::new(5));
1316 /// let _ = Weak::clone(&weak_five);
1319 fn clone(&self) -> Weak<T> {
1320 if let Some(inner) = self.inner() {
1323 Weak { ptr: self.ptr }
1327 #[stable(feature = "rc_weak", since = "1.4.0")]
1328 impl<T: ?Sized + fmt::Debug> fmt::Debug for Weak<T> {
1329 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1334 #[stable(feature = "downgraded_weak", since = "1.10.0")]
1335 impl<T> Default for Weak<T> {
1336 /// Constructs a new `Weak<T>`, allocating memory for `T` without initializing
1337 /// it. Calling [`upgrade`][Weak::upgrade] on the return value always gives [`None`].
1339 /// [`None`]: ../../std/option/enum.Option.html
1344 /// use std::rc::Weak;
1346 /// let empty: Weak<i64> = Default::default();
1347 /// assert!(empty.upgrade().is_none());
1349 fn default() -> Weak<T> {
1354 // NOTE: We checked_add here to deal with mem::forget safely. In particular
1355 // if you mem::forget Rcs (or Weaks), the ref-count can overflow, and then
1356 // you can free the allocation while outstanding Rcs (or Weaks) exist.
1357 // We abort because this is such a degenerate scenario that we don't care about
1358 // what happens -- no real program should ever experience this.
1360 // This should have negligible overhead since you don't actually need to
1361 // clone these much in Rust thanks to ownership and move-semantics.
1364 trait RcBoxPtr<T: ?Sized> {
1365 fn inner(&self) -> &RcBox<T>;
1368 fn strong(&self) -> usize {
1369 self.inner().strong.get()
1373 fn inc_strong(&self) {
1374 // We want to abort on overflow instead of dropping the value.
1375 // The reference count will never be zero when this is called;
1376 // nevertheless, we insert an abort here to hint LLVM at
1377 // an otherwise missed optimization.
1378 if self.strong() == 0 || self.strong() == usize::max_value() {
1381 self.inner().strong.set(self.strong() + 1);
1385 fn dec_strong(&self) {
1386 self.inner().strong.set(self.strong() - 1);
1390 fn weak(&self) -> usize {
1391 self.inner().weak.get()
1395 fn inc_weak(&self) {
1396 // We want to abort on overflow instead of dropping the value.
1397 // The reference count will never be zero when this is called;
1398 // nevertheless, we insert an abort here to hint LLVM at
1399 // an otherwise missed optimization.
1400 if self.weak() == 0 || self.weak() == usize::max_value() {
1403 self.inner().weak.set(self.weak() + 1);
1407 fn dec_weak(&self) {
1408 self.inner().weak.set(self.weak() - 1);
1412 impl<T: ?Sized> RcBoxPtr<T> for Rc<T> {
1414 fn inner(&self) -> &RcBox<T> {
1421 impl<T: ?Sized> RcBoxPtr<T> for RcBox<T> {
1423 fn inner(&self) -> &RcBox<T> {
1430 use super::{Rc, Weak};
1431 use std::boxed::Box;
1432 use std::cell::RefCell;
1433 use std::option::Option;
1434 use std::option::Option::{None, Some};
1435 use std::result::Result::{Err, Ok};
1437 use std::clone::Clone;
1438 use std::convert::From;
1442 let x = Rc::new(RefCell::new(5));
1444 *x.borrow_mut() = 20;
1445 assert_eq!(*y.borrow(), 20);
1455 fn test_simple_clone() {
1463 fn test_destructor() {
1464 let x: Rc<Box<_>> = Rc::new(box 5);
1471 let y = Rc::downgrade(&x);
1472 assert!(y.upgrade().is_some());
1478 let y = Rc::downgrade(&x);
1480 assert!(y.upgrade().is_none());
1484 fn weak_self_cyclic() {
1486 x: RefCell<Option<Weak<Cycle>>>,
1489 let a = Rc::new(Cycle { x: RefCell::new(None) });
1490 let b = Rc::downgrade(&a.clone());
1491 *a.x.borrow_mut() = Some(b);
1493 // hopefully we don't double-free (or leak)...
1499 assert!(Rc::is_unique(&x));
1501 assert!(!Rc::is_unique(&x));
1503 assert!(Rc::is_unique(&x));
1504 let w = Rc::downgrade(&x);
1505 assert!(!Rc::is_unique(&x));
1507 assert!(Rc::is_unique(&x));
1511 fn test_strong_count() {
1513 assert!(Rc::strong_count(&a) == 1);
1514 let w = Rc::downgrade(&a);
1515 assert!(Rc::strong_count(&a) == 1);
1516 let b = w.upgrade().expect("upgrade of live rc failed");
1517 assert!(Rc::strong_count(&b) == 2);
1518 assert!(Rc::strong_count(&a) == 2);
1521 assert!(Rc::strong_count(&b) == 1);
1523 assert!(Rc::strong_count(&b) == 2);
1524 assert!(Rc::strong_count(&c) == 2);
1528 fn test_weak_count() {
1530 assert!(Rc::strong_count(&a) == 1);
1531 assert!(Rc::weak_count(&a) == 0);
1532 let w = Rc::downgrade(&a);
1533 assert!(Rc::strong_count(&a) == 1);
1534 assert!(Rc::weak_count(&a) == 1);
1536 assert!(Rc::strong_count(&a) == 1);
1537 assert!(Rc::weak_count(&a) == 0);
1539 assert!(Rc::strong_count(&a) == 2);
1540 assert!(Rc::weak_count(&a) == 0);
1547 assert_eq!(Rc::try_unwrap(x), Ok(3));
1550 assert_eq!(Rc::try_unwrap(x), Err(Rc::new(4)));
1552 let _w = Rc::downgrade(&x);
1553 assert_eq!(Rc::try_unwrap(x), Ok(5));
1557 fn into_from_raw() {
1558 let x = Rc::new(box "hello");
1561 let x_ptr = Rc::into_raw(x);
1564 assert_eq!(**x_ptr, "hello");
1566 let x = Rc::from_raw(x_ptr);
1567 assert_eq!(**x, "hello");
1569 assert_eq!(Rc::try_unwrap(x).map(|x| *x), Ok("hello"));
1574 fn test_into_from_raw_unsized() {
1575 use std::fmt::Display;
1576 use std::string::ToString;
1578 let rc: Rc<str> = Rc::from("foo");
1580 let ptr = Rc::into_raw(rc.clone());
1581 let rc2 = unsafe { Rc::from_raw(ptr) };
1583 assert_eq!(unsafe { &*ptr }, "foo");
1584 assert_eq!(rc, rc2);
1586 let rc: Rc<dyn Display> = Rc::new(123);
1588 let ptr = Rc::into_raw(rc.clone());
1589 let rc2 = unsafe { Rc::from_raw(ptr) };
1591 assert_eq!(unsafe { &*ptr }.to_string(), "123");
1592 assert_eq!(rc2.to_string(), "123");
1597 let mut x = Rc::new(3);
1598 *Rc::get_mut(&mut x).unwrap() = 4;
1601 assert!(Rc::get_mut(&mut x).is_none());
1603 assert!(Rc::get_mut(&mut x).is_some());
1604 let _w = Rc::downgrade(&x);
1605 assert!(Rc::get_mut(&mut x).is_none());
1609 fn test_cowrc_clone_make_unique() {
1610 let mut cow0 = Rc::new(75);
1611 let mut cow1 = cow0.clone();
1612 let mut cow2 = cow1.clone();
1614 assert!(75 == *Rc::make_mut(&mut cow0));
1615 assert!(75 == *Rc::make_mut(&mut cow1));
1616 assert!(75 == *Rc::make_mut(&mut cow2));
1618 *Rc::make_mut(&mut cow0) += 1;
1619 *Rc::make_mut(&mut cow1) += 2;
1620 *Rc::make_mut(&mut cow2) += 3;
1622 assert!(76 == *cow0);
1623 assert!(77 == *cow1);
1624 assert!(78 == *cow2);
1626 // none should point to the same backing memory
1627 assert!(*cow0 != *cow1);
1628 assert!(*cow0 != *cow2);
1629 assert!(*cow1 != *cow2);
1633 fn test_cowrc_clone_unique2() {
1634 let mut cow0 = Rc::new(75);
1635 let cow1 = cow0.clone();
1636 let cow2 = cow1.clone();
1638 assert!(75 == *cow0);
1639 assert!(75 == *cow1);
1640 assert!(75 == *cow2);
1642 *Rc::make_mut(&mut cow0) += 1;
1644 assert!(76 == *cow0);
1645 assert!(75 == *cow1);
1646 assert!(75 == *cow2);
1648 // cow1 and cow2 should share the same contents
1649 // cow0 should have a unique reference
1650 assert!(*cow0 != *cow1);
1651 assert!(*cow0 != *cow2);
1652 assert!(*cow1 == *cow2);
1656 fn test_cowrc_clone_weak() {
1657 let mut cow0 = Rc::new(75);
1658 let cow1_weak = Rc::downgrade(&cow0);
1660 assert!(75 == *cow0);
1661 assert!(75 == *cow1_weak.upgrade().unwrap());
1663 *Rc::make_mut(&mut cow0) += 1;
1665 assert!(76 == *cow0);
1666 assert!(cow1_weak.upgrade().is_none());
1671 let foo = Rc::new(75);
1672 assert_eq!(format!("{:?}", foo), "75");
1677 let foo: Rc<[i32]> = Rc::new([1, 2, 3]);
1678 assert_eq!(foo, foo.clone());
1682 fn test_from_owned() {
1684 let foo_rc = Rc::from(foo);
1685 assert!(123 == *foo_rc);
1689 fn test_new_weak() {
1690 let foo: Weak<usize> = Weak::new();
1691 assert!(foo.upgrade().is_none());
1696 let five = Rc::new(5);
1697 let same_five = five.clone();
1698 let other_five = Rc::new(5);
1700 assert!(Rc::ptr_eq(&five, &same_five));
1701 assert!(!Rc::ptr_eq(&five, &other_five));
1705 fn test_from_str() {
1706 let r: Rc<str> = Rc::from("foo");
1708 assert_eq!(&r[..], "foo");
1712 fn test_copy_from_slice() {
1713 let s: &[u32] = &[1, 2, 3];
1714 let r: Rc<[u32]> = Rc::from(s);
1716 assert_eq!(&r[..], [1, 2, 3]);
1720 fn test_clone_from_slice() {
1721 #[derive(Clone, Debug, Eq, PartialEq)]
1724 let s: &[X] = &[X(1), X(2), X(3)];
1725 let r: Rc<[X]> = Rc::from(s);
1727 assert_eq!(&r[..], s);
1732 fn test_clone_from_slice_panic() {
1733 use std::string::{String, ToString};
1735 struct Fail(u32, String);
1737 impl Clone for Fail {
1738 fn clone(&self) -> Fail {
1742 Fail(self.0, self.1.clone())
1747 Fail(0, "foo".to_string()),
1748 Fail(1, "bar".to_string()),
1749 Fail(2, "baz".to_string()),
1752 // Should panic, but not cause memory corruption
1753 let _r: Rc<[Fail]> = Rc::from(s);
1757 fn test_from_box() {
1758 let b: Box<u32> = box 123;
1759 let r: Rc<u32> = Rc::from(b);
1761 assert_eq!(*r, 123);
1765 fn test_from_box_str() {
1766 use std::string::String;
1768 let s = String::from("foo").into_boxed_str();
1769 let r: Rc<str> = Rc::from(s);
1771 assert_eq!(&r[..], "foo");
1775 fn test_from_box_slice() {
1776 let s = vec![1, 2, 3].into_boxed_slice();
1777 let r: Rc<[u32]> = Rc::from(s);
1779 assert_eq!(&r[..], [1, 2, 3]);
1783 fn test_from_box_trait() {
1784 use std::fmt::Display;
1785 use std::string::ToString;
1787 let b: Box<dyn Display> = box 123;
1788 let r: Rc<dyn Display> = Rc::from(b);
1790 assert_eq!(r.to_string(), "123");
1794 fn test_from_box_trait_zero_sized() {
1795 use std::fmt::Debug;
1797 let b: Box<dyn Debug> = box ();
1798 let r: Rc<dyn Debug> = Rc::from(b);
1800 assert_eq!(format!("{:?}", r), "()");
1804 fn test_from_vec() {
1805 let v = vec![1, 2, 3];
1806 let r: Rc<[u32]> = Rc::from(v);
1808 assert_eq!(&r[..], [1, 2, 3]);
1812 fn test_downcast() {
1815 let r1: Rc<dyn Any> = Rc::new(i32::max_value());
1816 let r2: Rc<dyn Any> = Rc::new("abc");
1818 assert!(r1.clone().downcast::<u32>().is_err());
1820 let r1i32 = r1.downcast::<i32>();
1821 assert!(r1i32.is_ok());
1822 assert_eq!(r1i32.unwrap(), Rc::new(i32::max_value()));
1824 assert!(r2.clone().downcast::<i32>().is_err());
1826 let r2str = r2.downcast::<&'static str>();
1827 assert!(r2str.is_ok());
1828 assert_eq!(r2str.unwrap(), Rc::new("abc"));
1832 #[stable(feature = "rust1", since = "1.0.0")]
1833 impl<T: ?Sized> borrow::Borrow<T> for Rc<T> {
1834 fn borrow(&self) -> &T {
1839 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1840 impl<T: ?Sized> AsRef<T> for Rc<T> {
1841 fn as_ref(&self) -> &T {
1846 #[unstable(feature = "pin", issue = "49150")]
1847 impl<T: ?Sized> Unpin for Rc<T> { }