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