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