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