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