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