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