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