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