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