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