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