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