]> git.lizzy.rs Git - rust.git/blob - src/liballoc/rc.rs
Add tracking issue to unstable attribute
[rust.git] / src / liballoc / rc.rs
1 //! Single-threaded reference-counting pointers. 'Rc' stands for 'Reference
2 //! Counted'.
3 //!
4 //! The type [`Rc<T>`][`Rc`] provides shared ownership of a value of type `T`,
5 //! allocated in the heap. Invoking [`clone`][clone] on [`Rc`] produces a new
6 //! pointer to the same value in the heap. When the last [`Rc`] pointer to a
7 //! given value is destroyed, the pointed-to value is also destroyed.
8 //!
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].
14 //!
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].
21 //!
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.
26 //!
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.
31 //!
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:
36 //!
37 //! ```
38 //! use std::rc::Rc;
39 //! let my_rc = Rc::new(());
40 //!
41 //! Rc::downgrade(&my_rc);
42 //! ```
43 //!
44 //! [`Weak<T>`][`Weak`] does not auto-dereference to `T`, because the value may have
45 //! already been destroyed.
46 //!
47 //! # Cloning references
48 //!
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`].
51 //!
52 //! ```
53 //! use std::rc::Rc;
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.
59 //! ```
60 //!
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.
64 //!
65 //! # Examples
66 //!
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.
72 //!
73 //! ```
74 //! use std::rc::Rc;
75 //!
76 //! struct Owner {
77 //!     name: String,
78 //!     // ...other fields
79 //! }
80 //!
81 //! struct Gadget {
82 //!     id: i32,
83 //!     owner: Rc<Owner>,
84 //!     // ...other fields
85 //! }
86 //!
87 //! fn main() {
88 //!     // Create a reference-counted `Owner`.
89 //!     let gadget_owner: Rc<Owner> = Rc::new(
90 //!         Owner {
91 //!             name: "Gadget Man".to_string(),
92 //!         }
93 //!     );
94 //!
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 {
99 //!         id: 1,
100 //!         owner: Rc::clone(&gadget_owner),
101 //!     };
102 //!     let gadget2 = Gadget {
103 //!         id: 2,
104 //!         owner: Rc::clone(&gadget_owner),
105 //!     };
106 //!
107 //!     // Dispose of our local variable `gadget_owner`.
108 //!     drop(gadget_owner);
109 //!
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);
118 //!
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.
122 //! }
123 //! ```
124 //!
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`]
130 //! pointers.
131 //!
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.
140 //!
141 //! ```
142 //! use std::rc::Rc;
143 //! use std::rc::Weak;
144 //! use std::cell::RefCell;
145 //!
146 //! struct Owner {
147 //!     name: String,
148 //!     gadgets: RefCell<Vec<Weak<Gadget>>>,
149 //!     // ...other fields
150 //! }
151 //!
152 //! struct Gadget {
153 //!     id: i32,
154 //!     owner: Rc<Owner>,
155 //!     // ...other fields
156 //! }
157 //!
158 //! fn main() {
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(
163 //!         Owner {
164 //!             name: "Gadget Man".to_string(),
165 //!             gadgets: RefCell::new(vec![]),
166 //!         }
167 //!     );
168 //!
169 //!     // Create `Gadget`s belonging to `gadget_owner`, as before.
170 //!     let gadget1 = Rc::new(
171 //!         Gadget {
172 //!             id: 1,
173 //!             owner: Rc::clone(&gadget_owner),
174 //!         }
175 //!     );
176 //!     let gadget2 = Rc::new(
177 //!         Gadget {
178 //!             id: 2,
179 //!             owner: Rc::clone(&gadget_owner),
180 //!         }
181 //!     );
182 //!
183 //!     // Add the `Gadget`s to their `Owner`.
184 //!     {
185 //!         let mut gadgets = gadget_owner.gadgets.borrow_mut();
186 //!         gadgets.push(Rc::downgrade(&gadget1));
187 //!         gadgets.push(Rc::downgrade(&gadget2));
188 //!
189 //!         // `RefCell` dynamic borrow ends here.
190 //!     }
191 //!
192 //!     // Iterate over our `Gadget`s, printing their details out.
193 //!     for gadget_weak in gadget_owner.gadgets.borrow().iter() {
194 //!
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>>`.
198 //!         //
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.
202 //!
203 //!         let gadget = gadget_weak.upgrade().unwrap();
204 //!         println!("Gadget {} owned by {}", gadget.id, gadget.owner.name);
205 //!     }
206 //!
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.
211 //! }
212 //! ```
213 //!
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
226
227 #![stable(feature = "rust1", since = "1.0.0")]
228
229 #[cfg(not(test))]
230 use boxed::Box;
231 #[cfg(test)]
232 use std::boxed::Box;
233
234 use core::any::Any;
235 use core::borrow;
236 use core::cell::Cell;
237 use core::cmp::Ordering;
238 use core::fmt;
239 use core::hash::{Hash, Hasher};
240 use core::intrinsics::abort;
241 use core::marker;
242 use core::marker::{Unpin, Unsize, PhantomData};
243 use core::mem::{self, align_of_val, forget, size_of_val};
244 use core::ops::{Deref, Receiver};
245 use core::ops::{CoerceUnsized, DispatchFromDyn};
246 use core::pin::Pin;
247 use core::ptr::{self, NonNull};
248 use core::convert::From;
249 use core::usize;
250
251 use alloc::{Global, Alloc, Layout, box_free, handle_alloc_error};
252 use string::String;
253 use vec::Vec;
254
255 struct RcBox<T: ?Sized> {
256     strong: Cell<usize>,
257     weak: Cell<usize>,
258     value: T,
259 }
260
261 /// A single-threaded reference-counting pointer. 'Rc' stands for 'Reference
262 /// Counted'.
263 ///
264 /// See the [module-level documentation](./index.html) for more details.
265 ///
266 /// The inherent methods of `Rc` are all associated functions, which means
267 /// that you have to call them as e.g., [`Rc::get_mut(&mut value)`][get_mut] instead of
268 /// `value.get_mut()`. This avoids conflicts with methods of the inner
269 /// type `T`.
270 ///
271 /// [get_mut]: #method.get_mut
272 #[cfg_attr(not(test), lang = "rc")]
273 #[stable(feature = "rust1", since = "1.0.0")]
274 pub struct Rc<T: ?Sized> {
275     ptr: NonNull<RcBox<T>>,
276     phantom: PhantomData<T>,
277 }
278
279 #[stable(feature = "rust1", since = "1.0.0")]
280 impl<T: ?Sized> !marker::Send for Rc<T> {}
281 #[stable(feature = "rust1", since = "1.0.0")]
282 impl<T: ?Sized> !marker::Sync for Rc<T> {}
283
284 #[unstable(feature = "coerce_unsized", issue = "27732")]
285 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Rc<U>> for Rc<T> {}
286
287 #[unstable(feature = "dispatch_from_dyn", issue = "0")]
288 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Rc<U>> for Rc<T> {}
289
290 impl<T> Rc<T> {
291     /// Constructs a new `Rc<T>`.
292     ///
293     /// # Examples
294     ///
295     /// ```
296     /// use std::rc::Rc;
297     ///
298     /// let five = Rc::new(5);
299     /// ```
300     #[stable(feature = "rust1", since = "1.0.0")]
301     pub fn new(value: T) -> Rc<T> {
302         Rc {
303             // there is an implicit weak pointer owned by all the strong
304             // pointers, which ensures that the weak destructor never frees
305             // the allocation while the strong destructor is running, even
306             // if the weak pointer is stored inside the strong one.
307             ptr: Box::into_raw_non_null(box RcBox {
308                 strong: Cell::new(1),
309                 weak: Cell::new(1),
310                 value,
311             }),
312             phantom: PhantomData,
313         }
314     }
315
316     /// Constructs a new `Pin<Rc<T>>`. If `T` does not implement `Unpin`, then
317     /// `value` will be pinned in memory and unable to be moved.
318     #[stable(feature = "pin", since = "1.33.0")]
319     pub fn pin(value: T) -> Pin<Rc<T>> {
320         unsafe { Pin::new_unchecked(Rc::new(value)) }
321     }
322
323     /// Returns the contained value, if the `Rc` has exactly one strong reference.
324     ///
325     /// Otherwise, an [`Err`][result] is returned with the same `Rc` that was
326     /// passed in.
327     ///
328     /// This will succeed even if there are outstanding weak references.
329     ///
330     /// [result]: ../../std/result/enum.Result.html
331     ///
332     /// # Examples
333     ///
334     /// ```
335     /// use std::rc::Rc;
336     ///
337     /// let x = Rc::new(3);
338     /// assert_eq!(Rc::try_unwrap(x), Ok(3));
339     ///
340     /// let x = Rc::new(4);
341     /// let _y = Rc::clone(&x);
342     /// assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4);
343     /// ```
344     #[inline]
345     #[stable(feature = "rc_unique", since = "1.4.0")]
346     pub fn try_unwrap(this: Self) -> Result<T, Self> {
347         if Rc::strong_count(&this) == 1 {
348             unsafe {
349                 let val = ptr::read(&*this); // copy the contained object
350
351                 // Indicate to Weaks that they can't be promoted by decrementing
352                 // the strong count, and then remove the implicit "strong weak"
353                 // pointer while also handling drop logic by just crafting a
354                 // fake Weak.
355                 this.dec_strong();
356                 let _weak = Weak { ptr: this.ptr };
357                 forget(this);
358                 Ok(val)
359             }
360         } else {
361             Err(this)
362         }
363     }
364 }
365
366 impl<T: ?Sized> Rc<T> {
367     /// Consumes the `Rc`, returning the wrapped pointer.
368     ///
369     /// To avoid a memory leak the pointer must be converted back to an `Rc` using
370     /// [`Rc::from_raw`][from_raw].
371     ///
372     /// [from_raw]: struct.Rc.html#method.from_raw
373     ///
374     /// # Examples
375     ///
376     /// ```
377     /// use std::rc::Rc;
378     ///
379     /// let x = Rc::new(10);
380     /// let x_ptr = Rc::into_raw(x);
381     /// assert_eq!(unsafe { *x_ptr }, 10);
382     /// ```
383     #[stable(feature = "rc_raw", since = "1.17.0")]
384     pub fn into_raw(this: Self) -> *const T {
385         let ptr: *const T = &*this;
386         mem::forget(this);
387         ptr
388     }
389
390     /// Constructs an `Rc` from a raw pointer.
391     ///
392     /// The raw pointer must have been previously returned by a call to a
393     /// [`Rc::into_raw`][into_raw].
394     ///
395     /// This function is unsafe because improper use may lead to memory problems. For example, a
396     /// double-free may occur if the function is called twice on the same raw pointer.
397     ///
398     /// [into_raw]: struct.Rc.html#method.into_raw
399     ///
400     /// # Examples
401     ///
402     /// ```
403     /// use std::rc::Rc;
404     ///
405     /// let x = Rc::new(10);
406     /// let x_ptr = Rc::into_raw(x);
407     ///
408     /// unsafe {
409     ///     // Convert back to an `Rc` to prevent leak.
410     ///     let x = Rc::from_raw(x_ptr);
411     ///     assert_eq!(*x, 10);
412     ///
413     ///     // Further calls to `Rc::from_raw(x_ptr)` would be memory unsafe.
414     /// }
415     ///
416     /// // The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling!
417     /// ```
418     #[stable(feature = "rc_raw", since = "1.17.0")]
419     pub unsafe fn from_raw(ptr: *const T) -> Self {
420         // Align the unsized value to the end of the RcBox.
421         // Because it is ?Sized, it will always be the last field in memory.
422         let align = align_of_val(&*ptr);
423         let layout = Layout::new::<RcBox<()>>();
424         let offset = (layout.size() + layout.padding_needed_for(align)) as isize;
425
426         // Reverse the offset to find the original RcBox.
427         let fake_ptr = ptr as *mut RcBox<T>;
428         let rc_ptr = set_data_ptr(fake_ptr, (ptr as *mut u8).offset(-offset));
429
430         Rc {
431             ptr: NonNull::new_unchecked(rc_ptr),
432             phantom: PhantomData,
433         }
434     }
435
436     /// Creates a new [`Weak`][weak] pointer to this value.
437     ///
438     /// [weak]: struct.Weak.html
439     ///
440     /// # Examples
441     ///
442     /// ```
443     /// use std::rc::Rc;
444     ///
445     /// let five = Rc::new(5);
446     ///
447     /// let weak_five = Rc::downgrade(&five);
448     /// ```
449     #[stable(feature = "rc_weak", since = "1.4.0")]
450     pub fn downgrade(this: &Self) -> Weak<T> {
451         this.inc_weak();
452         // Make sure we do not create a dangling Weak
453         debug_assert!(!is_dangling(this.ptr));
454         Weak { ptr: this.ptr }
455     }
456
457     /// Gets the number of [`Weak`][weak] pointers to this value.
458     ///
459     /// [weak]: struct.Weak.html
460     ///
461     /// # Examples
462     ///
463     /// ```
464     /// use std::rc::Rc;
465     ///
466     /// let five = Rc::new(5);
467     /// let _weak_five = Rc::downgrade(&five);
468     ///
469     /// assert_eq!(1, Rc::weak_count(&five));
470     /// ```
471     #[inline]
472     #[stable(feature = "rc_counts", since = "1.15.0")]
473     pub fn weak_count(this: &Self) -> usize {
474         this.weak() - 1
475     }
476
477     /// Gets the number of strong (`Rc`) pointers to this value.
478     ///
479     /// # Examples
480     ///
481     /// ```
482     /// use std::rc::Rc;
483     ///
484     /// let five = Rc::new(5);
485     /// let _also_five = Rc::clone(&five);
486     ///
487     /// assert_eq!(2, Rc::strong_count(&five));
488     /// ```
489     #[inline]
490     #[stable(feature = "rc_counts", since = "1.15.0")]
491     pub fn strong_count(this: &Self) -> usize {
492         this.strong()
493     }
494
495     /// Returns true if there are no other `Rc` or [`Weak`][weak] pointers to
496     /// this inner value.
497     ///
498     /// [weak]: struct.Weak.html
499     #[inline]
500     fn is_unique(this: &Self) -> bool {
501         Rc::weak_count(this) == 0 && Rc::strong_count(this) == 1
502     }
503
504     /// Returns a mutable reference to the inner value, if there are
505     /// no other `Rc` or [`Weak`][weak] pointers to the same value.
506     ///
507     /// Returns [`None`] otherwise, because it is not safe to
508     /// mutate a shared value.
509     ///
510     /// See also [`make_mut`][make_mut], which will [`clone`][clone]
511     /// the inner value when it's shared.
512     ///
513     /// [weak]: struct.Weak.html
514     /// [`None`]: ../../std/option/enum.Option.html#variant.None
515     /// [make_mut]: struct.Rc.html#method.make_mut
516     /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
517     ///
518     /// # Examples
519     ///
520     /// ```
521     /// use std::rc::Rc;
522     ///
523     /// let mut x = Rc::new(3);
524     /// *Rc::get_mut(&mut x).unwrap() = 4;
525     /// assert_eq!(*x, 4);
526     ///
527     /// let _y = Rc::clone(&x);
528     /// assert!(Rc::get_mut(&mut x).is_none());
529     /// ```
530     #[inline]
531     #[stable(feature = "rc_unique", since = "1.4.0")]
532     pub fn get_mut(this: &mut Self) -> Option<&mut T> {
533         if Rc::is_unique(this) {
534             unsafe {
535                 Some(&mut this.ptr.as_mut().value)
536             }
537         } else {
538             None
539         }
540     }
541
542     #[inline]
543     #[stable(feature = "ptr_eq", since = "1.17.0")]
544     /// Returns true if the two `Rc`s point to the same value (not
545     /// just values that compare as equal).
546     ///
547     /// # Examples
548     ///
549     /// ```
550     /// use std::rc::Rc;
551     ///
552     /// let five = Rc::new(5);
553     /// let same_five = Rc::clone(&five);
554     /// let other_five = Rc::new(5);
555     ///
556     /// assert!(Rc::ptr_eq(&five, &same_five));
557     /// assert!(!Rc::ptr_eq(&five, &other_five));
558     /// ```
559     pub fn ptr_eq(this: &Self, other: &Self) -> bool {
560         this.ptr.as_ptr() == other.ptr.as_ptr()
561     }
562 }
563
564 impl<T: Clone> Rc<T> {
565     /// Makes a mutable reference into the given `Rc`.
566     ///
567     /// If there are other `Rc` or [`Weak`][weak] pointers to the same value,
568     /// then `make_mut` will invoke [`clone`][clone] on the inner value to
569     /// ensure unique ownership. This is also referred to as clone-on-write.
570     ///
571     /// See also [`get_mut`][get_mut], which will fail rather than cloning.
572     ///
573     /// [weak]: struct.Weak.html
574     /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
575     /// [get_mut]: struct.Rc.html#method.get_mut
576     ///
577     /// # Examples
578     ///
579     /// ```
580     /// use std::rc::Rc;
581     ///
582     /// let mut data = Rc::new(5);
583     ///
584     /// *Rc::make_mut(&mut data) += 1;        // Won't clone anything
585     /// let mut other_data = Rc::clone(&data);    // Won't clone inner data
586     /// *Rc::make_mut(&mut data) += 1;        // Clones inner data
587     /// *Rc::make_mut(&mut data) += 1;        // Won't clone anything
588     /// *Rc::make_mut(&mut other_data) *= 2;  // Won't clone anything
589     ///
590     /// // Now `data` and `other_data` point to different values.
591     /// assert_eq!(*data, 8);
592     /// assert_eq!(*other_data, 12);
593     /// ```
594     #[inline]
595     #[stable(feature = "rc_unique", since = "1.4.0")]
596     pub fn make_mut(this: &mut Self) -> &mut T {
597         if Rc::strong_count(this) != 1 {
598             // Gotta clone the data, there are other Rcs
599             *this = Rc::new((**this).clone())
600         } else if Rc::weak_count(this) != 0 {
601             // Can just steal the data, all that's left is Weaks
602             unsafe {
603                 let mut swap = Rc::new(ptr::read(&this.ptr.as_ref().value));
604                 mem::swap(this, &mut swap);
605                 swap.dec_strong();
606                 // Remove implicit strong-weak ref (no need to craft a fake
607                 // Weak here -- we know other Weaks can clean up for us)
608                 swap.dec_weak();
609                 forget(swap);
610             }
611         }
612         // This unsafety is ok because we're guaranteed that the pointer
613         // returned is the *only* pointer that will ever be returned to T. Our
614         // reference count is guaranteed to be 1 at this point, and we required
615         // the `Rc<T>` itself to be `mut`, so we're returning the only possible
616         // reference to the inner value.
617         unsafe {
618             &mut this.ptr.as_mut().value
619         }
620     }
621 }
622
623 impl Rc<dyn Any> {
624     #[inline]
625     #[stable(feature = "rc_downcast", since = "1.29.0")]
626     /// Attempt to downcast the `Rc<dyn Any>` to a concrete type.
627     ///
628     /// # Examples
629     ///
630     /// ```
631     /// use std::any::Any;
632     /// use std::rc::Rc;
633     ///
634     /// fn print_if_string(value: Rc<dyn Any>) {
635     ///     if let Ok(string) = value.downcast::<String>() {
636     ///         println!("String ({}): {}", string.len(), string);
637     ///     }
638     /// }
639     ///
640     /// fn main() {
641     ///     let my_string = "Hello World".to_string();
642     ///     print_if_string(Rc::new(my_string));
643     ///     print_if_string(Rc::new(0i8));
644     /// }
645     /// ```
646     pub fn downcast<T: Any>(self) -> Result<Rc<T>, Rc<dyn Any>> {
647         if (*self).is::<T>() {
648             let ptr = self.ptr.cast::<RcBox<T>>();
649             forget(self);
650             Ok(Rc { ptr, phantom: PhantomData })
651         } else {
652             Err(self)
653         }
654     }
655 }
656
657 impl<T: ?Sized> Rc<T> {
658     // Allocates an `RcBox<T>` with sufficient space for an unsized value
659     unsafe fn allocate_for_ptr(ptr: *const T) -> *mut RcBox<T> {
660         // Calculate layout using the given value.
661         // Previously, layout was calculated on the expression
662         // `&*(ptr as *const RcBox<T>)`, but this created a misaligned
663         // reference (see #54908).
664         let layout = Layout::new::<RcBox<()>>()
665             .extend(Layout::for_value(&*ptr)).unwrap().0
666             .pad_to_align().unwrap();
667
668         let mem = Global.alloc(layout)
669             .unwrap_or_else(|_| handle_alloc_error(layout));
670
671         // Initialize the RcBox
672         let inner = set_data_ptr(ptr as *mut T, mem.as_ptr() as *mut u8) as *mut RcBox<T>;
673         debug_assert_eq!(Layout::for_value(&*inner), layout);
674
675         ptr::write(&mut (*inner).strong, Cell::new(1));
676         ptr::write(&mut (*inner).weak, Cell::new(1));
677
678         inner
679     }
680
681     fn from_box(v: Box<T>) -> Rc<T> {
682         unsafe {
683             let box_unique = Box::into_unique(v);
684             let bptr = box_unique.as_ptr();
685
686             let value_size = size_of_val(&*bptr);
687             let ptr = Self::allocate_for_ptr(bptr);
688
689             // Copy value as bytes
690             ptr::copy_nonoverlapping(
691                 bptr as *const T as *const u8,
692                 &mut (*ptr).value as *mut _ as *mut u8,
693                 value_size);
694
695             // Free the allocation without dropping its contents
696             box_free(box_unique);
697
698             Rc { ptr: NonNull::new_unchecked(ptr), phantom: PhantomData }
699         }
700     }
701 }
702
703 // Sets the data pointer of a `?Sized` raw pointer.
704 //
705 // For a slice/trait object, this sets the `data` field and leaves the rest
706 // unchanged. For a sized raw pointer, this simply sets the pointer.
707 unsafe fn set_data_ptr<T: ?Sized, U>(mut ptr: *mut T, data: *mut U) -> *mut T {
708     ptr::write(&mut ptr as *mut _ as *mut *mut u8, data as *mut u8);
709     ptr
710 }
711
712 impl<T> Rc<[T]> {
713     // Copy elements from slice into newly allocated Rc<[T]>
714     //
715     // Unsafe because the caller must either take ownership or bind `T: Copy`
716     unsafe fn copy_from_slice(v: &[T]) -> Rc<[T]> {
717         let v_ptr = v as *const [T];
718         let ptr = Self::allocate_for_ptr(v_ptr);
719
720         ptr::copy_nonoverlapping(
721             v.as_ptr(),
722             &mut (*ptr).value as *mut [T] as *mut T,
723             v.len());
724
725         Rc { ptr: NonNull::new_unchecked(ptr), phantom: PhantomData }
726     }
727 }
728
729 trait RcFromSlice<T> {
730     fn from_slice(slice: &[T]) -> Self;
731 }
732
733 impl<T: Clone> RcFromSlice<T> for Rc<[T]> {
734     #[inline]
735     default fn from_slice(v: &[T]) -> Self {
736         // Panic guard while cloning T elements.
737         // In the event of a panic, elements that have been written
738         // into the new RcBox will be dropped, then the memory freed.
739         struct Guard<T> {
740             mem: NonNull<u8>,
741             elems: *mut T,
742             layout: Layout,
743             n_elems: usize,
744         }
745
746         impl<T> Drop for Guard<T> {
747             fn drop(&mut self) {
748                 use core::slice::from_raw_parts_mut;
749
750                 unsafe {
751                     let slice = from_raw_parts_mut(self.elems, self.n_elems);
752                     ptr::drop_in_place(slice);
753
754                     Global.dealloc(self.mem, self.layout.clone());
755                 }
756             }
757         }
758
759         unsafe {
760             let v_ptr = v as *const [T];
761             let ptr = Self::allocate_for_ptr(v_ptr);
762
763             let mem = ptr as *mut _ as *mut u8;
764             let layout = Layout::for_value(&*ptr);
765
766             // Pointer to first element
767             let elems = &mut (*ptr).value as *mut [T] as *mut T;
768
769             let mut guard = Guard{
770                 mem: NonNull::new_unchecked(mem),
771                 elems: elems,
772                 layout: layout,
773                 n_elems: 0,
774             };
775
776             for (i, item) in v.iter().enumerate() {
777                 ptr::write(elems.add(i), item.clone());
778                 guard.n_elems += 1;
779             }
780
781             // All clear. Forget the guard so it doesn't free the new RcBox.
782             forget(guard);
783
784             Rc { ptr: NonNull::new_unchecked(ptr), phantom: PhantomData }
785         }
786     }
787 }
788
789 impl<T: Copy> RcFromSlice<T> for Rc<[T]> {
790     #[inline]
791     fn from_slice(v: &[T]) -> Self {
792         unsafe { Rc::copy_from_slice(v) }
793     }
794 }
795
796 #[stable(feature = "rust1", since = "1.0.0")]
797 impl<T: ?Sized> Deref for Rc<T> {
798     type Target = T;
799
800     #[inline(always)]
801     fn deref(&self) -> &T {
802         &self.inner().value
803     }
804 }
805
806 #[unstable(feature = "receiver_trait", issue = "0")]
807 impl<T: ?Sized> Receiver for Rc<T> {}
808
809 #[stable(feature = "rust1", since = "1.0.0")]
810 unsafe impl<#[may_dangle] T: ?Sized> Drop for Rc<T> {
811     /// Drops the `Rc`.
812     ///
813     /// This will decrement the strong reference count. If the strong reference
814     /// count reaches zero then the only other references (if any) are
815     /// [`Weak`], so we `drop` the inner value.
816     ///
817     /// # Examples
818     ///
819     /// ```
820     /// use std::rc::Rc;
821     ///
822     /// struct Foo;
823     ///
824     /// impl Drop for Foo {
825     ///     fn drop(&mut self) {
826     ///         println!("dropped!");
827     ///     }
828     /// }
829     ///
830     /// let foo  = Rc::new(Foo);
831     /// let foo2 = Rc::clone(&foo);
832     ///
833     /// drop(foo);    // Doesn't print anything
834     /// drop(foo2);   // Prints "dropped!"
835     /// ```
836     ///
837     /// [`Weak`]: ../../std/rc/struct.Weak.html
838     fn drop(&mut self) {
839         unsafe {
840             self.dec_strong();
841             if self.strong() == 0 {
842                 // destroy the contained object
843                 ptr::drop_in_place(self.ptr.as_mut());
844
845                 // remove the implicit "strong weak" pointer now that we've
846                 // destroyed the contents.
847                 self.dec_weak();
848
849                 if self.weak() == 0 {
850                     Global.dealloc(self.ptr.cast(), Layout::for_value(self.ptr.as_ref()));
851                 }
852             }
853         }
854     }
855 }
856
857 #[stable(feature = "rust1", since = "1.0.0")]
858 impl<T: ?Sized> Clone for Rc<T> {
859     /// Makes a clone of the `Rc` pointer.
860     ///
861     /// This creates another pointer to the same inner value, increasing the
862     /// strong reference count.
863     ///
864     /// # Examples
865     ///
866     /// ```
867     /// use std::rc::Rc;
868     ///
869     /// let five = Rc::new(5);
870     ///
871     /// let _ = Rc::clone(&five);
872     /// ```
873     #[inline]
874     fn clone(&self) -> Rc<T> {
875         self.inc_strong();
876         Rc { ptr: self.ptr, phantom: PhantomData }
877     }
878 }
879
880 #[stable(feature = "rust1", since = "1.0.0")]
881 impl<T: Default> Default for Rc<T> {
882     /// Creates a new `Rc<T>`, with the `Default` value for `T`.
883     ///
884     /// # Examples
885     ///
886     /// ```
887     /// use std::rc::Rc;
888     ///
889     /// let x: Rc<i32> = Default::default();
890     /// assert_eq!(*x, 0);
891     /// ```
892     #[inline]
893     fn default() -> Rc<T> {
894         Rc::new(Default::default())
895     }
896 }
897
898 #[stable(feature = "rust1", since = "1.0.0")]
899 trait RcEqIdent<T: ?Sized + PartialEq> {
900     fn eq(&self, other: &Rc<T>) -> bool;
901     fn ne(&self, other: &Rc<T>) -> bool;
902 }
903
904 #[stable(feature = "rust1", since = "1.0.0")]
905 impl<T: ?Sized + PartialEq> RcEqIdent<T> for Rc<T> {
906     #[inline]
907     default fn eq(&self, other: &Rc<T>) -> bool {
908         **self == **other
909     }
910
911     #[inline]
912     default fn ne(&self, other: &Rc<T>) -> bool {
913         **self != **other
914     }
915 }
916
917 #[stable(feature = "rust1", since = "1.0.0")]
918 impl<T: ?Sized + Eq> RcEqIdent<T> for Rc<T> {
919     #[inline]
920     fn eq(&self, other: &Rc<T>) -> bool {
921         Rc::ptr_eq(self, other) || **self == **other
922     }
923
924     #[inline]
925     fn ne(&self, other: &Rc<T>) -> bool {
926         !Rc::ptr_eq(self, other) && **self != **other
927     }
928 }
929
930 #[stable(feature = "rust1", since = "1.0.0")]
931 impl<T: ?Sized + PartialEq> PartialEq for Rc<T> {
932     /// Equality for two `Rc`s.
933     ///
934     /// Two `Rc`s are equal if their inner values are equal.
935     ///
936     /// If `T` also implements `Eq`, two `Rc`s that point to the same value are
937     /// always equal.
938     ///
939     /// # Examples
940     ///
941     /// ```
942     /// use std::rc::Rc;
943     ///
944     /// let five = Rc::new(5);
945     ///
946     /// assert!(five == Rc::new(5));
947     /// ```
948     #[inline]
949     fn eq(&self, other: &Rc<T>) -> bool {
950         RcEqIdent::eq(self, other)
951     }
952
953     /// Inequality for two `Rc`s.
954     ///
955     /// Two `Rc`s are unequal if their inner values are unequal.
956     ///
957     /// If `T` also implements `Eq`, two `Rc`s that point to the same value are
958     /// never unequal.
959     ///
960     /// # Examples
961     ///
962     /// ```
963     /// use std::rc::Rc;
964     ///
965     /// let five = Rc::new(5);
966     ///
967     /// assert!(five != Rc::new(6));
968     /// ```
969     #[inline]
970     fn ne(&self, other: &Rc<T>) -> bool {
971         RcEqIdent::ne(self, other)
972     }
973 }
974
975 #[stable(feature = "rust1", since = "1.0.0")]
976 impl<T: ?Sized + Eq> Eq for Rc<T> {}
977
978 #[stable(feature = "rust1", since = "1.0.0")]
979 impl<T: ?Sized + PartialOrd> PartialOrd for Rc<T> {
980     /// Partial comparison for two `Rc`s.
981     ///
982     /// The two are compared by calling `partial_cmp()` on their inner values.
983     ///
984     /// # Examples
985     ///
986     /// ```
987     /// use std::rc::Rc;
988     /// use std::cmp::Ordering;
989     ///
990     /// let five = Rc::new(5);
991     ///
992     /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&Rc::new(6)));
993     /// ```
994     #[inline(always)]
995     fn partial_cmp(&self, other: &Rc<T>) -> Option<Ordering> {
996         (**self).partial_cmp(&**other)
997     }
998
999     /// Less-than comparison for two `Rc`s.
1000     ///
1001     /// The two are compared by calling `<` on their inner values.
1002     ///
1003     /// # Examples
1004     ///
1005     /// ```
1006     /// use std::rc::Rc;
1007     ///
1008     /// let five = Rc::new(5);
1009     ///
1010     /// assert!(five < Rc::new(6));
1011     /// ```
1012     #[inline(always)]
1013     fn lt(&self, other: &Rc<T>) -> bool {
1014         **self < **other
1015     }
1016
1017     /// 'Less than or equal to' comparison for two `Rc`s.
1018     ///
1019     /// The two are compared by calling `<=` on their inner values.
1020     ///
1021     /// # Examples
1022     ///
1023     /// ```
1024     /// use std::rc::Rc;
1025     ///
1026     /// let five = Rc::new(5);
1027     ///
1028     /// assert!(five <= Rc::new(5));
1029     /// ```
1030     #[inline(always)]
1031     fn le(&self, other: &Rc<T>) -> bool {
1032         **self <= **other
1033     }
1034
1035     /// Greater-than comparison for two `Rc`s.
1036     ///
1037     /// The two are compared by calling `>` on their inner values.
1038     ///
1039     /// # Examples
1040     ///
1041     /// ```
1042     /// use std::rc::Rc;
1043     ///
1044     /// let five = Rc::new(5);
1045     ///
1046     /// assert!(five > Rc::new(4));
1047     /// ```
1048     #[inline(always)]
1049     fn gt(&self, other: &Rc<T>) -> bool {
1050         **self > **other
1051     }
1052
1053     /// 'Greater than or equal to' comparison for two `Rc`s.
1054     ///
1055     /// The two are compared by calling `>=` on their inner values.
1056     ///
1057     /// # Examples
1058     ///
1059     /// ```
1060     /// use std::rc::Rc;
1061     ///
1062     /// let five = Rc::new(5);
1063     ///
1064     /// assert!(five >= Rc::new(5));
1065     /// ```
1066     #[inline(always)]
1067     fn ge(&self, other: &Rc<T>) -> bool {
1068         **self >= **other
1069     }
1070 }
1071
1072 #[stable(feature = "rust1", since = "1.0.0")]
1073 impl<T: ?Sized + Ord> Ord for Rc<T> {
1074     /// Comparison for two `Rc`s.
1075     ///
1076     /// The two are compared by calling `cmp()` on their inner values.
1077     ///
1078     /// # Examples
1079     ///
1080     /// ```
1081     /// use std::rc::Rc;
1082     /// use std::cmp::Ordering;
1083     ///
1084     /// let five = Rc::new(5);
1085     ///
1086     /// assert_eq!(Ordering::Less, five.cmp(&Rc::new(6)));
1087     /// ```
1088     #[inline]
1089     fn cmp(&self, other: &Rc<T>) -> Ordering {
1090         (**self).cmp(&**other)
1091     }
1092 }
1093
1094 #[stable(feature = "rust1", since = "1.0.0")]
1095 impl<T: ?Sized + Hash> Hash for Rc<T> {
1096     fn hash<H: Hasher>(&self, state: &mut H) {
1097         (**self).hash(state);
1098     }
1099 }
1100
1101 #[stable(feature = "rust1", since = "1.0.0")]
1102 impl<T: ?Sized + fmt::Display> fmt::Display for Rc<T> {
1103     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1104         fmt::Display::fmt(&**self, f)
1105     }
1106 }
1107
1108 #[stable(feature = "rust1", since = "1.0.0")]
1109 impl<T: ?Sized + fmt::Debug> fmt::Debug for Rc<T> {
1110     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1111         fmt::Debug::fmt(&**self, f)
1112     }
1113 }
1114
1115 #[stable(feature = "rust1", since = "1.0.0")]
1116 impl<T: ?Sized> fmt::Pointer for Rc<T> {
1117     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1118         fmt::Pointer::fmt(&(&**self as *const T), f)
1119     }
1120 }
1121
1122 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
1123 impl<T> From<T> for Rc<T> {
1124     fn from(t: T) -> Self {
1125         Rc::new(t)
1126     }
1127 }
1128
1129 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1130 impl<'a, T: Clone> From<&'a [T]> for Rc<[T]> {
1131     #[inline]
1132     fn from(v: &[T]) -> Rc<[T]> {
1133         <Self as RcFromSlice<T>>::from_slice(v)
1134     }
1135 }
1136
1137 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1138 impl<'a> From<&'a str> for Rc<str> {
1139     #[inline]
1140     fn from(v: &str) -> Rc<str> {
1141         let rc = Rc::<[u8]>::from(v.as_bytes());
1142         unsafe { Rc::from_raw(Rc::into_raw(rc) as *const str) }
1143     }
1144 }
1145
1146 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1147 impl From<String> for Rc<str> {
1148     #[inline]
1149     fn from(v: String) -> Rc<str> {
1150         Rc::from(&v[..])
1151     }
1152 }
1153
1154 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1155 impl<T: ?Sized> From<Box<T>> for Rc<T> {
1156     #[inline]
1157     fn from(v: Box<T>) -> Rc<T> {
1158         Rc::from_box(v)
1159     }
1160 }
1161
1162 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1163 impl<T> From<Vec<T>> for Rc<[T]> {
1164     #[inline]
1165     fn from(mut v: Vec<T>) -> Rc<[T]> {
1166         unsafe {
1167             let rc = Rc::copy_from_slice(&v);
1168
1169             // Allow the Vec to free its memory, but not destroy its contents
1170             v.set_len(0);
1171
1172             rc
1173         }
1174     }
1175 }
1176
1177 /// `Weak` is a version of [`Rc`] that holds a non-owning reference to the
1178 /// managed value. The value is accessed by calling [`upgrade`] on the `Weak`
1179 /// pointer, which returns an [`Option`]`<`[`Rc`]`<T>>`.
1180 ///
1181 /// Since a `Weak` reference does not count towards ownership, it will not
1182 /// prevent the inner value from being dropped, and `Weak` itself makes no
1183 /// guarantees about the value still being present and may return [`None`]
1184 /// when [`upgrade`]d.
1185 ///
1186 /// A `Weak` pointer is useful for keeping a temporary reference to the value
1187 /// within [`Rc`] without extending its lifetime. It is also used to prevent
1188 /// circular references between [`Rc`] pointers, since mutual owning references
1189 /// would never allow either [`Rc`] to be dropped. For example, a tree could
1190 /// have strong [`Rc`] pointers from parent nodes to children, and `Weak`
1191 /// pointers from children back to their parents.
1192 ///
1193 /// The typical way to obtain a `Weak` pointer is to call [`Rc::downgrade`].
1194 ///
1195 /// [`Rc`]: struct.Rc.html
1196 /// [`Rc::downgrade`]: struct.Rc.html#method.downgrade
1197 /// [`upgrade`]: struct.Weak.html#method.upgrade
1198 /// [`Option`]: ../../std/option/enum.Option.html
1199 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1200 #[stable(feature = "rc_weak", since = "1.4.0")]
1201 pub struct Weak<T: ?Sized> {
1202     // This is a `NonNull` to allow optimizing the size of this type in enums,
1203     // but it is not necessarily a valid pointer.
1204     // `Weak::new` sets this to `usize::MAX` so that it doesn’t need
1205     // to allocate space on the heap.  That's not a value a real pointer
1206     // will ever have because RcBox has alignment at least 2.
1207     ptr: NonNull<RcBox<T>>,
1208 }
1209
1210 #[stable(feature = "rc_weak", since = "1.4.0")]
1211 impl<T: ?Sized> !marker::Send for Weak<T> {}
1212 #[stable(feature = "rc_weak", since = "1.4.0")]
1213 impl<T: ?Sized> !marker::Sync for Weak<T> {}
1214
1215 #[unstable(feature = "coerce_unsized", issue = "27732")]
1216 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {}
1217
1218 #[unstable(feature = "dispatch_from_dyn", issue = "0")]
1219 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Weak<U>> for Weak<T> {}
1220
1221 impl<T> Weak<T> {
1222     /// Constructs a new `Weak<T>`, without allocating any memory.
1223     /// Calling [`upgrade`] on the return value always gives [`None`].
1224     ///
1225     /// [`upgrade`]: #method.upgrade
1226     /// [`None`]: ../../std/option/enum.Option.html
1227     ///
1228     /// # Examples
1229     ///
1230     /// ```
1231     /// use std::rc::Weak;
1232     ///
1233     /// let empty: Weak<i64> = Weak::new();
1234     /// assert!(empty.upgrade().is_none());
1235     /// ```
1236     #[stable(feature = "downgraded_weak", since = "1.10.0")]
1237     pub fn new() -> Weak<T> {
1238         Weak {
1239             ptr: NonNull::new(usize::MAX as *mut RcBox<T>).expect("MAX is not 0"),
1240         }
1241     }
1242 }
1243
1244 pub(crate) fn is_dangling<T: ?Sized>(ptr: NonNull<T>) -> bool {
1245     let address = ptr.as_ptr() as *mut () as usize;
1246     address == usize::MAX
1247 }
1248
1249 impl<T: ?Sized> Weak<T> {
1250     /// Attempts to upgrade the `Weak` pointer to an [`Rc`], extending
1251     /// the lifetime of the value if successful.
1252     ///
1253     /// Returns [`None`] if the value has since been dropped.
1254     ///
1255     /// [`Rc`]: struct.Rc.html
1256     /// [`None`]: ../../std/option/enum.Option.html
1257     ///
1258     /// # Examples
1259     ///
1260     /// ```
1261     /// use std::rc::Rc;
1262     ///
1263     /// let five = Rc::new(5);
1264     ///
1265     /// let weak_five = Rc::downgrade(&five);
1266     ///
1267     /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
1268     /// assert!(strong_five.is_some());
1269     ///
1270     /// // Destroy all strong pointers.
1271     /// drop(strong_five);
1272     /// drop(five);
1273     ///
1274     /// assert!(weak_five.upgrade().is_none());
1275     /// ```
1276     #[stable(feature = "rc_weak", since = "1.4.0")]
1277     pub fn upgrade(&self) -> Option<Rc<T>> {
1278         let inner = self.inner()?;
1279         if inner.strong() == 0 {
1280             None
1281         } else {
1282             inner.inc_strong();
1283             Some(Rc { ptr: self.ptr, phantom: PhantomData })
1284         }
1285     }
1286
1287     /// Gets the number of strong (`Rc`) pointers pointing to this value.
1288     ///
1289     /// If `self` was created using [`Weak::new`], this will return 0.
1290     ///
1291     /// [`Weak::new`]: #method.new
1292     #[unstable(feature = "weak_counts", issue = "57977")]
1293     pub fn strong_count(&self) -> usize {
1294         if let Some(inner) = self.inner() {
1295             inner.strong()
1296         } else {
1297             0
1298         }
1299     }
1300
1301     /// Gets the number of `Weak` pointers pointing to this value.
1302     ///
1303     /// If `self` was created using [`Weak::new`], this will return `None`. If
1304     /// not, the returned value is at least 1, since `self` still points to the
1305     /// value.
1306     ///
1307     /// [`Weak::new`]: #method.new
1308     #[unstable(feature = "weak_counts", issue = "57977")]
1309     pub fn weak_count(&self) -> Option<usize> {
1310         self.inner().map(|inner| {
1311             if inner.strong() > 0 {
1312                 inner.weak() - 1  // subtract the implicit weak ptr
1313             } else {
1314                 inner.weak()
1315             }
1316         })
1317     }
1318
1319     /// Return `None` when the pointer is dangling and there is no allocated `RcBox`,
1320     /// i.e., this `Weak` was created by `Weak::new`
1321     #[inline]
1322     fn inner(&self) -> Option<&RcBox<T>> {
1323         if is_dangling(self.ptr) {
1324             None
1325         } else {
1326             Some(unsafe { self.ptr.as_ref() })
1327         }
1328     }
1329
1330     /// Returns true if the two `Weak`s point to the same value (not just values
1331     /// that compare as equal).
1332     ///
1333     /// # Notes
1334     ///
1335     /// Since this compares pointers it means that `Weak::new()` will equal each
1336     /// other, even though they don't point to any value.
1337     ///
1338     /// # Examples
1339     ///
1340     /// ```
1341     /// #![feature(weak_ptr_eq)]
1342     /// use std::rc::{Rc, Weak};
1343     ///
1344     /// let first_rc = Rc::new(5);
1345     /// let first = Rc::downgrade(&first_rc);
1346     /// let second = Rc::downgrade(&first_rc);
1347     ///
1348     /// assert!(Weak::ptr_eq(&first, &second));
1349     ///
1350     /// let third_rc = Rc::new(5);
1351     /// let third = Rc::downgrade(&third_rc);
1352     ///
1353     /// assert!(!Weak::ptr_eq(&first, &third));
1354     /// ```
1355     ///
1356     /// Comparing `Weak::new`.
1357     ///
1358     /// ```
1359     /// #![feature(weak_ptr_eq)]
1360     /// use std::rc::{Rc, Weak};
1361     ///
1362     /// let first = Weak::new();
1363     /// let second = Weak::new();
1364     /// assert!(Weak::ptr_eq(&first, &second));
1365     ///
1366     /// let third_rc = Rc::new(());
1367     /// let third = Rc::downgrade(&third_rc);
1368     /// assert!(!Weak::ptr_eq(&first, &third));
1369     /// ```
1370     #[inline]
1371     #[unstable(feature = "weak_ptr_eq", issue = "55981")]
1372     pub fn ptr_eq(this: &Self, other: &Self) -> bool {
1373         this.ptr.as_ptr() == other.ptr.as_ptr()
1374     }
1375 }
1376
1377 #[stable(feature = "rc_weak", since = "1.4.0")]
1378 impl<T: ?Sized> Drop for Weak<T> {
1379     /// Drops the `Weak` pointer.
1380     ///
1381     /// # Examples
1382     ///
1383     /// ```
1384     /// use std::rc::{Rc, Weak};
1385     ///
1386     /// struct Foo;
1387     ///
1388     /// impl Drop for Foo {
1389     ///     fn drop(&mut self) {
1390     ///         println!("dropped!");
1391     ///     }
1392     /// }
1393     ///
1394     /// let foo = Rc::new(Foo);
1395     /// let weak_foo = Rc::downgrade(&foo);
1396     /// let other_weak_foo = Weak::clone(&weak_foo);
1397     ///
1398     /// drop(weak_foo);   // Doesn't print anything
1399     /// drop(foo);        // Prints "dropped!"
1400     ///
1401     /// assert!(other_weak_foo.upgrade().is_none());
1402     /// ```
1403     fn drop(&mut self) {
1404         if let Some(inner) = self.inner() {
1405             inner.dec_weak();
1406             // the weak count starts at 1, and will only go to zero if all
1407             // the strong pointers have disappeared.
1408             if inner.weak() == 0 {
1409                 unsafe {
1410                     Global.dealloc(self.ptr.cast(), Layout::for_value(self.ptr.as_ref()));
1411                 }
1412             }
1413         }
1414     }
1415 }
1416
1417 #[stable(feature = "rc_weak", since = "1.4.0")]
1418 impl<T: ?Sized> Clone for Weak<T> {
1419     /// Makes a clone of the `Weak` pointer that points to the same value.
1420     ///
1421     /// # Examples
1422     ///
1423     /// ```
1424     /// use std::rc::{Rc, Weak};
1425     ///
1426     /// let weak_five = Rc::downgrade(&Rc::new(5));
1427     ///
1428     /// let _ = Weak::clone(&weak_five);
1429     /// ```
1430     #[inline]
1431     fn clone(&self) -> Weak<T> {
1432         if let Some(inner) = self.inner() {
1433             inner.inc_weak()
1434         }
1435         Weak { ptr: self.ptr }
1436     }
1437 }
1438
1439 #[stable(feature = "rc_weak", since = "1.4.0")]
1440 impl<T: ?Sized + fmt::Debug> fmt::Debug for Weak<T> {
1441     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1442         write!(f, "(Weak)")
1443     }
1444 }
1445
1446 #[stable(feature = "downgraded_weak", since = "1.10.0")]
1447 impl<T> Default for Weak<T> {
1448     /// Constructs a new `Weak<T>`, allocating memory for `T` without initializing
1449     /// it. Calling [`upgrade`] on the return value always gives [`None`].
1450     ///
1451     /// [`None`]: ../../std/option/enum.Option.html
1452     /// [`upgrade`]: ../../std/rc/struct.Weak.html#method.upgrade
1453     ///
1454     /// # Examples
1455     ///
1456     /// ```
1457     /// use std::rc::Weak;
1458     ///
1459     /// let empty: Weak<i64> = Default::default();
1460     /// assert!(empty.upgrade().is_none());
1461     /// ```
1462     fn default() -> Weak<T> {
1463         Weak::new()
1464     }
1465 }
1466
1467 // NOTE: We checked_add here to deal with mem::forget safely. In particular
1468 // if you mem::forget Rcs (or Weaks), the ref-count can overflow, and then
1469 // you can free the allocation while outstanding Rcs (or Weaks) exist.
1470 // We abort because this is such a degenerate scenario that we don't care about
1471 // what happens -- no real program should ever experience this.
1472 //
1473 // This should have negligible overhead since you don't actually need to
1474 // clone these much in Rust thanks to ownership and move-semantics.
1475
1476 #[doc(hidden)]
1477 trait RcBoxPtr<T: ?Sized> {
1478     fn inner(&self) -> &RcBox<T>;
1479
1480     #[inline]
1481     fn strong(&self) -> usize {
1482         self.inner().strong.get()
1483     }
1484
1485     #[inline]
1486     fn inc_strong(&self) {
1487         // We want to abort on overflow instead of dropping the value.
1488         // The reference count will never be zero when this is called;
1489         // nevertheless, we insert an abort here to hint LLVM at
1490         // an otherwise missed optimization.
1491         if self.strong() == 0 || self.strong() == usize::max_value() {
1492             unsafe { abort(); }
1493         }
1494         self.inner().strong.set(self.strong() + 1);
1495     }
1496
1497     #[inline]
1498     fn dec_strong(&self) {
1499         self.inner().strong.set(self.strong() - 1);
1500     }
1501
1502     #[inline]
1503     fn weak(&self) -> usize {
1504         self.inner().weak.get()
1505     }
1506
1507     #[inline]
1508     fn inc_weak(&self) {
1509         // We want to abort on overflow instead of dropping the value.
1510         // The reference count will never be zero when this is called;
1511         // nevertheless, we insert an abort here to hint LLVM at
1512         // an otherwise missed optimization.
1513         if self.weak() == 0 || self.weak() == usize::max_value() {
1514             unsafe { abort(); }
1515         }
1516         self.inner().weak.set(self.weak() + 1);
1517     }
1518
1519     #[inline]
1520     fn dec_weak(&self) {
1521         self.inner().weak.set(self.weak() - 1);
1522     }
1523 }
1524
1525 impl<T: ?Sized> RcBoxPtr<T> for Rc<T> {
1526     #[inline(always)]
1527     fn inner(&self) -> &RcBox<T> {
1528         unsafe {
1529             self.ptr.as_ref()
1530         }
1531     }
1532 }
1533
1534 impl<T: ?Sized> RcBoxPtr<T> for RcBox<T> {
1535     #[inline(always)]
1536     fn inner(&self) -> &RcBox<T> {
1537         self
1538     }
1539 }
1540
1541 #[cfg(test)]
1542 mod tests {
1543     use super::{Rc, Weak};
1544     use std::boxed::Box;
1545     use std::cell::RefCell;
1546     use std::option::Option;
1547     use std::option::Option::{None, Some};
1548     use std::result::Result::{Err, Ok};
1549     use std::mem::drop;
1550     use std::clone::Clone;
1551     use std::convert::From;
1552
1553     #[test]
1554     fn test_clone() {
1555         let x = Rc::new(RefCell::new(5));
1556         let y = x.clone();
1557         *x.borrow_mut() = 20;
1558         assert_eq!(*y.borrow(), 20);
1559     }
1560
1561     #[test]
1562     fn test_simple() {
1563         let x = Rc::new(5);
1564         assert_eq!(*x, 5);
1565     }
1566
1567     #[test]
1568     fn test_simple_clone() {
1569         let x = Rc::new(5);
1570         let y = x.clone();
1571         assert_eq!(*x, 5);
1572         assert_eq!(*y, 5);
1573     }
1574
1575     #[test]
1576     fn test_destructor() {
1577         let x: Rc<Box<_>> = Rc::new(box 5);
1578         assert_eq!(**x, 5);
1579     }
1580
1581     #[test]
1582     fn test_live() {
1583         let x = Rc::new(5);
1584         let y = Rc::downgrade(&x);
1585         assert!(y.upgrade().is_some());
1586     }
1587
1588     #[test]
1589     fn test_dead() {
1590         let x = Rc::new(5);
1591         let y = Rc::downgrade(&x);
1592         drop(x);
1593         assert!(y.upgrade().is_none());
1594     }
1595
1596     #[test]
1597     fn weak_self_cyclic() {
1598         struct Cycle {
1599             x: RefCell<Option<Weak<Cycle>>>,
1600         }
1601
1602         let a = Rc::new(Cycle { x: RefCell::new(None) });
1603         let b = Rc::downgrade(&a.clone());
1604         *a.x.borrow_mut() = Some(b);
1605
1606         // hopefully we don't double-free (or leak)...
1607     }
1608
1609     #[test]
1610     fn is_unique() {
1611         let x = Rc::new(3);
1612         assert!(Rc::is_unique(&x));
1613         let y = x.clone();
1614         assert!(!Rc::is_unique(&x));
1615         drop(y);
1616         assert!(Rc::is_unique(&x));
1617         let w = Rc::downgrade(&x);
1618         assert!(!Rc::is_unique(&x));
1619         drop(w);
1620         assert!(Rc::is_unique(&x));
1621     }
1622
1623     #[test]
1624     fn test_strong_count() {
1625         let a = Rc::new(0);
1626         assert!(Rc::strong_count(&a) == 1);
1627         let w = Rc::downgrade(&a);
1628         assert!(Rc::strong_count(&a) == 1);
1629         let b = w.upgrade().expect("upgrade of live rc failed");
1630         assert!(Rc::strong_count(&b) == 2);
1631         assert!(Rc::strong_count(&a) == 2);
1632         drop(w);
1633         drop(a);
1634         assert!(Rc::strong_count(&b) == 1);
1635         let c = b.clone();
1636         assert!(Rc::strong_count(&b) == 2);
1637         assert!(Rc::strong_count(&c) == 2);
1638     }
1639
1640     #[test]
1641     fn test_weak_count() {
1642         let a = Rc::new(0);
1643         assert!(Rc::strong_count(&a) == 1);
1644         assert!(Rc::weak_count(&a) == 0);
1645         let w = Rc::downgrade(&a);
1646         assert!(Rc::strong_count(&a) == 1);
1647         assert!(Rc::weak_count(&a) == 1);
1648         drop(w);
1649         assert!(Rc::strong_count(&a) == 1);
1650         assert!(Rc::weak_count(&a) == 0);
1651         let c = a.clone();
1652         assert!(Rc::strong_count(&a) == 2);
1653         assert!(Rc::weak_count(&a) == 0);
1654         drop(c);
1655     }
1656
1657     #[test]
1658     fn weak_counts() {
1659         assert_eq!(Weak::weak_count(&Weak::<u64>::new()), None);
1660         assert_eq!(Weak::strong_count(&Weak::<u64>::new()), 0);
1661
1662         let a = Rc::new(0);
1663         let w = Rc::downgrade(&a);
1664         assert_eq!(Weak::strong_count(&w), 1);
1665         assert_eq!(Weak::weak_count(&w), Some(1));
1666         let w2 = w.clone();
1667         assert_eq!(Weak::strong_count(&w), 1);
1668         assert_eq!(Weak::weak_count(&w), Some(2));
1669         assert_eq!(Weak::strong_count(&w2), 1);
1670         assert_eq!(Weak::weak_count(&w2), Some(2));
1671         drop(w);
1672         assert_eq!(Weak::strong_count(&w2), 1);
1673         assert_eq!(Weak::weak_count(&w2), Some(1));
1674         let a2 = a.clone();
1675         assert_eq!(Weak::strong_count(&w2), 2);
1676         assert_eq!(Weak::weak_count(&w2), Some(1));
1677         drop(a2);
1678         drop(a);
1679         assert_eq!(Weak::strong_count(&w2), 0);
1680         assert_eq!(Weak::weak_count(&w2), Some(1));
1681         drop(w2);
1682     }
1683
1684     #[test]
1685     fn try_unwrap() {
1686         let x = Rc::new(3);
1687         assert_eq!(Rc::try_unwrap(x), Ok(3));
1688         let x = Rc::new(4);
1689         let _y = x.clone();
1690         assert_eq!(Rc::try_unwrap(x), Err(Rc::new(4)));
1691         let x = Rc::new(5);
1692         let _w = Rc::downgrade(&x);
1693         assert_eq!(Rc::try_unwrap(x), Ok(5));
1694     }
1695
1696     #[test]
1697     fn into_from_raw() {
1698         let x = Rc::new(box "hello");
1699         let y = x.clone();
1700
1701         let x_ptr = Rc::into_raw(x);
1702         drop(y);
1703         unsafe {
1704             assert_eq!(**x_ptr, "hello");
1705
1706             let x = Rc::from_raw(x_ptr);
1707             assert_eq!(**x, "hello");
1708
1709             assert_eq!(Rc::try_unwrap(x).map(|x| *x), Ok("hello"));
1710         }
1711     }
1712
1713     #[test]
1714     fn test_into_from_raw_unsized() {
1715         use std::fmt::Display;
1716         use std::string::ToString;
1717
1718         let rc: Rc<str> = Rc::from("foo");
1719
1720         let ptr = Rc::into_raw(rc.clone());
1721         let rc2 = unsafe { Rc::from_raw(ptr) };
1722
1723         assert_eq!(unsafe { &*ptr }, "foo");
1724         assert_eq!(rc, rc2);
1725
1726         let rc: Rc<dyn Display> = Rc::new(123);
1727
1728         let ptr = Rc::into_raw(rc.clone());
1729         let rc2 = unsafe { Rc::from_raw(ptr) };
1730
1731         assert_eq!(unsafe { &*ptr }.to_string(), "123");
1732         assert_eq!(rc2.to_string(), "123");
1733     }
1734
1735     #[test]
1736     fn get_mut() {
1737         let mut x = Rc::new(3);
1738         *Rc::get_mut(&mut x).unwrap() = 4;
1739         assert_eq!(*x, 4);
1740         let y = x.clone();
1741         assert!(Rc::get_mut(&mut x).is_none());
1742         drop(y);
1743         assert!(Rc::get_mut(&mut x).is_some());
1744         let _w = Rc::downgrade(&x);
1745         assert!(Rc::get_mut(&mut x).is_none());
1746     }
1747
1748     #[test]
1749     fn test_cowrc_clone_make_unique() {
1750         let mut cow0 = Rc::new(75);
1751         let mut cow1 = cow0.clone();
1752         let mut cow2 = cow1.clone();
1753
1754         assert!(75 == *Rc::make_mut(&mut cow0));
1755         assert!(75 == *Rc::make_mut(&mut cow1));
1756         assert!(75 == *Rc::make_mut(&mut cow2));
1757
1758         *Rc::make_mut(&mut cow0) += 1;
1759         *Rc::make_mut(&mut cow1) += 2;
1760         *Rc::make_mut(&mut cow2) += 3;
1761
1762         assert!(76 == *cow0);
1763         assert!(77 == *cow1);
1764         assert!(78 == *cow2);
1765
1766         // none should point to the same backing memory
1767         assert!(*cow0 != *cow1);
1768         assert!(*cow0 != *cow2);
1769         assert!(*cow1 != *cow2);
1770     }
1771
1772     #[test]
1773     fn test_cowrc_clone_unique2() {
1774         let mut cow0 = Rc::new(75);
1775         let cow1 = cow0.clone();
1776         let cow2 = cow1.clone();
1777
1778         assert!(75 == *cow0);
1779         assert!(75 == *cow1);
1780         assert!(75 == *cow2);
1781
1782         *Rc::make_mut(&mut cow0) += 1;
1783
1784         assert!(76 == *cow0);
1785         assert!(75 == *cow1);
1786         assert!(75 == *cow2);
1787
1788         // cow1 and cow2 should share the same contents
1789         // cow0 should have a unique reference
1790         assert!(*cow0 != *cow1);
1791         assert!(*cow0 != *cow2);
1792         assert!(*cow1 == *cow2);
1793     }
1794
1795     #[test]
1796     fn test_cowrc_clone_weak() {
1797         let mut cow0 = Rc::new(75);
1798         let cow1_weak = Rc::downgrade(&cow0);
1799
1800         assert!(75 == *cow0);
1801         assert!(75 == *cow1_weak.upgrade().unwrap());
1802
1803         *Rc::make_mut(&mut cow0) += 1;
1804
1805         assert!(76 == *cow0);
1806         assert!(cow1_weak.upgrade().is_none());
1807     }
1808
1809     #[test]
1810     fn test_show() {
1811         let foo = Rc::new(75);
1812         assert_eq!(format!("{:?}", foo), "75");
1813     }
1814
1815     #[test]
1816     fn test_unsized() {
1817         let foo: Rc<[i32]> = Rc::new([1, 2, 3]);
1818         assert_eq!(foo, foo.clone());
1819     }
1820
1821     #[test]
1822     fn test_from_owned() {
1823         let foo = 123;
1824         let foo_rc = Rc::from(foo);
1825         assert!(123 == *foo_rc);
1826     }
1827
1828     #[test]
1829     fn test_new_weak() {
1830         let foo: Weak<usize> = Weak::new();
1831         assert!(foo.upgrade().is_none());
1832     }
1833
1834     #[test]
1835     fn test_ptr_eq() {
1836         let five = Rc::new(5);
1837         let same_five = five.clone();
1838         let other_five = Rc::new(5);
1839
1840         assert!(Rc::ptr_eq(&five, &same_five));
1841         assert!(!Rc::ptr_eq(&five, &other_five));
1842     }
1843
1844     #[test]
1845     fn test_from_str() {
1846         let r: Rc<str> = Rc::from("foo");
1847
1848         assert_eq!(&r[..], "foo");
1849     }
1850
1851     #[test]
1852     fn test_copy_from_slice() {
1853         let s: &[u32] = &[1, 2, 3];
1854         let r: Rc<[u32]> = Rc::from(s);
1855
1856         assert_eq!(&r[..], [1, 2, 3]);
1857     }
1858
1859     #[test]
1860     fn test_clone_from_slice() {
1861         #[derive(Clone, Debug, Eq, PartialEq)]
1862         struct X(u32);
1863
1864         let s: &[X] = &[X(1), X(2), X(3)];
1865         let r: Rc<[X]> = Rc::from(s);
1866
1867         assert_eq!(&r[..], s);
1868     }
1869
1870     #[test]
1871     #[should_panic]
1872     fn test_clone_from_slice_panic() {
1873         use std::string::{String, ToString};
1874
1875         struct Fail(u32, String);
1876
1877         impl Clone for Fail {
1878             fn clone(&self) -> Fail {
1879                 if self.0 == 2 {
1880                     panic!();
1881                 }
1882                 Fail(self.0, self.1.clone())
1883             }
1884         }
1885
1886         let s: &[Fail] = &[
1887             Fail(0, "foo".to_string()),
1888             Fail(1, "bar".to_string()),
1889             Fail(2, "baz".to_string()),
1890         ];
1891
1892         // Should panic, but not cause memory corruption
1893         let _r: Rc<[Fail]> = Rc::from(s);
1894     }
1895
1896     #[test]
1897     fn test_from_box() {
1898         let b: Box<u32> = box 123;
1899         let r: Rc<u32> = Rc::from(b);
1900
1901         assert_eq!(*r, 123);
1902     }
1903
1904     #[test]
1905     fn test_from_box_str() {
1906         use std::string::String;
1907
1908         let s = String::from("foo").into_boxed_str();
1909         let r: Rc<str> = Rc::from(s);
1910
1911         assert_eq!(&r[..], "foo");
1912     }
1913
1914     #[test]
1915     fn test_from_box_slice() {
1916         let s = vec![1, 2, 3].into_boxed_slice();
1917         let r: Rc<[u32]> = Rc::from(s);
1918
1919         assert_eq!(&r[..], [1, 2, 3]);
1920     }
1921
1922     #[test]
1923     fn test_from_box_trait() {
1924         use std::fmt::Display;
1925         use std::string::ToString;
1926
1927         let b: Box<dyn Display> = box 123;
1928         let r: Rc<dyn Display> = Rc::from(b);
1929
1930         assert_eq!(r.to_string(), "123");
1931     }
1932
1933     #[test]
1934     fn test_from_box_trait_zero_sized() {
1935         use std::fmt::Debug;
1936
1937         let b: Box<dyn Debug> = box ();
1938         let r: Rc<dyn Debug> = Rc::from(b);
1939
1940         assert_eq!(format!("{:?}", r), "()");
1941     }
1942
1943     #[test]
1944     fn test_from_vec() {
1945         let v = vec![1, 2, 3];
1946         let r: Rc<[u32]> = Rc::from(v);
1947
1948         assert_eq!(&r[..], [1, 2, 3]);
1949     }
1950
1951     #[test]
1952     fn test_downcast() {
1953         use std::any::Any;
1954
1955         let r1: Rc<dyn Any> = Rc::new(i32::max_value());
1956         let r2: Rc<dyn Any> = Rc::new("abc");
1957
1958         assert!(r1.clone().downcast::<u32>().is_err());
1959
1960         let r1i32 = r1.downcast::<i32>();
1961         assert!(r1i32.is_ok());
1962         assert_eq!(r1i32.unwrap(), Rc::new(i32::max_value()));
1963
1964         assert!(r2.clone().downcast::<i32>().is_err());
1965
1966         let r2str = r2.downcast::<&'static str>();
1967         assert!(r2str.is_ok());
1968         assert_eq!(r2str.unwrap(), Rc::new("abc"));
1969     }
1970 }
1971
1972 #[stable(feature = "rust1", since = "1.0.0")]
1973 impl<T: ?Sized> borrow::Borrow<T> for Rc<T> {
1974     fn borrow(&self) -> &T {
1975         &**self
1976     }
1977 }
1978
1979 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1980 impl<T: ?Sized> AsRef<T> for Rc<T> {
1981     fn as_ref(&self) -> &T {
1982         &**self
1983     }
1984 }
1985
1986 #[stable(feature = "pin", since = "1.33.0")]
1987 impl<T: ?Sized> Unpin for Rc<T> { }