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