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