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