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