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