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