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