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