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