]> git.lizzy.rs Git - rust.git/blob - src/liballoc/rc.rs
da803f57a59d3a2324ca9e0189975861745ab61b
[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 //! Thread-local reference-counted boxes (the `Rc<T>` type).
14 //!
15 //! The `Rc<T>` type provides shared ownership of an immutable value.
16 //! Destruction is deterministic, and will occur as soon as the last owner is
17 //! gone. It is marked as non-sendable because it avoids the overhead of atomic
18 //! reference counting.
19 //!
20 //! The `downgrade` method can be used to create a non-owning `Weak<T>` pointer
21 //! to the box. A `Weak<T>` pointer can be upgraded to an `Rc<T>` pointer, but
22 //! will return `None` if the value has already been dropped.
23 //!
24 //! For example, a tree with parent pointers can be represented by putting the
25 //! nodes behind strong `Rc<T>` pointers, and then storing the parent pointers
26 //! as `Weak<T>` pointers.
27 //!
28 //! # Examples
29 //!
30 //! Consider a scenario where a set of `Gadget`s are owned by a given `Owner`.
31 //! We want to have our `Gadget`s point to their `Owner`. We can't do this with
32 //! unique ownership, because more than one gadget may belong to the same
33 //! `Owner`. `Rc<T>` allows us to share an `Owner` between multiple `Gadget`s,
34 //! and have the `Owner` remain allocated as long as any `Gadget` points at it.
35 //!
36 //! ```rust
37 //! use std::rc::Rc;
38 //!
39 //! struct Owner {
40 //!     name: String
41 //!     // ...other fields
42 //! }
43 //!
44 //! struct Gadget {
45 //!     id: i32,
46 //!     owner: Rc<Owner>
47 //!     // ...other fields
48 //! }
49 //!
50 //! fn main() {
51 //!     // Create a reference counted Owner.
52 //!     let gadget_owner : Rc<Owner> = Rc::new(
53 //!         Owner { name: String::from("Gadget Man") }
54 //!     );
55 //!
56 //!     // Create Gadgets belonging to gadget_owner. To increment the reference
57 //!     // count we clone the `Rc<T>` object.
58 //!     let gadget1 = Gadget { id: 1, owner: gadget_owner.clone() };
59 //!     let gadget2 = Gadget { id: 2, owner: gadget_owner.clone() };
60 //!
61 //!     drop(gadget_owner);
62 //!
63 //!     // Despite dropping gadget_owner, we're still able to print out the name
64 //!     // of the Owner of the Gadgets. This is because we've only dropped the
65 //!     // reference count object, not the Owner it wraps. As long as there are
66 //!     // other `Rc<T>` objects pointing at the same Owner, it will remain
67 //!     // allocated. Notice that the `Rc<T>` wrapper around Gadget.owner gets
68 //!     // automatically dereferenced for us.
69 //!     println!("Gadget {} owned by {}", gadget1.id, gadget1.owner.name);
70 //!     println!("Gadget {} owned by {}", gadget2.id, gadget2.owner.name);
71 //!
72 //!     // At the end of the method, gadget1 and gadget2 get destroyed, and with
73 //!     // them the last counted references to our Owner. Gadget Man now gets
74 //!     // destroyed as well.
75 //! }
76 //! ```
77 //!
78 //! If our requirements change, and we also need to be able to traverse from
79 //! Owner → Gadget, we will run into problems: an `Rc<T>` pointer from Owner
80 //! → Gadget introduces a cycle between the objects. This means that their
81 //! reference counts can never reach 0, and the objects will remain allocated: a
82 //! memory leak. In order to get around this, we can use `Weak<T>` pointers.
83 //! These pointers don't contribute to the total count.
84 //!
85 //! Rust actually makes it somewhat difficult to produce this loop in the first
86 //! place: in order to end up with two objects that point at each other, one of
87 //! them needs to be mutable. This is problematic because `Rc<T>` enforces
88 //! memory safety by only giving out shared references to the object it wraps,
89 //! and these don't allow direct mutation. We need to wrap the part of the
90 //! object we wish to mutate in a `RefCell`, which provides *interior
91 //! mutability*: a method to achieve mutability through a shared reference.
92 //! `RefCell` enforces Rust's borrowing rules at runtime.  Read the `Cell`
93 //! documentation for more details on interior mutability.
94 //!
95 //! ```rust
96 //! use std::rc::Rc;
97 //! use std::rc::Weak;
98 //! use std::cell::RefCell;
99 //!
100 //! struct Owner {
101 //!     name: String,
102 //!     gadgets: RefCell<Vec<Weak<Gadget>>>,
103 //!     // ...other fields
104 //! }
105 //!
106 //! struct Gadget {
107 //!     id: i32,
108 //!     owner: Rc<Owner>,
109 //!     // ...other fields
110 //! }
111 //!
112 //! fn main() {
113 //!     // Create a reference counted Owner. Note the fact that we've put the
114 //!     // Owner's vector of Gadgets inside a RefCell so that we can mutate it
115 //!     // through a shared reference.
116 //!     let gadget_owner : Rc<Owner> = Rc::new(
117 //!         Owner {
118 //!             name: "Gadget Man".to_string(),
119 //!             gadgets: RefCell::new(Vec::new()),
120 //!         }
121 //!     );
122 //!
123 //!     // Create Gadgets belonging to gadget_owner as before.
124 //!     let gadget1 = Rc::new(Gadget{id: 1, owner: gadget_owner.clone()});
125 //!     let gadget2 = Rc::new(Gadget{id: 2, owner: gadget_owner.clone()});
126 //!
127 //!     // Add the Gadgets to their Owner. To do this we mutably borrow from
128 //!     // the RefCell holding the Owner's Gadgets.
129 //!     gadget_owner.gadgets.borrow_mut().push(Rc::downgrade(&gadget1));
130 //!     gadget_owner.gadgets.borrow_mut().push(Rc::downgrade(&gadget2));
131 //!
132 //!     // Iterate over our Gadgets, printing their details out
133 //!     for gadget_opt in gadget_owner.gadgets.borrow().iter() {
134 //!
135 //!         // gadget_opt is a Weak<Gadget>. Since weak pointers can't guarantee
136 //!         // that their object is still allocated, we need to call upgrade()
137 //!         // on them to turn them into a strong reference. This returns an
138 //!         // Option, which contains a reference to our object if it still
139 //!         // exists.
140 //!         let gadget = gadget_opt.upgrade().unwrap();
141 //!         println!("Gadget {} owned by {}", gadget.id, gadget.owner.name);
142 //!     }
143 //!
144 //!     // At the end of the method, gadget_owner, gadget1 and gadget2 get
145 //!     // destroyed. There are now no strong (`Rc<T>`) references to the gadgets.
146 //!     // Once they get destroyed, the Gadgets get destroyed. This zeroes the
147 //!     // reference count on Gadget Man, they get destroyed as well.
148 //! }
149 //! ```
150
151 #![stable(feature = "rust1", since = "1.0.0")]
152
153 #[cfg(not(test))]
154 use boxed::Box;
155 #[cfg(test)]
156 use std::boxed::Box;
157
158 use core::borrow;
159 use core::cell::Cell;
160 use core::cmp::Ordering;
161 use core::fmt;
162 use core::hash::{Hasher, Hash};
163 use core::intrinsics::{assume, abort};
164 use core::marker;
165 use core::marker::Unsize;
166 use core::mem::{self, align_of_val, size_of_val, forget, uninitialized};
167 use core::ops::Deref;
168 use core::ops::CoerceUnsized;
169 use core::ptr::{self, Shared};
170 use core::convert::From;
171
172 use heap::deallocate;
173
174 struct RcBox<T: ?Sized> {
175     strong: Cell<usize>,
176     weak: Cell<usize>,
177     value: T,
178 }
179
180
181 /// A reference-counted pointer type over an immutable value.
182 ///
183 /// See the [module level documentation](./index.html) for more details.
184 #[unsafe_no_drop_flag]
185 #[stable(feature = "rust1", since = "1.0.0")]
186 pub struct Rc<T: ?Sized> {
187     // FIXME #12808: strange names to try to avoid interfering with field
188     // accesses of the contained type via Deref
189     _ptr: Shared<RcBox<T>>,
190 }
191
192 #[stable(feature = "rust1", since = "1.0.0")]
193 impl<T: ?Sized> !marker::Send for Rc<T> {}
194 #[stable(feature = "rust1", since = "1.0.0")]
195 impl<T: ?Sized> !marker::Sync for Rc<T> {}
196
197 #[unstable(feature = "coerce_unsized", issue = "27732")]
198 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Rc<U>> for Rc<T> {}
199
200 impl<T> Rc<T> {
201     /// Constructs a new `Rc<T>`.
202     ///
203     /// # Examples
204     ///
205     /// ```
206     /// use std::rc::Rc;
207     ///
208     /// let five = Rc::new(5);
209     /// ```
210     #[stable(feature = "rust1", since = "1.0.0")]
211     pub fn new(value: T) -> Rc<T> {
212         unsafe {
213             Rc {
214                 // there is an implicit weak pointer owned by all the strong
215                 // pointers, which ensures that the weak destructor never frees
216                 // the allocation while the strong destructor is running, even
217                 // if the weak pointer is stored inside the strong one.
218                 _ptr: Shared::new(Box::into_raw(box RcBox {
219                     strong: Cell::new(1),
220                     weak: Cell::new(1),
221                     value: value,
222                 })),
223             }
224         }
225     }
226
227     /// Unwraps the contained value if the `Rc<T>` has exactly one strong reference.
228     ///
229     /// Otherwise, an `Err` is returned with the same `Rc<T>`.
230     ///
231     /// This will succeed even if there are outstanding weak references.
232     ///
233     /// # Examples
234     ///
235     /// ```
236     /// use std::rc::Rc;
237     ///
238     /// let x = Rc::new(3);
239     /// assert_eq!(Rc::try_unwrap(x), Ok(3));
240     ///
241     /// let x = Rc::new(4);
242     /// let _y = x.clone();
243     /// assert_eq!(Rc::try_unwrap(x), Err(Rc::new(4)));
244     /// ```
245     #[inline]
246     #[stable(feature = "rc_unique", since = "1.4.0")]
247     pub fn try_unwrap(this: Self) -> Result<T, Self> {
248         if Rc::would_unwrap(&this) {
249             unsafe {
250                 let val = ptr::read(&*this); // copy the contained object
251
252                 // Indicate to Weaks that they can't be promoted by decrememting
253                 // the strong count, and then remove the implicit "strong weak"
254                 // pointer while also handling drop logic by just crafting a
255                 // fake Weak.
256                 this.dec_strong();
257                 let _weak = Weak { _ptr: this._ptr };
258                 forget(this);
259                 Ok(val)
260             }
261         } else {
262             Err(this)
263         }
264     }
265
266     /// Checks if `Rc::try_unwrap` would return `Ok`.
267     #[unstable(feature = "rc_would_unwrap",
268                reason = "just added for niche usecase",
269                issue = "28356")]
270     pub fn would_unwrap(this: &Self) -> bool {
271         Rc::strong_count(&this) == 1
272     }
273 }
274
275 impl<T: ?Sized> Rc<T> {
276     /// Downgrades the `Rc<T>` to a `Weak<T>` reference.
277     ///
278     /// # Examples
279     ///
280     /// ```
281     /// use std::rc::Rc;
282     ///
283     /// let five = Rc::new(5);
284     ///
285     /// let weak_five = Rc::downgrade(&five);
286     /// ```
287     #[stable(feature = "rc_weak", since = "1.4.0")]
288     pub fn downgrade(this: &Self) -> Weak<T> {
289         this.inc_weak();
290         Weak { _ptr: this._ptr }
291     }
292
293     /// Get the number of weak references to this value.
294     #[inline]
295     #[unstable(feature = "rc_counts", reason = "not clearly useful",
296                issue = "28356")]
297     pub fn weak_count(this: &Self) -> usize {
298         this.weak() - 1
299     }
300
301     /// Get the number of strong references to this value.
302     #[inline]
303     #[unstable(feature = "rc_counts", reason = "not clearly useful",
304                issue = "28356")]
305     pub fn strong_count(this: &Self) -> usize {
306         this.strong()
307     }
308
309     /// Returns true if there are no other `Rc` or `Weak<T>` values that share
310     /// the same inner value.
311     ///
312     /// # Examples
313     ///
314     /// ```
315     /// #![feature(rc_counts)]
316     ///
317     /// use std::rc::Rc;
318     ///
319     /// let five = Rc::new(5);
320     ///
321     /// assert!(Rc::is_unique(&five));
322     /// ```
323     #[inline]
324     #[unstable(feature = "rc_counts", reason = "uniqueness has unclear meaning",
325                issue = "28356")]
326     pub fn is_unique(this: &Self) -> bool {
327         Rc::weak_count(this) == 0 && Rc::strong_count(this) == 1
328     }
329
330     /// Returns a mutable reference to the contained value if the `Rc<T>` has
331     /// one strong reference and no weak references.
332     ///
333     /// Returns `None` if the `Rc<T>` is not unique.
334     ///
335     /// # Examples
336     ///
337     /// ```
338     /// use std::rc::Rc;
339     ///
340     /// let mut x = Rc::new(3);
341     /// *Rc::get_mut(&mut x).unwrap() = 4;
342     /// assert_eq!(*x, 4);
343     ///
344     /// let _y = x.clone();
345     /// assert!(Rc::get_mut(&mut x).is_none());
346     /// ```
347     #[inline]
348     #[stable(feature = "rc_unique", since = "1.4.0")]
349     pub fn get_mut(this: &mut Self) -> Option<&mut T> {
350         if Rc::is_unique(this) {
351             let inner = unsafe { &mut **this._ptr };
352             Some(&mut inner.value)
353         } else {
354             None
355         }
356     }
357 }
358
359 impl<T: Clone> Rc<T> {
360     /// Make a mutable reference into the given `Rc<T>` by cloning the inner
361     /// data if the `Rc<T>` doesn't have one strong reference and no weak
362     /// references.
363     ///
364     /// This is also referred to as a copy-on-write.
365     ///
366     /// # Examples
367     ///
368     /// ```
369     /// use std::rc::Rc;
370     ///
371     /// let mut data = Rc::new(5);
372     ///
373     /// *Rc::make_mut(&mut data) += 1;             // Won't clone anything
374     /// let mut other_data = data.clone(); // Won't clone inner data
375     /// *Rc::make_mut(&mut data) += 1;             // Clones inner data
376     /// *Rc::make_mut(&mut data) += 1;             // Won't clone anything
377     /// *Rc::make_mut(&mut other_data) *= 2;       // Won't clone anything
378     ///
379     /// // Note: data and other_data now point to different numbers
380     /// assert_eq!(*data, 8);
381     /// assert_eq!(*other_data, 12);
382     ///
383     /// ```
384     #[inline]
385     #[stable(feature = "rc_unique", since = "1.4.0")]
386     pub fn make_mut(this: &mut Self) -> &mut T {
387         if Rc::strong_count(this) != 1 {
388             // Gotta clone the data, there are other Rcs
389             *this = Rc::new((**this).clone())
390         } else if Rc::weak_count(this) != 0 {
391             // Can just steal the data, all that's left is Weaks
392             unsafe {
393                 let mut swap = Rc::new(ptr::read(&(**this._ptr).value));
394                 mem::swap(this, &mut swap);
395                 swap.dec_strong();
396                 // Remove implicit strong-weak ref (no need to craft a fake
397                 // Weak here -- we know other Weaks can clean up for us)
398                 swap.dec_weak();
399                 forget(swap);
400             }
401         }
402         // This unsafety is ok because we're guaranteed that the pointer
403         // returned is the *only* pointer that will ever be returned to T. Our
404         // reference count is guaranteed to be 1 at this point, and we required
405         // the `Rc<T>` itself to be `mut`, so we're returning the only possible
406         // reference to the inner value.
407         let inner = unsafe { &mut **this._ptr };
408         &mut inner.value
409     }
410 }
411
412 #[stable(feature = "rust1", since = "1.0.0")]
413 impl<T: ?Sized> Deref for Rc<T> {
414     type Target = T;
415
416     #[inline(always)]
417     fn deref(&self) -> &T {
418         &self.inner().value
419     }
420 }
421
422 #[stable(feature = "rust1", since = "1.0.0")]
423 impl<T: ?Sized> Drop for Rc<T> {
424     /// Drops the `Rc<T>`.
425     ///
426     /// This will decrement the strong reference count. If the strong reference
427     /// count becomes zero and the only other references are `Weak<T>` ones,
428     /// `drop`s the inner value.
429     ///
430     /// # Examples
431     ///
432     /// ```
433     /// use std::rc::Rc;
434     ///
435     /// {
436     ///     let five = Rc::new(5);
437     ///
438     ///     // stuff
439     ///
440     ///     drop(five); // explicit drop
441     /// }
442     /// {
443     ///     let five = Rc::new(5);
444     ///
445     ///     // stuff
446     ///
447     /// } // implicit drop
448     /// ```
449     #[unsafe_destructor_blind_to_params]
450     fn drop(&mut self) {
451         unsafe {
452             let ptr = *self._ptr;
453             let thin = ptr as *const ();
454
455             if thin as usize != mem::POST_DROP_USIZE {
456                 self.dec_strong();
457                 if self.strong() == 0 {
458                     // destroy the contained object
459                     ptr::drop_in_place(&mut (*ptr).value);
460
461                     // remove the implicit "strong weak" pointer now that we've
462                     // destroyed the contents.
463                     self.dec_weak();
464
465                     if self.weak() == 0 {
466                         deallocate(ptr as *mut u8, size_of_val(&*ptr), align_of_val(&*ptr))
467                     }
468                 }
469             }
470         }
471     }
472 }
473
474 #[stable(feature = "rust1", since = "1.0.0")]
475 impl<T: ?Sized> Clone for Rc<T> {
476     /// Makes a clone of the `Rc<T>`.
477     ///
478     /// When you clone an `Rc<T>`, it will create another pointer to the data and
479     /// increase the strong reference counter.
480     ///
481     /// # Examples
482     ///
483     /// ```
484     /// use std::rc::Rc;
485     ///
486     /// let five = Rc::new(5);
487     ///
488     /// five.clone();
489     /// ```
490     #[inline]
491     fn clone(&self) -> Rc<T> {
492         self.inc_strong();
493         Rc { _ptr: self._ptr }
494     }
495 }
496
497 #[stable(feature = "rust1", since = "1.0.0")]
498 impl<T: Default> Default for Rc<T> {
499     /// Creates a new `Rc<T>`, with the `Default` value for `T`.
500     ///
501     /// # Examples
502     ///
503     /// ```
504     /// use std::rc::Rc;
505     ///
506     /// let x: Rc<i32> = Default::default();
507     /// ```
508     #[inline]
509     fn default() -> Rc<T> {
510         Rc::new(Default::default())
511     }
512 }
513
514 #[stable(feature = "rust1", since = "1.0.0")]
515 impl<T: ?Sized + PartialEq> PartialEq for Rc<T> {
516     /// Equality for two `Rc<T>`s.
517     ///
518     /// Two `Rc<T>`s are equal if their inner value are equal.
519     ///
520     /// # Examples
521     ///
522     /// ```
523     /// use std::rc::Rc;
524     ///
525     /// let five = Rc::new(5);
526     ///
527     /// five == Rc::new(5);
528     /// ```
529     #[inline(always)]
530     fn eq(&self, other: &Rc<T>) -> bool {
531         **self == **other
532     }
533
534     /// Inequality for two `Rc<T>`s.
535     ///
536     /// Two `Rc<T>`s are unequal if their inner value are unequal.
537     ///
538     /// # Examples
539     ///
540     /// ```
541     /// use std::rc::Rc;
542     ///
543     /// let five = Rc::new(5);
544     ///
545     /// five != Rc::new(5);
546     /// ```
547     #[inline(always)]
548     fn ne(&self, other: &Rc<T>) -> bool {
549         **self != **other
550     }
551 }
552
553 #[stable(feature = "rust1", since = "1.0.0")]
554 impl<T: ?Sized + Eq> Eq for Rc<T> {}
555
556 #[stable(feature = "rust1", since = "1.0.0")]
557 impl<T: ?Sized + PartialOrd> PartialOrd for Rc<T> {
558     /// Partial comparison for two `Rc<T>`s.
559     ///
560     /// The two are compared by calling `partial_cmp()` on their inner values.
561     ///
562     /// # Examples
563     ///
564     /// ```
565     /// use std::rc::Rc;
566     ///
567     /// let five = Rc::new(5);
568     ///
569     /// five.partial_cmp(&Rc::new(5));
570     /// ```
571     #[inline(always)]
572     fn partial_cmp(&self, other: &Rc<T>) -> Option<Ordering> {
573         (**self).partial_cmp(&**other)
574     }
575
576     /// Less-than comparison for two `Rc<T>`s.
577     ///
578     /// The two are compared by calling `<` on their inner values.
579     ///
580     /// # Examples
581     ///
582     /// ```
583     /// use std::rc::Rc;
584     ///
585     /// let five = Rc::new(5);
586     ///
587     /// five < Rc::new(5);
588     /// ```
589     #[inline(always)]
590     fn lt(&self, other: &Rc<T>) -> bool {
591         **self < **other
592     }
593
594     /// 'Less-than or equal to' comparison for two `Rc<T>`s.
595     ///
596     /// The two are compared by calling `<=` on their inner values.
597     ///
598     /// # Examples
599     ///
600     /// ```
601     /// use std::rc::Rc;
602     ///
603     /// let five = Rc::new(5);
604     ///
605     /// five <= Rc::new(5);
606     /// ```
607     #[inline(always)]
608     fn le(&self, other: &Rc<T>) -> bool {
609         **self <= **other
610     }
611
612     /// Greater-than comparison for two `Rc<T>`s.
613     ///
614     /// The two are compared by calling `>` on their inner values.
615     ///
616     /// # Examples
617     ///
618     /// ```
619     /// use std::rc::Rc;
620     ///
621     /// let five = Rc::new(5);
622     ///
623     /// five > Rc::new(5);
624     /// ```
625     #[inline(always)]
626     fn gt(&self, other: &Rc<T>) -> bool {
627         **self > **other
628     }
629
630     /// 'Greater-than or equal to' comparison for two `Rc<T>`s.
631     ///
632     /// The two are compared by calling `>=` on their inner values.
633     ///
634     /// # Examples
635     ///
636     /// ```
637     /// use std::rc::Rc;
638     ///
639     /// let five = Rc::new(5);
640     ///
641     /// five >= Rc::new(5);
642     /// ```
643     #[inline(always)]
644     fn ge(&self, other: &Rc<T>) -> bool {
645         **self >= **other
646     }
647 }
648
649 #[stable(feature = "rust1", since = "1.0.0")]
650 impl<T: ?Sized + Ord> Ord for Rc<T> {
651     /// Comparison for two `Rc<T>`s.
652     ///
653     /// The two are compared by calling `cmp()` on their inner values.
654     ///
655     /// # Examples
656     ///
657     /// ```
658     /// use std::rc::Rc;
659     ///
660     /// let five = Rc::new(5);
661     ///
662     /// five.partial_cmp(&Rc::new(5));
663     /// ```
664     #[inline]
665     fn cmp(&self, other: &Rc<T>) -> Ordering {
666         (**self).cmp(&**other)
667     }
668 }
669
670 #[stable(feature = "rust1", since = "1.0.0")]
671 impl<T: ?Sized + Hash> Hash for Rc<T> {
672     fn hash<H: Hasher>(&self, state: &mut H) {
673         (**self).hash(state);
674     }
675 }
676
677 #[stable(feature = "rust1", since = "1.0.0")]
678 impl<T: ?Sized + fmt::Display> fmt::Display for Rc<T> {
679     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
680         fmt::Display::fmt(&**self, f)
681     }
682 }
683
684 #[stable(feature = "rust1", since = "1.0.0")]
685 impl<T: ?Sized + fmt::Debug> fmt::Debug for Rc<T> {
686     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
687         fmt::Debug::fmt(&**self, f)
688     }
689 }
690
691 #[stable(feature = "rust1", since = "1.0.0")]
692 impl<T: ?Sized> fmt::Pointer for Rc<T> {
693     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
694         fmt::Pointer::fmt(&*self._ptr, f)
695     }
696 }
697
698 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
699 impl<T> From<T> for Rc<T> {
700     fn from(t: T) -> Self {
701         Rc::new(t)
702     }
703 }
704
705 /// A weak version of `Rc<T>`.
706 ///
707 /// Weak references do not count when determining if the inner value should be
708 /// dropped.
709 ///
710 /// See the [module level documentation](./index.html) for more.
711 #[unsafe_no_drop_flag]
712 #[stable(feature = "rc_weak", since = "1.4.0")]
713 pub struct Weak<T: ?Sized> {
714     // FIXME #12808: strange names to try to avoid interfering with
715     // field accesses of the contained type via Deref
716     _ptr: Shared<RcBox<T>>,
717 }
718
719 #[stable(feature = "rc_weak", since = "1.4.0")]
720 impl<T: ?Sized> !marker::Send for Weak<T> {}
721 #[stable(feature = "rc_weak", since = "1.4.0")]
722 impl<T: ?Sized> !marker::Sync for Weak<T> {}
723
724 #[unstable(feature = "coerce_unsized", issue = "27732")]
725 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {}
726
727 impl<T: ?Sized> Weak<T> {
728     /// Upgrades a weak reference to a strong reference.
729     ///
730     /// Upgrades the `Weak<T>` reference to an `Rc<T>`, if possible.
731     ///
732     /// Returns `None` if there were no strong references and the data was
733     /// destroyed.
734     ///
735     /// # Examples
736     ///
737     /// ```
738     /// use std::rc::Rc;
739     ///
740     /// let five = Rc::new(5);
741     ///
742     /// let weak_five = Rc::downgrade(&five);
743     ///
744     /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
745     /// ```
746     #[stable(feature = "rc_weak", since = "1.4.0")]
747     pub fn upgrade(&self) -> Option<Rc<T>> {
748         if self.strong() == 0 {
749             None
750         } else {
751             self.inc_strong();
752             Some(Rc { _ptr: self._ptr })
753         }
754     }
755 }
756
757 #[stable(feature = "rc_weak", since = "1.4.0")]
758 impl<T: ?Sized> Drop for Weak<T> {
759     /// Drops the `Weak<T>`.
760     ///
761     /// This will decrement the weak reference count.
762     ///
763     /// # Examples
764     ///
765     /// ```
766     /// use std::rc::Rc;
767     ///
768     /// {
769     ///     let five = Rc::new(5);
770     ///     let weak_five = Rc::downgrade(&five);
771     ///
772     ///     // stuff
773     ///
774     ///     drop(weak_five); // explicit drop
775     /// }
776     /// {
777     ///     let five = Rc::new(5);
778     ///     let weak_five = Rc::downgrade(&five);
779     ///
780     ///     // stuff
781     ///
782     /// } // implicit drop
783     /// ```
784     fn drop(&mut self) {
785         unsafe {
786             let ptr = *self._ptr;
787             let thin = ptr as *const ();
788
789             if thin as usize != mem::POST_DROP_USIZE {
790                 self.dec_weak();
791                 // the weak count starts at 1, and will only go to zero if all
792                 // the strong pointers have disappeared.
793                 if self.weak() == 0 {
794                     deallocate(ptr as *mut u8, size_of_val(&*ptr), align_of_val(&*ptr))
795                 }
796             }
797         }
798     }
799 }
800
801 #[stable(feature = "rc_weak", since = "1.4.0")]
802 impl<T: ?Sized> Clone for Weak<T> {
803     /// Makes a clone of the `Weak<T>`.
804     ///
805     /// This increases the weak reference count.
806     ///
807     /// # Examples
808     ///
809     /// ```
810     /// use std::rc::Rc;
811     ///
812     /// let weak_five = Rc::downgrade(&Rc::new(5));
813     ///
814     /// weak_five.clone();
815     /// ```
816     #[inline]
817     fn clone(&self) -> Weak<T> {
818         self.inc_weak();
819         Weak { _ptr: self._ptr }
820     }
821 }
822
823 #[stable(feature = "rc_weak", since = "1.4.0")]
824 impl<T: ?Sized + fmt::Debug> fmt::Debug for Weak<T> {
825     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
826         write!(f, "(Weak)")
827     }
828 }
829
830 impl<T> Weak<T> {
831     /// Constructs a new `Weak<T>` without an accompanying instance of T.
832     ///
833     /// This allocates memory for T, but does not initialize it. Calling
834     /// Weak<T>::upgrade() on the return value always gives None.
835     ///
836     /// # Examples
837     ///
838     /// ```
839     /// #![feature(downgraded_weak)]
840     ///
841     /// use std::rc::Weak;
842     ///
843     /// let empty: Weak<i64> = Weak::new();
844     /// ```
845     #[unstable(feature = "downgraded_weak",
846                reason = "recently added",
847                issue="30425")]
848     pub fn new() -> Weak<T> {
849         unsafe {
850             Weak {
851                 _ptr: Shared::new(Box::into_raw(box RcBox {
852                     strong: Cell::new(0),
853                     weak: Cell::new(1),
854                     value: uninitialized(),
855                 })),
856             }
857         }
858     }
859 }
860
861 // NOTE: We checked_add here to deal with mem::forget safety. In particular
862 // if you mem::forget Rcs (or Weaks), the ref-count can overflow, and then
863 // you can free the allocation while outstanding Rcs (or Weaks) exist.
864 // We abort because this is such a degenerate scenario that we don't care about
865 // what happens -- no real program should ever experience this.
866 //
867 // This should have negligible overhead since you don't actually need to
868 // clone these much in Rust thanks to ownership and move-semantics.
869
870 #[doc(hidden)]
871 trait RcBoxPtr<T: ?Sized> {
872     fn inner(&self) -> &RcBox<T>;
873
874     #[inline]
875     fn strong(&self) -> usize {
876         self.inner().strong.get()
877     }
878
879     #[inline]
880     fn inc_strong(&self) {
881         self.inner().strong.set(self.strong().checked_add(1).unwrap_or_else(|| unsafe { abort() }));
882     }
883
884     #[inline]
885     fn dec_strong(&self) {
886         self.inner().strong.set(self.strong() - 1);
887     }
888
889     #[inline]
890     fn weak(&self) -> usize {
891         self.inner().weak.get()
892     }
893
894     #[inline]
895     fn inc_weak(&self) {
896         self.inner().weak.set(self.weak().checked_add(1).unwrap_or_else(|| unsafe { abort() }));
897     }
898
899     #[inline]
900     fn dec_weak(&self) {
901         self.inner().weak.set(self.weak() - 1);
902     }
903 }
904
905 impl<T: ?Sized> RcBoxPtr<T> for Rc<T> {
906     #[inline(always)]
907     fn inner(&self) -> &RcBox<T> {
908         unsafe {
909             // Safe to assume this here, as if it weren't true, we'd be breaking
910             // the contract anyway.
911             // This allows the null check to be elided in the destructor if we
912             // manipulated the reference count in the same function.
913             assume(!(*(&self._ptr as *const _ as *const *const ())).is_null());
914             &(**self._ptr)
915         }
916     }
917 }
918
919 impl<T: ?Sized> RcBoxPtr<T> for Weak<T> {
920     #[inline(always)]
921     fn inner(&self) -> &RcBox<T> {
922         unsafe {
923             // Safe to assume this here, as if it weren't true, we'd be breaking
924             // the contract anyway.
925             // This allows the null check to be elided in the destructor if we
926             // manipulated the reference count in the same function.
927             assume(!(*(&self._ptr as *const _ as *const *const ())).is_null());
928             &(**self._ptr)
929         }
930     }
931 }
932
933 #[cfg(test)]
934 mod tests {
935     use super::{Rc, Weak};
936     use std::boxed::Box;
937     use std::cell::RefCell;
938     use std::option::Option;
939     use std::option::Option::{Some, None};
940     use std::result::Result::{Err, Ok};
941     use std::mem::drop;
942     use std::clone::Clone;
943     use std::convert::From;
944
945     #[test]
946     fn test_clone() {
947         let x = Rc::new(RefCell::new(5));
948         let y = x.clone();
949         *x.borrow_mut() = 20;
950         assert_eq!(*y.borrow(), 20);
951     }
952
953     #[test]
954     fn test_simple() {
955         let x = Rc::new(5);
956         assert_eq!(*x, 5);
957     }
958
959     #[test]
960     fn test_simple_clone() {
961         let x = Rc::new(5);
962         let y = x.clone();
963         assert_eq!(*x, 5);
964         assert_eq!(*y, 5);
965     }
966
967     #[test]
968     fn test_destructor() {
969         let x: Rc<Box<_>> = Rc::new(box 5);
970         assert_eq!(**x, 5);
971     }
972
973     #[test]
974     fn test_live() {
975         let x = Rc::new(5);
976         let y = Rc::downgrade(&x);
977         assert!(y.upgrade().is_some());
978     }
979
980     #[test]
981     fn test_dead() {
982         let x = Rc::new(5);
983         let y = Rc::downgrade(&x);
984         drop(x);
985         assert!(y.upgrade().is_none());
986     }
987
988     #[test]
989     fn weak_self_cyclic() {
990         struct Cycle {
991             x: RefCell<Option<Weak<Cycle>>>,
992         }
993
994         let a = Rc::new(Cycle { x: RefCell::new(None) });
995         let b = Rc::downgrade(&a.clone());
996         *a.x.borrow_mut() = Some(b);
997
998         // hopefully we don't double-free (or leak)...
999     }
1000
1001     #[test]
1002     fn is_unique() {
1003         let x = Rc::new(3);
1004         assert!(Rc::is_unique(&x));
1005         let y = x.clone();
1006         assert!(!Rc::is_unique(&x));
1007         drop(y);
1008         assert!(Rc::is_unique(&x));
1009         let w = Rc::downgrade(&x);
1010         assert!(!Rc::is_unique(&x));
1011         drop(w);
1012         assert!(Rc::is_unique(&x));
1013     }
1014
1015     #[test]
1016     fn test_strong_count() {
1017         let a = Rc::new(0);
1018         assert!(Rc::strong_count(&a) == 1);
1019         let w = Rc::downgrade(&a);
1020         assert!(Rc::strong_count(&a) == 1);
1021         let b = w.upgrade().expect("upgrade of live rc failed");
1022         assert!(Rc::strong_count(&b) == 2);
1023         assert!(Rc::strong_count(&a) == 2);
1024         drop(w);
1025         drop(a);
1026         assert!(Rc::strong_count(&b) == 1);
1027         let c = b.clone();
1028         assert!(Rc::strong_count(&b) == 2);
1029         assert!(Rc::strong_count(&c) == 2);
1030     }
1031
1032     #[test]
1033     fn test_weak_count() {
1034         let a = Rc::new(0);
1035         assert!(Rc::strong_count(&a) == 1);
1036         assert!(Rc::weak_count(&a) == 0);
1037         let w = Rc::downgrade(&a);
1038         assert!(Rc::strong_count(&a) == 1);
1039         assert!(Rc::weak_count(&a) == 1);
1040         drop(w);
1041         assert!(Rc::strong_count(&a) == 1);
1042         assert!(Rc::weak_count(&a) == 0);
1043         let c = a.clone();
1044         assert!(Rc::strong_count(&a) == 2);
1045         assert!(Rc::weak_count(&a) == 0);
1046         drop(c);
1047     }
1048
1049     #[test]
1050     fn try_unwrap() {
1051         let x = Rc::new(3);
1052         assert_eq!(Rc::try_unwrap(x), Ok(3));
1053         let x = Rc::new(4);
1054         let _y = x.clone();
1055         assert_eq!(Rc::try_unwrap(x), Err(Rc::new(4)));
1056         let x = Rc::new(5);
1057         let _w = Rc::downgrade(&x);
1058         assert_eq!(Rc::try_unwrap(x), Ok(5));
1059     }
1060
1061     #[test]
1062     fn get_mut() {
1063         let mut x = Rc::new(3);
1064         *Rc::get_mut(&mut x).unwrap() = 4;
1065         assert_eq!(*x, 4);
1066         let y = x.clone();
1067         assert!(Rc::get_mut(&mut x).is_none());
1068         drop(y);
1069         assert!(Rc::get_mut(&mut x).is_some());
1070         let _w = Rc::downgrade(&x);
1071         assert!(Rc::get_mut(&mut x).is_none());
1072     }
1073
1074     #[test]
1075     fn test_cowrc_clone_make_unique() {
1076         let mut cow0 = Rc::new(75);
1077         let mut cow1 = cow0.clone();
1078         let mut cow2 = cow1.clone();
1079
1080         assert!(75 == *Rc::make_mut(&mut cow0));
1081         assert!(75 == *Rc::make_mut(&mut cow1));
1082         assert!(75 == *Rc::make_mut(&mut cow2));
1083
1084         *Rc::make_mut(&mut cow0) += 1;
1085         *Rc::make_mut(&mut cow1) += 2;
1086         *Rc::make_mut(&mut cow2) += 3;
1087
1088         assert!(76 == *cow0);
1089         assert!(77 == *cow1);
1090         assert!(78 == *cow2);
1091
1092         // none should point to the same backing memory
1093         assert!(*cow0 != *cow1);
1094         assert!(*cow0 != *cow2);
1095         assert!(*cow1 != *cow2);
1096     }
1097
1098     #[test]
1099     fn test_cowrc_clone_unique2() {
1100         let mut cow0 = Rc::new(75);
1101         let cow1 = cow0.clone();
1102         let cow2 = cow1.clone();
1103
1104         assert!(75 == *cow0);
1105         assert!(75 == *cow1);
1106         assert!(75 == *cow2);
1107
1108         *Rc::make_mut(&mut cow0) += 1;
1109
1110         assert!(76 == *cow0);
1111         assert!(75 == *cow1);
1112         assert!(75 == *cow2);
1113
1114         // cow1 and cow2 should share the same contents
1115         // cow0 should have a unique reference
1116         assert!(*cow0 != *cow1);
1117         assert!(*cow0 != *cow2);
1118         assert!(*cow1 == *cow2);
1119     }
1120
1121     #[test]
1122     fn test_cowrc_clone_weak() {
1123         let mut cow0 = Rc::new(75);
1124         let cow1_weak = Rc::downgrade(&cow0);
1125
1126         assert!(75 == *cow0);
1127         assert!(75 == *cow1_weak.upgrade().unwrap());
1128
1129         *Rc::make_mut(&mut cow0) += 1;
1130
1131         assert!(76 == *cow0);
1132         assert!(cow1_weak.upgrade().is_none());
1133     }
1134
1135     #[test]
1136     fn test_show() {
1137         let foo = Rc::new(75);
1138         assert_eq!(format!("{:?}", foo), "75");
1139     }
1140
1141     #[test]
1142     fn test_unsized() {
1143         let foo: Rc<[i32]> = Rc::new([1, 2, 3]);
1144         assert_eq!(foo, foo.clone());
1145     }
1146
1147     #[test]
1148     fn test_from_owned() {
1149         let foo = 123;
1150         let foo_rc = Rc::from(foo);
1151         assert!(123 == *foo_rc);
1152     }
1153
1154     #[test]
1155     fn test_new_weak() {
1156         let foo: Weak<usize> = Weak::new();
1157         assert!(foo.upgrade().is_none());
1158     }
1159 }
1160
1161 #[stable(feature = "rust1", since = "1.0.0")]
1162 impl<T: ?Sized> borrow::Borrow<T> for Rc<T> {
1163     fn borrow(&self) -> &T {
1164         &**self
1165     }
1166 }
1167
1168 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1169 impl<T: ?Sized> AsRef<T> for Rc<T> {
1170     fn as_ref(&self) -> &T {
1171         &**self
1172     }
1173 }