]> git.lizzy.rs Git - rust.git/blob - src/liballoc/rc.rs
Auto merge of #74060 - kpp:remove_length_at_most_32, r=dtolnay
[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 allocation in the heap. When the last [`Rc`] pointer to a
7 //! given allocation is destroyed, the value stored in that allocation (often
8 //! referred to as "inner value") is also dropped.
9 //!
10 //! Shared references in Rust disallow mutation by default, and [`Rc`]
11 //! is no exception: you cannot generally obtain a mutable reference to
12 //! something inside an [`Rc`]. If you need mutability, put a [`Cell`]
13 //! or [`RefCell`] inside the [`Rc`]; see [an example of mutability
14 //! inside an Rc][mutability].
15 //!
16 //! [`Rc`] uses non-atomic reference counting. This means that overhead is very
17 //! low, but an [`Rc`] cannot be sent between threads, and consequently [`Rc`]
18 //! does not implement [`Send`][send]. As a result, the Rust compiler
19 //! will check *at compile time* that you are not sending [`Rc`]s between
20 //! threads. If you need multi-threaded, atomic reference counting, use
21 //! [`sync::Arc`][arc].
22 //!
23 //! The [`downgrade`][downgrade] method can be used to create a non-owning
24 //! [`Weak`] pointer. A [`Weak`] pointer can be [`upgrade`][upgrade]d
25 //! to an [`Rc`], but this will return [`None`] if the value stored in the allocation has
26 //! already been dropped. In other words, `Weak` pointers do not keep the value
27 //! inside the allocation alive; however, they *do* keep the allocation
28 //! (the backing store for the inner value) alive.
29 //!
30 //! A cycle between [`Rc`] pointers will never be deallocated. For this reason,
31 //! [`Weak`] is used to break cycles. For example, a tree could have strong
32 //! [`Rc`] pointers from parent nodes to children, and [`Weak`] pointers from
33 //! children back to their parents.
34 //!
35 //! `Rc<T>` automatically dereferences to `T` (via the [`Deref`] trait),
36 //! so you can call `T`'s methods on a value of type [`Rc<T>`][`Rc`]. To avoid name
37 //! clashes with `T`'s methods, the methods of [`Rc<T>`][`Rc`] itself are associated
38 //! functions, called using function-like syntax:
39 //!
40 //! ```
41 //! use std::rc::Rc;
42 //! let my_rc = Rc::new(());
43 //!
44 //! Rc::downgrade(&my_rc);
45 //! ```
46 //!
47 //! [`Weak<T>`][`Weak`] does not auto-dereference to `T`, because the inner value may have
48 //! already been dropped.
49 //!
50 //! # Cloning references
51 //!
52 //! Creating a new reference to the same allocation as an existing reference counted pointer
53 //! is done using the `Clone` trait implemented for [`Rc<T>`][`Rc`] and [`Weak<T>`][`Weak`].
54 //!
55 //! ```
56 //! use std::rc::Rc;
57 //! let foo = Rc::new(vec![1.0, 2.0, 3.0]);
58 //! // The two syntaxes below are equivalent.
59 //! let a = foo.clone();
60 //! let b = Rc::clone(&foo);
61 //! // a and b both point to the same memory location as foo.
62 //! ```
63 //!
64 //! The `Rc::clone(&from)` syntax is the most idiomatic because it conveys more explicitly
65 //! the meaning of the code. In the example above, this syntax makes it easier to see that
66 //! this code is creating a new reference rather than copying the whole content of foo.
67 //!
68 //! # Examples
69 //!
70 //! Consider a scenario where a set of `Gadget`s are owned by a given `Owner`.
71 //! We want to have our `Gadget`s point to their `Owner`. We can't do this with
72 //! unique ownership, because more than one gadget may belong to the same
73 //! `Owner`. [`Rc`] allows us to share an `Owner` between multiple `Gadget`s,
74 //! and have the `Owner` remain allocated as long as any `Gadget` points at it.
75 //!
76 //! ```
77 //! use std::rc::Rc;
78 //!
79 //! struct Owner {
80 //!     name: String,
81 //!     // ...other fields
82 //! }
83 //!
84 //! struct Gadget {
85 //!     id: i32,
86 //!     owner: Rc<Owner>,
87 //!     // ...other fields
88 //! }
89 //!
90 //! fn main() {
91 //!     // Create a reference-counted `Owner`.
92 //!     let gadget_owner: Rc<Owner> = Rc::new(
93 //!         Owner {
94 //!             name: "Gadget Man".to_string(),
95 //!         }
96 //!     );
97 //!
98 //!     // Create `Gadget`s belonging to `gadget_owner`. Cloning the `Rc<Owner>`
99 //!     // gives us a new pointer to the same `Owner` allocation, incrementing
100 //!     // the reference count in the process.
101 //!     let gadget1 = Gadget {
102 //!         id: 1,
103 //!         owner: Rc::clone(&gadget_owner),
104 //!     };
105 //!     let gadget2 = Gadget {
106 //!         id: 2,
107 //!         owner: Rc::clone(&gadget_owner),
108 //!     };
109 //!
110 //!     // Dispose of our local variable `gadget_owner`.
111 //!     drop(gadget_owner);
112 //!
113 //!     // Despite dropping `gadget_owner`, we're still able to print out the name
114 //!     // of the `Owner` of the `Gadget`s. This is because we've only dropped a
115 //!     // single `Rc<Owner>`, not the `Owner` it points to. As long as there are
116 //!     // other `Rc<Owner>` pointing at the same `Owner` allocation, it will remain
117 //!     // live. The field projection `gadget1.owner.name` works because
118 //!     // `Rc<Owner>` automatically dereferences to `Owner`.
119 //!     println!("Gadget {} owned by {}", gadget1.id, gadget1.owner.name);
120 //!     println!("Gadget {} owned by {}", gadget2.id, gadget2.owner.name);
121 //!
122 //!     // At the end of the function, `gadget1` and `gadget2` are destroyed, and
123 //!     // with them the last counted references to our `Owner`. Gadget Man now
124 //!     // gets destroyed as well.
125 //! }
126 //! ```
127 //!
128 //! If our requirements change, and we also need to be able to traverse from
129 //! `Owner` to `Gadget`, we will run into problems. An [`Rc`] pointer from `Owner`
130 //! to `Gadget` introduces a cycle. This means that their
131 //! reference counts can never reach 0, and the allocation will never be destroyed:
132 //! a memory leak. In order to get around this, we can use [`Weak`]
133 //! pointers.
134 //!
135 //! Rust actually makes it somewhat difficult to produce this loop in the first
136 //! place. In order to end up with two values that point at each other, one of
137 //! them needs to be mutable. This is difficult because [`Rc`] enforces
138 //! memory safety by only giving out shared references to the value it wraps,
139 //! and these don't allow direct mutation. We need to wrap the part of the
140 //! value we wish to mutate in a [`RefCell`], which provides *interior
141 //! mutability*: a method to achieve mutability through a shared reference.
142 //! [`RefCell`] enforces Rust's borrowing rules at runtime.
143 //!
144 //! ```
145 //! use std::rc::Rc;
146 //! use std::rc::Weak;
147 //! use std::cell::RefCell;
148 //!
149 //! struct Owner {
150 //!     name: String,
151 //!     gadgets: RefCell<Vec<Weak<Gadget>>>,
152 //!     // ...other fields
153 //! }
154 //!
155 //! struct Gadget {
156 //!     id: i32,
157 //!     owner: Rc<Owner>,
158 //!     // ...other fields
159 //! }
160 //!
161 //! fn main() {
162 //!     // Create a reference-counted `Owner`. Note that we've put the `Owner`'s
163 //!     // vector of `Gadget`s inside a `RefCell` so that we can mutate it through
164 //!     // a shared reference.
165 //!     let gadget_owner: Rc<Owner> = Rc::new(
166 //!         Owner {
167 //!             name: "Gadget Man".to_string(),
168 //!             gadgets: RefCell::new(vec![]),
169 //!         }
170 //!     );
171 //!
172 //!     // Create `Gadget`s belonging to `gadget_owner`, as before.
173 //!     let gadget1 = Rc::new(
174 //!         Gadget {
175 //!             id: 1,
176 //!             owner: Rc::clone(&gadget_owner),
177 //!         }
178 //!     );
179 //!     let gadget2 = Rc::new(
180 //!         Gadget {
181 //!             id: 2,
182 //!             owner: Rc::clone(&gadget_owner),
183 //!         }
184 //!     );
185 //!
186 //!     // Add the `Gadget`s to their `Owner`.
187 //!     {
188 //!         let mut gadgets = gadget_owner.gadgets.borrow_mut();
189 //!         gadgets.push(Rc::downgrade(&gadget1));
190 //!         gadgets.push(Rc::downgrade(&gadget2));
191 //!
192 //!         // `RefCell` dynamic borrow ends here.
193 //!     }
194 //!
195 //!     // Iterate over our `Gadget`s, printing their details out.
196 //!     for gadget_weak in gadget_owner.gadgets.borrow().iter() {
197 //!
198 //!         // `gadget_weak` is a `Weak<Gadget>`. Since `Weak` pointers can't
199 //!         // guarantee the allocation still exists, we need to call
200 //!         // `upgrade`, which returns an `Option<Rc<Gadget>>`.
201 //!         //
202 //!         // In this case we know the allocation still exists, so we simply
203 //!         // `unwrap` the `Option`. In a more complicated program, you might
204 //!         // need graceful error handling for a `None` result.
205 //!
206 //!         let gadget = gadget_weak.upgrade().unwrap();
207 //!         println!("Gadget {} owned by {}", gadget.id, gadget.owner.name);
208 //!     }
209 //!
210 //!     // At the end of the function, `gadget_owner`, `gadget1`, and `gadget2`
211 //!     // are destroyed. There are now no strong (`Rc`) pointers to the
212 //!     // gadgets, so they are destroyed. This zeroes the reference count on
213 //!     // Gadget Man, so he gets destroyed as well.
214 //! }
215 //! ```
216 //!
217 //! [`Rc`]: struct.Rc.html
218 //! [`Weak`]: struct.Weak.html
219 //! [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
220 //! [`Cell`]: ../../std/cell/struct.Cell.html
221 //! [`RefCell`]: ../../std/cell/struct.RefCell.html
222 //! [send]: ../../std/marker/trait.Send.html
223 //! [arc]: ../../std/sync/struct.Arc.html
224 //! [`Deref`]: ../../std/ops/trait.Deref.html
225 //! [downgrade]: struct.Rc.html#method.downgrade
226 //! [upgrade]: struct.Weak.html#method.upgrade
227 //! [`None`]: ../../std/option/enum.Option.html#variant.None
228 //! [mutability]: ../../std/cell/index.html#introducing-mutability-inside-of-something-immutable
229
230 #![stable(feature = "rust1", since = "1.0.0")]
231
232 #[cfg(not(test))]
233 use crate::boxed::Box;
234 #[cfg(test)]
235 use std::boxed::Box;
236
237 use core::any::Any;
238 use core::borrow;
239 use core::cell::Cell;
240 use core::cmp::Ordering;
241 use core::convert::{From, TryFrom};
242 use core::fmt;
243 use core::hash::{Hash, Hasher};
244 use core::intrinsics::abort;
245 use core::iter;
246 use core::marker::{self, PhantomData, Unpin, Unsize};
247 use core::mem::{self, align_of_val_raw, forget, size_of_val};
248 use core::ops::{CoerceUnsized, Deref, DispatchFromDyn, Receiver};
249 use core::pin::Pin;
250 use core::ptr::{self, NonNull};
251 use core::slice::from_raw_parts_mut;
252
253 use crate::alloc::{box_free, handle_alloc_error, AllocInit, AllocRef, Global, Layout};
254 use crate::borrow::{Cow, ToOwned};
255 use crate::string::String;
256 use crate::vec::Vec;
257
258 #[cfg(test)]
259 mod tests;
260
261 // This is repr(C) to future-proof against possible field-reordering, which
262 // would interfere with otherwise safe [into|from]_raw() of transmutable
263 // inner types.
264 #[repr(C)]
265 struct RcBox<T: ?Sized> {
266     strong: Cell<usize>,
267     weak: Cell<usize>,
268     value: T,
269 }
270
271 /// A single-threaded reference-counting pointer. 'Rc' stands for 'Reference
272 /// Counted'.
273 ///
274 /// See the [module-level documentation](./index.html) for more details.
275 ///
276 /// The inherent methods of `Rc` are all associated functions, which means
277 /// that you have to call them as e.g., [`Rc::get_mut(&mut value)`][get_mut] instead of
278 /// `value.get_mut()`. This avoids conflicts with methods of the inner
279 /// type `T`.
280 ///
281 /// [get_mut]: #method.get_mut
282 #[cfg_attr(not(test), rustc_diagnostic_item = "Rc")]
283 #[stable(feature = "rust1", since = "1.0.0")]
284 pub struct Rc<T: ?Sized> {
285     ptr: NonNull<RcBox<T>>,
286     phantom: PhantomData<RcBox<T>>,
287 }
288
289 #[stable(feature = "rust1", since = "1.0.0")]
290 impl<T: ?Sized> !marker::Send for Rc<T> {}
291 #[stable(feature = "rust1", since = "1.0.0")]
292 impl<T: ?Sized> !marker::Sync for Rc<T> {}
293
294 #[unstable(feature = "coerce_unsized", issue = "27732")]
295 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Rc<U>> for Rc<T> {}
296
297 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
298 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Rc<U>> for Rc<T> {}
299
300 impl<T: ?Sized> Rc<T> {
301     fn from_inner(ptr: NonNull<RcBox<T>>) -> Self {
302         Self { ptr, phantom: PhantomData }
303     }
304
305     unsafe fn from_ptr(ptr: *mut RcBox<T>) -> Self {
306         Self::from_inner(unsafe { NonNull::new_unchecked(ptr) })
307     }
308 }
309
310 impl<T> Rc<T> {
311     /// Constructs a new `Rc<T>`.
312     ///
313     /// # Examples
314     ///
315     /// ```
316     /// use std::rc::Rc;
317     ///
318     /// let five = Rc::new(5);
319     /// ```
320     #[stable(feature = "rust1", since = "1.0.0")]
321     pub fn new(value: T) -> Rc<T> {
322         // There is an implicit weak pointer owned by all the strong
323         // pointers, which ensures that the weak destructor never frees
324         // the allocation while the strong destructor is running, even
325         // if the weak pointer is stored inside the strong one.
326         Self::from_inner(
327             Box::leak(box RcBox { strong: Cell::new(1), weak: Cell::new(1), value }).into(),
328         )
329     }
330
331     /// Constructs a new `Rc` with uninitialized contents.
332     ///
333     /// # Examples
334     ///
335     /// ```
336     /// #![feature(new_uninit)]
337     /// #![feature(get_mut_unchecked)]
338     ///
339     /// use std::rc::Rc;
340     ///
341     /// let mut five = Rc::<u32>::new_uninit();
342     ///
343     /// let five = unsafe {
344     ///     // Deferred initialization:
345     ///     Rc::get_mut_unchecked(&mut five).as_mut_ptr().write(5);
346     ///
347     ///     five.assume_init()
348     /// };
349     ///
350     /// assert_eq!(*five, 5)
351     /// ```
352     #[unstable(feature = "new_uninit", issue = "63291")]
353     pub fn new_uninit() -> Rc<mem::MaybeUninit<T>> {
354         unsafe {
355             Rc::from_ptr(Rc::allocate_for_layout(Layout::new::<T>(), |mem| {
356                 mem as *mut RcBox<mem::MaybeUninit<T>>
357             }))
358         }
359     }
360
361     /// Constructs a new `Rc` with uninitialized contents, with the memory
362     /// being filled with `0` bytes.
363     ///
364     /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and
365     /// incorrect usage of this method.
366     ///
367     /// # Examples
368     ///
369     /// ```
370     /// #![feature(new_uninit)]
371     ///
372     /// use std::rc::Rc;
373     ///
374     /// let zero = Rc::<u32>::new_zeroed();
375     /// let zero = unsafe { zero.assume_init() };
376     ///
377     /// assert_eq!(*zero, 0)
378     /// ```
379     ///
380     /// [zeroed]: ../../std/mem/union.MaybeUninit.html#method.zeroed
381     #[unstable(feature = "new_uninit", issue = "63291")]
382     pub fn new_zeroed() -> Rc<mem::MaybeUninit<T>> {
383         unsafe {
384             let mut uninit = Self::new_uninit();
385             ptr::write_bytes::<T>(Rc::get_mut_unchecked(&mut uninit).as_mut_ptr(), 0, 1);
386             uninit
387         }
388     }
389
390     /// Constructs a new `Pin<Rc<T>>`. If `T` does not implement `Unpin`, then
391     /// `value` will be pinned in memory and unable to be moved.
392     #[stable(feature = "pin", since = "1.33.0")]
393     pub fn pin(value: T) -> Pin<Rc<T>> {
394         unsafe { Pin::new_unchecked(Rc::new(value)) }
395     }
396
397     /// Returns the inner value, if the `Rc` has exactly one strong reference.
398     ///
399     /// Otherwise, an [`Err`][result] is returned with the same `Rc` that was
400     /// passed in.
401     ///
402     /// This will succeed even if there are outstanding weak references.
403     ///
404     /// [result]: ../../std/result/enum.Result.html
405     ///
406     /// # Examples
407     ///
408     /// ```
409     /// use std::rc::Rc;
410     ///
411     /// let x = Rc::new(3);
412     /// assert_eq!(Rc::try_unwrap(x), Ok(3));
413     ///
414     /// let x = Rc::new(4);
415     /// let _y = Rc::clone(&x);
416     /// assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4);
417     /// ```
418     #[inline]
419     #[stable(feature = "rc_unique", since = "1.4.0")]
420     pub fn try_unwrap(this: Self) -> Result<T, Self> {
421         if Rc::strong_count(&this) == 1 {
422             unsafe {
423                 let val = ptr::read(&*this); // copy the contained object
424
425                 // Indicate to Weaks that they can't be promoted by decrementing
426                 // the strong count, and then remove the implicit "strong weak"
427                 // pointer while also handling drop logic by just crafting a
428                 // fake Weak.
429                 this.dec_strong();
430                 let _weak = Weak { ptr: this.ptr };
431                 forget(this);
432                 Ok(val)
433             }
434         } else {
435             Err(this)
436         }
437     }
438 }
439
440 impl<T> Rc<[T]> {
441     /// Constructs a new reference-counted slice with uninitialized contents.
442     ///
443     /// # Examples
444     ///
445     /// ```
446     /// #![feature(new_uninit)]
447     /// #![feature(get_mut_unchecked)]
448     ///
449     /// use std::rc::Rc;
450     ///
451     /// let mut values = Rc::<[u32]>::new_uninit_slice(3);
452     ///
453     /// let values = unsafe {
454     ///     // Deferred initialization:
455     ///     Rc::get_mut_unchecked(&mut values)[0].as_mut_ptr().write(1);
456     ///     Rc::get_mut_unchecked(&mut values)[1].as_mut_ptr().write(2);
457     ///     Rc::get_mut_unchecked(&mut values)[2].as_mut_ptr().write(3);
458     ///
459     ///     values.assume_init()
460     /// };
461     ///
462     /// assert_eq!(*values, [1, 2, 3])
463     /// ```
464     #[unstable(feature = "new_uninit", issue = "63291")]
465     pub fn new_uninit_slice(len: usize) -> Rc<[mem::MaybeUninit<T>]> {
466         unsafe { Rc::from_ptr(Rc::allocate_for_slice(len)) }
467     }
468 }
469
470 impl<T> Rc<mem::MaybeUninit<T>> {
471     /// Converts to `Rc<T>`.
472     ///
473     /// # Safety
474     ///
475     /// As with [`MaybeUninit::assume_init`],
476     /// it is up to the caller to guarantee that the inner value
477     /// really is in an initialized state.
478     /// Calling this when the content is not yet fully initialized
479     /// causes immediate undefined behavior.
480     ///
481     /// [`MaybeUninit::assume_init`]: ../../std/mem/union.MaybeUninit.html#method.assume_init
482     ///
483     /// # Examples
484     ///
485     /// ```
486     /// #![feature(new_uninit)]
487     /// #![feature(get_mut_unchecked)]
488     ///
489     /// use std::rc::Rc;
490     ///
491     /// let mut five = Rc::<u32>::new_uninit();
492     ///
493     /// let five = unsafe {
494     ///     // Deferred initialization:
495     ///     Rc::get_mut_unchecked(&mut five).as_mut_ptr().write(5);
496     ///
497     ///     five.assume_init()
498     /// };
499     ///
500     /// assert_eq!(*five, 5)
501     /// ```
502     #[unstable(feature = "new_uninit", issue = "63291")]
503     #[inline]
504     pub unsafe fn assume_init(self) -> Rc<T> {
505         Rc::from_inner(mem::ManuallyDrop::new(self).ptr.cast())
506     }
507 }
508
509 impl<T> Rc<[mem::MaybeUninit<T>]> {
510     /// Converts to `Rc<[T]>`.
511     ///
512     /// # Safety
513     ///
514     /// As with [`MaybeUninit::assume_init`],
515     /// it is up to the caller to guarantee that the inner value
516     /// really is in an initialized state.
517     /// Calling this when the content is not yet fully initialized
518     /// causes immediate undefined behavior.
519     ///
520     /// [`MaybeUninit::assume_init`]: ../../std/mem/union.MaybeUninit.html#method.assume_init
521     ///
522     /// # Examples
523     ///
524     /// ```
525     /// #![feature(new_uninit)]
526     /// #![feature(get_mut_unchecked)]
527     ///
528     /// use std::rc::Rc;
529     ///
530     /// let mut values = Rc::<[u32]>::new_uninit_slice(3);
531     ///
532     /// let values = unsafe {
533     ///     // Deferred initialization:
534     ///     Rc::get_mut_unchecked(&mut values)[0].as_mut_ptr().write(1);
535     ///     Rc::get_mut_unchecked(&mut values)[1].as_mut_ptr().write(2);
536     ///     Rc::get_mut_unchecked(&mut values)[2].as_mut_ptr().write(3);
537     ///
538     ///     values.assume_init()
539     /// };
540     ///
541     /// assert_eq!(*values, [1, 2, 3])
542     /// ```
543     #[unstable(feature = "new_uninit", issue = "63291")]
544     #[inline]
545     pub unsafe fn assume_init(self) -> Rc<[T]> {
546         unsafe { Rc::from_ptr(mem::ManuallyDrop::new(self).ptr.as_ptr() as _) }
547     }
548 }
549
550 impl<T: ?Sized> Rc<T> {
551     /// Consumes the `Rc`, returning the wrapped pointer.
552     ///
553     /// To avoid a memory leak the pointer must be converted back to an `Rc` using
554     /// [`Rc::from_raw`][from_raw].
555     ///
556     /// [from_raw]: struct.Rc.html#method.from_raw
557     ///
558     /// # Examples
559     ///
560     /// ```
561     /// use std::rc::Rc;
562     ///
563     /// let x = Rc::new("hello".to_owned());
564     /// let x_ptr = Rc::into_raw(x);
565     /// assert_eq!(unsafe { &*x_ptr }, "hello");
566     /// ```
567     #[stable(feature = "rc_raw", since = "1.17.0")]
568     pub fn into_raw(this: Self) -> *const T {
569         let ptr = Self::as_ptr(&this);
570         mem::forget(this);
571         ptr
572     }
573
574     /// Provides a raw pointer to the data.
575     ///
576     /// The counts are not affected in any way and the `Rc` is not consumed. The pointer is valid
577     /// for as long there are strong counts in the `Rc`.
578     ///
579     /// # Examples
580     ///
581     /// ```
582     /// use std::rc::Rc;
583     ///
584     /// let x = Rc::new("hello".to_owned());
585     /// let y = Rc::clone(&x);
586     /// let x_ptr = Rc::as_ptr(&x);
587     /// assert_eq!(x_ptr, Rc::as_ptr(&y));
588     /// assert_eq!(unsafe { &*x_ptr }, "hello");
589     /// ```
590     #[stable(feature = "weak_into_raw", since = "1.45.0")]
591     pub fn as_ptr(this: &Self) -> *const T {
592         let ptr: *mut RcBox<T> = NonNull::as_ptr(this.ptr);
593
594         // SAFETY: This cannot go through Deref::deref or Rc::inner because
595         // this is required to retain raw/mut provenance such that e.g. `get_mut` can
596         // write through the pointer after the Rc is recovered through `from_raw`.
597         unsafe { &raw const (*ptr).value }
598     }
599
600     /// Constructs an `Rc<T>` from a raw pointer.
601     ///
602     /// The raw pointer must have been previously returned by a call to
603     /// [`Rc<U>::into_raw`][into_raw] where `U` must have the same size
604     /// and alignment as `T`. This is trivially true if `U` is `T`.
605     /// Note that if `U` is not `T` but has the same size and alignment, this is
606     /// basically like transmuting references of different types. See
607     /// [`mem::transmute`][transmute] for more information on what
608     /// restrictions apply in this case.
609     ///
610     /// The user of `from_raw` has to make sure a specific value of `T` is only
611     /// dropped once.
612     ///
613     /// This function is unsafe because improper use may lead to memory unsafety,
614     /// even if the returned `Rc<T>` is never accessed.
615     ///
616     /// [into_raw]: struct.Rc.html#method.into_raw
617     /// [transmute]: ../../std/mem/fn.transmute.html
618     ///
619     /// # Examples
620     ///
621     /// ```
622     /// use std::rc::Rc;
623     ///
624     /// let x = Rc::new("hello".to_owned());
625     /// let x_ptr = Rc::into_raw(x);
626     ///
627     /// unsafe {
628     ///     // Convert back to an `Rc` to prevent leak.
629     ///     let x = Rc::from_raw(x_ptr);
630     ///     assert_eq!(&*x, "hello");
631     ///
632     ///     // Further calls to `Rc::from_raw(x_ptr)` would be memory-unsafe.
633     /// }
634     ///
635     /// // The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling!
636     /// ```
637     #[stable(feature = "rc_raw", since = "1.17.0")]
638     pub unsafe fn from_raw(ptr: *const T) -> Self {
639         let offset = unsafe { data_offset(ptr) };
640
641         // Reverse the offset to find the original RcBox.
642         let fake_ptr = ptr as *mut RcBox<T>;
643         let rc_ptr = unsafe { set_data_ptr(fake_ptr, (ptr as *mut u8).offset(-offset)) };
644
645         unsafe { Self::from_ptr(rc_ptr) }
646     }
647
648     /// Consumes the `Rc`, returning the wrapped pointer as `NonNull<T>`.
649     ///
650     /// # Examples
651     ///
652     /// ```
653     /// #![feature(rc_into_raw_non_null)]
654     /// #![allow(deprecated)]
655     ///
656     /// use std::rc::Rc;
657     ///
658     /// let x = Rc::new("hello".to_owned());
659     /// let ptr = Rc::into_raw_non_null(x);
660     /// let deref = unsafe { ptr.as_ref() };
661     /// assert_eq!(deref, "hello");
662     /// ```
663     #[unstable(feature = "rc_into_raw_non_null", issue = "47336")]
664     #[rustc_deprecated(since = "1.44.0", reason = "use `Rc::into_raw` instead")]
665     #[inline]
666     pub fn into_raw_non_null(this: Self) -> NonNull<T> {
667         // safe because Rc guarantees its pointer is non-null
668         unsafe { NonNull::new_unchecked(Rc::into_raw(this) as *mut _) }
669     }
670
671     /// Creates a new [`Weak`][weak] pointer to this allocation.
672     ///
673     /// [weak]: struct.Weak.html
674     ///
675     /// # Examples
676     ///
677     /// ```
678     /// use std::rc::Rc;
679     ///
680     /// let five = Rc::new(5);
681     ///
682     /// let weak_five = Rc::downgrade(&five);
683     /// ```
684     #[stable(feature = "rc_weak", since = "1.4.0")]
685     pub fn downgrade(this: &Self) -> Weak<T> {
686         this.inc_weak();
687         // Make sure we do not create a dangling Weak
688         debug_assert!(!is_dangling(this.ptr));
689         Weak { ptr: this.ptr }
690     }
691
692     /// Gets the number of [`Weak`][weak] pointers to this allocation.
693     ///
694     /// [weak]: struct.Weak.html
695     ///
696     /// # Examples
697     ///
698     /// ```
699     /// use std::rc::Rc;
700     ///
701     /// let five = Rc::new(5);
702     /// let _weak_five = Rc::downgrade(&five);
703     ///
704     /// assert_eq!(1, Rc::weak_count(&five));
705     /// ```
706     #[inline]
707     #[stable(feature = "rc_counts", since = "1.15.0")]
708     pub fn weak_count(this: &Self) -> usize {
709         this.weak() - 1
710     }
711
712     /// Gets the number of strong (`Rc`) pointers to this allocation.
713     ///
714     /// # Examples
715     ///
716     /// ```
717     /// use std::rc::Rc;
718     ///
719     /// let five = Rc::new(5);
720     /// let _also_five = Rc::clone(&five);
721     ///
722     /// assert_eq!(2, Rc::strong_count(&five));
723     /// ```
724     #[inline]
725     #[stable(feature = "rc_counts", since = "1.15.0")]
726     pub fn strong_count(this: &Self) -> usize {
727         this.strong()
728     }
729
730     /// Returns `true` if there are no other `Rc` or [`Weak`][weak] pointers to
731     /// this allocation.
732     ///
733     /// [weak]: struct.Weak.html
734     #[inline]
735     fn is_unique(this: &Self) -> bool {
736         Rc::weak_count(this) == 0 && Rc::strong_count(this) == 1
737     }
738
739     /// Returns a mutable reference into the given `Rc`, if there are
740     /// no other `Rc` or [`Weak`][weak] pointers to the same allocation.
741     ///
742     /// Returns [`None`] otherwise, because it is not safe to
743     /// mutate a shared value.
744     ///
745     /// See also [`make_mut`][make_mut], which will [`clone`][clone]
746     /// the inner value when there are other pointers.
747     ///
748     /// [weak]: struct.Weak.html
749     /// [`None`]: ../../std/option/enum.Option.html#variant.None
750     /// [make_mut]: struct.Rc.html#method.make_mut
751     /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
752     ///
753     /// # Examples
754     ///
755     /// ```
756     /// use std::rc::Rc;
757     ///
758     /// let mut x = Rc::new(3);
759     /// *Rc::get_mut(&mut x).unwrap() = 4;
760     /// assert_eq!(*x, 4);
761     ///
762     /// let _y = Rc::clone(&x);
763     /// assert!(Rc::get_mut(&mut x).is_none());
764     /// ```
765     #[inline]
766     #[stable(feature = "rc_unique", since = "1.4.0")]
767     pub fn get_mut(this: &mut Self) -> Option<&mut T> {
768         if Rc::is_unique(this) { unsafe { Some(Rc::get_mut_unchecked(this)) } } else { None }
769     }
770
771     /// Returns a mutable reference into the given `Rc`,
772     /// without any check.
773     ///
774     /// See also [`get_mut`], which is safe and does appropriate checks.
775     ///
776     /// [`get_mut`]: struct.Rc.html#method.get_mut
777     ///
778     /// # Safety
779     ///
780     /// Any other `Rc` or [`Weak`] pointers to the same allocation must not be dereferenced
781     /// for the duration of the returned borrow.
782     /// This is trivially the case if no such pointers exist,
783     /// for example immediately after `Rc::new`.
784     ///
785     /// # Examples
786     ///
787     /// ```
788     /// #![feature(get_mut_unchecked)]
789     ///
790     /// use std::rc::Rc;
791     ///
792     /// let mut x = Rc::new(String::new());
793     /// unsafe {
794     ///     Rc::get_mut_unchecked(&mut x).push_str("foo")
795     /// }
796     /// assert_eq!(*x, "foo");
797     /// ```
798     #[inline]
799     #[unstable(feature = "get_mut_unchecked", issue = "63292")]
800     pub unsafe fn get_mut_unchecked(this: &mut Self) -> &mut T {
801         unsafe { &mut this.ptr.as_mut().value }
802     }
803
804     #[inline]
805     #[stable(feature = "ptr_eq", since = "1.17.0")]
806     /// Returns `true` if the two `Rc`s point to the same allocation
807     /// (in a vein similar to [`ptr::eq`]).
808     ///
809     /// # Examples
810     ///
811     /// ```
812     /// use std::rc::Rc;
813     ///
814     /// let five = Rc::new(5);
815     /// let same_five = Rc::clone(&five);
816     /// let other_five = Rc::new(5);
817     ///
818     /// assert!(Rc::ptr_eq(&five, &same_five));
819     /// assert!(!Rc::ptr_eq(&five, &other_five));
820     /// ```
821     ///
822     /// [`ptr::eq`]: ../../std/ptr/fn.eq.html
823     pub fn ptr_eq(this: &Self, other: &Self) -> bool {
824         this.ptr.as_ptr() == other.ptr.as_ptr()
825     }
826 }
827
828 impl<T: Clone> Rc<T> {
829     /// Makes a mutable reference into the given `Rc`.
830     ///
831     /// If there are other `Rc` pointers to the same allocation, then `make_mut` will
832     /// [`clone`] the inner value to a new allocation to ensure unique ownership.  This is also
833     /// referred to as clone-on-write.
834     ///
835     /// If there are no other `Rc` pointers to this allocation, then [`Weak`]
836     /// pointers to this allocation will be disassociated.
837     ///
838     /// See also [`get_mut`], which will fail rather than cloning.
839     ///
840     /// [`Weak`]: struct.Weak.html
841     /// [`clone`]: ../../std/clone/trait.Clone.html#tymethod.clone
842     /// [`get_mut`]: struct.Rc.html#method.get_mut
843     ///
844     /// # Examples
845     ///
846     /// ```
847     /// use std::rc::Rc;
848     ///
849     /// let mut data = Rc::new(5);
850     ///
851     /// *Rc::make_mut(&mut data) += 1;        // Won't clone anything
852     /// let mut other_data = Rc::clone(&data);    // Won't clone inner data
853     /// *Rc::make_mut(&mut data) += 1;        // Clones inner data
854     /// *Rc::make_mut(&mut data) += 1;        // Won't clone anything
855     /// *Rc::make_mut(&mut other_data) *= 2;  // Won't clone anything
856     ///
857     /// // Now `data` and `other_data` point to different allocations.
858     /// assert_eq!(*data, 8);
859     /// assert_eq!(*other_data, 12);
860     /// ```
861     ///
862     /// [`Weak`] pointers will be disassociated:
863     ///
864     /// ```
865     /// use std::rc::Rc;
866     ///
867     /// let mut data = Rc::new(75);
868     /// let weak = Rc::downgrade(&data);
869     ///
870     /// assert!(75 == *data);
871     /// assert!(75 == *weak.upgrade().unwrap());
872     ///
873     /// *Rc::make_mut(&mut data) += 1;
874     ///
875     /// assert!(76 == *data);
876     /// assert!(weak.upgrade().is_none());
877     /// ```
878     #[inline]
879     #[stable(feature = "rc_unique", since = "1.4.0")]
880     pub fn make_mut(this: &mut Self) -> &mut T {
881         if Rc::strong_count(this) != 1 {
882             // Gotta clone the data, there are other Rcs
883             *this = Rc::new((**this).clone())
884         } else if Rc::weak_count(this) != 0 {
885             // Can just steal the data, all that's left is Weaks
886             unsafe {
887                 let mut swap = Rc::new(ptr::read(&this.ptr.as_ref().value));
888                 mem::swap(this, &mut swap);
889                 swap.dec_strong();
890                 // Remove implicit strong-weak ref (no need to craft a fake
891                 // Weak here -- we know other Weaks can clean up for us)
892                 swap.dec_weak();
893                 forget(swap);
894             }
895         }
896         // This unsafety is ok because we're guaranteed that the pointer
897         // returned is the *only* pointer that will ever be returned to T. Our
898         // reference count is guaranteed to be 1 at this point, and we required
899         // the `Rc<T>` itself to be `mut`, so we're returning the only possible
900         // reference to the allocation.
901         unsafe { &mut this.ptr.as_mut().value }
902     }
903 }
904
905 impl Rc<dyn Any> {
906     #[inline]
907     #[stable(feature = "rc_downcast", since = "1.29.0")]
908     /// Attempt to downcast the `Rc<dyn Any>` to a concrete type.
909     ///
910     /// # Examples
911     ///
912     /// ```
913     /// use std::any::Any;
914     /// use std::rc::Rc;
915     ///
916     /// fn print_if_string(value: Rc<dyn Any>) {
917     ///     if let Ok(string) = value.downcast::<String>() {
918     ///         println!("String ({}): {}", string.len(), string);
919     ///     }
920     /// }
921     ///
922     /// let my_string = "Hello World".to_string();
923     /// print_if_string(Rc::new(my_string));
924     /// print_if_string(Rc::new(0i8));
925     /// ```
926     pub fn downcast<T: Any>(self) -> Result<Rc<T>, Rc<dyn Any>> {
927         if (*self).is::<T>() {
928             let ptr = self.ptr.cast::<RcBox<T>>();
929             forget(self);
930             Ok(Rc::from_inner(ptr))
931         } else {
932             Err(self)
933         }
934     }
935 }
936
937 impl<T: ?Sized> Rc<T> {
938     /// Allocates an `RcBox<T>` with sufficient space for
939     /// a possibly-unsized inner value where the value has the layout provided.
940     ///
941     /// The function `mem_to_rcbox` is called with the data pointer
942     /// and must return back a (potentially fat)-pointer for the `RcBox<T>`.
943     unsafe fn allocate_for_layout(
944         value_layout: Layout,
945         mem_to_rcbox: impl FnOnce(*mut u8) -> *mut RcBox<T>,
946     ) -> *mut RcBox<T> {
947         // Calculate layout using the given value layout.
948         // Previously, layout was calculated on the expression
949         // `&*(ptr as *const RcBox<T>)`, but this created a misaligned
950         // reference (see #54908).
951         let layout = Layout::new::<RcBox<()>>().extend(value_layout).unwrap().0.pad_to_align();
952
953         // Allocate for the layout.
954         let mem = Global
955             .alloc(layout, AllocInit::Uninitialized)
956             .unwrap_or_else(|_| handle_alloc_error(layout));
957
958         // Initialize the RcBox
959         let inner = mem_to_rcbox(mem.ptr.as_ptr());
960         unsafe {
961             debug_assert_eq!(Layout::for_value(&*inner), layout);
962
963             ptr::write(&mut (*inner).strong, Cell::new(1));
964             ptr::write(&mut (*inner).weak, Cell::new(1));
965         }
966
967         inner
968     }
969
970     /// Allocates an `RcBox<T>` with sufficient space for an unsized inner value
971     unsafe fn allocate_for_ptr(ptr: *const T) -> *mut RcBox<T> {
972         // Allocate for the `RcBox<T>` using the given value.
973         unsafe {
974             Self::allocate_for_layout(Layout::for_value(&*ptr), |mem| {
975                 set_data_ptr(ptr as *mut T, mem) as *mut RcBox<T>
976             })
977         }
978     }
979
980     fn from_box(v: Box<T>) -> Rc<T> {
981         unsafe {
982             let box_unique = Box::into_unique(v);
983             let bptr = box_unique.as_ptr();
984
985             let value_size = size_of_val(&*bptr);
986             let ptr = Self::allocate_for_ptr(bptr);
987
988             // Copy value as bytes
989             ptr::copy_nonoverlapping(
990                 bptr as *const T as *const u8,
991                 &mut (*ptr).value as *mut _ as *mut u8,
992                 value_size,
993             );
994
995             // Free the allocation without dropping its contents
996             box_free(box_unique);
997
998             Self::from_ptr(ptr)
999         }
1000     }
1001 }
1002
1003 impl<T> Rc<[T]> {
1004     /// Allocates an `RcBox<[T]>` with the given length.
1005     unsafe fn allocate_for_slice(len: usize) -> *mut RcBox<[T]> {
1006         unsafe {
1007             Self::allocate_for_layout(Layout::array::<T>(len).unwrap(), |mem| {
1008                 ptr::slice_from_raw_parts_mut(mem as *mut T, len) as *mut RcBox<[T]>
1009             })
1010         }
1011     }
1012 }
1013
1014 /// Sets the data pointer of a `?Sized` raw pointer.
1015 ///
1016 /// For a slice/trait object, this sets the `data` field and leaves the rest
1017 /// unchanged. For a sized raw pointer, this simply sets the pointer.
1018 unsafe fn set_data_ptr<T: ?Sized, U>(mut ptr: *mut T, data: *mut U) -> *mut T {
1019     unsafe {
1020         ptr::write(&mut ptr as *mut _ as *mut *mut u8, data as *mut u8);
1021     }
1022     ptr
1023 }
1024
1025 impl<T> Rc<[T]> {
1026     /// Copy elements from slice into newly allocated Rc<\[T\]>
1027     ///
1028     /// Unsafe because the caller must either take ownership or bind `T: Copy`
1029     unsafe fn copy_from_slice(v: &[T]) -> Rc<[T]> {
1030         unsafe {
1031             let ptr = Self::allocate_for_slice(v.len());
1032             ptr::copy_nonoverlapping(v.as_ptr(), &mut (*ptr).value as *mut [T] as *mut T, v.len());
1033             Self::from_ptr(ptr)
1034         }
1035     }
1036
1037     /// Constructs an `Rc<[T]>` from an iterator known to be of a certain size.
1038     ///
1039     /// Behavior is undefined should the size be wrong.
1040     unsafe fn from_iter_exact(iter: impl iter::Iterator<Item = T>, len: usize) -> Rc<[T]> {
1041         // Panic guard while cloning T elements.
1042         // In the event of a panic, elements that have been written
1043         // into the new RcBox will be dropped, then the memory freed.
1044         struct Guard<T> {
1045             mem: NonNull<u8>,
1046             elems: *mut T,
1047             layout: Layout,
1048             n_elems: usize,
1049         }
1050
1051         impl<T> Drop for Guard<T> {
1052             fn drop(&mut self) {
1053                 unsafe {
1054                     let slice = from_raw_parts_mut(self.elems, self.n_elems);
1055                     ptr::drop_in_place(slice);
1056
1057                     Global.dealloc(self.mem, self.layout);
1058                 }
1059             }
1060         }
1061
1062         unsafe {
1063             let ptr = Self::allocate_for_slice(len);
1064
1065             let mem = ptr as *mut _ as *mut u8;
1066             let layout = Layout::for_value(&*ptr);
1067
1068             // Pointer to first element
1069             let elems = &mut (*ptr).value as *mut [T] as *mut T;
1070
1071             let mut guard = Guard { mem: NonNull::new_unchecked(mem), elems, layout, n_elems: 0 };
1072
1073             for (i, item) in iter.enumerate() {
1074                 ptr::write(elems.add(i), item);
1075                 guard.n_elems += 1;
1076             }
1077
1078             // All clear. Forget the guard so it doesn't free the new RcBox.
1079             forget(guard);
1080
1081             Self::from_ptr(ptr)
1082         }
1083     }
1084 }
1085
1086 /// Specialization trait used for `From<&[T]>`.
1087 trait RcFromSlice<T> {
1088     fn from_slice(slice: &[T]) -> Self;
1089 }
1090
1091 impl<T: Clone> RcFromSlice<T> for Rc<[T]> {
1092     #[inline]
1093     default fn from_slice(v: &[T]) -> Self {
1094         unsafe { Self::from_iter_exact(v.iter().cloned(), v.len()) }
1095     }
1096 }
1097
1098 impl<T: Copy> RcFromSlice<T> for Rc<[T]> {
1099     #[inline]
1100     fn from_slice(v: &[T]) -> Self {
1101         unsafe { Rc::copy_from_slice(v) }
1102     }
1103 }
1104
1105 #[stable(feature = "rust1", since = "1.0.0")]
1106 impl<T: ?Sized> Deref for Rc<T> {
1107     type Target = T;
1108
1109     #[inline(always)]
1110     fn deref(&self) -> &T {
1111         &self.inner().value
1112     }
1113 }
1114
1115 #[unstable(feature = "receiver_trait", issue = "none")]
1116 impl<T: ?Sized> Receiver for Rc<T> {}
1117
1118 #[stable(feature = "rust1", since = "1.0.0")]
1119 unsafe impl<#[may_dangle] T: ?Sized> Drop for Rc<T> {
1120     /// Drops the `Rc`.
1121     ///
1122     /// This will decrement the strong reference count. If the strong reference
1123     /// count reaches zero then the only other references (if any) are
1124     /// [`Weak`], so we `drop` the inner value.
1125     ///
1126     /// # Examples
1127     ///
1128     /// ```
1129     /// use std::rc::Rc;
1130     ///
1131     /// struct Foo;
1132     ///
1133     /// impl Drop for Foo {
1134     ///     fn drop(&mut self) {
1135     ///         println!("dropped!");
1136     ///     }
1137     /// }
1138     ///
1139     /// let foo  = Rc::new(Foo);
1140     /// let foo2 = Rc::clone(&foo);
1141     ///
1142     /// drop(foo);    // Doesn't print anything
1143     /// drop(foo2);   // Prints "dropped!"
1144     /// ```
1145     ///
1146     /// [`Weak`]: ../../std/rc/struct.Weak.html
1147     fn drop(&mut self) {
1148         unsafe {
1149             self.dec_strong();
1150             if self.strong() == 0 {
1151                 // destroy the contained object
1152                 ptr::drop_in_place(self.ptr.as_mut());
1153
1154                 // remove the implicit "strong weak" pointer now that we've
1155                 // destroyed the contents.
1156                 self.dec_weak();
1157
1158                 if self.weak() == 0 {
1159                     Global.dealloc(self.ptr.cast(), Layout::for_value(self.ptr.as_ref()));
1160                 }
1161             }
1162         }
1163     }
1164 }
1165
1166 #[stable(feature = "rust1", since = "1.0.0")]
1167 impl<T: ?Sized> Clone for Rc<T> {
1168     /// Makes a clone of the `Rc` pointer.
1169     ///
1170     /// This creates another pointer to the same allocation, increasing the
1171     /// strong reference count.
1172     ///
1173     /// # Examples
1174     ///
1175     /// ```
1176     /// use std::rc::Rc;
1177     ///
1178     /// let five = Rc::new(5);
1179     ///
1180     /// let _ = Rc::clone(&five);
1181     /// ```
1182     #[inline]
1183     fn clone(&self) -> Rc<T> {
1184         self.inc_strong();
1185         Self::from_inner(self.ptr)
1186     }
1187 }
1188
1189 #[stable(feature = "rust1", since = "1.0.0")]
1190 impl<T: Default> Default for Rc<T> {
1191     /// Creates a new `Rc<T>`, with the `Default` value for `T`.
1192     ///
1193     /// # Examples
1194     ///
1195     /// ```
1196     /// use std::rc::Rc;
1197     ///
1198     /// let x: Rc<i32> = Default::default();
1199     /// assert_eq!(*x, 0);
1200     /// ```
1201     #[inline]
1202     fn default() -> Rc<T> {
1203         Rc::new(Default::default())
1204     }
1205 }
1206
1207 #[stable(feature = "rust1", since = "1.0.0")]
1208 trait RcEqIdent<T: ?Sized + PartialEq> {
1209     fn eq(&self, other: &Rc<T>) -> bool;
1210     fn ne(&self, other: &Rc<T>) -> bool;
1211 }
1212
1213 #[stable(feature = "rust1", since = "1.0.0")]
1214 impl<T: ?Sized + PartialEq> RcEqIdent<T> for Rc<T> {
1215     #[inline]
1216     default fn eq(&self, other: &Rc<T>) -> bool {
1217         **self == **other
1218     }
1219
1220     #[inline]
1221     default fn ne(&self, other: &Rc<T>) -> bool {
1222         **self != **other
1223     }
1224 }
1225
1226 // Hack to allow specializing on `Eq` even though `Eq` has a method.
1227 #[rustc_unsafe_specialization_marker]
1228 pub(crate) trait MarkerEq: PartialEq<Self> {}
1229
1230 impl<T: Eq> MarkerEq for T {}
1231
1232 /// We're doing this specialization here, and not as a more general optimization on `&T`, because it
1233 /// would otherwise add a cost to all equality checks on refs. We assume that `Rc`s are used to
1234 /// store large values, that are slow to clone, but also heavy to check for equality, causing this
1235 /// cost to pay off more easily. It's also more likely to have two `Rc` clones, that point to
1236 /// the same value, than two `&T`s.
1237 ///
1238 /// We can only do this when `T: Eq` as a `PartialEq` might be deliberately irreflexive.
1239 #[stable(feature = "rust1", since = "1.0.0")]
1240 impl<T: ?Sized + MarkerEq> RcEqIdent<T> for Rc<T> {
1241     #[inline]
1242     fn eq(&self, other: &Rc<T>) -> bool {
1243         Rc::ptr_eq(self, other) || **self == **other
1244     }
1245
1246     #[inline]
1247     fn ne(&self, other: &Rc<T>) -> bool {
1248         !Rc::ptr_eq(self, other) && **self != **other
1249     }
1250 }
1251
1252 #[stable(feature = "rust1", since = "1.0.0")]
1253 impl<T: ?Sized + PartialEq> PartialEq for Rc<T> {
1254     /// Equality for two `Rc`s.
1255     ///
1256     /// Two `Rc`s are equal if their inner values are equal, even if they are
1257     /// stored in different allocation.
1258     ///
1259     /// If `T` also implements `Eq` (implying reflexivity of equality),
1260     /// two `Rc`s that point to the same allocation are
1261     /// always equal.
1262     ///
1263     /// # Examples
1264     ///
1265     /// ```
1266     /// use std::rc::Rc;
1267     ///
1268     /// let five = Rc::new(5);
1269     ///
1270     /// assert!(five == Rc::new(5));
1271     /// ```
1272     #[inline]
1273     fn eq(&self, other: &Rc<T>) -> bool {
1274         RcEqIdent::eq(self, other)
1275     }
1276
1277     /// Inequality for two `Rc`s.
1278     ///
1279     /// Two `Rc`s are unequal if their inner values are unequal.
1280     ///
1281     /// If `T` also implements `Eq` (implying reflexivity of equality),
1282     /// two `Rc`s that point to the same allocation are
1283     /// never unequal.
1284     ///
1285     /// # Examples
1286     ///
1287     /// ```
1288     /// use std::rc::Rc;
1289     ///
1290     /// let five = Rc::new(5);
1291     ///
1292     /// assert!(five != Rc::new(6));
1293     /// ```
1294     #[inline]
1295     fn ne(&self, other: &Rc<T>) -> bool {
1296         RcEqIdent::ne(self, other)
1297     }
1298 }
1299
1300 #[stable(feature = "rust1", since = "1.0.0")]
1301 impl<T: ?Sized + Eq> Eq for Rc<T> {}
1302
1303 #[stable(feature = "rust1", since = "1.0.0")]
1304 impl<T: ?Sized + PartialOrd> PartialOrd for Rc<T> {
1305     /// Partial comparison for two `Rc`s.
1306     ///
1307     /// The two are compared by calling `partial_cmp()` on their inner values.
1308     ///
1309     /// # Examples
1310     ///
1311     /// ```
1312     /// use std::rc::Rc;
1313     /// use std::cmp::Ordering;
1314     ///
1315     /// let five = Rc::new(5);
1316     ///
1317     /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&Rc::new(6)));
1318     /// ```
1319     #[inline(always)]
1320     fn partial_cmp(&self, other: &Rc<T>) -> Option<Ordering> {
1321         (**self).partial_cmp(&**other)
1322     }
1323
1324     /// Less-than comparison for two `Rc`s.
1325     ///
1326     /// The two are compared by calling `<` on their inner values.
1327     ///
1328     /// # Examples
1329     ///
1330     /// ```
1331     /// use std::rc::Rc;
1332     ///
1333     /// let five = Rc::new(5);
1334     ///
1335     /// assert!(five < Rc::new(6));
1336     /// ```
1337     #[inline(always)]
1338     fn lt(&self, other: &Rc<T>) -> bool {
1339         **self < **other
1340     }
1341
1342     /// 'Less than or equal to' comparison for two `Rc`s.
1343     ///
1344     /// The two are compared by calling `<=` on their inner values.
1345     ///
1346     /// # Examples
1347     ///
1348     /// ```
1349     /// use std::rc::Rc;
1350     ///
1351     /// let five = Rc::new(5);
1352     ///
1353     /// assert!(five <= Rc::new(5));
1354     /// ```
1355     #[inline(always)]
1356     fn le(&self, other: &Rc<T>) -> bool {
1357         **self <= **other
1358     }
1359
1360     /// Greater-than comparison for two `Rc`s.
1361     ///
1362     /// The two are compared by calling `>` on their inner values.
1363     ///
1364     /// # Examples
1365     ///
1366     /// ```
1367     /// use std::rc::Rc;
1368     ///
1369     /// let five = Rc::new(5);
1370     ///
1371     /// assert!(five > Rc::new(4));
1372     /// ```
1373     #[inline(always)]
1374     fn gt(&self, other: &Rc<T>) -> bool {
1375         **self > **other
1376     }
1377
1378     /// 'Greater than or equal to' comparison for two `Rc`s.
1379     ///
1380     /// The two are compared by calling `>=` on their inner values.
1381     ///
1382     /// # Examples
1383     ///
1384     /// ```
1385     /// use std::rc::Rc;
1386     ///
1387     /// let five = Rc::new(5);
1388     ///
1389     /// assert!(five >= Rc::new(5));
1390     /// ```
1391     #[inline(always)]
1392     fn ge(&self, other: &Rc<T>) -> bool {
1393         **self >= **other
1394     }
1395 }
1396
1397 #[stable(feature = "rust1", since = "1.0.0")]
1398 impl<T: ?Sized + Ord> Ord for Rc<T> {
1399     /// Comparison for two `Rc`s.
1400     ///
1401     /// The two are compared by calling `cmp()` on their inner values.
1402     ///
1403     /// # Examples
1404     ///
1405     /// ```
1406     /// use std::rc::Rc;
1407     /// use std::cmp::Ordering;
1408     ///
1409     /// let five = Rc::new(5);
1410     ///
1411     /// assert_eq!(Ordering::Less, five.cmp(&Rc::new(6)));
1412     /// ```
1413     #[inline]
1414     fn cmp(&self, other: &Rc<T>) -> Ordering {
1415         (**self).cmp(&**other)
1416     }
1417 }
1418
1419 #[stable(feature = "rust1", since = "1.0.0")]
1420 impl<T: ?Sized + Hash> Hash for Rc<T> {
1421     fn hash<H: Hasher>(&self, state: &mut H) {
1422         (**self).hash(state);
1423     }
1424 }
1425
1426 #[stable(feature = "rust1", since = "1.0.0")]
1427 impl<T: ?Sized + fmt::Display> fmt::Display for Rc<T> {
1428     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1429         fmt::Display::fmt(&**self, f)
1430     }
1431 }
1432
1433 #[stable(feature = "rust1", since = "1.0.0")]
1434 impl<T: ?Sized + fmt::Debug> fmt::Debug for Rc<T> {
1435     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1436         fmt::Debug::fmt(&**self, f)
1437     }
1438 }
1439
1440 #[stable(feature = "rust1", since = "1.0.0")]
1441 impl<T: ?Sized> fmt::Pointer for Rc<T> {
1442     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1443         fmt::Pointer::fmt(&(&**self as *const T), f)
1444     }
1445 }
1446
1447 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
1448 impl<T> From<T> for Rc<T> {
1449     fn from(t: T) -> Self {
1450         Rc::new(t)
1451     }
1452 }
1453
1454 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1455 impl<T: Clone> From<&[T]> for Rc<[T]> {
1456     #[inline]
1457     fn from(v: &[T]) -> Rc<[T]> {
1458         <Self as RcFromSlice<T>>::from_slice(v)
1459     }
1460 }
1461
1462 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1463 impl From<&str> for Rc<str> {
1464     #[inline]
1465     fn from(v: &str) -> Rc<str> {
1466         let rc = Rc::<[u8]>::from(v.as_bytes());
1467         unsafe { Rc::from_raw(Rc::into_raw(rc) as *const str) }
1468     }
1469 }
1470
1471 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1472 impl From<String> for Rc<str> {
1473     #[inline]
1474     fn from(v: String) -> Rc<str> {
1475         Rc::from(&v[..])
1476     }
1477 }
1478
1479 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1480 impl<T: ?Sized> From<Box<T>> for Rc<T> {
1481     #[inline]
1482     fn from(v: Box<T>) -> Rc<T> {
1483         Rc::from_box(v)
1484     }
1485 }
1486
1487 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1488 impl<T> From<Vec<T>> for Rc<[T]> {
1489     #[inline]
1490     fn from(mut v: Vec<T>) -> Rc<[T]> {
1491         unsafe {
1492             let rc = Rc::copy_from_slice(&v);
1493
1494             // Allow the Vec to free its memory, but not destroy its contents
1495             v.set_len(0);
1496
1497             rc
1498         }
1499     }
1500 }
1501
1502 #[stable(feature = "shared_from_cow", since = "1.45.0")]
1503 impl<'a, B> From<Cow<'a, B>> for Rc<B>
1504 where
1505     B: ToOwned + ?Sized,
1506     Rc<B>: From<&'a B> + From<B::Owned>,
1507 {
1508     #[inline]
1509     fn from(cow: Cow<'a, B>) -> Rc<B> {
1510         match cow {
1511             Cow::Borrowed(s) => Rc::from(s),
1512             Cow::Owned(s) => Rc::from(s),
1513         }
1514     }
1515 }
1516
1517 #[stable(feature = "boxed_slice_try_from", since = "1.43.0")]
1518 impl<T, const N: usize> TryFrom<Rc<[T]>> for Rc<[T; N]> {
1519     type Error = Rc<[T]>;
1520
1521     fn try_from(boxed_slice: Rc<[T]>) -> Result<Self, Self::Error> {
1522         if boxed_slice.len() == N {
1523             Ok(unsafe { Rc::from_raw(Rc::into_raw(boxed_slice) as *mut [T; N]) })
1524         } else {
1525             Err(boxed_slice)
1526         }
1527     }
1528 }
1529
1530 #[stable(feature = "shared_from_iter", since = "1.37.0")]
1531 impl<T> iter::FromIterator<T> for Rc<[T]> {
1532     /// Takes each element in the `Iterator` and collects it into an `Rc<[T]>`.
1533     ///
1534     /// # Performance characteristics
1535     ///
1536     /// ## The general case
1537     ///
1538     /// In the general case, collecting into `Rc<[T]>` is done by first
1539     /// collecting into a `Vec<T>`. That is, when writing the following:
1540     ///
1541     /// ```rust
1542     /// # use std::rc::Rc;
1543     /// let evens: Rc<[u8]> = (0..10).filter(|&x| x % 2 == 0).collect();
1544     /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]);
1545     /// ```
1546     ///
1547     /// this behaves as if we wrote:
1548     ///
1549     /// ```rust
1550     /// # use std::rc::Rc;
1551     /// let evens: Rc<[u8]> = (0..10).filter(|&x| x % 2 == 0)
1552     ///     .collect::<Vec<_>>() // The first set of allocations happens here.
1553     ///     .into(); // A second allocation for `Rc<[T]>` happens here.
1554     /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]);
1555     /// ```
1556     ///
1557     /// This will allocate as many times as needed for constructing the `Vec<T>`
1558     /// and then it will allocate once for turning the `Vec<T>` into the `Rc<[T]>`.
1559     ///
1560     /// ## Iterators of known length
1561     ///
1562     /// When your `Iterator` implements `TrustedLen` and is of an exact size,
1563     /// a single allocation will be made for the `Rc<[T]>`. For example:
1564     ///
1565     /// ```rust
1566     /// # use std::rc::Rc;
1567     /// let evens: Rc<[u8]> = (0..10).collect(); // Just a single allocation happens here.
1568     /// # assert_eq!(&*evens, &*(0..10).collect::<Vec<_>>());
1569     /// ```
1570     fn from_iter<I: iter::IntoIterator<Item = T>>(iter: I) -> Self {
1571         ToRcSlice::to_rc_slice(iter.into_iter())
1572     }
1573 }
1574
1575 /// Specialization trait used for collecting into `Rc<[T]>`.
1576 trait ToRcSlice<T>: Iterator<Item = T> + Sized {
1577     fn to_rc_slice(self) -> Rc<[T]>;
1578 }
1579
1580 impl<T, I: Iterator<Item = T>> ToRcSlice<T> for I {
1581     default fn to_rc_slice(self) -> Rc<[T]> {
1582         self.collect::<Vec<T>>().into()
1583     }
1584 }
1585
1586 impl<T, I: iter::TrustedLen<Item = T>> ToRcSlice<T> for I {
1587     fn to_rc_slice(self) -> Rc<[T]> {
1588         // This is the case for a `TrustedLen` iterator.
1589         let (low, high) = self.size_hint();
1590         if let Some(high) = high {
1591             debug_assert_eq!(
1592                 low,
1593                 high,
1594                 "TrustedLen iterator's size hint is not exact: {:?}",
1595                 (low, high)
1596             );
1597
1598             unsafe {
1599                 // SAFETY: We need to ensure that the iterator has an exact length and we have.
1600                 Rc::from_iter_exact(self, low)
1601             }
1602         } else {
1603             // Fall back to normal implementation.
1604             self.collect::<Vec<T>>().into()
1605         }
1606     }
1607 }
1608
1609 /// `Weak` is a version of [`Rc`] that holds a non-owning reference to the
1610 /// managed allocation. The allocation is accessed by calling [`upgrade`] on the `Weak`
1611 /// pointer, which returns an [`Option`]`<`[`Rc`]`<T>>`.
1612 ///
1613 /// Since a `Weak` reference does not count towards ownership, it will not
1614 /// prevent the value stored in the allocation from being dropped, and `Weak` itself makes no
1615 /// guarantees about the value still being present. Thus it may return [`None`]
1616 /// when [`upgrade`]d. Note however that a `Weak` reference *does* prevent the allocation
1617 /// itself (the backing store) from being deallocated.
1618 ///
1619 /// A `Weak` pointer is useful for keeping a temporary reference to the allocation
1620 /// managed by [`Rc`] without preventing its inner value from being dropped. It is also used to
1621 /// prevent circular references between [`Rc`] pointers, since mutual owning references
1622 /// would never allow either [`Rc`] to be dropped. For example, a tree could
1623 /// have strong [`Rc`] pointers from parent nodes to children, and `Weak`
1624 /// pointers from children back to their parents.
1625 ///
1626 /// The typical way to obtain a `Weak` pointer is to call [`Rc::downgrade`].
1627 ///
1628 /// [`Rc`]: struct.Rc.html
1629 /// [`Rc::downgrade`]: struct.Rc.html#method.downgrade
1630 /// [`upgrade`]: struct.Weak.html#method.upgrade
1631 /// [`Option`]: ../../std/option/enum.Option.html
1632 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1633 #[stable(feature = "rc_weak", since = "1.4.0")]
1634 pub struct Weak<T: ?Sized> {
1635     // This is a `NonNull` to allow optimizing the size of this type in enums,
1636     // but it is not necessarily a valid pointer.
1637     // `Weak::new` sets this to `usize::MAX` so that it doesn’t need
1638     // to allocate space on the heap.  That's not a value a real pointer
1639     // will ever have because RcBox has alignment at least 2.
1640     // This is only possible when `T: Sized`; unsized `T` never dangle.
1641     ptr: NonNull<RcBox<T>>,
1642 }
1643
1644 #[stable(feature = "rc_weak", since = "1.4.0")]
1645 impl<T: ?Sized> !marker::Send for Weak<T> {}
1646 #[stable(feature = "rc_weak", since = "1.4.0")]
1647 impl<T: ?Sized> !marker::Sync for Weak<T> {}
1648
1649 #[unstable(feature = "coerce_unsized", issue = "27732")]
1650 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {}
1651
1652 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
1653 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Weak<U>> for Weak<T> {}
1654
1655 impl<T> Weak<T> {
1656     /// Constructs a new `Weak<T>`, without allocating any memory.
1657     /// Calling [`upgrade`] on the return value always gives [`None`].
1658     ///
1659     /// [`upgrade`]: #method.upgrade
1660     /// [`None`]: ../../std/option/enum.Option.html
1661     ///
1662     /// # Examples
1663     ///
1664     /// ```
1665     /// use std::rc::Weak;
1666     ///
1667     /// let empty: Weak<i64> = Weak::new();
1668     /// assert!(empty.upgrade().is_none());
1669     /// ```
1670     #[stable(feature = "downgraded_weak", since = "1.10.0")]
1671     pub fn new() -> Weak<T> {
1672         Weak { ptr: NonNull::new(usize::MAX as *mut RcBox<T>).expect("MAX is not 0") }
1673     }
1674
1675     /// Returns a raw pointer to the object `T` pointed to by this `Weak<T>`.
1676     ///
1677     /// The pointer is valid only if there are some strong references. The pointer may be dangling,
1678     /// unaligned or even [`null`] otherwise.
1679     ///
1680     /// # Examples
1681     ///
1682     /// ```
1683     /// use std::rc::Rc;
1684     /// use std::ptr;
1685     ///
1686     /// let strong = Rc::new("hello".to_owned());
1687     /// let weak = Rc::downgrade(&strong);
1688     /// // Both point to the same object
1689     /// assert!(ptr::eq(&*strong, weak.as_ptr()));
1690     /// // The strong here keeps it alive, so we can still access the object.
1691     /// assert_eq!("hello", unsafe { &*weak.as_ptr() });
1692     ///
1693     /// drop(strong);
1694     /// // But not any more. We can do weak.as_ptr(), but accessing the pointer would lead to
1695     /// // undefined behaviour.
1696     /// // assert_eq!("hello", unsafe { &*weak.as_ptr() });
1697     /// ```
1698     ///
1699     /// [`null`]: ../../std/ptr/fn.null.html
1700     #[stable(feature = "rc_as_ptr", since = "1.45.0")]
1701     pub fn as_ptr(&self) -> *const T {
1702         let ptr: *mut RcBox<T> = NonNull::as_ptr(self.ptr);
1703
1704         // SAFETY: we must offset the pointer manually, and said pointer may be
1705         // a dangling weak (usize::MAX) if T is sized. data_offset is safe to call,
1706         // because we know that a pointer to unsized T was derived from a real
1707         // unsized T, as dangling weaks are only created for sized T. wrapping_offset
1708         // is used so that we can use the same code path for the non-dangling
1709         // unsized case and the potentially dangling sized case.
1710         unsafe {
1711             let offset = data_offset(ptr as *mut T);
1712             set_data_ptr(ptr as *mut T, (ptr as *mut u8).wrapping_offset(offset))
1713         }
1714     }
1715
1716     /// Consumes the `Weak<T>` and turns it into a raw pointer.
1717     ///
1718     /// This converts the weak pointer into a raw pointer, preserving the original weak count. It
1719     /// can be turned back into the `Weak<T>` with [`from_raw`].
1720     ///
1721     /// The same restrictions of accessing the target of the pointer as with
1722     /// [`as_ptr`] apply.
1723     ///
1724     /// # Examples
1725     ///
1726     /// ```
1727     /// use std::rc::{Rc, Weak};
1728     ///
1729     /// let strong = Rc::new("hello".to_owned());
1730     /// let weak = Rc::downgrade(&strong);
1731     /// let raw = weak.into_raw();
1732     ///
1733     /// assert_eq!(1, Rc::weak_count(&strong));
1734     /// assert_eq!("hello", unsafe { &*raw });
1735     ///
1736     /// drop(unsafe { Weak::from_raw(raw) });
1737     /// assert_eq!(0, Rc::weak_count(&strong));
1738     /// ```
1739     ///
1740     /// [`from_raw`]: struct.Weak.html#method.from_raw
1741     /// [`as_ptr`]: struct.Weak.html#method.as_ptr
1742     #[stable(feature = "weak_into_raw", since = "1.45.0")]
1743     pub fn into_raw(self) -> *const T {
1744         let result = self.as_ptr();
1745         mem::forget(self);
1746         result
1747     }
1748
1749     /// Converts a raw pointer previously created by [`into_raw`] back into `Weak<T>`.
1750     ///
1751     /// This can be used to safely get a strong reference (by calling [`upgrade`]
1752     /// later) or to deallocate the weak count by dropping the `Weak<T>`.
1753     ///
1754     /// It takes ownership of one weak count (with the exception of pointers created by [`new`],
1755     /// as these don't have any corresponding weak count).
1756     ///
1757     /// # Safety
1758     ///
1759     /// The pointer must have originated from the [`into_raw`]  and must still own its potential
1760     /// weak reference count.
1761     ///
1762     /// It is allowed for the strong count to be 0 at the time of calling this, but the weak count
1763     /// must be non-zero or the pointer must have originated from a dangling `Weak<T>` (one created
1764     /// by [`new`]).
1765     ///
1766     /// # Examples
1767     ///
1768     /// ```
1769     /// use std::rc::{Rc, Weak};
1770     ///
1771     /// let strong = Rc::new("hello".to_owned());
1772     ///
1773     /// let raw_1 = Rc::downgrade(&strong).into_raw();
1774     /// let raw_2 = Rc::downgrade(&strong).into_raw();
1775     ///
1776     /// assert_eq!(2, Rc::weak_count(&strong));
1777     ///
1778     /// assert_eq!("hello", &*unsafe { Weak::from_raw(raw_1) }.upgrade().unwrap());
1779     /// assert_eq!(1, Rc::weak_count(&strong));
1780     ///
1781     /// drop(strong);
1782     ///
1783     /// // Decrement the last weak count.
1784     /// assert!(unsafe { Weak::from_raw(raw_2) }.upgrade().is_none());
1785     /// ```
1786     ///
1787     /// [`into_raw`]: struct.Weak.html#method.into_raw
1788     /// [`upgrade`]: struct.Weak.html#method.upgrade
1789     /// [`Rc`]: struct.Rc.html
1790     /// [`Weak`]: struct.Weak.html
1791     /// [`new`]: struct.Weak.html#method.new
1792     /// [`forget`]: ../../std/mem/fn.forget.html
1793     #[stable(feature = "weak_into_raw", since = "1.45.0")]
1794     pub unsafe fn from_raw(ptr: *const T) -> Self {
1795         if ptr.is_null() {
1796             Self::new()
1797         } else {
1798             // See Rc::from_raw for details
1799             unsafe {
1800                 let offset = data_offset(ptr);
1801                 let fake_ptr = ptr as *mut RcBox<T>;
1802                 let ptr = set_data_ptr(fake_ptr, (ptr as *mut u8).offset(-offset));
1803                 Weak { ptr: NonNull::new(ptr).expect("Invalid pointer passed to from_raw") }
1804             }
1805         }
1806     }
1807 }
1808
1809 pub(crate) fn is_dangling<T: ?Sized>(ptr: NonNull<T>) -> bool {
1810     let address = ptr.as_ptr() as *mut () as usize;
1811     address == usize::MAX
1812 }
1813
1814 impl<T: ?Sized> Weak<T> {
1815     /// Attempts to upgrade the `Weak` pointer to an [`Rc`], delaying
1816     /// dropping of the inner value if successful.
1817     ///
1818     /// Returns [`None`] if the inner value has since been dropped.
1819     ///
1820     /// [`Rc`]: struct.Rc.html
1821     /// [`None`]: ../../std/option/enum.Option.html
1822     ///
1823     /// # Examples
1824     ///
1825     /// ```
1826     /// use std::rc::Rc;
1827     ///
1828     /// let five = Rc::new(5);
1829     ///
1830     /// let weak_five = Rc::downgrade(&five);
1831     ///
1832     /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
1833     /// assert!(strong_five.is_some());
1834     ///
1835     /// // Destroy all strong pointers.
1836     /// drop(strong_five);
1837     /// drop(five);
1838     ///
1839     /// assert!(weak_five.upgrade().is_none());
1840     /// ```
1841     #[stable(feature = "rc_weak", since = "1.4.0")]
1842     pub fn upgrade(&self) -> Option<Rc<T>> {
1843         let inner = self.inner()?;
1844         if inner.strong() == 0 {
1845             None
1846         } else {
1847             inner.inc_strong();
1848             Some(Rc::from_inner(self.ptr))
1849         }
1850     }
1851
1852     /// Gets the number of strong (`Rc`) pointers pointing to this allocation.
1853     ///
1854     /// If `self` was created using [`Weak::new`], this will return 0.
1855     ///
1856     /// [`Weak::new`]: #method.new
1857     #[stable(feature = "weak_counts", since = "1.41.0")]
1858     pub fn strong_count(&self) -> usize {
1859         if let Some(inner) = self.inner() { inner.strong() } else { 0 }
1860     }
1861
1862     /// Gets the number of `Weak` pointers pointing to this allocation.
1863     ///
1864     /// If no strong pointers remain, this will return zero.
1865     #[stable(feature = "weak_counts", since = "1.41.0")]
1866     pub fn weak_count(&self) -> usize {
1867         self.inner()
1868             .map(|inner| {
1869                 if inner.strong() > 0 {
1870                     inner.weak() - 1 // subtract the implicit weak ptr
1871                 } else {
1872                     0
1873                 }
1874             })
1875             .unwrap_or(0)
1876     }
1877
1878     /// Returns `None` when the pointer is dangling and there is no allocated `RcBox`
1879     /// (i.e., when this `Weak` was created by `Weak::new`).
1880     #[inline]
1881     fn inner(&self) -> Option<&RcBox<T>> {
1882         if is_dangling(self.ptr) { None } else { Some(unsafe { self.ptr.as_ref() }) }
1883     }
1884
1885     /// Returns `true` if the two `Weak`s point to the same allocation (similar to
1886     /// [`ptr::eq`]), or if both don't point to any allocation
1887     /// (because they were created with `Weak::new()`).
1888     ///
1889     /// # Notes
1890     ///
1891     /// Since this compares pointers it means that `Weak::new()` will equal each
1892     /// other, even though they don't point to any allocation.
1893     ///
1894     /// # Examples
1895     ///
1896     /// ```
1897     /// use std::rc::Rc;
1898     ///
1899     /// let first_rc = Rc::new(5);
1900     /// let first = Rc::downgrade(&first_rc);
1901     /// let second = Rc::downgrade(&first_rc);
1902     ///
1903     /// assert!(first.ptr_eq(&second));
1904     ///
1905     /// let third_rc = Rc::new(5);
1906     /// let third = Rc::downgrade(&third_rc);
1907     ///
1908     /// assert!(!first.ptr_eq(&third));
1909     /// ```
1910     ///
1911     /// Comparing `Weak::new`.
1912     ///
1913     /// ```
1914     /// use std::rc::{Rc, Weak};
1915     ///
1916     /// let first = Weak::new();
1917     /// let second = Weak::new();
1918     /// assert!(first.ptr_eq(&second));
1919     ///
1920     /// let third_rc = Rc::new(());
1921     /// let third = Rc::downgrade(&third_rc);
1922     /// assert!(!first.ptr_eq(&third));
1923     /// ```
1924     ///
1925     /// [`ptr::eq`]: ../../std/ptr/fn.eq.html
1926     #[inline]
1927     #[stable(feature = "weak_ptr_eq", since = "1.39.0")]
1928     pub fn ptr_eq(&self, other: &Self) -> bool {
1929         self.ptr.as_ptr() == other.ptr.as_ptr()
1930     }
1931 }
1932
1933 #[stable(feature = "rc_weak", since = "1.4.0")]
1934 impl<T: ?Sized> Drop for Weak<T> {
1935     /// Drops the `Weak` pointer.
1936     ///
1937     /// # Examples
1938     ///
1939     /// ```
1940     /// use std::rc::{Rc, Weak};
1941     ///
1942     /// struct Foo;
1943     ///
1944     /// impl Drop for Foo {
1945     ///     fn drop(&mut self) {
1946     ///         println!("dropped!");
1947     ///     }
1948     /// }
1949     ///
1950     /// let foo = Rc::new(Foo);
1951     /// let weak_foo = Rc::downgrade(&foo);
1952     /// let other_weak_foo = Weak::clone(&weak_foo);
1953     ///
1954     /// drop(weak_foo);   // Doesn't print anything
1955     /// drop(foo);        // Prints "dropped!"
1956     ///
1957     /// assert!(other_weak_foo.upgrade().is_none());
1958     /// ```
1959     fn drop(&mut self) {
1960         if let Some(inner) = self.inner() {
1961             inner.dec_weak();
1962             // the weak count starts at 1, and will only go to zero if all
1963             // the strong pointers have disappeared.
1964             if inner.weak() == 0 {
1965                 unsafe {
1966                     Global.dealloc(self.ptr.cast(), Layout::for_value(self.ptr.as_ref()));
1967                 }
1968             }
1969         }
1970     }
1971 }
1972
1973 #[stable(feature = "rc_weak", since = "1.4.0")]
1974 impl<T: ?Sized> Clone for Weak<T> {
1975     /// Makes a clone of the `Weak` pointer that points to the same allocation.
1976     ///
1977     /// # Examples
1978     ///
1979     /// ```
1980     /// use std::rc::{Rc, Weak};
1981     ///
1982     /// let weak_five = Rc::downgrade(&Rc::new(5));
1983     ///
1984     /// let _ = Weak::clone(&weak_five);
1985     /// ```
1986     #[inline]
1987     fn clone(&self) -> Weak<T> {
1988         if let Some(inner) = self.inner() {
1989             inner.inc_weak()
1990         }
1991         Weak { ptr: self.ptr }
1992     }
1993 }
1994
1995 #[stable(feature = "rc_weak", since = "1.4.0")]
1996 impl<T: ?Sized + fmt::Debug> fmt::Debug for Weak<T> {
1997     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1998         write!(f, "(Weak)")
1999     }
2000 }
2001
2002 #[stable(feature = "downgraded_weak", since = "1.10.0")]
2003 impl<T> Default for Weak<T> {
2004     /// Constructs a new `Weak<T>`, allocating memory for `T` without initializing
2005     /// it. Calling [`upgrade`] on the return value always gives [`None`].
2006     ///
2007     /// [`None`]: ../../std/option/enum.Option.html
2008     /// [`upgrade`]: ../../std/rc/struct.Weak.html#method.upgrade
2009     ///
2010     /// # Examples
2011     ///
2012     /// ```
2013     /// use std::rc::Weak;
2014     ///
2015     /// let empty: Weak<i64> = Default::default();
2016     /// assert!(empty.upgrade().is_none());
2017     /// ```
2018     fn default() -> Weak<T> {
2019         Weak::new()
2020     }
2021 }
2022
2023 // NOTE: We checked_add here to deal with mem::forget safely. In particular
2024 // if you mem::forget Rcs (or Weaks), the ref-count can overflow, and then
2025 // you can free the allocation while outstanding Rcs (or Weaks) exist.
2026 // We abort because this is such a degenerate scenario that we don't care about
2027 // what happens -- no real program should ever experience this.
2028 //
2029 // This should have negligible overhead since you don't actually need to
2030 // clone these much in Rust thanks to ownership and move-semantics.
2031
2032 #[doc(hidden)]
2033 trait RcBoxPtr<T: ?Sized> {
2034     fn inner(&self) -> &RcBox<T>;
2035
2036     #[inline]
2037     fn strong(&self) -> usize {
2038         self.inner().strong.get()
2039     }
2040
2041     #[inline]
2042     fn inc_strong(&self) {
2043         let strong = self.strong();
2044
2045         // We want to abort on overflow instead of dropping the value.
2046         // The reference count will never be zero when this is called;
2047         // nevertheless, we insert an abort here to hint LLVM at
2048         // an otherwise missed optimization.
2049         if strong == 0 || strong == usize::MAX {
2050             abort();
2051         }
2052         self.inner().strong.set(strong + 1);
2053     }
2054
2055     #[inline]
2056     fn dec_strong(&self) {
2057         self.inner().strong.set(self.strong() - 1);
2058     }
2059
2060     #[inline]
2061     fn weak(&self) -> usize {
2062         self.inner().weak.get()
2063     }
2064
2065     #[inline]
2066     fn inc_weak(&self) {
2067         let weak = self.weak();
2068
2069         // We want to abort on overflow instead of dropping the value.
2070         // The reference count will never be zero when this is called;
2071         // nevertheless, we insert an abort here to hint LLVM at
2072         // an otherwise missed optimization.
2073         if weak == 0 || weak == usize::MAX {
2074             abort();
2075         }
2076         self.inner().weak.set(weak + 1);
2077     }
2078
2079     #[inline]
2080     fn dec_weak(&self) {
2081         self.inner().weak.set(self.weak() - 1);
2082     }
2083 }
2084
2085 impl<T: ?Sized> RcBoxPtr<T> for Rc<T> {
2086     #[inline(always)]
2087     fn inner(&self) -> &RcBox<T> {
2088         unsafe { self.ptr.as_ref() }
2089     }
2090 }
2091
2092 impl<T: ?Sized> RcBoxPtr<T> for RcBox<T> {
2093     #[inline(always)]
2094     fn inner(&self) -> &RcBox<T> {
2095         self
2096     }
2097 }
2098
2099 #[stable(feature = "rust1", since = "1.0.0")]
2100 impl<T: ?Sized> borrow::Borrow<T> for Rc<T> {
2101     fn borrow(&self) -> &T {
2102         &**self
2103     }
2104 }
2105
2106 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
2107 impl<T: ?Sized> AsRef<T> for Rc<T> {
2108     fn as_ref(&self) -> &T {
2109         &**self
2110     }
2111 }
2112
2113 #[stable(feature = "pin", since = "1.33.0")]
2114 impl<T: ?Sized> Unpin for Rc<T> {}
2115
2116 /// Get the offset within an `ArcInner` for
2117 /// a payload of type described by a pointer.
2118 ///
2119 /// # Safety
2120 ///
2121 /// This has the same safety requirements as `align_of_val_raw`. In effect:
2122 ///
2123 /// - This function is safe for any argument if `T` is sized, and
2124 /// - if `T` is unsized, the pointer must have appropriate pointer metadata
2125 ///   aquired from the real instance that you are getting this offset for.
2126 unsafe fn data_offset<T: ?Sized>(ptr: *const T) -> isize {
2127     // Align the unsized value to the end of the `RcBox`.
2128     // Because it is ?Sized, it will always be the last field in memory.
2129     // Note: This is a detail of the current implementation of the compiler,
2130     // and is not a guaranteed language detail. Do not rely on it outside of std.
2131     unsafe { data_offset_align(align_of_val_raw(ptr)) }
2132 }
2133
2134 #[inline]
2135 fn data_offset_align(align: usize) -> isize {
2136     let layout = Layout::new::<RcBox<()>>();
2137     (layout.size() + layout.padding_needed_for(align)) as isize
2138 }