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