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