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