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