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