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