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