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