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