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