]> git.lizzy.rs Git - rust.git/blob - src/liballoc/rc.rs
aa7b96139fa20a734b453ecbd52a96faf0c36cca
[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::{Unsize, PhantomData};
256 use core::mem::{self, align_of_val, forget, size_of_val, uninitialized};
257 use core::ops::Deref;
258 use core::ops::CoerceUnsized;
259 use core::ptr::{self, NonNull};
260 use core::convert::From;
261
262 use heap::{Heap, Alloc, Layout, box_free};
263 use string::String;
264 use vec::Vec;
265
266 struct RcBox<T: ?Sized> {
267     strong: Cell<usize>,
268     weak: Cell<usize>,
269     value: T,
270 }
271
272 /// A single-threaded reference-counting pointer. 'Rc' stands for 'Reference
273 /// Counted'.
274 ///
275 /// See the [module-level documentation](./index.html) for more details.
276 ///
277 /// The inherent methods of `Rc` are all associated functions, which means
278 /// that you have to call them as e.g. [`Rc::get_mut(&mut value)`][get_mut] instead of
279 /// `value.get_mut()`. This avoids conflicts with methods of the inner
280 /// type `T`.
281 ///
282 /// [get_mut]: #method.get_mut
283 #[stable(feature = "rust1", since = "1.0.0")]
284 pub struct Rc<T: ?Sized> {
285     ptr: NonNull<RcBox<T>>,
286     phantom: PhantomData<T>,
287 }
288
289 #[stable(feature = "rust1", since = "1.0.0")]
290 impl<T: ?Sized> !marker::Send for Rc<T> {}
291 #[stable(feature = "rust1", since = "1.0.0")]
292 impl<T: ?Sized> !marker::Sync for Rc<T> {}
293
294 #[unstable(feature = "coerce_unsized", issue = "27732")]
295 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Rc<U>> for Rc<T> {}
296
297 impl<T> Rc<T> {
298     /// Constructs a new `Rc<T>`.
299     ///
300     /// # Examples
301     ///
302     /// ```
303     /// use std::rc::Rc;
304     ///
305     /// let five = Rc::new(5);
306     /// ```
307     #[stable(feature = "rust1", since = "1.0.0")]
308     pub fn new(value: T) -> Rc<T> {
309         Rc {
310             // there is an implicit weak pointer owned by all the strong
311             // pointers, which ensures that the weak destructor never frees
312             // the allocation while the strong destructor is running, even
313             // if the weak pointer is stored inside the strong one.
314             ptr: NonNull::from(Box::into_unique(box RcBox {
315                 strong: Cell::new(1),
316                 weak: Cell::new(1),
317                 value,
318             })),
319             phantom: PhantomData,
320         }
321     }
322
323     /// Returns the contained value, if the `Rc` has exactly one strong reference.
324     ///
325     /// Otherwise, an [`Err`][result] is returned with the same `Rc` that was
326     /// passed in.
327     ///
328     /// This will succeed even if there are outstanding weak references.
329     ///
330     /// [result]: ../../std/result/enum.Result.html
331     ///
332     /// # Examples
333     ///
334     /// ```
335     /// use std::rc::Rc;
336     ///
337     /// let x = Rc::new(3);
338     /// assert_eq!(Rc::try_unwrap(x), Ok(3));
339     ///
340     /// let x = Rc::new(4);
341     /// let _y = Rc::clone(&x);
342     /// assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4);
343     /// ```
344     #[inline]
345     #[stable(feature = "rc_unique", since = "1.4.0")]
346     pub fn try_unwrap(this: Self) -> Result<T, Self> {
347         if Rc::strong_count(&this) == 1 {
348             unsafe {
349                 let val = ptr::read(&*this); // copy the contained object
350
351                 // Indicate to Weaks that they can't be promoted by decrementing
352                 // the strong count, and then remove the implicit "strong weak"
353                 // pointer while also handling drop logic by just crafting a
354                 // fake Weak.
355                 this.dec_strong();
356                 let _weak = Weak { ptr: this.ptr };
357                 forget(this);
358                 Ok(val)
359             }
360         } else {
361             Err(this)
362         }
363     }
364 }
365
366 impl<T: ?Sized> Rc<T> {
367     /// Consumes the `Rc`, returning the wrapped pointer.
368     ///
369     /// To avoid a memory leak the pointer must be converted back to an `Rc` using
370     /// [`Rc::from_raw`][from_raw].
371     ///
372     /// [from_raw]: struct.Rc.html#method.from_raw
373     ///
374     /// # Examples
375     ///
376     /// ```
377     /// use std::rc::Rc;
378     ///
379     /// let x = Rc::new(10);
380     /// let x_ptr = Rc::into_raw(x);
381     /// assert_eq!(unsafe { *x_ptr }, 10);
382     /// ```
383     #[stable(feature = "rc_raw", since = "1.17.0")]
384     pub fn into_raw(this: Self) -> *const T {
385         let ptr: *const T = &*this;
386         mem::forget(this);
387         ptr
388     }
389
390     /// Constructs an `Rc` from a raw pointer.
391     ///
392     /// The raw pointer must have been previously returned by a call to a
393     /// [`Rc::into_raw`][into_raw].
394     ///
395     /// This function is unsafe because improper use may lead to memory problems. For example, a
396     /// double-free may occur if the function is called twice on the same raw pointer.
397     ///
398     /// [into_raw]: struct.Rc.html#method.into_raw
399     ///
400     /// # Examples
401     ///
402     /// ```
403     /// use std::rc::Rc;
404     ///
405     /// let x = Rc::new(10);
406     /// let x_ptr = Rc::into_raw(x);
407     ///
408     /// unsafe {
409     ///     // Convert back to an `Rc` to prevent leak.
410     ///     let x = Rc::from_raw(x_ptr);
411     ///     assert_eq!(*x, 10);
412     ///
413     ///     // Further calls to `Rc::from_raw(x_ptr)` would be memory unsafe.
414     /// }
415     ///
416     /// // The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling!
417     /// ```
418     #[stable(feature = "rc_raw", since = "1.17.0")]
419     pub unsafe fn from_raw(ptr: *const T) -> Self {
420         // Align the unsized value to the end of the RcBox.
421         // Because it is ?Sized, it will always be the last field in memory.
422         let align = align_of_val(&*ptr);
423         let layout = Layout::new::<RcBox<()>>();
424         let offset = (layout.size() + layout.padding_needed_for(align)) as isize;
425
426         // Reverse the offset to find the original RcBox.
427         let fake_ptr = ptr as *mut RcBox<T>;
428         let rc_ptr = set_data_ptr(fake_ptr, (ptr as *mut u8).offset(-offset));
429
430         Rc {
431             ptr: NonNull::new_unchecked(rc_ptr),
432             phantom: PhantomData,
433         }
434     }
435
436     /// Creates a new [`Weak`][weak] pointer to this value.
437     ///
438     /// [weak]: struct.Weak.html
439     ///
440     /// # Examples
441     ///
442     /// ```
443     /// use std::rc::Rc;
444     ///
445     /// let five = Rc::new(5);
446     ///
447     /// let weak_five = Rc::downgrade(&five);
448     /// ```
449     #[stable(feature = "rc_weak", since = "1.4.0")]
450     pub fn downgrade(this: &Self) -> Weak<T> {
451         this.inc_weak();
452         Weak { ptr: this.ptr }
453     }
454
455     /// Gets the number of [`Weak`][weak] pointers to this value.
456     ///
457     /// [weak]: struct.Weak.html
458     ///
459     /// # Examples
460     ///
461     /// ```
462     /// use std::rc::Rc;
463     ///
464     /// let five = Rc::new(5);
465     /// let _weak_five = Rc::downgrade(&five);
466     ///
467     /// assert_eq!(1, Rc::weak_count(&five));
468     /// ```
469     #[inline]
470     #[stable(feature = "rc_counts", since = "1.15.0")]
471     pub fn weak_count(this: &Self) -> usize {
472         this.weak() - 1
473     }
474
475     /// Gets the number of strong (`Rc`) pointers to this value.
476     ///
477     /// # Examples
478     ///
479     /// ```
480     /// use std::rc::Rc;
481     ///
482     /// let five = Rc::new(5);
483     /// let _also_five = Rc::clone(&five);
484     ///
485     /// assert_eq!(2, Rc::strong_count(&five));
486     /// ```
487     #[inline]
488     #[stable(feature = "rc_counts", since = "1.15.0")]
489     pub fn strong_count(this: &Self) -> usize {
490         this.strong()
491     }
492
493     /// Returns true if there are no other `Rc` or [`Weak`][weak] pointers to
494     /// this inner value.
495     ///
496     /// [weak]: struct.Weak.html
497     #[inline]
498     fn is_unique(this: &Self) -> bool {
499         Rc::weak_count(this) == 0 && Rc::strong_count(this) == 1
500     }
501
502     /// Returns a mutable reference to the inner value, if there are
503     /// no other `Rc` or [`Weak`][weak] pointers to the same value.
504     ///
505     /// Returns [`None`] otherwise, because it is not safe to
506     /// mutate a shared value.
507     ///
508     /// See also [`make_mut`][make_mut], which will [`clone`][clone]
509     /// the inner value when it's shared.
510     ///
511     /// [weak]: struct.Weak.html
512     /// [`None`]: ../../std/option/enum.Option.html#variant.None
513     /// [make_mut]: struct.Rc.html#method.make_mut
514     /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
515     ///
516     /// # Examples
517     ///
518     /// ```
519     /// use std::rc::Rc;
520     ///
521     /// let mut x = Rc::new(3);
522     /// *Rc::get_mut(&mut x).unwrap() = 4;
523     /// assert_eq!(*x, 4);
524     ///
525     /// let _y = Rc::clone(&x);
526     /// assert!(Rc::get_mut(&mut x).is_none());
527     /// ```
528     #[inline]
529     #[stable(feature = "rc_unique", since = "1.4.0")]
530     pub fn get_mut(this: &mut Self) -> Option<&mut T> {
531         if Rc::is_unique(this) {
532             unsafe {
533                 Some(&mut this.ptr.as_mut().value)
534             }
535         } else {
536             None
537         }
538     }
539
540     #[inline]
541     #[stable(feature = "ptr_eq", since = "1.17.0")]
542     /// Returns true if the two `Rc`s point to the same value (not
543     /// just values that compare as equal).
544     ///
545     /// # Examples
546     ///
547     /// ```
548     /// use std::rc::Rc;
549     ///
550     /// let five = Rc::new(5);
551     /// let same_five = Rc::clone(&five);
552     /// let other_five = Rc::new(5);
553     ///
554     /// assert!(Rc::ptr_eq(&five, &same_five));
555     /// assert!(!Rc::ptr_eq(&five, &other_five));
556     /// ```
557     pub fn ptr_eq(this: &Self, other: &Self) -> bool {
558         this.ptr.as_ptr() == other.ptr.as_ptr()
559     }
560 }
561
562 impl<T: Clone> Rc<T> {
563     /// Makes a mutable reference into the given `Rc`.
564     ///
565     /// If there are other `Rc` or [`Weak`][weak] pointers to the same value,
566     /// then `make_mut` will invoke [`clone`][clone] on the inner value to
567     /// ensure unique ownership. This is also referred to as clone-on-write.
568     ///
569     /// See also [`get_mut`][get_mut], which will fail rather than cloning.
570     ///
571     /// [weak]: struct.Weak.html
572     /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
573     /// [get_mut]: struct.Rc.html#method.get_mut
574     ///
575     /// # Examples
576     ///
577     /// ```
578     /// use std::rc::Rc;
579     ///
580     /// let mut data = Rc::new(5);
581     ///
582     /// *Rc::make_mut(&mut data) += 1;        // Won't clone anything
583     /// let mut other_data = Rc::clone(&data);    // Won't clone inner data
584     /// *Rc::make_mut(&mut data) += 1;        // Clones inner data
585     /// *Rc::make_mut(&mut data) += 1;        // Won't clone anything
586     /// *Rc::make_mut(&mut other_data) *= 2;  // Won't clone anything
587     ///
588     /// // Now `data` and `other_data` point to different values.
589     /// assert_eq!(*data, 8);
590     /// assert_eq!(*other_data, 12);
591     /// ```
592     #[inline]
593     #[stable(feature = "rc_unique", since = "1.4.0")]
594     pub fn make_mut(this: &mut Self) -> &mut T {
595         if Rc::strong_count(this) != 1 {
596             // Gotta clone the data, there are other Rcs
597             *this = Rc::new((**this).clone())
598         } else if Rc::weak_count(this) != 0 {
599             // Can just steal the data, all that's left is Weaks
600             unsafe {
601                 let mut swap = Rc::new(ptr::read(&this.ptr.as_ref().value));
602                 mem::swap(this, &mut swap);
603                 swap.dec_strong();
604                 // Remove implicit strong-weak ref (no need to craft a fake
605                 // Weak here -- we know other Weaks can clean up for us)
606                 swap.dec_weak();
607                 forget(swap);
608             }
609         }
610         // This unsafety is ok because we're guaranteed that the pointer
611         // returned is the *only* pointer that will ever be returned to T. Our
612         // reference count is guaranteed to be 1 at this point, and we required
613         // the `Rc<T>` itself to be `mut`, so we're returning the only possible
614         // reference to the inner value.
615         unsafe {
616             &mut this.ptr.as_mut().value
617         }
618     }
619 }
620
621 impl Rc<Any> {
622     #[inline]
623     #[unstable(feature = "rc_downcast", issue = "44608")]
624     /// Attempt to downcast the `Rc<Any>` to a concrete type.
625     ///
626     /// # Examples
627     ///
628     /// ```
629     /// #![feature(rc_downcast)]
630     /// use std::any::Any;
631     /// use std::rc::Rc;
632     ///
633     /// fn print_if_string(value: Rc<Any>) {
634     ///     if let Ok(string) = value.downcast::<String>() {
635     ///         println!("String ({}): {}", string.len(), string);
636     ///     }
637     /// }
638     ///
639     /// fn main() {
640     ///     let my_string = "Hello World".to_string();
641     ///     print_if_string(Rc::new(my_string));
642     ///     print_if_string(Rc::new(0i8));
643     /// }
644     /// ```
645     pub fn downcast<T: Any>(self) -> Result<Rc<T>, Rc<Any>> {
646         if (*self).is::<T>() {
647             // avoid the pointer arithmetic in from_raw
648             unsafe {
649                 let raw: *const RcBox<Any> = self.ptr.as_ptr();
650                 forget(self);
651                 Ok(Rc {
652                     ptr: NonNull::new_unchecked(raw as *const RcBox<T> as *mut _),
653                     phantom: PhantomData,
654                 })
655             }
656         } else {
657             Err(self)
658         }
659     }
660 }
661
662 impl<T: ?Sized> Rc<T> {
663     // Allocates an `RcBox<T>` with sufficient space for an unsized value
664     unsafe fn allocate_for_ptr(ptr: *const T) -> *mut RcBox<T> {
665         // Create a fake RcBox to find allocation size and alignment
666         let fake_ptr = ptr as *mut RcBox<T>;
667
668         let layout = Layout::for_value(&*fake_ptr);
669
670         let mem = Heap.alloc(layout)
671             .unwrap_or_else(|e| Heap.oom(e));
672
673         // Initialize the real RcBox
674         let inner = set_data_ptr(ptr as *mut T, mem) as *mut RcBox<T>;
675
676         ptr::write(&mut (*inner).strong, Cell::new(1));
677         ptr::write(&mut (*inner).weak, Cell::new(1));
678
679         inner
680     }
681
682     fn from_box(v: Box<T>) -> Rc<T> {
683         unsafe {
684             let bptr = Box::into_raw(v);
685
686             let value_size = size_of_val(&*bptr);
687             let ptr = Self::allocate_for_ptr(bptr);
688
689             // Copy value as bytes
690             ptr::copy_nonoverlapping(
691                 bptr as *const T as *const u8,
692                 &mut (*ptr).value as *mut _ as *mut u8,
693                 value_size);
694
695             // Free the allocation without dropping its contents
696             box_free(bptr);
697
698             Rc { ptr: NonNull::new_unchecked(ptr), phantom: PhantomData }
699         }
700     }
701 }
702
703 // Sets the data pointer of a `?Sized` raw pointer.
704 //
705 // For a slice/trait object, this sets the `data` field and leaves the rest
706 // unchanged. For a sized raw pointer, this simply sets the pointer.
707 unsafe fn set_data_ptr<T: ?Sized, U>(mut ptr: *mut T, data: *mut U) -> *mut T {
708     ptr::write(&mut ptr as *mut _ as *mut *mut u8, data as *mut u8);
709     ptr
710 }
711
712 impl<T> Rc<[T]> {
713     // Copy elements from slice into newly allocated Rc<[T]>
714     //
715     // Unsafe because the caller must either take ownership or bind `T: Copy`
716     unsafe fn copy_from_slice(v: &[T]) -> Rc<[T]> {
717         let v_ptr = v as *const [T];
718         let ptr = Self::allocate_for_ptr(v_ptr);
719
720         ptr::copy_nonoverlapping(
721             v.as_ptr(),
722             &mut (*ptr).value as *mut [T] as *mut T,
723             v.len());
724
725         Rc { ptr: NonNull::new_unchecked(ptr), phantom: PhantomData }
726     }
727 }
728
729 trait RcFromSlice<T> {
730     fn from_slice(slice: &[T]) -> Self;
731 }
732
733 impl<T: Clone> RcFromSlice<T> for Rc<[T]> {
734     #[inline]
735     default fn from_slice(v: &[T]) -> Self {
736         // Panic guard while cloning T elements.
737         // In the event of a panic, elements that have been written
738         // into the new RcBox will be dropped, then the memory freed.
739         struct Guard<T> {
740             mem: *mut u8,
741             elems: *mut T,
742             layout: Layout,
743             n_elems: usize,
744         }
745
746         impl<T> Drop for Guard<T> {
747             fn drop(&mut self) {
748                 use core::slice::from_raw_parts_mut;
749
750                 unsafe {
751                     let slice = from_raw_parts_mut(self.elems, self.n_elems);
752                     ptr::drop_in_place(slice);
753
754                     Heap.dealloc(self.mem, self.layout.clone());
755                 }
756             }
757         }
758
759         unsafe {
760             let v_ptr = v as *const [T];
761             let ptr = Self::allocate_for_ptr(v_ptr);
762
763             let mem = ptr as *mut _ as *mut u8;
764             let layout = Layout::for_value(&*ptr);
765
766             // Pointer to first element
767             let elems = &mut (*ptr).value as *mut [T] as *mut T;
768
769             let mut guard = Guard{
770                 mem: mem,
771                 elems: elems,
772                 layout: layout,
773                 n_elems: 0,
774             };
775
776             for (i, item) in v.iter().enumerate() {
777                 ptr::write(elems.offset(i as isize), item.clone());
778                 guard.n_elems += 1;
779             }
780
781             // All clear. Forget the guard so it doesn't free the new RcBox.
782             forget(guard);
783
784             Rc { ptr: NonNull::new_unchecked(ptr), phantom: PhantomData }
785         }
786     }
787 }
788
789 impl<T: Copy> RcFromSlice<T> for Rc<[T]> {
790     #[inline]
791     fn from_slice(v: &[T]) -> Self {
792         unsafe { Rc::copy_from_slice(v) }
793     }
794 }
795
796 #[stable(feature = "rust1", since = "1.0.0")]
797 impl<T: ?Sized> Deref for Rc<T> {
798     type Target = T;
799
800     #[inline(always)]
801     fn deref(&self) -> &T {
802         &self.inner().value
803     }
804 }
805
806 #[stable(feature = "rust1", since = "1.0.0")]
807 unsafe impl<#[may_dangle] T: ?Sized> Drop for Rc<T> {
808     /// Drops the `Rc`.
809     ///
810     /// This will decrement the strong reference count. If the strong reference
811     /// count reaches zero then the only other references (if any) are
812     /// [`Weak`][weak], so we `drop` the inner value.
813     ///
814     /// [weak]: struct.Weak.html
815     ///
816     /// # Examples
817     ///
818     /// ```
819     /// use std::rc::Rc;
820     ///
821     /// struct Foo;
822     ///
823     /// impl Drop for Foo {
824     ///     fn drop(&mut self) {
825     ///         println!("dropped!");
826     ///     }
827     /// }
828     ///
829     /// let foo  = Rc::new(Foo);
830     /// let foo2 = Rc::clone(&foo);
831     ///
832     /// drop(foo);    // Doesn't print anything
833     /// drop(foo2);   // Prints "dropped!"
834     /// ```
835     fn drop(&mut self) {
836         unsafe {
837             let ptr = self.ptr.as_ptr();
838
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                     Heap.dealloc(ptr as *mut u8, Layout::for_value(&*ptr));
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     /// 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     ptr: NonNull<RcBox<T>>,
1164 }
1165
1166 #[stable(feature = "rc_weak", since = "1.4.0")]
1167 impl<T: ?Sized> !marker::Send for Weak<T> {}
1168 #[stable(feature = "rc_weak", since = "1.4.0")]
1169 impl<T: ?Sized> !marker::Sync for Weak<T> {}
1170
1171 #[unstable(feature = "coerce_unsized", issue = "27732")]
1172 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {}
1173
1174 impl<T> Weak<T> {
1175     /// Constructs a new `Weak<T>`, allocating memory for `T` without initializing
1176     /// it. Calling [`upgrade`] on the return value always gives [`None`].
1177     ///
1178     /// [`upgrade`]: struct.Weak.html#method.upgrade
1179     /// [`None`]: ../../std/option/enum.Option.html
1180     ///
1181     /// # Examples
1182     ///
1183     /// ```
1184     /// use std::rc::Weak;
1185     ///
1186     /// let empty: Weak<i64> = Weak::new();
1187     /// assert!(empty.upgrade().is_none());
1188     /// ```
1189     #[stable(feature = "downgraded_weak", since = "1.10.0")]
1190     pub fn new() -> Weak<T> {
1191         unsafe {
1192             Weak {
1193                 ptr: NonNull::from(Box::into_unique(box RcBox {
1194                     strong: Cell::new(0),
1195                     weak: Cell::new(1),
1196                     value: uninitialized(),
1197                 })),
1198             }
1199         }
1200     }
1201 }
1202
1203 impl<T: ?Sized> Weak<T> {
1204     /// Attempts to upgrade the `Weak` pointer to an [`Rc`], extending
1205     /// the lifetime of the value if successful.
1206     ///
1207     /// Returns [`None`] if the value has since been dropped.
1208     ///
1209     /// [`Rc`]: struct.Rc.html
1210     /// [`None`]: ../../std/option/enum.Option.html
1211     ///
1212     /// # Examples
1213     ///
1214     /// ```
1215     /// use std::rc::Rc;
1216     ///
1217     /// let five = Rc::new(5);
1218     ///
1219     /// let weak_five = Rc::downgrade(&five);
1220     ///
1221     /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
1222     /// assert!(strong_five.is_some());
1223     ///
1224     /// // Destroy all strong pointers.
1225     /// drop(strong_five);
1226     /// drop(five);
1227     ///
1228     /// assert!(weak_five.upgrade().is_none());
1229     /// ```
1230     #[stable(feature = "rc_weak", since = "1.4.0")]
1231     pub fn upgrade(&self) -> Option<Rc<T>> {
1232         if self.strong() == 0 {
1233             None
1234         } else {
1235             self.inc_strong();
1236             Some(Rc { ptr: self.ptr, phantom: PhantomData })
1237         }
1238     }
1239 }
1240
1241 #[stable(feature = "rc_weak", since = "1.4.0")]
1242 impl<T: ?Sized> Drop for Weak<T> {
1243     /// Drops the `Weak` pointer.
1244     ///
1245     /// # Examples
1246     ///
1247     /// ```
1248     /// use std::rc::{Rc, Weak};
1249     ///
1250     /// struct Foo;
1251     ///
1252     /// impl Drop for Foo {
1253     ///     fn drop(&mut self) {
1254     ///         println!("dropped!");
1255     ///     }
1256     /// }
1257     ///
1258     /// let foo = Rc::new(Foo);
1259     /// let weak_foo = Rc::downgrade(&foo);
1260     /// let other_weak_foo = Weak::clone(&weak_foo);
1261     ///
1262     /// drop(weak_foo);   // Doesn't print anything
1263     /// drop(foo);        // Prints "dropped!"
1264     ///
1265     /// assert!(other_weak_foo.upgrade().is_none());
1266     /// ```
1267     fn drop(&mut self) {
1268         unsafe {
1269             let ptr = self.ptr.as_ptr();
1270
1271             self.dec_weak();
1272             // the weak count starts at 1, and will only go to zero if all
1273             // the strong pointers have disappeared.
1274             if self.weak() == 0 {
1275                 Heap.dealloc(ptr as *mut u8, Layout::for_value(&*ptr));
1276             }
1277         }
1278     }
1279 }
1280
1281 #[stable(feature = "rc_weak", since = "1.4.0")]
1282 impl<T: ?Sized> Clone for Weak<T> {
1283     /// Makes a clone of the `Weak` pointer that points to the same value.
1284     ///
1285     /// # Examples
1286     ///
1287     /// ```
1288     /// use std::rc::{Rc, Weak};
1289     ///
1290     /// let weak_five = Rc::downgrade(&Rc::new(5));
1291     ///
1292     /// Weak::clone(&weak_five);
1293     /// ```
1294     #[inline]
1295     fn clone(&self) -> Weak<T> {
1296         self.inc_weak();
1297         Weak { ptr: self.ptr }
1298     }
1299 }
1300
1301 #[stable(feature = "rc_weak", since = "1.4.0")]
1302 impl<T: ?Sized + fmt::Debug> fmt::Debug for Weak<T> {
1303     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1304         write!(f, "(Weak)")
1305     }
1306 }
1307
1308 #[stable(feature = "downgraded_weak", since = "1.10.0")]
1309 impl<T> Default for Weak<T> {
1310     /// Constructs a new `Weak<T>`, allocating memory for `T` without initializing
1311     /// it. Calling [`upgrade`] on the return value always gives [`None`].
1312     ///
1313     /// [`upgrade`]: struct.Weak.html#method.upgrade
1314     /// [`None`]: ../../std/option/enum.Option.html
1315     ///
1316     /// # Examples
1317     ///
1318     /// ```
1319     /// use std::rc::Weak;
1320     ///
1321     /// let empty: Weak<i64> = Default::default();
1322     /// assert!(empty.upgrade().is_none());
1323     /// ```
1324     fn default() -> Weak<T> {
1325         Weak::new()
1326     }
1327 }
1328
1329 // NOTE: We checked_add here to deal with mem::forget safety. In particular
1330 // if you mem::forget Rcs (or Weaks), the ref-count can overflow, and then
1331 // you can free the allocation while outstanding Rcs (or Weaks) exist.
1332 // We abort because this is such a degenerate scenario that we don't care about
1333 // what happens -- no real program should ever experience this.
1334 //
1335 // This should have negligible overhead since you don't actually need to
1336 // clone these much in Rust thanks to ownership and move-semantics.
1337
1338 #[doc(hidden)]
1339 trait RcBoxPtr<T: ?Sized> {
1340     fn inner(&self) -> &RcBox<T>;
1341
1342     #[inline]
1343     fn strong(&self) -> usize {
1344         self.inner().strong.get()
1345     }
1346
1347     #[inline]
1348     fn inc_strong(&self) {
1349         self.inner().strong.set(self.strong().checked_add(1).unwrap_or_else(|| unsafe { abort() }));
1350     }
1351
1352     #[inline]
1353     fn dec_strong(&self) {
1354         self.inner().strong.set(self.strong() - 1);
1355     }
1356
1357     #[inline]
1358     fn weak(&self) -> usize {
1359         self.inner().weak.get()
1360     }
1361
1362     #[inline]
1363     fn inc_weak(&self) {
1364         self.inner().weak.set(self.weak().checked_add(1).unwrap_or_else(|| unsafe { abort() }));
1365     }
1366
1367     #[inline]
1368     fn dec_weak(&self) {
1369         self.inner().weak.set(self.weak() - 1);
1370     }
1371 }
1372
1373 impl<T: ?Sized> RcBoxPtr<T> for Rc<T> {
1374     #[inline(always)]
1375     fn inner(&self) -> &RcBox<T> {
1376         unsafe {
1377             self.ptr.as_ref()
1378         }
1379     }
1380 }
1381
1382 impl<T: ?Sized> RcBoxPtr<T> for Weak<T> {
1383     #[inline(always)]
1384     fn inner(&self) -> &RcBox<T> {
1385         unsafe {
1386             self.ptr.as_ref()
1387         }
1388     }
1389 }
1390
1391 #[cfg(test)]
1392 mod tests {
1393     use super::{Rc, Weak};
1394     use std::boxed::Box;
1395     use std::cell::RefCell;
1396     use std::option::Option;
1397     use std::option::Option::{None, Some};
1398     use std::result::Result::{Err, Ok};
1399     use std::mem::drop;
1400     use std::clone::Clone;
1401     use std::convert::From;
1402
1403     #[test]
1404     fn test_clone() {
1405         let x = Rc::new(RefCell::new(5));
1406         let y = x.clone();
1407         *x.borrow_mut() = 20;
1408         assert_eq!(*y.borrow(), 20);
1409     }
1410
1411     #[test]
1412     fn test_simple() {
1413         let x = Rc::new(5);
1414         assert_eq!(*x, 5);
1415     }
1416
1417     #[test]
1418     fn test_simple_clone() {
1419         let x = Rc::new(5);
1420         let y = x.clone();
1421         assert_eq!(*x, 5);
1422         assert_eq!(*y, 5);
1423     }
1424
1425     #[test]
1426     fn test_destructor() {
1427         let x: Rc<Box<_>> = Rc::new(box 5);
1428         assert_eq!(**x, 5);
1429     }
1430
1431     #[test]
1432     fn test_live() {
1433         let x = Rc::new(5);
1434         let y = Rc::downgrade(&x);
1435         assert!(y.upgrade().is_some());
1436     }
1437
1438     #[test]
1439     fn test_dead() {
1440         let x = Rc::new(5);
1441         let y = Rc::downgrade(&x);
1442         drop(x);
1443         assert!(y.upgrade().is_none());
1444     }
1445
1446     #[test]
1447     fn weak_self_cyclic() {
1448         struct Cycle {
1449             x: RefCell<Option<Weak<Cycle>>>,
1450         }
1451
1452         let a = Rc::new(Cycle { x: RefCell::new(None) });
1453         let b = Rc::downgrade(&a.clone());
1454         *a.x.borrow_mut() = Some(b);
1455
1456         // hopefully we don't double-free (or leak)...
1457     }
1458
1459     #[test]
1460     fn is_unique() {
1461         let x = Rc::new(3);
1462         assert!(Rc::is_unique(&x));
1463         let y = x.clone();
1464         assert!(!Rc::is_unique(&x));
1465         drop(y);
1466         assert!(Rc::is_unique(&x));
1467         let w = Rc::downgrade(&x);
1468         assert!(!Rc::is_unique(&x));
1469         drop(w);
1470         assert!(Rc::is_unique(&x));
1471     }
1472
1473     #[test]
1474     fn test_strong_count() {
1475         let a = Rc::new(0);
1476         assert!(Rc::strong_count(&a) == 1);
1477         let w = Rc::downgrade(&a);
1478         assert!(Rc::strong_count(&a) == 1);
1479         let b = w.upgrade().expect("upgrade of live rc failed");
1480         assert!(Rc::strong_count(&b) == 2);
1481         assert!(Rc::strong_count(&a) == 2);
1482         drop(w);
1483         drop(a);
1484         assert!(Rc::strong_count(&b) == 1);
1485         let c = b.clone();
1486         assert!(Rc::strong_count(&b) == 2);
1487         assert!(Rc::strong_count(&c) == 2);
1488     }
1489
1490     #[test]
1491     fn test_weak_count() {
1492         let a = Rc::new(0);
1493         assert!(Rc::strong_count(&a) == 1);
1494         assert!(Rc::weak_count(&a) == 0);
1495         let w = Rc::downgrade(&a);
1496         assert!(Rc::strong_count(&a) == 1);
1497         assert!(Rc::weak_count(&a) == 1);
1498         drop(w);
1499         assert!(Rc::strong_count(&a) == 1);
1500         assert!(Rc::weak_count(&a) == 0);
1501         let c = a.clone();
1502         assert!(Rc::strong_count(&a) == 2);
1503         assert!(Rc::weak_count(&a) == 0);
1504         drop(c);
1505     }
1506
1507     #[test]
1508     fn try_unwrap() {
1509         let x = Rc::new(3);
1510         assert_eq!(Rc::try_unwrap(x), Ok(3));
1511         let x = Rc::new(4);
1512         let _y = x.clone();
1513         assert_eq!(Rc::try_unwrap(x), Err(Rc::new(4)));
1514         let x = Rc::new(5);
1515         let _w = Rc::downgrade(&x);
1516         assert_eq!(Rc::try_unwrap(x), Ok(5));
1517     }
1518
1519     #[test]
1520     fn into_from_raw() {
1521         let x = Rc::new(box "hello");
1522         let y = x.clone();
1523
1524         let x_ptr = Rc::into_raw(x);
1525         drop(y);
1526         unsafe {
1527             assert_eq!(**x_ptr, "hello");
1528
1529             let x = Rc::from_raw(x_ptr);
1530             assert_eq!(**x, "hello");
1531
1532             assert_eq!(Rc::try_unwrap(x).map(|x| *x), Ok("hello"));
1533         }
1534     }
1535
1536     #[test]
1537     fn test_into_from_raw_unsized() {
1538         use std::fmt::Display;
1539         use std::string::ToString;
1540
1541         let rc: Rc<str> = Rc::from("foo");
1542
1543         let ptr = Rc::into_raw(rc.clone());
1544         let rc2 = unsafe { Rc::from_raw(ptr) };
1545
1546         assert_eq!(unsafe { &*ptr }, "foo");
1547         assert_eq!(rc, rc2);
1548
1549         let rc: Rc<Display> = Rc::new(123);
1550
1551         let ptr = Rc::into_raw(rc.clone());
1552         let rc2 = unsafe { Rc::from_raw(ptr) };
1553
1554         assert_eq!(unsafe { &*ptr }.to_string(), "123");
1555         assert_eq!(rc2.to_string(), "123");
1556     }
1557
1558     #[test]
1559     fn get_mut() {
1560         let mut x = Rc::new(3);
1561         *Rc::get_mut(&mut x).unwrap() = 4;
1562         assert_eq!(*x, 4);
1563         let y = x.clone();
1564         assert!(Rc::get_mut(&mut x).is_none());
1565         drop(y);
1566         assert!(Rc::get_mut(&mut x).is_some());
1567         let _w = Rc::downgrade(&x);
1568         assert!(Rc::get_mut(&mut x).is_none());
1569     }
1570
1571     #[test]
1572     fn test_cowrc_clone_make_unique() {
1573         let mut cow0 = Rc::new(75);
1574         let mut cow1 = cow0.clone();
1575         let mut cow2 = cow1.clone();
1576
1577         assert!(75 == *Rc::make_mut(&mut cow0));
1578         assert!(75 == *Rc::make_mut(&mut cow1));
1579         assert!(75 == *Rc::make_mut(&mut cow2));
1580
1581         *Rc::make_mut(&mut cow0) += 1;
1582         *Rc::make_mut(&mut cow1) += 2;
1583         *Rc::make_mut(&mut cow2) += 3;
1584
1585         assert!(76 == *cow0);
1586         assert!(77 == *cow1);
1587         assert!(78 == *cow2);
1588
1589         // none should point to the same backing memory
1590         assert!(*cow0 != *cow1);
1591         assert!(*cow0 != *cow2);
1592         assert!(*cow1 != *cow2);
1593     }
1594
1595     #[test]
1596     fn test_cowrc_clone_unique2() {
1597         let mut cow0 = Rc::new(75);
1598         let cow1 = cow0.clone();
1599         let cow2 = cow1.clone();
1600
1601         assert!(75 == *cow0);
1602         assert!(75 == *cow1);
1603         assert!(75 == *cow2);
1604
1605         *Rc::make_mut(&mut cow0) += 1;
1606
1607         assert!(76 == *cow0);
1608         assert!(75 == *cow1);
1609         assert!(75 == *cow2);
1610
1611         // cow1 and cow2 should share the same contents
1612         // cow0 should have a unique reference
1613         assert!(*cow0 != *cow1);
1614         assert!(*cow0 != *cow2);
1615         assert!(*cow1 == *cow2);
1616     }
1617
1618     #[test]
1619     fn test_cowrc_clone_weak() {
1620         let mut cow0 = Rc::new(75);
1621         let cow1_weak = Rc::downgrade(&cow0);
1622
1623         assert!(75 == *cow0);
1624         assert!(75 == *cow1_weak.upgrade().unwrap());
1625
1626         *Rc::make_mut(&mut cow0) += 1;
1627
1628         assert!(76 == *cow0);
1629         assert!(cow1_weak.upgrade().is_none());
1630     }
1631
1632     #[test]
1633     fn test_show() {
1634         let foo = Rc::new(75);
1635         assert_eq!(format!("{:?}", foo), "75");
1636     }
1637
1638     #[test]
1639     fn test_unsized() {
1640         let foo: Rc<[i32]> = Rc::new([1, 2, 3]);
1641         assert_eq!(foo, foo.clone());
1642     }
1643
1644     #[test]
1645     fn test_from_owned() {
1646         let foo = 123;
1647         let foo_rc = Rc::from(foo);
1648         assert!(123 == *foo_rc);
1649     }
1650
1651     #[test]
1652     fn test_new_weak() {
1653         let foo: Weak<usize> = Weak::new();
1654         assert!(foo.upgrade().is_none());
1655     }
1656
1657     #[test]
1658     fn test_ptr_eq() {
1659         let five = Rc::new(5);
1660         let same_five = five.clone();
1661         let other_five = Rc::new(5);
1662
1663         assert!(Rc::ptr_eq(&five, &same_five));
1664         assert!(!Rc::ptr_eq(&five, &other_five));
1665     }
1666
1667     #[test]
1668     fn test_from_str() {
1669         let r: Rc<str> = Rc::from("foo");
1670
1671         assert_eq!(&r[..], "foo");
1672     }
1673
1674     #[test]
1675     fn test_copy_from_slice() {
1676         let s: &[u32] = &[1, 2, 3];
1677         let r: Rc<[u32]> = Rc::from(s);
1678
1679         assert_eq!(&r[..], [1, 2, 3]);
1680     }
1681
1682     #[test]
1683     fn test_clone_from_slice() {
1684         #[derive(Clone, Debug, Eq, PartialEq)]
1685         struct X(u32);
1686
1687         let s: &[X] = &[X(1), X(2), X(3)];
1688         let r: Rc<[X]> = Rc::from(s);
1689
1690         assert_eq!(&r[..], s);
1691     }
1692
1693     #[test]
1694     #[should_panic]
1695     fn test_clone_from_slice_panic() {
1696         use std::string::{String, ToString};
1697
1698         struct Fail(u32, String);
1699
1700         impl Clone for Fail {
1701             fn clone(&self) -> Fail {
1702                 if self.0 == 2 {
1703                     panic!();
1704                 }
1705                 Fail(self.0, self.1.clone())
1706             }
1707         }
1708
1709         let s: &[Fail] = &[
1710             Fail(0, "foo".to_string()),
1711             Fail(1, "bar".to_string()),
1712             Fail(2, "baz".to_string()),
1713         ];
1714
1715         // Should panic, but not cause memory corruption
1716         let _r: Rc<[Fail]> = Rc::from(s);
1717     }
1718
1719     #[test]
1720     fn test_from_box() {
1721         let b: Box<u32> = box 123;
1722         let r: Rc<u32> = Rc::from(b);
1723
1724         assert_eq!(*r, 123);
1725     }
1726
1727     #[test]
1728     fn test_from_box_str() {
1729         use std::string::String;
1730
1731         let s = String::from("foo").into_boxed_str();
1732         let r: Rc<str> = Rc::from(s);
1733
1734         assert_eq!(&r[..], "foo");
1735     }
1736
1737     #[test]
1738     fn test_from_box_slice() {
1739         let s = vec![1, 2, 3].into_boxed_slice();
1740         let r: Rc<[u32]> = Rc::from(s);
1741
1742         assert_eq!(&r[..], [1, 2, 3]);
1743     }
1744
1745     #[test]
1746     fn test_from_box_trait() {
1747         use std::fmt::Display;
1748         use std::string::ToString;
1749
1750         let b: Box<Display> = box 123;
1751         let r: Rc<Display> = Rc::from(b);
1752
1753         assert_eq!(r.to_string(), "123");
1754     }
1755
1756     #[test]
1757     fn test_from_box_trait_zero_sized() {
1758         use std::fmt::Debug;
1759
1760         let b: Box<Debug> = box ();
1761         let r: Rc<Debug> = Rc::from(b);
1762
1763         assert_eq!(format!("{:?}", r), "()");
1764     }
1765
1766     #[test]
1767     fn test_from_vec() {
1768         let v = vec![1, 2, 3];
1769         let r: Rc<[u32]> = Rc::from(v);
1770
1771         assert_eq!(&r[..], [1, 2, 3]);
1772     }
1773
1774     #[test]
1775     fn test_downcast() {
1776         use std::any::Any;
1777
1778         let r1: Rc<Any> = Rc::new(i32::max_value());
1779         let r2: Rc<Any> = Rc::new("abc");
1780
1781         assert!(r1.clone().downcast::<u32>().is_err());
1782
1783         let r1i32 = r1.downcast::<i32>();
1784         assert!(r1i32.is_ok());
1785         assert_eq!(r1i32.unwrap(), Rc::new(i32::max_value()));
1786
1787         assert!(r2.clone().downcast::<i32>().is_err());
1788
1789         let r2str = r2.downcast::<&'static str>();
1790         assert!(r2str.is_ok());
1791         assert_eq!(r2str.unwrap(), Rc::new("abc"));
1792     }
1793 }
1794
1795 #[stable(feature = "rust1", since = "1.0.0")]
1796 impl<T: ?Sized> borrow::Borrow<T> for Rc<T> {
1797     fn borrow(&self) -> &T {
1798         &**self
1799     }
1800 }
1801
1802 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1803 impl<T: ?Sized> AsRef<T> for Rc<T> {
1804     fn as_ref(&self) -> &T {
1805         &**self
1806     }
1807 }