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