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