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