]> git.lizzy.rs Git - rust.git/blob - src/liballoc/rc.rs
Add `{into,from}_raw` to Rc and Arc
[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.
14 //!
15 //! The type [`Rc<T>`][rc] provides shared ownership of a value of type `T`,
16 //! allocated in the heap. Invoking [`clone`][clone] on `Rc` produces a new
17 //! pointer to the same value in the heap. When the last `Rc` pointer to a
18 //! given value is destroyed, the pointed-to value is also destroyed.
19 //!
20 //! Shared references in Rust disallow mutation by default, and `Rc` is no
21 //! exception. If you need to mutate through an `Rc`, use [`Cell`][cell] or
22 //! [`RefCell`][refcell].
23 //!
24 //! `Rc` uses non-atomic reference counting. This means that overhead is very
25 //! low, but an `Rc` cannot be sent between threads, and consequently `Rc`
26 //! does not implement [`Send`][send]. As a result, the Rust compiler
27 //! will check *at compile time* that you are not sending `Rc`s between
28 //! threads. If you need multi-threaded, atomic reference counting, use
29 //! [`sync::Arc`][arc].
30 //!
31 //! The [`downgrade`][downgrade] method can be used to create a non-owning
32 //! [`Weak`][weak] pointer. A `Weak` pointer can be [`upgrade`][upgrade]d
33 //! to an `Rc`, but this will return [`None`][option] if the value has
34 //! already been dropped.
35 //!
36 //! A cycle between `Rc` pointers will never be deallocated. For this reason,
37 //! `Weak` is used to break cycles. For example, a tree could have strong
38 //! `Rc` pointers from parent nodes to children, and `Weak` pointers from
39 //! children back to their parents.
40 //!
41 //! `Rc<T>` automatically dereferences to `T` (via the [`Deref`][deref] trait),
42 //! so you can call `T`'s methods on a value of type `Rc<T>`. To avoid name
43 //! clashes with `T`'s methods, the methods of `Rc<T>` itself are [associated
44 //! functions][assoc], called using function-like syntax:
45 //!
46 //! ```
47 //! use std::rc::Rc;
48 //! let my_rc = Rc::new(());
49 //!
50 //! Rc::downgrade(&my_rc);
51 //! ```
52 //!
53 //! `Weak<T>` does not auto-dereference to `T`, because the value may have
54 //! already been destroyed.
55 //!
56 //! [rc]: struct.Rc.html
57 //! [weak]: struct.Weak.html
58 //! [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
59 //! [cell]: ../../std/cell/struct.Cell.html
60 //! [refcell]: ../../std/cell/struct.RefCell.html
61 //! [send]: ../../std/marker/trait.Send.html
62 //! [arc]: ../../std/sync/struct.Arc.html
63 //! [deref]: ../../std/ops/trait.Deref.html
64 //! [downgrade]: struct.Rc.html#method.downgrade
65 //! [upgrade]: struct.Weak.html#method.upgrade
66 //! [option]: ../../std/option/enum.Option.html
67 //! [assoc]: ../../book/method-syntax.html#associated-functions
68 //!
69 //! # Examples
70 //!
71 //! Consider a scenario where a set of `Gadget`s are owned by a given `Owner`.
72 //! We want to have our `Gadget`s point to their `Owner`. We can't do this with
73 //! unique ownership, because more than one gadget may belong to the same
74 //! `Owner`. `Rc` allows us to share an `Owner` between multiple `Gadget`s,
75 //! and have the `Owner` remain allocated as long as any `Gadget` points at it.
76 //!
77 //! ```
78 //! use std::rc::Rc;
79 //!
80 //! struct Owner {
81 //!     name: String,
82 //!     // ...other fields
83 //! }
84 //!
85 //! struct Gadget {
86 //!     id: i32,
87 //!     owner: Rc<Owner>,
88 //!     // ...other fields
89 //! }
90 //!
91 //! fn main() {
92 //!     // Create a reference-counted `Owner`.
93 //!     let gadget_owner: Rc<Owner> = Rc::new(
94 //!         Owner {
95 //!             name: "Gadget Man".to_string(),
96 //!         }
97 //!     );
98 //!
99 //!     // Create `Gadget`s belonging to `gadget_owner`. Cloning the `Rc<Owner>`
100 //!     // value gives us a new pointer to the same `Owner` value, incrementing
101 //!     // the reference count in the process.
102 //!     let gadget1 = Gadget {
103 //!         id: 1,
104 //!         owner: gadget_owner.clone(),
105 //!     };
106 //!     let gadget2 = Gadget {
107 //!         id: 2,
108 //!         owner: gadget_owner.clone(),
109 //!     };
110 //!
111 //!     // Dispose of our local variable `gadget_owner`.
112 //!     drop(gadget_owner);
113 //!
114 //!     // Despite dropping `gadget_owner`, we're still able to print out the name
115 //!     // of the `Owner` of the `Gadget`s. This is because we've only dropped a
116 //!     // single `Rc<Owner>`, not the `Owner` it points to. As long as there are
117 //!     // other `Rc<Owner>` values pointing at the same `Owner`, it will remain
118 //!     // allocated. The field projection `gadget1.owner.name` works because
119 //!     // `Rc<Owner>` automatically dereferences to `Owner`.
120 //!     println!("Gadget {} owned by {}", gadget1.id, gadget1.owner.name);
121 //!     println!("Gadget {} owned by {}", gadget2.id, gadget2.owner.name);
122 //!
123 //!     // At the end of the function, `gadget1` and `gadget2` are destroyed, and
124 //!     // with them the last counted references to our `Owner`. Gadget Man now
125 //!     // gets destroyed as well.
126 //! }
127 //! ```
128 //!
129 //! If our requirements change, and we also need to be able to traverse from
130 //! `Owner` to `Gadget`, we will run into problems. An `Rc` pointer from `Owner`
131 //! to `Gadget` introduces a cycle between the values. This means that their
132 //! reference counts can never reach 0, and the values will remain allocated
133 //! forever: a memory leak. In order to get around this, we can use `Weak`
134 //! pointers.
135 //!
136 //! Rust actually makes it somewhat difficult to produce this loop in the first
137 //! place. In order to end up with two values that point at each other, one of
138 //! them needs to be mutable. This is difficult because `Rc` enforces
139 //! memory safety by only giving out shared references to the value it wraps,
140 //! and these don't allow direct mutation. We need to wrap the part of the
141 //! value we wish to mutate in a [`RefCell`][refcell], which provides *interior
142 //! mutability*: a method to achieve mutability through a shared reference.
143 //! `RefCell` enforces Rust's borrowing rules at runtime.
144 //!
145 //! ```
146 //! use std::rc::Rc;
147 //! use std::rc::Weak;
148 //! use std::cell::RefCell;
149 //!
150 //! struct Owner {
151 //!     name: String,
152 //!     gadgets: RefCell<Vec<Weak<Gadget>>>,
153 //!     // ...other fields
154 //! }
155 //!
156 //! struct Gadget {
157 //!     id: i32,
158 //!     owner: Rc<Owner>,
159 //!     // ...other fields
160 //! }
161 //!
162 //! fn main() {
163 //!     // Create a reference-counted `Owner`. Note that we've put the `Owner`'s
164 //!     // vector of `Gadget`s inside a `RefCell` so that we can mutate it through
165 //!     // a shared reference.
166 //!     let gadget_owner: Rc<Owner> = Rc::new(
167 //!         Owner {
168 //!             name: "Gadget Man".to_string(),
169 //!             gadgets: RefCell::new(vec![]),
170 //!         }
171 //!     );
172 //!
173 //!     // Create `Gadget`s belonging to `gadget_owner`, as before.
174 //!     let gadget1 = Rc::new(
175 //!         Gadget {
176 //!             id: 1,
177 //!             owner: gadget_owner.clone(),
178 //!         }
179 //!     );
180 //!     let gadget2 = Rc::new(
181 //!         Gadget {
182 //!             id: 2,
183 //!             owner: gadget_owner.clone(),
184 //!         }
185 //!     );
186 //!
187 //!     // Add the `Gadget`s to their `Owner`.
188 //!     {
189 //!         let mut gadgets = gadget_owner.gadgets.borrow_mut();
190 //!         gadgets.push(Rc::downgrade(&gadget1));
191 //!         gadgets.push(Rc::downgrade(&gadget2));
192 //!
193 //!         // `RefCell` dynamic borrow ends here.
194 //!     }
195 //!
196 //!     // Iterate over our `Gadget`s, printing their details out.
197 //!     for gadget_weak in gadget_owner.gadgets.borrow().iter() {
198 //!
199 //!         // `gadget_weak` is a `Weak<Gadget>`. Since `Weak` pointers can't
200 //!         // guarantee the value is still allocated, we need to call
201 //!         // `upgrade`, which returns an `Option<Rc<Gadget>>`.
202 //!         //
203 //!         // In this case we know the value still exists, so we simply
204 //!         // `unwrap` the `Option`. In a more complicated program, you might
205 //!         // need graceful error handling for a `None` result.
206 //!
207 //!         let gadget = gadget_weak.upgrade().unwrap();
208 //!         println!("Gadget {} owned by {}", gadget.id, gadget.owner.name);
209 //!     }
210 //!
211 //!     // At the end of the function, `gadget_owner`, `gadget1`, and `gadget2`
212 //!     // are destroyed. There are now no strong (`Rc`) pointers to the
213 //!     // gadgets, so they are destroyed. This zeroes the reference count on
214 //!     // Gadget Man, so he gets destroyed as well.
215 //! }
216 //! ```
217
218 #![stable(feature = "rust1", since = "1.0.0")]
219
220 #[cfg(not(test))]
221 use boxed::Box;
222 #[cfg(test)]
223 use std::boxed::Box;
224
225 use core::borrow;
226 use core::cell::Cell;
227 use core::cmp::Ordering;
228 use core::fmt;
229 use core::hash::{Hash, Hasher};
230 use core::intrinsics::{abort, assume};
231 use core::marker;
232 use core::marker::Unsize;
233 use core::mem::{self, align_of_val, forget, size_of_val, uninitialized};
234 use core::ops::Deref;
235 use core::ops::CoerceUnsized;
236 use core::ptr::{self, Shared};
237 use core::convert::From;
238
239 use heap::deallocate;
240
241 struct RcBox<T: ?Sized> {
242     strong: Cell<usize>,
243     weak: Cell<usize>,
244     value: T,
245 }
246
247
248 /// A single-threaded reference-counting pointer.
249 ///
250 /// See the [module-level documentation](./index.html) for more details.
251 ///
252 /// The inherent methods of `Rc` are all associated functions, which means
253 /// that you have to call them as e.g. `Rc::get_mut(&value)` instead of
254 /// `value.get_mut()`.  This avoids conflicts with methods of the inner
255 /// type `T`.
256 #[stable(feature = "rust1", since = "1.0.0")]
257 pub struct Rc<T: ?Sized> {
258     ptr: Shared<RcBox<T>>,
259 }
260
261 #[stable(feature = "rust1", since = "1.0.0")]
262 impl<T: ?Sized> !marker::Send for Rc<T> {}
263 #[stable(feature = "rust1", since = "1.0.0")]
264 impl<T: ?Sized> !marker::Sync for Rc<T> {}
265
266 #[unstable(feature = "coerce_unsized", issue = "27732")]
267 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Rc<U>> for Rc<T> {}
268
269 impl<T> Rc<T> {
270     /// Constructs a new `Rc<T>`.
271     ///
272     /// # Examples
273     ///
274     /// ```
275     /// use std::rc::Rc;
276     ///
277     /// let five = Rc::new(5);
278     /// ```
279     #[stable(feature = "rust1", since = "1.0.0")]
280     pub fn new(value: T) -> Rc<T> {
281         unsafe {
282             Rc {
283                 // there is an implicit weak pointer owned by all the strong
284                 // pointers, which ensures that the weak destructor never frees
285                 // the allocation while the strong destructor is running, even
286                 // if the weak pointer is stored inside the strong one.
287                 ptr: Shared::new(Box::into_raw(box RcBox {
288                     strong: Cell::new(1),
289                     weak: Cell::new(1),
290                     value: value,
291                 })),
292             }
293         }
294     }
295
296     /// Returns the contained value, if the `Rc` has exactly one strong reference.
297     ///
298     /// Otherwise, an [`Err`][result] is returned with the same `Rc` that was
299     /// passed in.
300     ///
301     /// This will succeed even if there are outstanding weak references.
302     ///
303     /// [result]: ../../std/result/enum.Result.html
304     ///
305     /// # Examples
306     ///
307     /// ```
308     /// use std::rc::Rc;
309     ///
310     /// let x = Rc::new(3);
311     /// assert_eq!(Rc::try_unwrap(x), Ok(3));
312     ///
313     /// let x = Rc::new(4);
314     /// let _y = x.clone();
315     /// assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4);
316     /// ```
317     #[inline]
318     #[stable(feature = "rc_unique", since = "1.4.0")]
319     pub fn try_unwrap(this: Self) -> Result<T, Self> {
320         if Rc::would_unwrap(&this) {
321             unsafe {
322                 let val = ptr::read(&*this); // copy the contained object
323
324                 // Indicate to Weaks that they can't be promoted by decrememting
325                 // the strong count, and then remove the implicit "strong weak"
326                 // pointer while also handling drop logic by just crafting a
327                 // fake Weak.
328                 this.dec_strong();
329                 let _weak = Weak { ptr: this.ptr };
330                 forget(this);
331                 Ok(val)
332             }
333         } else {
334             Err(this)
335         }
336     }
337
338     /// Checks whether [`Rc::try_unwrap`][try_unwrap] would return
339     /// [`Ok`][result].
340     ///
341     /// [try_unwrap]: struct.Rc.html#method.try_unwrap
342     /// [result]: ../../std/result/enum.Result.html
343     ///
344     /// # Examples
345     ///
346     /// ```
347     /// #![feature(rc_would_unwrap)]
348     ///
349     /// use std::rc::Rc;
350     ///
351     /// let x = Rc::new(3);
352     /// assert!(Rc::would_unwrap(&x));
353     /// assert_eq!(Rc::try_unwrap(x), Ok(3));
354     ///
355     /// let x = Rc::new(4);
356     /// let _y = x.clone();
357     /// assert!(!Rc::would_unwrap(&x));
358     /// assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4);
359     /// ```
360     #[unstable(feature = "rc_would_unwrap",
361                reason = "just added for niche usecase",
362                issue = "28356")]
363     pub fn would_unwrap(this: &Self) -> bool {
364         Rc::strong_count(&this) == 1
365     }
366
367     /// Consumes the `Rc`, returning the wrapped pointer.
368     ///
369     /// To avoid a memory leak the pointer must be converted back to an `Rc` using
370     /// [`Rc::from_raw`][from_raw].
371     ///
372     /// [from_raw]: struct.Rc.html#method.from_raw
373     ///
374     /// # Examples
375     ///
376     /// ```
377     /// #![feature(rc_raw)]
378     ///
379     /// use std::rc::Rc;
380     ///
381     /// let x = Rc::new(10);
382     /// let x_ptr = Rc::into_raw(x);
383     /// assert_eq!(unsafe { *x_ptr }, 10);
384     /// ```
385     #[unstable(feature = "rc_raw", issue = "37197")]
386     pub fn into_raw(this: Self) -> *mut T {
387         let ptr = unsafe { &mut (**this.ptr).value as *mut _ };
388         mem::forget(this);
389         ptr
390     }
391
392     /// Constructs an `Rc` from a raw pointer.
393     ///
394     /// The raw pointer must have been previously returned by a call to a
395     /// [`Rc::into_raw`][into_raw].
396     ///
397     /// This function is unsafe because improper use may lead to memory problems. For example, a
398     /// double-free may occur if the function is called twice on the same raw pointer.
399     ///
400     /// [into_raw]: struct.Rc.html#method.into_raw
401     ///
402     /// # Examples
403     ///
404     /// ```
405     /// #![feature(rc_raw)]
406     ///
407     /// use std::rc::Rc;
408     ///
409     /// let x = Rc::new(10);
410     /// let x_ptr = Rc::into_raw(x);
411     ///
412     /// unsafe {
413     ///     // Convert back to an `Rc` to prevent leak.
414     ///     let x = Rc::from_raw(x_ptr);
415     ///     assert_eq!(*x, 10);
416     ///
417     ///     // Further calls to `Rc::from_raw(x_ptr)` would be memory unsafe.
418     /// }
419     ///
420     /// // The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling!
421     /// ```
422     #[unstable(feature = "rc_raw", issue = "37197")]
423     pub unsafe fn from_raw(ptr: *mut T) -> Self {
424         // To find the corresponding pointer to the `RcBox` we need to subtract the offset of the
425         // `value` field from the pointer.
426         Rc { ptr: Shared::new((ptr as *mut u8).offset(-offset_of!(RcBox<T>, value)) as *mut _) }
427     }
428 }
429
430 impl<T: ?Sized> Rc<T> {
431     /// Creates a new [`Weak`][weak] pointer to this value.
432     ///
433     /// [weak]: struct.Weak.html
434     ///
435     /// # Examples
436     ///
437     /// ```
438     /// use std::rc::Rc;
439     ///
440     /// let five = Rc::new(5);
441     ///
442     /// let weak_five = Rc::downgrade(&five);
443     /// ```
444     #[stable(feature = "rc_weak", since = "1.4.0")]
445     pub fn downgrade(this: &Self) -> Weak<T> {
446         this.inc_weak();
447         Weak { ptr: this.ptr }
448     }
449
450     /// Gets the number of [`Weak`][weak] pointers to this value.
451     ///
452     /// [weak]: struct.Weak.html
453     ///
454     /// # Examples
455     ///
456     /// ```
457     /// #![feature(rc_counts)]
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     #[unstable(feature = "rc_counts", reason = "not clearly useful",
468                issue = "28356")]
469     pub fn weak_count(this: &Self) -> usize {
470         this.weak() - 1
471     }
472
473     /// Gets the number of strong (`Rc`) pointers to this value.
474     ///
475     /// # Examples
476     ///
477     /// ```
478     /// #![feature(rc_counts)]
479     ///
480     /// use std::rc::Rc;
481     ///
482     /// let five = Rc::new(5);
483     /// let _also_five = five.clone();
484     ///
485     /// assert_eq!(2, Rc::strong_count(&five));
486     /// ```
487     #[inline]
488     #[unstable(feature = "rc_counts", reason = "not clearly useful",
489                issue = "28356")]
490     pub fn strong_count(this: &Self) -> usize {
491         this.strong()
492     }
493
494     /// Returns true if there are no other `Rc` or [`Weak`][weak] pointers to
495     /// this inner value.
496     ///
497     /// [weak]: struct.Weak.html
498     ///
499     /// # Examples
500     ///
501     /// ```
502     /// #![feature(rc_counts)]
503     ///
504     /// use std::rc::Rc;
505     ///
506     /// let five = Rc::new(5);
507     ///
508     /// assert!(Rc::is_unique(&five));
509     /// ```
510     #[inline]
511     #[unstable(feature = "rc_counts", reason = "uniqueness has unclear meaning",
512                issue = "28356")]
513     pub fn is_unique(this: &Self) -> bool {
514         Rc::weak_count(this) == 0 && Rc::strong_count(this) == 1
515     }
516
517     /// Returns a mutable reference to the inner value, if there are
518     /// no other `Rc` or [`Weak`][weak] pointers to the same value.
519     ///
520     /// Returns [`None`][option] otherwise, because it is not safe to
521     /// mutate a shared value.
522     ///
523     /// See also [`make_mut`][make_mut], which will [`clone`][clone]
524     /// the inner value when it's shared.
525     ///
526     /// [weak]: struct.Weak.html
527     /// [option]: ../../std/option/enum.Option.html
528     /// [make_mut]: struct.Rc.html#method.make_mut
529     /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
530     ///
531     /// # Examples
532     ///
533     /// ```
534     /// use std::rc::Rc;
535     ///
536     /// let mut x = Rc::new(3);
537     /// *Rc::get_mut(&mut x).unwrap() = 4;
538     /// assert_eq!(*x, 4);
539     ///
540     /// let _y = x.clone();
541     /// assert!(Rc::get_mut(&mut x).is_none());
542     /// ```
543     #[inline]
544     #[stable(feature = "rc_unique", since = "1.4.0")]
545     pub fn get_mut(this: &mut Self) -> Option<&mut T> {
546         if Rc::is_unique(this) {
547             let inner = unsafe { &mut **this.ptr };
548             Some(&mut inner.value)
549         } else {
550             None
551         }
552     }
553
554     #[inline]
555     #[unstable(feature = "ptr_eq",
556                reason = "newly added",
557                issue = "36497")]
558     /// Returns true if the two `Rc`s point to the same value (not
559     /// just values that compare as equal).
560     ///
561     /// # Examples
562     ///
563     /// ```
564     /// #![feature(ptr_eq)]
565     ///
566     /// use std::rc::Rc;
567     ///
568     /// let five = Rc::new(5);
569     /// let same_five = five.clone();
570     /// let other_five = Rc::new(5);
571     ///
572     /// assert!(Rc::ptr_eq(&five, &same_five));
573     /// assert!(!Rc::ptr_eq(&five, &other_five));
574     /// ```
575     pub fn ptr_eq(this: &Self, other: &Self) -> bool {
576         let this_ptr: *const RcBox<T> = *this.ptr;
577         let other_ptr: *const RcBox<T> = *other.ptr;
578         this_ptr == other_ptr
579     }
580 }
581
582 impl<T: Clone> Rc<T> {
583     /// Makes a mutable reference into the given `Rc`.
584     ///
585     /// If there are other `Rc` or [`Weak`][weak] pointers to the same value,
586     /// then `make_mut` will invoke [`clone`][clone] on the inner value to
587     /// ensure unique ownership. This is also referred to as clone-on-write.
588     ///
589     /// See also [`get_mut`][get_mut], which will fail rather than cloning.
590     ///
591     /// [weak]: struct.Weak.html
592     /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
593     /// [get_mut]: struct.Rc.html#method.get_mut
594     ///
595     /// # Examples
596     ///
597     /// ```
598     /// use std::rc::Rc;
599     ///
600     /// let mut data = Rc::new(5);
601     ///
602     /// *Rc::make_mut(&mut data) += 1;        // Won't clone anything
603     /// let mut other_data = data.clone();    // Won't clone inner data
604     /// *Rc::make_mut(&mut data) += 1;        // Clones inner data
605     /// *Rc::make_mut(&mut data) += 1;        // Won't clone anything
606     /// *Rc::make_mut(&mut other_data) *= 2;  // Won't clone anything
607     ///
608     /// // Now `data` and `other_data` point to different values.
609     /// assert_eq!(*data, 8);
610     /// assert_eq!(*other_data, 12);
611     /// ```
612     #[inline]
613     #[stable(feature = "rc_unique", since = "1.4.0")]
614     pub fn make_mut(this: &mut Self) -> &mut T {
615         if Rc::strong_count(this) != 1 {
616             // Gotta clone the data, there are other Rcs
617             *this = Rc::new((**this).clone())
618         } else if Rc::weak_count(this) != 0 {
619             // Can just steal the data, all that's left is Weaks
620             unsafe {
621                 let mut swap = Rc::new(ptr::read(&(**this.ptr).value));
622                 mem::swap(this, &mut swap);
623                 swap.dec_strong();
624                 // Remove implicit strong-weak ref (no need to craft a fake
625                 // Weak here -- we know other Weaks can clean up for us)
626                 swap.dec_weak();
627                 forget(swap);
628             }
629         }
630         // This unsafety is ok because we're guaranteed that the pointer
631         // returned is the *only* pointer that will ever be returned to T. Our
632         // reference count is guaranteed to be 1 at this point, and we required
633         // the `Rc<T>` itself to be `mut`, so we're returning the only possible
634         // reference to the inner value.
635         let inner = unsafe { &mut **this.ptr };
636         &mut inner.value
637     }
638 }
639
640 #[stable(feature = "rust1", since = "1.0.0")]
641 impl<T: ?Sized> Deref for Rc<T> {
642     type Target = T;
643
644     #[inline(always)]
645     fn deref(&self) -> &T {
646         &self.inner().value
647     }
648 }
649
650 #[stable(feature = "rust1", since = "1.0.0")]
651 impl<T: ?Sized> Drop for Rc<T> {
652     /// Drops the `Rc`.
653     ///
654     /// This will decrement the strong reference count. If the strong reference
655     /// count reaches zero then the only other references (if any) are
656     /// [`Weak`][weak], so we `drop` the inner value.
657     ///
658     /// [weak]: struct.Weak.html
659     ///
660     /// # Examples
661     ///
662     /// ```
663     /// use std::rc::Rc;
664     ///
665     /// struct Foo;
666     ///
667     /// impl Drop for Foo {
668     ///     fn drop(&mut self) {
669     ///         println!("dropped!");
670     ///     }
671     /// }
672     ///
673     /// let foo  = Rc::new(Foo);
674     /// let foo2 = foo.clone();
675     ///
676     /// drop(foo);    // Doesn't print anything
677     /// drop(foo2);   // Prints "dropped!"
678     /// ```
679     #[unsafe_destructor_blind_to_params]
680     fn drop(&mut self) {
681         unsafe {
682             let ptr = *self.ptr;
683
684             self.dec_strong();
685             if self.strong() == 0 {
686                 // destroy the contained object
687                 ptr::drop_in_place(&mut (*ptr).value);
688
689                 // remove the implicit "strong weak" pointer now that we've
690                 // destroyed the contents.
691                 self.dec_weak();
692
693                 if self.weak() == 0 {
694                     deallocate(ptr as *mut u8, size_of_val(&*ptr), align_of_val(&*ptr))
695                 }
696             }
697         }
698     }
699 }
700
701 #[stable(feature = "rust1", since = "1.0.0")]
702 impl<T: ?Sized> Clone for Rc<T> {
703     /// Makes a clone of the `Rc` pointer.
704     ///
705     /// This creates another pointer to the same inner value, increasing the
706     /// strong reference count.
707     ///
708     /// # Examples
709     ///
710     /// ```
711     /// use std::rc::Rc;
712     ///
713     /// let five = Rc::new(5);
714     ///
715     /// five.clone();
716     /// ```
717     #[inline]
718     fn clone(&self) -> Rc<T> {
719         self.inc_strong();
720         Rc { ptr: self.ptr }
721     }
722 }
723
724 #[stable(feature = "rust1", since = "1.0.0")]
725 impl<T: Default> Default for Rc<T> {
726     /// Creates a new `Rc<T>`, with the `Default` value for `T`.
727     ///
728     /// # Examples
729     ///
730     /// ```
731     /// use std::rc::Rc;
732     ///
733     /// let x: Rc<i32> = Default::default();
734     /// assert_eq!(*x, 0);
735     /// ```
736     #[inline]
737     fn default() -> Rc<T> {
738         Rc::new(Default::default())
739     }
740 }
741
742 #[stable(feature = "rust1", since = "1.0.0")]
743 impl<T: ?Sized + PartialEq> PartialEq for Rc<T> {
744     /// Equality for two `Rc`s.
745     ///
746     /// Two `Rc`s are equal if their inner values are equal.
747     ///
748     /// # Examples
749     ///
750     /// ```
751     /// use std::rc::Rc;
752     ///
753     /// let five = Rc::new(5);
754     ///
755     /// assert!(five == Rc::new(5));
756     /// ```
757     #[inline(always)]
758     fn eq(&self, other: &Rc<T>) -> bool {
759         **self == **other
760     }
761
762     /// Inequality for two `Rc`s.
763     ///
764     /// Two `Rc`s are unequal if their inner values are unequal.
765     ///
766     /// # Examples
767     ///
768     /// ```
769     /// use std::rc::Rc;
770     ///
771     /// let five = Rc::new(5);
772     ///
773     /// assert!(five != Rc::new(6));
774     /// ```
775     #[inline(always)]
776     fn ne(&self, other: &Rc<T>) -> bool {
777         **self != **other
778     }
779 }
780
781 #[stable(feature = "rust1", since = "1.0.0")]
782 impl<T: ?Sized + Eq> Eq for Rc<T> {}
783
784 #[stable(feature = "rust1", since = "1.0.0")]
785 impl<T: ?Sized + PartialOrd> PartialOrd for Rc<T> {
786     /// Partial comparison for two `Rc`s.
787     ///
788     /// The two are compared by calling `partial_cmp()` on their inner values.
789     ///
790     /// # Examples
791     ///
792     /// ```
793     /// use std::rc::Rc;
794     /// use std::cmp::Ordering;
795     ///
796     /// let five = Rc::new(5);
797     ///
798     /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&Rc::new(6)));
799     /// ```
800     #[inline(always)]
801     fn partial_cmp(&self, other: &Rc<T>) -> Option<Ordering> {
802         (**self).partial_cmp(&**other)
803     }
804
805     /// Less-than comparison for two `Rc`s.
806     ///
807     /// The two are compared by calling `<` on their inner values.
808     ///
809     /// # Examples
810     ///
811     /// ```
812     /// use std::rc::Rc;
813     ///
814     /// let five = Rc::new(5);
815     ///
816     /// assert!(five < Rc::new(6));
817     /// ```
818     #[inline(always)]
819     fn lt(&self, other: &Rc<T>) -> bool {
820         **self < **other
821     }
822
823     /// 'Less than or equal to' comparison for two `Rc`s.
824     ///
825     /// The two are compared by calling `<=` on their inner values.
826     ///
827     /// # Examples
828     ///
829     /// ```
830     /// use std::rc::Rc;
831     ///
832     /// let five = Rc::new(5);
833     ///
834     /// assert!(five <= Rc::new(5));
835     /// ```
836     #[inline(always)]
837     fn le(&self, other: &Rc<T>) -> bool {
838         **self <= **other
839     }
840
841     /// Greater-than comparison for two `Rc`s.
842     ///
843     /// The two are compared by calling `>` on their inner values.
844     ///
845     /// # Examples
846     ///
847     /// ```
848     /// use std::rc::Rc;
849     ///
850     /// let five = Rc::new(5);
851     ///
852     /// assert!(five > Rc::new(4));
853     /// ```
854     #[inline(always)]
855     fn gt(&self, other: &Rc<T>) -> bool {
856         **self > **other
857     }
858
859     /// 'Greater than or equal to' comparison for two `Rc`s.
860     ///
861     /// The two are compared by calling `>=` on their inner values.
862     ///
863     /// # Examples
864     ///
865     /// ```
866     /// use std::rc::Rc;
867     ///
868     /// let five = Rc::new(5);
869     ///
870     /// assert!(five >= Rc::new(5));
871     /// ```
872     #[inline(always)]
873     fn ge(&self, other: &Rc<T>) -> bool {
874         **self >= **other
875     }
876 }
877
878 #[stable(feature = "rust1", since = "1.0.0")]
879 impl<T: ?Sized + Ord> Ord for Rc<T> {
880     /// Comparison for two `Rc`s.
881     ///
882     /// The two are compared by calling `cmp()` on their inner values.
883     ///
884     /// # Examples
885     ///
886     /// ```
887     /// use std::rc::Rc;
888     /// use std::cmp::Ordering;
889     ///
890     /// let five = Rc::new(5);
891     ///
892     /// assert_eq!(Ordering::Less, five.cmp(&Rc::new(6)));
893     /// ```
894     #[inline]
895     fn cmp(&self, other: &Rc<T>) -> Ordering {
896         (**self).cmp(&**other)
897     }
898 }
899
900 #[stable(feature = "rust1", since = "1.0.0")]
901 impl<T: ?Sized + Hash> Hash for Rc<T> {
902     fn hash<H: Hasher>(&self, state: &mut H) {
903         (**self).hash(state);
904     }
905 }
906
907 #[stable(feature = "rust1", since = "1.0.0")]
908 impl<T: ?Sized + fmt::Display> fmt::Display for Rc<T> {
909     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
910         fmt::Display::fmt(&**self, f)
911     }
912 }
913
914 #[stable(feature = "rust1", since = "1.0.0")]
915 impl<T: ?Sized + fmt::Debug> fmt::Debug for Rc<T> {
916     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
917         fmt::Debug::fmt(&**self, f)
918     }
919 }
920
921 #[stable(feature = "rust1", since = "1.0.0")]
922 impl<T: ?Sized> fmt::Pointer for Rc<T> {
923     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
924         fmt::Pointer::fmt(&*self.ptr, f)
925     }
926 }
927
928 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
929 impl<T> From<T> for Rc<T> {
930     fn from(t: T) -> Self {
931         Rc::new(t)
932     }
933 }
934
935 /// A weak version of [`Rc`][rc].
936 ///
937 /// `Weak` pointers do not count towards determining if the inner value
938 /// should be dropped.
939 ///
940 /// The typical way to obtain a `Weak` pointer is to call
941 /// [`Rc::downgrade`][downgrade].
942 ///
943 /// See the [module-level documentation](./index.html) for more details.
944 ///
945 /// [rc]: struct.Rc.html
946 /// [downgrade]: struct.Rc.html#method.downgrade
947 #[stable(feature = "rc_weak", since = "1.4.0")]
948 pub struct Weak<T: ?Sized> {
949     ptr: Shared<RcBox<T>>,
950 }
951
952 #[stable(feature = "rc_weak", since = "1.4.0")]
953 impl<T: ?Sized> !marker::Send for Weak<T> {}
954 #[stable(feature = "rc_weak", since = "1.4.0")]
955 impl<T: ?Sized> !marker::Sync for Weak<T> {}
956
957 #[unstable(feature = "coerce_unsized", issue = "27732")]
958 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {}
959
960 impl<T> Weak<T> {
961     /// Constructs a new `Weak<T>`, without an accompanying instance of `T`.
962     ///
963     /// This allocates memory for `T`, but does not initialize it. Calling
964     /// [`upgrade`][upgrade] on the return value always gives
965     /// [`None`][option].
966     ///
967     /// [upgrade]: struct.Weak.html#method.upgrade
968     /// [option]: ../../std/option/enum.Option.html
969     ///
970     /// # Examples
971     ///
972     /// ```
973     /// use std::rc::Weak;
974     ///
975     /// let empty: Weak<i64> = Weak::new();
976     /// assert!(empty.upgrade().is_none());
977     /// ```
978     #[stable(feature = "downgraded_weak", since = "1.10.0")]
979     pub fn new() -> Weak<T> {
980         unsafe {
981             Weak {
982                 ptr: Shared::new(Box::into_raw(box RcBox {
983                     strong: Cell::new(0),
984                     weak: Cell::new(1),
985                     value: uninitialized(),
986                 })),
987             }
988         }
989     }
990 }
991
992 impl<T: ?Sized> Weak<T> {
993     /// Upgrades the `Weak` pointer to an [`Rc`][rc], if possible.
994     ///
995     /// Returns [`None`][option] if the strong count has reached zero and the
996     /// inner value was destroyed.
997     ///
998     /// [rc]: struct.Rc.html
999     /// [option]: ../../std/option/enum.Option.html
1000     ///
1001     /// # Examples
1002     ///
1003     /// ```
1004     /// use std::rc::Rc;
1005     ///
1006     /// let five = Rc::new(5);
1007     ///
1008     /// let weak_five = Rc::downgrade(&five);
1009     ///
1010     /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
1011     /// assert!(strong_five.is_some());
1012     ///
1013     /// // Destroy all strong pointers.
1014     /// drop(strong_five);
1015     /// drop(five);
1016     ///
1017     /// assert!(weak_five.upgrade().is_none());
1018     /// ```
1019     #[stable(feature = "rc_weak", since = "1.4.0")]
1020     pub fn upgrade(&self) -> Option<Rc<T>> {
1021         if self.strong() == 0 {
1022             None
1023         } else {
1024             self.inc_strong();
1025             Some(Rc { ptr: self.ptr })
1026         }
1027     }
1028 }
1029
1030 #[stable(feature = "rc_weak", since = "1.4.0")]
1031 impl<T: ?Sized> Drop for Weak<T> {
1032     /// Drops the `Weak` pointer.
1033     ///
1034     /// This will decrement the weak reference count.
1035     ///
1036     /// # Examples
1037     ///
1038     /// ```
1039     /// use std::rc::Rc;
1040     ///
1041     /// struct Foo;
1042     ///
1043     /// impl Drop for Foo {
1044     ///     fn drop(&mut self) {
1045     ///         println!("dropped!");
1046     ///     }
1047     /// }
1048     ///
1049     /// let foo = Rc::new(Foo);
1050     /// let weak_foo = Rc::downgrade(&foo);
1051     /// let other_weak_foo = weak_foo.clone();
1052     ///
1053     /// drop(weak_foo);   // Doesn't print anything
1054     /// drop(foo);        // Prints "dropped!"
1055     ///
1056     /// assert!(other_weak_foo.upgrade().is_none());
1057     /// ```
1058     fn drop(&mut self) {
1059         unsafe {
1060             let ptr = *self.ptr;
1061
1062             self.dec_weak();
1063             // the weak count starts at 1, and will only go to zero if all
1064             // the strong pointers have disappeared.
1065             if self.weak() == 0 {
1066                 deallocate(ptr as *mut u8, size_of_val(&*ptr), align_of_val(&*ptr))
1067             }
1068         }
1069     }
1070 }
1071
1072 #[stable(feature = "rc_weak", since = "1.4.0")]
1073 impl<T: ?Sized> Clone for Weak<T> {
1074     /// Makes a clone of the `Weak` pointer.
1075     ///
1076     /// This creates another pointer to the same inner value, increasing the
1077     /// weak reference count.
1078     ///
1079     /// # Examples
1080     ///
1081     /// ```
1082     /// use std::rc::Rc;
1083     ///
1084     /// let weak_five = Rc::downgrade(&Rc::new(5));
1085     ///
1086     /// weak_five.clone();
1087     /// ```
1088     #[inline]
1089     fn clone(&self) -> Weak<T> {
1090         self.inc_weak();
1091         Weak { ptr: self.ptr }
1092     }
1093 }
1094
1095 #[stable(feature = "rc_weak", since = "1.4.0")]
1096 impl<T: ?Sized + fmt::Debug> fmt::Debug for Weak<T> {
1097     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1098         write!(f, "(Weak)")
1099     }
1100 }
1101
1102 #[stable(feature = "downgraded_weak", since = "1.10.0")]
1103 impl<T> Default for Weak<T> {
1104     /// Constructs a new `Weak<T>`, without an accompanying instance of `T`.
1105     ///
1106     /// This allocates memory for `T`, but does not initialize it. Calling
1107     /// [`upgrade`][upgrade] on the return value always gives
1108     /// [`None`][option].
1109     ///
1110     /// [upgrade]: struct.Weak.html#method.upgrade
1111     /// [option]: ../../std/option/enum.Option.html
1112     ///
1113     /// # Examples
1114     ///
1115     /// ```
1116     /// use std::rc::Weak;
1117     ///
1118     /// let empty: Weak<i64> = Default::default();
1119     /// assert!(empty.upgrade().is_none());
1120     /// ```
1121     fn default() -> Weak<T> {
1122         Weak::new()
1123     }
1124 }
1125
1126 // NOTE: We checked_add here to deal with mem::forget safety. In particular
1127 // if you mem::forget Rcs (or Weaks), the ref-count can overflow, and then
1128 // you can free the allocation while outstanding Rcs (or Weaks) exist.
1129 // We abort because this is such a degenerate scenario that we don't care about
1130 // what happens -- no real program should ever experience this.
1131 //
1132 // This should have negligible overhead since you don't actually need to
1133 // clone these much in Rust thanks to ownership and move-semantics.
1134
1135 #[doc(hidden)]
1136 trait RcBoxPtr<T: ?Sized> {
1137     fn inner(&self) -> &RcBox<T>;
1138
1139     #[inline]
1140     fn strong(&self) -> usize {
1141         self.inner().strong.get()
1142     }
1143
1144     #[inline]
1145     fn inc_strong(&self) {
1146         self.inner().strong.set(self.strong().checked_add(1).unwrap_or_else(|| unsafe { abort() }));
1147     }
1148
1149     #[inline]
1150     fn dec_strong(&self) {
1151         self.inner().strong.set(self.strong() - 1);
1152     }
1153
1154     #[inline]
1155     fn weak(&self) -> usize {
1156         self.inner().weak.get()
1157     }
1158
1159     #[inline]
1160     fn inc_weak(&self) {
1161         self.inner().weak.set(self.weak().checked_add(1).unwrap_or_else(|| unsafe { abort() }));
1162     }
1163
1164     #[inline]
1165     fn dec_weak(&self) {
1166         self.inner().weak.set(self.weak() - 1);
1167     }
1168 }
1169
1170 impl<T: ?Sized> RcBoxPtr<T> for Rc<T> {
1171     #[inline(always)]
1172     fn inner(&self) -> &RcBox<T> {
1173         unsafe {
1174             // Safe to assume this here, as if it weren't true, we'd be breaking
1175             // the contract anyway.
1176             // This allows the null check to be elided in the destructor if we
1177             // manipulated the reference count in the same function.
1178             assume(!(*(&self.ptr as *const _ as *const *const ())).is_null());
1179             &(**self.ptr)
1180         }
1181     }
1182 }
1183
1184 impl<T: ?Sized> RcBoxPtr<T> for Weak<T> {
1185     #[inline(always)]
1186     fn inner(&self) -> &RcBox<T> {
1187         unsafe {
1188             // Safe to assume this here, as if it weren't true, we'd be breaking
1189             // the contract anyway.
1190             // This allows the null check to be elided in the destructor if we
1191             // manipulated the reference count in the same function.
1192             assume(!(*(&self.ptr as *const _ as *const *const ())).is_null());
1193             &(**self.ptr)
1194         }
1195     }
1196 }
1197
1198 #[cfg(test)]
1199 mod tests {
1200     use super::{Rc, Weak};
1201     use std::boxed::Box;
1202     use std::cell::RefCell;
1203     use std::option::Option;
1204     use std::option::Option::{None, Some};
1205     use std::result::Result::{Err, Ok};
1206     use std::mem::drop;
1207     use std::clone::Clone;
1208     use std::convert::From;
1209
1210     #[test]
1211     fn test_clone() {
1212         let x = Rc::new(RefCell::new(5));
1213         let y = x.clone();
1214         *x.borrow_mut() = 20;
1215         assert_eq!(*y.borrow(), 20);
1216     }
1217
1218     #[test]
1219     fn test_simple() {
1220         let x = Rc::new(5);
1221         assert_eq!(*x, 5);
1222     }
1223
1224     #[test]
1225     fn test_simple_clone() {
1226         let x = Rc::new(5);
1227         let y = x.clone();
1228         assert_eq!(*x, 5);
1229         assert_eq!(*y, 5);
1230     }
1231
1232     #[test]
1233     fn test_destructor() {
1234         let x: Rc<Box<_>> = Rc::new(box 5);
1235         assert_eq!(**x, 5);
1236     }
1237
1238     #[test]
1239     fn test_live() {
1240         let x = Rc::new(5);
1241         let y = Rc::downgrade(&x);
1242         assert!(y.upgrade().is_some());
1243     }
1244
1245     #[test]
1246     fn test_dead() {
1247         let x = Rc::new(5);
1248         let y = Rc::downgrade(&x);
1249         drop(x);
1250         assert!(y.upgrade().is_none());
1251     }
1252
1253     #[test]
1254     fn weak_self_cyclic() {
1255         struct Cycle {
1256             x: RefCell<Option<Weak<Cycle>>>,
1257         }
1258
1259         let a = Rc::new(Cycle { x: RefCell::new(None) });
1260         let b = Rc::downgrade(&a.clone());
1261         *a.x.borrow_mut() = Some(b);
1262
1263         // hopefully we don't double-free (or leak)...
1264     }
1265
1266     #[test]
1267     fn is_unique() {
1268         let x = Rc::new(3);
1269         assert!(Rc::is_unique(&x));
1270         let y = x.clone();
1271         assert!(!Rc::is_unique(&x));
1272         drop(y);
1273         assert!(Rc::is_unique(&x));
1274         let w = Rc::downgrade(&x);
1275         assert!(!Rc::is_unique(&x));
1276         drop(w);
1277         assert!(Rc::is_unique(&x));
1278     }
1279
1280     #[test]
1281     fn test_strong_count() {
1282         let a = Rc::new(0);
1283         assert!(Rc::strong_count(&a) == 1);
1284         let w = Rc::downgrade(&a);
1285         assert!(Rc::strong_count(&a) == 1);
1286         let b = w.upgrade().expect("upgrade of live rc failed");
1287         assert!(Rc::strong_count(&b) == 2);
1288         assert!(Rc::strong_count(&a) == 2);
1289         drop(w);
1290         drop(a);
1291         assert!(Rc::strong_count(&b) == 1);
1292         let c = b.clone();
1293         assert!(Rc::strong_count(&b) == 2);
1294         assert!(Rc::strong_count(&c) == 2);
1295     }
1296
1297     #[test]
1298     fn test_weak_count() {
1299         let a = Rc::new(0);
1300         assert!(Rc::strong_count(&a) == 1);
1301         assert!(Rc::weak_count(&a) == 0);
1302         let w = Rc::downgrade(&a);
1303         assert!(Rc::strong_count(&a) == 1);
1304         assert!(Rc::weak_count(&a) == 1);
1305         drop(w);
1306         assert!(Rc::strong_count(&a) == 1);
1307         assert!(Rc::weak_count(&a) == 0);
1308         let c = a.clone();
1309         assert!(Rc::strong_count(&a) == 2);
1310         assert!(Rc::weak_count(&a) == 0);
1311         drop(c);
1312     }
1313
1314     #[test]
1315     fn try_unwrap() {
1316         let x = Rc::new(3);
1317         assert_eq!(Rc::try_unwrap(x), Ok(3));
1318         let x = Rc::new(4);
1319         let _y = x.clone();
1320         assert_eq!(Rc::try_unwrap(x), Err(Rc::new(4)));
1321         let x = Rc::new(5);
1322         let _w = Rc::downgrade(&x);
1323         assert_eq!(Rc::try_unwrap(x), Ok(5));
1324     }
1325
1326     #[test]
1327     fn into_from_raw() {
1328         let x = Rc::new(box "hello");
1329         let y = x.clone();
1330
1331         let x_ptr = Rc::into_raw(x);
1332         drop(y);
1333         unsafe {
1334             assert_eq!(**x_ptr, "hello");
1335
1336             let x = Rc::from_raw(x_ptr);
1337             assert_eq!(**x, "hello");
1338
1339             assert_eq!(Rc::try_unwrap(x).map(|x| *x), Ok("hello"));
1340         }
1341     }
1342
1343     #[test]
1344     fn get_mut() {
1345         let mut x = Rc::new(3);
1346         *Rc::get_mut(&mut x).unwrap() = 4;
1347         assert_eq!(*x, 4);
1348         let y = x.clone();
1349         assert!(Rc::get_mut(&mut x).is_none());
1350         drop(y);
1351         assert!(Rc::get_mut(&mut x).is_some());
1352         let _w = Rc::downgrade(&x);
1353         assert!(Rc::get_mut(&mut x).is_none());
1354     }
1355
1356     #[test]
1357     fn test_cowrc_clone_make_unique() {
1358         let mut cow0 = Rc::new(75);
1359         let mut cow1 = cow0.clone();
1360         let mut cow2 = cow1.clone();
1361
1362         assert!(75 == *Rc::make_mut(&mut cow0));
1363         assert!(75 == *Rc::make_mut(&mut cow1));
1364         assert!(75 == *Rc::make_mut(&mut cow2));
1365
1366         *Rc::make_mut(&mut cow0) += 1;
1367         *Rc::make_mut(&mut cow1) += 2;
1368         *Rc::make_mut(&mut cow2) += 3;
1369
1370         assert!(76 == *cow0);
1371         assert!(77 == *cow1);
1372         assert!(78 == *cow2);
1373
1374         // none should point to the same backing memory
1375         assert!(*cow0 != *cow1);
1376         assert!(*cow0 != *cow2);
1377         assert!(*cow1 != *cow2);
1378     }
1379
1380     #[test]
1381     fn test_cowrc_clone_unique2() {
1382         let mut cow0 = Rc::new(75);
1383         let cow1 = cow0.clone();
1384         let cow2 = cow1.clone();
1385
1386         assert!(75 == *cow0);
1387         assert!(75 == *cow1);
1388         assert!(75 == *cow2);
1389
1390         *Rc::make_mut(&mut cow0) += 1;
1391
1392         assert!(76 == *cow0);
1393         assert!(75 == *cow1);
1394         assert!(75 == *cow2);
1395
1396         // cow1 and cow2 should share the same contents
1397         // cow0 should have a unique reference
1398         assert!(*cow0 != *cow1);
1399         assert!(*cow0 != *cow2);
1400         assert!(*cow1 == *cow2);
1401     }
1402
1403     #[test]
1404     fn test_cowrc_clone_weak() {
1405         let mut cow0 = Rc::new(75);
1406         let cow1_weak = Rc::downgrade(&cow0);
1407
1408         assert!(75 == *cow0);
1409         assert!(75 == *cow1_weak.upgrade().unwrap());
1410
1411         *Rc::make_mut(&mut cow0) += 1;
1412
1413         assert!(76 == *cow0);
1414         assert!(cow1_weak.upgrade().is_none());
1415     }
1416
1417     #[test]
1418     fn test_show() {
1419         let foo = Rc::new(75);
1420         assert_eq!(format!("{:?}", foo), "75");
1421     }
1422
1423     #[test]
1424     fn test_unsized() {
1425         let foo: Rc<[i32]> = Rc::new([1, 2, 3]);
1426         assert_eq!(foo, foo.clone());
1427     }
1428
1429     #[test]
1430     fn test_from_owned() {
1431         let foo = 123;
1432         let foo_rc = Rc::from(foo);
1433         assert!(123 == *foo_rc);
1434     }
1435
1436     #[test]
1437     fn test_new_weak() {
1438         let foo: Weak<usize> = Weak::new();
1439         assert!(foo.upgrade().is_none());
1440     }
1441
1442     #[test]
1443     fn test_ptr_eq() {
1444         let five = Rc::new(5);
1445         let same_five = five.clone();
1446         let other_five = Rc::new(5);
1447
1448         assert!(Rc::ptr_eq(&five, &same_five));
1449         assert!(!Rc::ptr_eq(&five, &other_five));
1450     }
1451 }
1452
1453 #[stable(feature = "rust1", since = "1.0.0")]
1454 impl<T: ?Sized> borrow::Borrow<T> for Rc<T> {
1455     fn borrow(&self) -> &T {
1456         &**self
1457     }
1458 }
1459
1460 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1461 impl<T: ?Sized> AsRef<T> for Rc<T> {
1462     fn as_ref(&self) -> &T {
1463         &**self
1464     }
1465 }