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