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