]> git.lizzy.rs Git - rust.git/blob - src/liballoc/rc.rs
94fe36d01a5a529dd9aa0a18f2a06ca23cbff682
[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. 'Rc' stands for 'Reference
14 //! Counted'.
15 //!
16 //! The type [`Rc<T>`][`Rc`] provides shared ownership of a value of type `T`,
17 //! allocated in the heap. Invoking [`clone`][clone] on [`Rc`] produces a new
18 //! pointer to the same value in the heap. When the last [`Rc`] pointer to a
19 //! given value is destroyed, the pointed-to value is also destroyed.
20 //!
21 //! Shared references in Rust disallow mutation by default, and [`Rc`]
22 //! is no exception: you cannot obtain a mutable reference to
23 //! something inside an [`Rc`]. If you need mutability, put a [`Cell`]
24 //! or [`RefCell`] inside the [`Rc`]; see [an example of mutability
25 //! inside an Rc][mutability].
26 //!
27 //! [`Rc`] uses non-atomic reference counting. This means that overhead is very
28 //! low, but an [`Rc`] cannot be sent between threads, and consequently [`Rc`]
29 //! does not implement [`Send`][send]. As a result, the Rust compiler
30 //! will check *at compile time* that you are not sending [`Rc`]s between
31 //! threads. If you need multi-threaded, atomic reference counting, use
32 //! [`sync::Arc`][arc].
33 //!
34 //! The [`downgrade`][downgrade] method can be used to create a non-owning
35 //! [`Weak`] pointer. A [`Weak`] pointer can be [`upgrade`][upgrade]d
36 //! to an [`Rc`], but this will return [`None`] if the value has
37 //! already been dropped.
38 //!
39 //! A cycle between [`Rc`] pointers will never be deallocated. For this reason,
40 //! [`Weak`] is used to break cycles. For example, a tree could have strong
41 //! [`Rc`] pointers from parent nodes to children, and [`Weak`] pointers from
42 //! children back to their parents.
43 //!
44 //! `Rc<T>` automatically dereferences to `T` (via the [`Deref`] trait),
45 //! so you can call `T`'s methods on a value of type [`Rc<T>`][`Rc`]. To avoid name
46 //! clashes with `T`'s methods, the methods of [`Rc<T>`][`Rc`] itself are [associated
47 //! functions][assoc], called using function-like syntax:
48 //!
49 //! ```
50 //! use std::rc::Rc;
51 //! let my_rc = Rc::new(());
52 //!
53 //! Rc::downgrade(&my_rc);
54 //! ```
55 //!
56 //! [`Weak<T>`][`Weak`] does not auto-dereference to `T`, because the value may have
57 //! already been destroyed.
58 //!
59 //! # Cloning references
60 //!
61 //! Creating a new reference from an existing reference counted pointer is done using the
62 //! `Clone` trait implemented for [`Rc<T>`][`Rc`] and [`Weak<T>`][`Weak`].
63 //!
64 //! ```
65 //! use std::rc::Rc;
66 //! let foo = Rc::new(vec![1.0, 2.0, 3.0]);
67 //! // The two syntaxes below are equivalent.
68 //! let a = foo.clone();
69 //! let b = Rc::clone(&foo);
70 //! // a and b both point to the same memory location as foo.
71 //! ```
72 //!
73 //! The `Rc::clone(&from)` syntax is the most idiomatic because it conveys more explicitly
74 //! the meaning of the code. In the example above, this syntax makes it easier to see that
75 //! this code is creating a new reference rather than copying the whole content of foo.
76 //!
77 //! # Examples
78 //!
79 //! Consider a scenario where a set of `Gadget`s are owned by a given `Owner`.
80 //! We want to have our `Gadget`s point to their `Owner`. We can't do this with
81 //! unique ownership, because more than one gadget may belong to the same
82 //! `Owner`. [`Rc`] allows us to share an `Owner` between multiple `Gadget`s,
83 //! and have the `Owner` remain allocated as long as any `Gadget` points at it.
84 //!
85 //! ```
86 //! use std::rc::Rc;
87 //!
88 //! struct Owner {
89 //!     name: String,
90 //!     // ...other fields
91 //! }
92 //!
93 //! struct Gadget {
94 //!     id: i32,
95 //!     owner: Rc<Owner>,
96 //!     // ...other fields
97 //! }
98 //!
99 //! fn main() {
100 //!     // Create a reference-counted `Owner`.
101 //!     let gadget_owner: Rc<Owner> = Rc::new(
102 //!         Owner {
103 //!             name: "Gadget Man".to_string(),
104 //!         }
105 //!     );
106 //!
107 //!     // Create `Gadget`s belonging to `gadget_owner`. Cloning the `Rc<Owner>`
108 //!     // value gives us a new pointer to the same `Owner` value, incrementing
109 //!     // the reference count in the process.
110 //!     let gadget1 = Gadget {
111 //!         id: 1,
112 //!         owner: Rc::clone(&gadget_owner),
113 //!     };
114 //!     let gadget2 = Gadget {
115 //!         id: 2,
116 //!         owner: Rc::clone(&gadget_owner),
117 //!     };
118 //!
119 //!     // Dispose of our local variable `gadget_owner`.
120 //!     drop(gadget_owner);
121 //!
122 //!     // Despite dropping `gadget_owner`, we're still able to print out the name
123 //!     // of the `Owner` of the `Gadget`s. This is because we've only dropped a
124 //!     // single `Rc<Owner>`, not the `Owner` it points to. As long as there are
125 //!     // other `Rc<Owner>` values pointing at the same `Owner`, it will remain
126 //!     // allocated. The field projection `gadget1.owner.name` works because
127 //!     // `Rc<Owner>` automatically dereferences to `Owner`.
128 //!     println!("Gadget {} owned by {}", gadget1.id, gadget1.owner.name);
129 //!     println!("Gadget {} owned by {}", gadget2.id, gadget2.owner.name);
130 //!
131 //!     // At the end of the function, `gadget1` and `gadget2` are destroyed, and
132 //!     // with them the last counted references to our `Owner`. Gadget Man now
133 //!     // gets destroyed as well.
134 //! }
135 //! ```
136 //!
137 //! If our requirements change, and we also need to be able to traverse from
138 //! `Owner` to `Gadget`, we will run into problems. An [`Rc`] pointer from `Owner`
139 //! to `Gadget` introduces a cycle between the values. This means that their
140 //! reference counts can never reach 0, and the values will remain allocated
141 //! forever: a memory leak. In order to get around this, we can use [`Weak`]
142 //! pointers.
143 //!
144 //! Rust actually makes it somewhat difficult to produce this loop in the first
145 //! place. In order to end up with two values that point at each other, one of
146 //! them needs to be mutable. This is difficult because [`Rc`] enforces
147 //! memory safety by only giving out shared references to the value it wraps,
148 //! and these don't allow direct mutation. We need to wrap the part of the
149 //! value we wish to mutate in a [`RefCell`], which provides *interior
150 //! mutability*: a method to achieve mutability through a shared reference.
151 //! [`RefCell`] enforces Rust's borrowing rules at runtime.
152 //!
153 //! ```
154 //! use std::rc::Rc;
155 //! use std::rc::Weak;
156 //! use std::cell::RefCell;
157 //!
158 //! struct Owner {
159 //!     name: String,
160 //!     gadgets: RefCell<Vec<Weak<Gadget>>>,
161 //!     // ...other fields
162 //! }
163 //!
164 //! struct Gadget {
165 //!     id: i32,
166 //!     owner: Rc<Owner>,
167 //!     // ...other fields
168 //! }
169 //!
170 //! fn main() {
171 //!     // Create a reference-counted `Owner`. Note that we've put the `Owner`'s
172 //!     // vector of `Gadget`s inside a `RefCell` so that we can mutate it through
173 //!     // a shared reference.
174 //!     let gadget_owner: Rc<Owner> = Rc::new(
175 //!         Owner {
176 //!             name: "Gadget Man".to_string(),
177 //!             gadgets: RefCell::new(vec![]),
178 //!         }
179 //!     );
180 //!
181 //!     // Create `Gadget`s belonging to `gadget_owner`, as before.
182 //!     let gadget1 = Rc::new(
183 //!         Gadget {
184 //!             id: 1,
185 //!             owner: Rc::clone(&gadget_owner),
186 //!         }
187 //!     );
188 //!     let gadget2 = Rc::new(
189 //!         Gadget {
190 //!             id: 2,
191 //!             owner: Rc::clone(&gadget_owner),
192 //!         }
193 //!     );
194 //!
195 //!     // Add the `Gadget`s to their `Owner`.
196 //!     {
197 //!         let mut gadgets = gadget_owner.gadgets.borrow_mut();
198 //!         gadgets.push(Rc::downgrade(&gadget1));
199 //!         gadgets.push(Rc::downgrade(&gadget2));
200 //!
201 //!         // `RefCell` dynamic borrow ends here.
202 //!     }
203 //!
204 //!     // Iterate over our `Gadget`s, printing their details out.
205 //!     for gadget_weak in gadget_owner.gadgets.borrow().iter() {
206 //!
207 //!         // `gadget_weak` is a `Weak<Gadget>`. Since `Weak` pointers can't
208 //!         // guarantee the value is still allocated, we need to call
209 //!         // `upgrade`, which returns an `Option<Rc<Gadget>>`.
210 //!         //
211 //!         // In this case we know the value still exists, so we simply
212 //!         // `unwrap` the `Option`. In a more complicated program, you might
213 //!         // need graceful error handling for a `None` result.
214 //!
215 //!         let gadget = gadget_weak.upgrade().unwrap();
216 //!         println!("Gadget {} owned by {}", gadget.id, gadget.owner.name);
217 //!     }
218 //!
219 //!     // At the end of the function, `gadget_owner`, `gadget1`, and `gadget2`
220 //!     // are destroyed. There are now no strong (`Rc`) pointers to the
221 //!     // gadgets, so they are destroyed. This zeroes the reference count on
222 //!     // Gadget Man, so he gets destroyed as well.
223 //! }
224 //! ```
225 //!
226 //! [`Rc`]: struct.Rc.html
227 //! [`Weak`]: struct.Weak.html
228 //! [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
229 //! [`Cell`]: ../../std/cell/struct.Cell.html
230 //! [`RefCell`]: ../../std/cell/struct.RefCell.html
231 //! [send]: ../../std/marker/trait.Send.html
232 //! [arc]: ../../std/sync/struct.Arc.html
233 //! [`Deref`]: ../../std/ops/trait.Deref.html
234 //! [downgrade]: struct.Rc.html#method.downgrade
235 //! [upgrade]: struct.Weak.html#method.upgrade
236 //! [`None`]: ../../std/option/enum.Option.html#variant.None
237 //! [assoc]: ../../book/first-edition/method-syntax.html#associated-functions
238 //! [mutability]: ../../std/cell/index.html#introducing-mutability-inside-of-something-immutable
239
240 #![stable(feature = "rust1", since = "1.0.0")]
241
242 #[cfg(not(test))]
243 use boxed::Box;
244 #[cfg(test)]
245 use std::boxed::Box;
246
247 use core::borrow;
248 use core::cell::Cell;
249 use core::cmp::Ordering;
250 use core::fmt;
251 use core::hash::{Hash, Hasher};
252 use core::intrinsics::abort;
253 use core::marker;
254 use core::marker::Unsize;
255 use core::mem::{self, align_of_val, forget, size_of, size_of_val, uninitialized};
256 use core::ops::Deref;
257 use core::ops::CoerceUnsized;
258 use core::ptr::{self, Shared};
259 use core::convert::From;
260
261 use heap::{allocate, deallocate, box_free};
262 use raw_vec::RawVec;
263
264 struct RcBox<T: ?Sized> {
265     strong: Cell<usize>,
266     weak: Cell<usize>,
267     value: T,
268 }
269
270 /// A single-threaded reference-counting pointer. 'Rc' stands for 'Reference
271 /// Counted'.
272 ///
273 /// See the [module-level documentation](./index.html) for more details.
274 ///
275 /// The inherent methods of `Rc` are all associated functions, which means
276 /// that you have to call them as e.g. [`Rc::get_mut(&mut value)`][get_mut] instead of
277 /// `value.get_mut()`. This avoids conflicts with methods of the inner
278 /// type `T`.
279 ///
280 /// [get_mut]: #method.get_mut
281 #[stable(feature = "rust1", since = "1.0.0")]
282 pub struct Rc<T: ?Sized> {
283     ptr: Shared<RcBox<T>>,
284 }
285
286 #[stable(feature = "rust1", since = "1.0.0")]
287 impl<T: ?Sized> !marker::Send for Rc<T> {}
288 #[stable(feature = "rust1", since = "1.0.0")]
289 impl<T: ?Sized> !marker::Sync for Rc<T> {}
290
291 #[unstable(feature = "coerce_unsized", issue = "27732")]
292 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Rc<U>> for Rc<T> {}
293
294 impl<T> Rc<T> {
295     /// Constructs a new `Rc<T>`.
296     ///
297     /// # Examples
298     ///
299     /// ```
300     /// use std::rc::Rc;
301     ///
302     /// let five = Rc::new(5);
303     /// ```
304     #[stable(feature = "rust1", since = "1.0.0")]
305     pub fn new(value: T) -> Rc<T> {
306         unsafe {
307             Rc {
308                 // there is an implicit weak pointer owned by all the strong
309                 // pointers, which ensures that the weak destructor never frees
310                 // the allocation while the strong destructor is running, even
311                 // if the weak pointer is stored inside the strong one.
312                 ptr: Shared::new(Box::into_raw(box RcBox {
313                     strong: Cell::new(1),
314                     weak: Cell::new(1),
315                     value: value,
316                 })),
317             }
318         }
319     }
320
321     /// Returns the contained value, if the `Rc` has exactly one strong reference.
322     ///
323     /// Otherwise, an [`Err`][result] is returned with the same `Rc` that was
324     /// passed in.
325     ///
326     /// This will succeed even if there are outstanding weak references.
327     ///
328     /// [result]: ../../std/result/enum.Result.html
329     ///
330     /// # Examples
331     ///
332     /// ```
333     /// use std::rc::Rc;
334     ///
335     /// let x = Rc::new(3);
336     /// assert_eq!(Rc::try_unwrap(x), Ok(3));
337     ///
338     /// let x = Rc::new(4);
339     /// let _y = Rc::clone(&x);
340     /// assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4);
341     /// ```
342     #[inline]
343     #[stable(feature = "rc_unique", since = "1.4.0")]
344     pub fn try_unwrap(this: Self) -> Result<T, Self> {
345         if Rc::strong_count(&this) == 1 {
346             unsafe {
347                 let val = ptr::read(&*this); // copy the contained object
348
349                 // Indicate to Weaks that they can't be promoted by decrememting
350                 // the strong count, and then remove the implicit "strong weak"
351                 // pointer while also handling drop logic by just crafting a
352                 // fake Weak.
353                 this.dec_strong();
354                 let _weak = Weak { ptr: this.ptr };
355                 forget(this);
356                 Ok(val)
357             }
358         } else {
359             Err(this)
360         }
361     }
362
363     /// Consumes the `Rc`, returning the wrapped pointer.
364     ///
365     /// To avoid a memory leak the pointer must be converted back to an `Rc` using
366     /// [`Rc::from_raw`][from_raw].
367     ///
368     /// [from_raw]: struct.Rc.html#method.from_raw
369     ///
370     /// # Examples
371     ///
372     /// ```
373     /// use std::rc::Rc;
374     ///
375     /// let x = Rc::new(10);
376     /// let x_ptr = Rc::into_raw(x);
377     /// assert_eq!(unsafe { *x_ptr }, 10);
378     /// ```
379     #[stable(feature = "rc_raw", since = "1.17.0")]
380     pub fn into_raw(this: Self) -> *const T {
381         let ptr: *const T = &*this;
382         mem::forget(this);
383         ptr
384     }
385
386     /// Constructs an `Rc` from a raw pointer.
387     ///
388     /// The raw pointer must have been previously returned by a call to a
389     /// [`Rc::into_raw`][into_raw].
390     ///
391     /// This function is unsafe because improper use may lead to memory problems. For example, a
392     /// double-free may occur if the function is called twice on the same raw pointer.
393     ///
394     /// [into_raw]: struct.Rc.html#method.into_raw
395     ///
396     /// # Examples
397     ///
398     /// ```
399     /// use std::rc::Rc;
400     ///
401     /// let x = Rc::new(10);
402     /// let x_ptr = Rc::into_raw(x);
403     ///
404     /// unsafe {
405     ///     // Convert back to an `Rc` to prevent leak.
406     ///     let x = Rc::from_raw(x_ptr);
407     ///     assert_eq!(*x, 10);
408     ///
409     ///     // Further calls to `Rc::from_raw(x_ptr)` would be memory unsafe.
410     /// }
411     ///
412     /// // The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling!
413     /// ```
414     #[stable(feature = "rc_raw", since = "1.17.0")]
415     pub unsafe fn from_raw(ptr: *const T) -> Self {
416         // To find the corresponding pointer to the `RcBox` we need to subtract the offset of the
417         // `value` field from the pointer.
418
419         let ptr = (ptr as *const u8).offset(-offset_of!(RcBox<T>, value));
420         Rc {
421             ptr: Shared::new(ptr as *mut u8 as *mut _)
422         }
423     }
424 }
425
426 impl Rc<str> {
427     /// Constructs a new `Rc<str>` from a string slice.
428     #[doc(hidden)]
429     #[unstable(feature = "rustc_private",
430                reason = "for internal use in rustc",
431                issue = "27812")]
432     pub fn __from_str(value: &str) -> Rc<str> {
433         unsafe {
434             // Allocate enough space for `RcBox<str>`.
435             let aligned_len = 2 + (value.len() + size_of::<usize>() - 1) / size_of::<usize>();
436             let vec = RawVec::<usize>::with_capacity(aligned_len);
437             let ptr = vec.ptr();
438             forget(vec);
439             // Initialize fields of `RcBox<str>`.
440             *ptr.offset(0) = 1; // strong: Cell::new(1)
441             *ptr.offset(1) = 1; // weak: Cell::new(1)
442             ptr::copy_nonoverlapping(value.as_ptr(), ptr.offset(2) as *mut u8, value.len());
443             // Combine the allocation address and the string length into a fat pointer to `RcBox`.
444             let rcbox_ptr: *mut RcBox<str> = mem::transmute([ptr as usize, value.len()]);
445             assert!(aligned_len * size_of::<usize>() == size_of_val(&*rcbox_ptr));
446             Rc { ptr: Shared::new(rcbox_ptr) }
447         }
448     }
449 }
450
451 impl<T> Rc<[T]> {
452     /// Constructs a new `Rc<[T]>` from a `Box<[T]>`.
453     #[doc(hidden)]
454     #[unstable(feature = "rustc_private",
455                reason = "for internal use in rustc",
456                issue = "27812")]
457     pub fn __from_array(value: Box<[T]>) -> Rc<[T]> {
458         unsafe {
459             let ptr: *mut RcBox<[T]> =
460                 mem::transmute([mem::align_of::<RcBox<[T; 1]>>(), value.len()]);
461             // FIXME(custom-DST): creating this invalid &[T] is dubiously defined,
462             // we should have a better way of getting the size/align
463             // of a DST from its unsized part.
464             let ptr = allocate(size_of_val(&*ptr), align_of_val(&*ptr));
465             let ptr: *mut RcBox<[T]> = mem::transmute([ptr as usize, value.len()]);
466
467             // Initialize the new RcBox.
468             ptr::write(&mut (*ptr).strong, Cell::new(1));
469             ptr::write(&mut (*ptr).weak, Cell::new(1));
470             ptr::copy_nonoverlapping(
471                 value.as_ptr(),
472                 &mut (*ptr).value as *mut [T] as *mut T,
473                 value.len());
474
475             // Free the original allocation without freeing its (moved) contents.
476             box_free(Box::into_raw(value));
477
478             Rc { ptr: Shared::new(ptr as *mut _) }
479         }
480     }
481 }
482
483 impl<T: ?Sized> Rc<T> {
484     /// Creates a new [`Weak`][weak] pointer to this value.
485     ///
486     /// [weak]: struct.Weak.html
487     ///
488     /// # Examples
489     ///
490     /// ```
491     /// use std::rc::Rc;
492     ///
493     /// let five = Rc::new(5);
494     ///
495     /// let weak_five = Rc::downgrade(&five);
496     /// ```
497     #[stable(feature = "rc_weak", since = "1.4.0")]
498     pub fn downgrade(this: &Self) -> Weak<T> {
499         this.inc_weak();
500         Weak { ptr: this.ptr }
501     }
502
503     /// Gets the number of [`Weak`][weak] pointers to this value.
504     ///
505     /// [weak]: struct.Weak.html
506     ///
507     /// # Examples
508     ///
509     /// ```
510     /// use std::rc::Rc;
511     ///
512     /// let five = Rc::new(5);
513     /// let _weak_five = Rc::downgrade(&five);
514     ///
515     /// assert_eq!(1, Rc::weak_count(&five));
516     /// ```
517     #[inline]
518     #[stable(feature = "rc_counts", since = "1.15.0")]
519     pub fn weak_count(this: &Self) -> usize {
520         this.weak() - 1
521     }
522
523     /// Gets the number of strong (`Rc`) pointers to this value.
524     ///
525     /// # Examples
526     ///
527     /// ```
528     /// use std::rc::Rc;
529     ///
530     /// let five = Rc::new(5);
531     /// let _also_five = Rc::clone(&five);
532     ///
533     /// assert_eq!(2, Rc::strong_count(&five));
534     /// ```
535     #[inline]
536     #[stable(feature = "rc_counts", since = "1.15.0")]
537     pub fn strong_count(this: &Self) -> usize {
538         this.strong()
539     }
540
541     /// Returns true if there are no other `Rc` or [`Weak`][weak] pointers to
542     /// this inner value.
543     ///
544     /// [weak]: struct.Weak.html
545     #[inline]
546     fn is_unique(this: &Self) -> bool {
547         Rc::weak_count(this) == 0 && Rc::strong_count(this) == 1
548     }
549
550     /// Returns a mutable reference to the inner value, if there are
551     /// no other `Rc` or [`Weak`][weak] pointers to the same value.
552     ///
553     /// Returns [`None`] otherwise, because it is not safe to
554     /// mutate a shared value.
555     ///
556     /// See also [`make_mut`][make_mut], which will [`clone`][clone]
557     /// the inner value when it's shared.
558     ///
559     /// [weak]: struct.Weak.html
560     /// [`None`]: ../../std/option/enum.Option.html#variant.None
561     /// [make_mut]: struct.Rc.html#method.make_mut
562     /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
563     ///
564     /// # Examples
565     ///
566     /// ```
567     /// use std::rc::Rc;
568     ///
569     /// let mut x = Rc::new(3);
570     /// *Rc::get_mut(&mut x).unwrap() = 4;
571     /// assert_eq!(*x, 4);
572     ///
573     /// let _y = Rc::clone(&x);
574     /// assert!(Rc::get_mut(&mut x).is_none());
575     /// ```
576     #[inline]
577     #[stable(feature = "rc_unique", since = "1.4.0")]
578     pub fn get_mut(this: &mut Self) -> Option<&mut T> {
579         if Rc::is_unique(this) {
580             unsafe {
581                 Some(&mut this.ptr.as_mut().value)
582             }
583         } else {
584             None
585         }
586     }
587
588     #[inline]
589     #[stable(feature = "ptr_eq", since = "1.17.0")]
590     /// Returns true if the two `Rc`s point to the same value (not
591     /// just values that compare as equal).
592     ///
593     /// # Examples
594     ///
595     /// ```
596     /// use std::rc::Rc;
597     ///
598     /// let five = Rc::new(5);
599     /// let same_five = Rc::clone(&five);
600     /// let other_five = Rc::new(5);
601     ///
602     /// assert!(Rc::ptr_eq(&five, &same_five));
603     /// assert!(!Rc::ptr_eq(&five, &other_five));
604     /// ```
605     pub fn ptr_eq(this: &Self, other: &Self) -> bool {
606         this.ptr.as_ptr() == other.ptr.as_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 = Rc::clone(&data);    // 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.as_ref().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         unsafe {
664             &mut this.ptr.as_mut().value
665         }
666     }
667 }
668
669 #[stable(feature = "rust1", since = "1.0.0")]
670 impl<T: ?Sized> Deref for Rc<T> {
671     type Target = T;
672
673     #[inline(always)]
674     fn deref(&self) -> &T {
675         &self.inner().value
676     }
677 }
678
679 #[stable(feature = "rust1", since = "1.0.0")]
680 unsafe impl<#[may_dangle] T: ?Sized> Drop for Rc<T> {
681     /// Drops the `Rc`.
682     ///
683     /// This will decrement the strong reference count. If the strong reference
684     /// count reaches zero then the only other references (if any) are
685     /// [`Weak`][weak], so we `drop` the inner value.
686     ///
687     /// [weak]: struct.Weak.html
688     ///
689     /// # Examples
690     ///
691     /// ```
692     /// use std::rc::Rc;
693     ///
694     /// struct Foo;
695     ///
696     /// impl Drop for Foo {
697     ///     fn drop(&mut self) {
698     ///         println!("dropped!");
699     ///     }
700     /// }
701     ///
702     /// let foo  = Rc::new(Foo);
703     /// let foo2 = Rc::clone(&foo);
704     ///
705     /// drop(foo);    // Doesn't print anything
706     /// drop(foo2);   // Prints "dropped!"
707     /// ```
708     fn drop(&mut self) {
709         unsafe {
710             let ptr = self.ptr.as_ptr();
711
712             self.dec_strong();
713             if self.strong() == 0 {
714                 // destroy the contained object
715                 ptr::drop_in_place(self.ptr.as_mut());
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     /// Rc::clone(&five);
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 /// `Weak` is a version of [`Rc`] that holds a non-owning reference to the
964 /// managed value. The value is accessed by calling [`upgrade`] on the `Weak`
965 /// pointer, which returns an [`Option`]`<`[`Rc`]`<T>>`.
966 ///
967 /// Since a `Weak` reference does not count towards ownership, it will not
968 /// prevent the inner value from being dropped, and `Weak` itself makes no
969 /// guarantees about the value still being present and may return [`None`]
970 /// when [`upgrade`]d.
971 ///
972 /// A `Weak` pointer is useful for keeping a temporary reference to the value
973 /// within [`Rc`] without extending its lifetime. It is also used to prevent
974 /// circular references between [`Rc`] pointers, since mutual owning references
975 /// would never allow either [`Arc`] to be dropped. For example, a tree could
976 /// have strong [`Rc`] pointers from parent nodes to children, and `Weak`
977 /// pointers from children back to their parents.
978 ///
979 /// The typical way to obtain a `Weak` pointer is to call [`Rc::downgrade`].
980 ///
981 /// [`Rc`]: struct.Rc.html
982 /// [`Rc::downgrade`]: struct.Rc.html#method.downgrade
983 /// [`upgrade`]: struct.Weak.html#method.upgrade
984 /// [`Option`]: ../../std/option/enum.Option.html
985 /// [`None`]: ../../std/option/enum.Option.html#variant.None
986 #[stable(feature = "rc_weak", since = "1.4.0")]
987 pub struct Weak<T: ?Sized> {
988     ptr: Shared<RcBox<T>>,
989 }
990
991 #[stable(feature = "rc_weak", since = "1.4.0")]
992 impl<T: ?Sized> !marker::Send for Weak<T> {}
993 #[stable(feature = "rc_weak", since = "1.4.0")]
994 impl<T: ?Sized> !marker::Sync for Weak<T> {}
995
996 #[unstable(feature = "coerce_unsized", issue = "27732")]
997 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {}
998
999 impl<T> Weak<T> {
1000     /// Constructs a new `Weak<T>`, allocating memory for `T` without initializing
1001     /// it. Calling [`upgrade`] on the return value always gives [`None`].
1002     ///
1003     /// [`upgrade`]: struct.Weak.html#method.upgrade
1004     /// [`None`]: ../../std/option/enum.Option.html
1005     ///
1006     /// # Examples
1007     ///
1008     /// ```
1009     /// use std::rc::Weak;
1010     ///
1011     /// let empty: Weak<i64> = Weak::new();
1012     /// assert!(empty.upgrade().is_none());
1013     /// ```
1014     #[stable(feature = "downgraded_weak", since = "1.10.0")]
1015     pub fn new() -> Weak<T> {
1016         unsafe {
1017             Weak {
1018                 ptr: Shared::new(Box::into_raw(box RcBox {
1019                     strong: Cell::new(0),
1020                     weak: Cell::new(1),
1021                     value: uninitialized(),
1022                 })),
1023             }
1024         }
1025     }
1026 }
1027
1028 impl<T: ?Sized> Weak<T> {
1029     /// Attempts to upgrade the `Weak` pointer to an [`Rc`], extending
1030     /// the lifetime of the value if successful.
1031     ///
1032     /// Returns [`None`] if the value has since been dropped.
1033     ///
1034     /// [`Rc`]: struct.Rc.html
1035     /// [`None`]: ../../std/option/enum.Option.html
1036     ///
1037     /// # Examples
1038     ///
1039     /// ```
1040     /// use std::rc::Rc;
1041     ///
1042     /// let five = Rc::new(5);
1043     ///
1044     /// let weak_five = Rc::downgrade(&five);
1045     ///
1046     /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
1047     /// assert!(strong_five.is_some());
1048     ///
1049     /// // Destroy all strong pointers.
1050     /// drop(strong_five);
1051     /// drop(five);
1052     ///
1053     /// assert!(weak_five.upgrade().is_none());
1054     /// ```
1055     #[stable(feature = "rc_weak", since = "1.4.0")]
1056     pub fn upgrade(&self) -> Option<Rc<T>> {
1057         if self.strong() == 0 {
1058             None
1059         } else {
1060             self.inc_strong();
1061             Some(Rc { ptr: self.ptr })
1062         }
1063     }
1064 }
1065
1066 #[stable(feature = "rc_weak", since = "1.4.0")]
1067 impl<T: ?Sized> Drop for Weak<T> {
1068     /// Drops the `Weak` pointer.
1069     ///
1070     /// # Examples
1071     ///
1072     /// ```
1073     /// use std::rc::{Rc, Weak};
1074     ///
1075     /// struct Foo;
1076     ///
1077     /// impl Drop for Foo {
1078     ///     fn drop(&mut self) {
1079     ///         println!("dropped!");
1080     ///     }
1081     /// }
1082     ///
1083     /// let foo = Rc::new(Foo);
1084     /// let weak_foo = Rc::downgrade(&foo);
1085     /// let other_weak_foo = Weak::clone(&weak_foo);
1086     ///
1087     /// drop(weak_foo);   // Doesn't print anything
1088     /// drop(foo);        // Prints "dropped!"
1089     ///
1090     /// assert!(other_weak_foo.upgrade().is_none());
1091     /// ```
1092     fn drop(&mut self) {
1093         unsafe {
1094             let ptr = self.ptr.as_ptr();
1095
1096             self.dec_weak();
1097             // the weak count starts at 1, and will only go to zero if all
1098             // the strong pointers have disappeared.
1099             if self.weak() == 0 {
1100                 deallocate(ptr as *mut u8, size_of_val(&*ptr), align_of_val(&*ptr))
1101             }
1102         }
1103     }
1104 }
1105
1106 #[stable(feature = "rc_weak", since = "1.4.0")]
1107 impl<T: ?Sized> Clone for Weak<T> {
1108     /// Makes a clone of the `Weak` pointer that points to the same value.
1109     ///
1110     /// # Examples
1111     ///
1112     /// ```
1113     /// use std::rc::{Rc, Weak};
1114     ///
1115     /// let weak_five = Rc::downgrade(&Rc::new(5));
1116     ///
1117     /// Weak::clone(&weak_five);
1118     /// ```
1119     #[inline]
1120     fn clone(&self) -> Weak<T> {
1121         self.inc_weak();
1122         Weak { ptr: self.ptr }
1123     }
1124 }
1125
1126 #[stable(feature = "rc_weak", since = "1.4.0")]
1127 impl<T: ?Sized + fmt::Debug> fmt::Debug for Weak<T> {
1128     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1129         write!(f, "(Weak)")
1130     }
1131 }
1132
1133 #[stable(feature = "downgraded_weak", since = "1.10.0")]
1134 impl<T> Default for Weak<T> {
1135     /// Constructs a new `Weak<T>`, allocating memory for `T` without initializing
1136     /// it. Calling [`upgrade`] on the return value always gives [`None`].
1137     ///
1138     /// [`upgrade`]: struct.Weak.html#method.upgrade
1139     /// [`None`]: ../../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             self.ptr.as_ref()
1203         }
1204     }
1205 }
1206
1207 impl<T: ?Sized> RcBoxPtr<T> for Weak<T> {
1208     #[inline(always)]
1209     fn inner(&self) -> &RcBox<T> {
1210         unsafe {
1211             self.ptr.as_ref()
1212         }
1213     }
1214 }
1215
1216 #[cfg(test)]
1217 mod tests {
1218     use super::{Rc, Weak};
1219     use std::boxed::Box;
1220     use std::cell::RefCell;
1221     use std::option::Option;
1222     use std::option::Option::{None, Some};
1223     use std::result::Result::{Err, Ok};
1224     use std::mem::drop;
1225     use std::clone::Clone;
1226     use std::convert::From;
1227
1228     #[test]
1229     fn test_clone() {
1230         let x = Rc::new(RefCell::new(5));
1231         let y = x.clone();
1232         *x.borrow_mut() = 20;
1233         assert_eq!(*y.borrow(), 20);
1234     }
1235
1236     #[test]
1237     fn test_simple() {
1238         let x = Rc::new(5);
1239         assert_eq!(*x, 5);
1240     }
1241
1242     #[test]
1243     fn test_simple_clone() {
1244         let x = Rc::new(5);
1245         let y = x.clone();
1246         assert_eq!(*x, 5);
1247         assert_eq!(*y, 5);
1248     }
1249
1250     #[test]
1251     fn test_destructor() {
1252         let x: Rc<Box<_>> = Rc::new(box 5);
1253         assert_eq!(**x, 5);
1254     }
1255
1256     #[test]
1257     fn test_live() {
1258         let x = Rc::new(5);
1259         let y = Rc::downgrade(&x);
1260         assert!(y.upgrade().is_some());
1261     }
1262
1263     #[test]
1264     fn test_dead() {
1265         let x = Rc::new(5);
1266         let y = Rc::downgrade(&x);
1267         drop(x);
1268         assert!(y.upgrade().is_none());
1269     }
1270
1271     #[test]
1272     fn weak_self_cyclic() {
1273         struct Cycle {
1274             x: RefCell<Option<Weak<Cycle>>>,
1275         }
1276
1277         let a = Rc::new(Cycle { x: RefCell::new(None) });
1278         let b = Rc::downgrade(&a.clone());
1279         *a.x.borrow_mut() = Some(b);
1280
1281         // hopefully we don't double-free (or leak)...
1282     }
1283
1284     #[test]
1285     fn is_unique() {
1286         let x = Rc::new(3);
1287         assert!(Rc::is_unique(&x));
1288         let y = x.clone();
1289         assert!(!Rc::is_unique(&x));
1290         drop(y);
1291         assert!(Rc::is_unique(&x));
1292         let w = Rc::downgrade(&x);
1293         assert!(!Rc::is_unique(&x));
1294         drop(w);
1295         assert!(Rc::is_unique(&x));
1296     }
1297
1298     #[test]
1299     fn test_strong_count() {
1300         let a = Rc::new(0);
1301         assert!(Rc::strong_count(&a) == 1);
1302         let w = Rc::downgrade(&a);
1303         assert!(Rc::strong_count(&a) == 1);
1304         let b = w.upgrade().expect("upgrade of live rc failed");
1305         assert!(Rc::strong_count(&b) == 2);
1306         assert!(Rc::strong_count(&a) == 2);
1307         drop(w);
1308         drop(a);
1309         assert!(Rc::strong_count(&b) == 1);
1310         let c = b.clone();
1311         assert!(Rc::strong_count(&b) == 2);
1312         assert!(Rc::strong_count(&c) == 2);
1313     }
1314
1315     #[test]
1316     fn test_weak_count() {
1317         let a = Rc::new(0);
1318         assert!(Rc::strong_count(&a) == 1);
1319         assert!(Rc::weak_count(&a) == 0);
1320         let w = Rc::downgrade(&a);
1321         assert!(Rc::strong_count(&a) == 1);
1322         assert!(Rc::weak_count(&a) == 1);
1323         drop(w);
1324         assert!(Rc::strong_count(&a) == 1);
1325         assert!(Rc::weak_count(&a) == 0);
1326         let c = a.clone();
1327         assert!(Rc::strong_count(&a) == 2);
1328         assert!(Rc::weak_count(&a) == 0);
1329         drop(c);
1330     }
1331
1332     #[test]
1333     fn try_unwrap() {
1334         let x = Rc::new(3);
1335         assert_eq!(Rc::try_unwrap(x), Ok(3));
1336         let x = Rc::new(4);
1337         let _y = x.clone();
1338         assert_eq!(Rc::try_unwrap(x), Err(Rc::new(4)));
1339         let x = Rc::new(5);
1340         let _w = Rc::downgrade(&x);
1341         assert_eq!(Rc::try_unwrap(x), Ok(5));
1342     }
1343
1344     #[test]
1345     fn into_from_raw() {
1346         let x = Rc::new(box "hello");
1347         let y = x.clone();
1348
1349         let x_ptr = Rc::into_raw(x);
1350         drop(y);
1351         unsafe {
1352             assert_eq!(**x_ptr, "hello");
1353
1354             let x = Rc::from_raw(x_ptr);
1355             assert_eq!(**x, "hello");
1356
1357             assert_eq!(Rc::try_unwrap(x).map(|x| *x), Ok("hello"));
1358         }
1359     }
1360
1361     #[test]
1362     fn get_mut() {
1363         let mut x = Rc::new(3);
1364         *Rc::get_mut(&mut x).unwrap() = 4;
1365         assert_eq!(*x, 4);
1366         let y = x.clone();
1367         assert!(Rc::get_mut(&mut x).is_none());
1368         drop(y);
1369         assert!(Rc::get_mut(&mut x).is_some());
1370         let _w = Rc::downgrade(&x);
1371         assert!(Rc::get_mut(&mut x).is_none());
1372     }
1373
1374     #[test]
1375     fn test_cowrc_clone_make_unique() {
1376         let mut cow0 = Rc::new(75);
1377         let mut cow1 = cow0.clone();
1378         let mut cow2 = cow1.clone();
1379
1380         assert!(75 == *Rc::make_mut(&mut cow0));
1381         assert!(75 == *Rc::make_mut(&mut cow1));
1382         assert!(75 == *Rc::make_mut(&mut cow2));
1383
1384         *Rc::make_mut(&mut cow0) += 1;
1385         *Rc::make_mut(&mut cow1) += 2;
1386         *Rc::make_mut(&mut cow2) += 3;
1387
1388         assert!(76 == *cow0);
1389         assert!(77 == *cow1);
1390         assert!(78 == *cow2);
1391
1392         // none should point to the same backing memory
1393         assert!(*cow0 != *cow1);
1394         assert!(*cow0 != *cow2);
1395         assert!(*cow1 != *cow2);
1396     }
1397
1398     #[test]
1399     fn test_cowrc_clone_unique2() {
1400         let mut cow0 = Rc::new(75);
1401         let cow1 = cow0.clone();
1402         let cow2 = cow1.clone();
1403
1404         assert!(75 == *cow0);
1405         assert!(75 == *cow1);
1406         assert!(75 == *cow2);
1407
1408         *Rc::make_mut(&mut cow0) += 1;
1409
1410         assert!(76 == *cow0);
1411         assert!(75 == *cow1);
1412         assert!(75 == *cow2);
1413
1414         // cow1 and cow2 should share the same contents
1415         // cow0 should have a unique reference
1416         assert!(*cow0 != *cow1);
1417         assert!(*cow0 != *cow2);
1418         assert!(*cow1 == *cow2);
1419     }
1420
1421     #[test]
1422     fn test_cowrc_clone_weak() {
1423         let mut cow0 = Rc::new(75);
1424         let cow1_weak = Rc::downgrade(&cow0);
1425
1426         assert!(75 == *cow0);
1427         assert!(75 == *cow1_weak.upgrade().unwrap());
1428
1429         *Rc::make_mut(&mut cow0) += 1;
1430
1431         assert!(76 == *cow0);
1432         assert!(cow1_weak.upgrade().is_none());
1433     }
1434
1435     #[test]
1436     fn test_show() {
1437         let foo = Rc::new(75);
1438         assert_eq!(format!("{:?}", foo), "75");
1439     }
1440
1441     #[test]
1442     fn test_unsized() {
1443         let foo: Rc<[i32]> = Rc::new([1, 2, 3]);
1444         assert_eq!(foo, foo.clone());
1445     }
1446
1447     #[test]
1448     fn test_from_owned() {
1449         let foo = 123;
1450         let foo_rc = Rc::from(foo);
1451         assert!(123 == *foo_rc);
1452     }
1453
1454     #[test]
1455     fn test_new_weak() {
1456         let foo: Weak<usize> = Weak::new();
1457         assert!(foo.upgrade().is_none());
1458     }
1459
1460     #[test]
1461     fn test_ptr_eq() {
1462         let five = Rc::new(5);
1463         let same_five = five.clone();
1464         let other_five = Rc::new(5);
1465
1466         assert!(Rc::ptr_eq(&five, &same_five));
1467         assert!(!Rc::ptr_eq(&five, &other_five));
1468     }
1469 }
1470
1471 #[stable(feature = "rust1", since = "1.0.0")]
1472 impl<T: ?Sized> borrow::Borrow<T> for Rc<T> {
1473     fn borrow(&self) -> &T {
1474         &**self
1475     }
1476 }
1477
1478 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1479 impl<T: ?Sized> AsRef<T> for Rc<T> {
1480     fn as_ref(&self) -> &T {
1481         &**self
1482     }
1483 }