]> git.lizzy.rs Git - rust.git/blob - src/liballoc/rc.rs
collections: Avoid unstable code in examples for String
[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 //! # #![feature(alloc)]
36 //! use std::rc::Rc;
37 //!
38 //! struct Owner {
39 //!     name: String
40 //!     // ...other fields
41 //! }
42 //!
43 //! struct Gadget {
44 //!     id: i32,
45 //!     owner: Rc<Owner>
46 //!     // ...other fields
47 //! }
48 //!
49 //! fn main() {
50 //!     // Create a reference counted Owner.
51 //!     let gadget_owner : Rc<Owner> = Rc::new(
52 //!             Owner { name: String::from("Gadget Man") }
53 //!     );
54 //!
55 //!     // Create Gadgets belonging to gadget_owner. To increment the reference
56 //!     // count we clone the `Rc<T>` object.
57 //!     let gadget1 = Gadget { id: 1, owner: gadget_owner.clone() };
58 //!     let gadget2 = Gadget { id: 2, owner: gadget_owner.clone() };
59 //!
60 //!     drop(gadget_owner);
61 //!
62 //!     // Despite dropping gadget_owner, we're still able to print out the name
63 //!     // of the Owner of the Gadgets. This is because we've only dropped the
64 //!     // reference count object, not the Owner it wraps. As long as there are
65 //!     // other `Rc<T>` objects pointing at the same Owner, it will remain
66 //!     // allocated. Notice that the `Rc<T>` wrapper around Gadget.owner gets
67 //!     // automatically dereferenced for us.
68 //!     println!("Gadget {} owned by {}", gadget1.id, gadget1.owner.name);
69 //!     println!("Gadget {} owned by {}", gadget2.id, gadget2.owner.name);
70 //!
71 //!     // At the end of the method, gadget1 and gadget2 get destroyed, and with
72 //!     // them the last counted references to our Owner. Gadget Man now gets
73 //!     // destroyed as well.
74 //! }
75 //! ```
76 //!
77 //! If our requirements change, and we also need to be able to traverse from
78 //! Owner → Gadget, we will run into problems: an `Rc<T>` pointer from Owner
79 //! → Gadget introduces a cycle between the objects. This means that their
80 //! reference counts can never reach 0, and the objects will remain allocated: a
81 //! memory leak. In order to get around this, we can use `Weak<T>` pointers.
82 //! These pointers don't contribute to the total count.
83 //!
84 //! Rust actually makes it somewhat difficult to produce this loop in the first
85 //! place: in order to end up with two objects that point at each other, one of
86 //! them needs to be mutable. This is problematic because `Rc<T>` enforces
87 //! memory safety by only giving out shared references to the object it wraps,
88 //! and these don't allow direct mutation. We need to wrap the part of the
89 //! object we wish to mutate in a `RefCell`, which provides *interior
90 //! mutability*: a method to achieve mutability through a shared reference.
91 //! `RefCell` enforces Rust's borrowing rules at runtime.  Read the `Cell`
92 //! documentation for more details on interior mutability.
93 //!
94 //! ```rust
95 //! # #![feature(alloc)]
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(gadget1.clone().downgrade());
130 //!     gadget_owner.gadgets.borrow_mut().push(gadget2.clone().downgrade());
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, so he gets destroyed as well.
148 //! }
149 //! ```
150
151 #![stable(feature = "rust1", since = "1.0.0")]
152 #[cfg(not(test))]
153 use boxed;
154 #[cfg(test)]
155 use std::boxed;
156 use core::cell::Cell;
157 use core::clone::Clone;
158 use core::cmp::{PartialEq, PartialOrd, Eq, Ord, Ordering};
159 use core::default::Default;
160 use core::fmt;
161 use core::hash::{Hasher, Hash};
162 use core::marker::{self, Sized};
163 use core::mem::{self, min_align_of, size_of, forget};
164 use core::nonzero::NonZero;
165 use core::ops::{Deref, Drop};
166 use core::option::Option;
167 use core::option::Option::{Some, None};
168 use core::ptr;
169 use core::result::Result;
170 use core::result::Result::{Ok, Err};
171 use core::intrinsics::assume;
172
173 #[cfg(not(stage0))]
174 use core::intrinsics::drop_in_place;
175 #[cfg(not(stage0))]
176 use core::marker::Unsize;
177 #[cfg(not(stage0))]
178 use core::mem::{min_align_of_val, size_of_val};
179 #[cfg(not(stage0))]
180 use core::ops::CoerceUnsized;
181
182 use heap::deallocate;
183
184 #[cfg(stage0)]
185 struct RcBox<T> {
186     strong: Cell<usize>,
187     weak: Cell<usize>,
188     value: T,
189 }
190
191 #[cfg(not(stage0))]
192 struct RcBox<T: ?Sized> {
193     strong: Cell<usize>,
194     weak: Cell<usize>,
195     value: T,
196 }
197
198
199 /// A reference-counted pointer type over an immutable value.
200 ///
201 /// See the [module level documentation](./index.html) for more details.
202 #[cfg(stage0)]
203 #[unsafe_no_drop_flag]
204 #[stable(feature = "rust1", since = "1.0.0")]
205 pub struct Rc<T> {
206     // FIXME #12808: strange names to try to avoid interfering with field
207     // accesses of the contained type via Deref
208     _ptr: NonZero<*mut RcBox<T>>,
209 }
210 #[cfg(not(stage0))]
211 #[unsafe_no_drop_flag]
212 #[stable(feature = "rust1", since = "1.0.0")]
213 pub struct Rc<T: ?Sized> {
214     // FIXME #12808: strange names to try to avoid interfering with field
215     // accesses of the contained type via Deref
216     _ptr: NonZero<*mut RcBox<T>>,
217 }
218
219 #[cfg(stage0)]
220 impl<T> !marker::Send for Rc<T> {}
221
222 #[cfg(not(stage0))]
223 impl<T: ?Sized> !marker::Send for Rc<T> {}
224
225 #[cfg(stage0)]
226 impl<T> !marker::Sync for Rc<T> {}
227
228 #[cfg(not(stage0))]
229 impl<T: ?Sized> !marker::Sync for Rc<T> {}
230
231 #[cfg(not(stage0))]
232 impl<T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<Rc<U>> for Rc<T> {}
233
234 impl<T> Rc<T> {
235     /// Constructs a new `Rc<T>`.
236     ///
237     /// # Examples
238     ///
239     /// ```
240     /// use std::rc::Rc;
241     ///
242     /// let five = Rc::new(5);
243     /// ```
244     #[stable(feature = "rust1", since = "1.0.0")]
245     pub fn new(value: T) -> Rc<T> {
246         unsafe {
247             Rc {
248                 // there is an implicit weak pointer owned by all the strong
249                 // pointers, which ensures that the weak destructor never frees
250                 // the allocation while the strong destructor is running, even
251                 // if the weak pointer is stored inside the strong one.
252                 _ptr: NonZero::new(boxed::into_raw(box RcBox {
253                     strong: Cell::new(1),
254                     weak: Cell::new(1),
255                     value: value
256                 })),
257             }
258         }
259     }
260 }
261
262 #[cfg(not(stage0))]
263 impl<T: ?Sized> Rc<T> {
264     /// Downgrades the `Rc<T>` to a `Weak<T>` reference.
265     ///
266     /// # Examples
267     ///
268     /// ```
269     /// # #![feature(alloc)]
270     /// use std::rc::Rc;
271     ///
272     /// let five = Rc::new(5);
273     ///
274     /// let weak_five = five.downgrade();
275     /// ```
276     #[unstable(feature = "alloc",
277                reason = "Weak pointers may not belong in this module")]
278     pub fn downgrade(&self) -> Weak<T> {
279         self.inc_weak();
280         Weak { _ptr: self._ptr }
281     }
282 }
283
284 #[cfg(stage0)]
285 impl<T> Rc<T> {
286     /// Downgrades the `Rc<T>` to a `Weak<T>` reference.
287     ///
288     /// # Examples
289     ///
290     /// ```
291     /// # #![feature(alloc)]
292     /// use std::rc::Rc;
293     ///
294     /// let five = Rc::new(5);
295     ///
296     /// let weak_five = five.downgrade();
297     /// ```
298     #[unstable(feature = "alloc",
299                reason = "Weak pointers may not belong in this module")]
300     pub fn downgrade(&self) -> Weak<T> {
301         self.inc_weak();
302         Weak { _ptr: self._ptr }
303     }
304 }
305
306 /// Get the number of weak references to this value.
307 #[cfg(stage0)]
308 #[inline]
309 #[unstable(feature = "alloc")]
310 pub fn weak_count<T>(this: &Rc<T>) -> usize { this.weak() - 1 }
311 #[cfg(not(stage0))]
312 #[inline]
313 #[unstable(feature = "alloc")]
314 pub fn weak_count<T: ?Sized>(this: &Rc<T>) -> usize { this.weak() - 1 }
315
316 /// Get the number of strong references to this value.
317 #[cfg(stage0)]
318 #[inline]
319 #[unstable(feature = "alloc")]
320 pub fn strong_count<T>(this: &Rc<T>) -> usize { this.strong() }
321 #[cfg(not(stage0))]
322 #[inline]
323 #[unstable(feature = "alloc")]
324 pub fn strong_count<T: ?Sized>(this: &Rc<T>) -> usize { this.strong() }
325
326 /// Returns true if there are no other `Rc` or `Weak<T>` values that share the
327 /// same inner value.
328 ///
329 /// # Examples
330 ///
331 /// ```
332 /// # #![feature(alloc)]
333 /// use std::rc;
334 /// use std::rc::Rc;
335 ///
336 /// let five = Rc::new(5);
337 ///
338 /// rc::is_unique(&five);
339 /// ```
340 #[inline]
341 #[unstable(feature = "alloc")]
342 pub fn is_unique<T>(rc: &Rc<T>) -> bool {
343     weak_count(rc) == 0 && strong_count(rc) == 1
344 }
345
346 /// Unwraps the contained value if the `Rc<T>` is unique.
347 ///
348 /// If the `Rc<T>` is not unique, an `Err` is returned with the same `Rc<T>`.
349 ///
350 /// # Examples
351 ///
352 /// ```
353 /// # #![feature(alloc)]
354 /// use std::rc::{self, Rc};
355 ///
356 /// let x = Rc::new(3);
357 /// assert_eq!(rc::try_unwrap(x), Ok(3));
358 ///
359 /// let x = Rc::new(4);
360 /// let _y = x.clone();
361 /// assert_eq!(rc::try_unwrap(x), Err(Rc::new(4)));
362 /// ```
363 #[inline]
364 #[unstable(feature = "alloc")]
365 pub fn try_unwrap<T>(rc: Rc<T>) -> Result<T, Rc<T>> {
366     if is_unique(&rc) {
367         unsafe {
368             let val = ptr::read(&*rc); // copy the contained object
369             // destruct the box and skip our Drop
370             // we can ignore the refcounts because we know we're unique
371             deallocate(*rc._ptr as *mut u8, size_of::<RcBox<T>>(),
372                         min_align_of::<RcBox<T>>());
373             forget(rc);
374             Ok(val)
375         }
376     } else {
377         Err(rc)
378     }
379 }
380
381 /// Returns a mutable reference to the contained value if the `Rc<T>` is unique.
382 ///
383 /// Returns `None` if the `Rc<T>` is not unique.
384 ///
385 /// # Examples
386 ///
387 /// ```
388 /// # #![feature(alloc)]
389 /// use std::rc::{self, Rc};
390 ///
391 /// let mut x = Rc::new(3);
392 /// *rc::get_mut(&mut x).unwrap() = 4;
393 /// assert_eq!(*x, 4);
394 ///
395 /// let _y = x.clone();
396 /// assert!(rc::get_mut(&mut x).is_none());
397 /// ```
398 #[inline]
399 #[unstable(feature = "alloc")]
400 pub fn get_mut<T>(rc: &mut Rc<T>) -> Option<&mut T> {
401     if is_unique(rc) {
402         let inner = unsafe { &mut **rc._ptr };
403         Some(&mut inner.value)
404     } else {
405         None
406     }
407 }
408
409 impl<T: Clone> Rc<T> {
410     /// Make a mutable reference from the given `Rc<T>`.
411     ///
412     /// This is also referred to as a copy-on-write operation because the inner
413     /// data is cloned if the reference count is greater than one.
414     ///
415     /// # Examples
416     ///
417     /// ```
418     /// # #![feature(alloc)]
419     /// use std::rc::Rc;
420     ///
421     /// let mut five = Rc::new(5);
422     ///
423     /// let mut_five = five.make_unique();
424     /// ```
425     #[inline]
426     #[unstable(feature = "alloc")]
427     pub fn make_unique(&mut self) -> &mut T {
428         if !is_unique(self) {
429             *self = Rc::new((**self).clone())
430         }
431         // This unsafety is ok because we're guaranteed that the pointer
432         // returned is the *only* pointer that will ever be returned to T. Our
433         // reference count is guaranteed to be 1 at this point, and we required
434         // the `Rc<T>` itself to be `mut`, so we're returning the only possible
435         // reference to the inner value.
436         let inner = unsafe { &mut **self._ptr };
437         &mut inner.value
438     }
439 }
440
441 #[cfg(stage0)]
442 #[stable(feature = "rust1", since = "1.0.0")]
443 impl<T> Deref for Rc<T> {
444     type Target = T;
445
446     #[inline(always)]
447     fn deref(&self) -> &T {
448         &self.inner().value
449     }
450 }
451 #[cfg(not(stage0))]
452 #[stable(feature = "rust1", since = "1.0.0")]
453 impl<T: ?Sized> Deref for Rc<T> {
454     type Target = T;
455
456     #[inline(always)]
457     fn deref(&self) -> &T {
458         &self.inner().value
459     }
460 }
461
462 #[cfg(stage0)]
463 #[stable(feature = "rust1", since = "1.0.0")]
464 impl<T> Drop for Rc<T> {
465     /// Drops the `Rc<T>`.
466     ///
467     /// This will decrement the strong reference count. If the strong reference
468     /// count becomes zero and the only other references are `Weak<T>` ones,
469     /// `drop`s the inner value.
470     ///
471     /// # Examples
472     ///
473     /// ```
474     /// # #![feature(alloc)]
475     /// use std::rc::Rc;
476     ///
477     /// {
478     ///     let five = Rc::new(5);
479     ///
480     ///     // stuff
481     ///
482     ///     drop(five); // explicit drop
483     /// }
484     /// {
485     ///     let five = Rc::new(5);
486     ///
487     ///     // stuff
488     ///
489     /// } // implicit drop
490     /// ```
491     fn drop(&mut self) {
492         unsafe {
493             let ptr = *self._ptr;
494             if !ptr.is_null() && ptr as usize != mem::POST_DROP_USIZE {
495                 self.dec_strong();
496                 if self.strong() == 0 {
497                     ptr::read(&**self); // destroy the contained object
498
499                     // remove the implicit "strong weak" pointer now that we've
500                     // destroyed the contents.
501                     self.dec_weak();
502
503                     if self.weak() == 0 {
504                         deallocate(ptr as *mut u8, size_of::<RcBox<T>>(),
505                                    min_align_of::<RcBox<T>>())
506                     }
507                 }
508             }
509         }
510     }
511 }
512
513 #[cfg(not(stage0))]
514 #[stable(feature = "rust1", since = "1.0.0")]
515 impl<T: ?Sized> Drop for Rc<T> {
516     /// Drops the `Rc<T>`.
517     ///
518     /// This will decrement the strong reference count. If the strong reference
519     /// count becomes zero and the only other references are `Weak<T>` ones,
520     /// `drop`s the inner value.
521     ///
522     /// # Examples
523     ///
524     /// ```
525     /// # #![feature(alloc)]
526     /// use std::rc::Rc;
527     ///
528     /// {
529     ///     let five = Rc::new(5);
530     ///
531     ///     // stuff
532     ///
533     ///     drop(five); // explicit drop
534     /// }
535     /// {
536     ///     let five = Rc::new(5);
537     ///
538     ///     // stuff
539     ///
540     /// } // implicit drop
541     /// ```
542     fn drop(&mut self) {
543         unsafe {
544             let ptr = *self._ptr;
545             if !(*(&ptr as *const _ as *const *const ())).is_null() &&
546                ptr as usize != mem::POST_DROP_USIZE {
547                 self.dec_strong();
548                 if self.strong() == 0 {
549                     // destroy the contained object
550                     drop_in_place(&mut (*ptr).value);
551
552                     // remove the implicit "strong weak" pointer now that we've
553                     // destroyed the contents.
554                     self.dec_weak();
555
556                     if self.weak() == 0 {
557                         deallocate(ptr as *mut u8,
558                                    size_of_val(&*ptr),
559                                    min_align_of_val(&*ptr))
560                     }
561                 }
562             }
563         }
564     }
565 }
566
567 #[cfg(stage0)]
568 #[stable(feature = "rust1", since = "1.0.0")]
569 impl<T> Clone for Rc<T> {
570
571     /// Makes a clone of the `Rc<T>`.
572     ///
573     /// When you clone an `Rc<T>`, it will create another pointer to the data and
574     /// increase the strong reference counter.
575     ///
576     /// # Examples
577     ///
578     /// ```
579     /// # #![feature(alloc)]
580     /// use std::rc::Rc;
581     ///
582     /// let five = Rc::new(5);
583     ///
584     /// five.clone();
585     /// ```
586     #[inline]
587     fn clone(&self) -> Rc<T> {
588         self.inc_strong();
589         Rc { _ptr: self._ptr }
590     }
591 }
592 #[cfg(not(stage0))]
593 #[stable(feature = "rust1", since = "1.0.0")]
594 impl<T: ?Sized> Clone for Rc<T> {
595
596     /// Makes a clone of the `Rc<T>`.
597     ///
598     /// When you clone an `Rc<T>`, it will create another pointer to the data and
599     /// increase the strong reference counter.
600     ///
601     /// # Examples
602     ///
603     /// ```
604     /// # #![feature(alloc)]
605     /// use std::rc::Rc;
606     ///
607     /// let five = Rc::new(5);
608     ///
609     /// five.clone();
610     /// ```
611     #[inline]
612     fn clone(&self) -> Rc<T> {
613         self.inc_strong();
614         Rc { _ptr: self._ptr }
615     }
616 }
617
618 #[stable(feature = "rust1", since = "1.0.0")]
619 impl<T: Default> Default for Rc<T> {
620     /// Creates a new `Rc<T>`, with the `Default` value for `T`.
621     ///
622     /// # Examples
623     ///
624     /// ```
625     /// use std::rc::Rc;
626     ///
627     /// let x: Rc<i32> = Default::default();
628     /// ```
629     #[inline]
630     #[stable(feature = "rust1", since = "1.0.0")]
631     fn default() -> Rc<T> {
632         Rc::new(Default::default())
633     }
634 }
635
636 #[stable(feature = "rust1", since = "1.0.0")]
637 #[cfg(stage0)]
638 impl<T: PartialEq> PartialEq for Rc<T> {
639     #[inline(always)]
640     fn eq(&self, other: &Rc<T>) -> bool { **self == **other }
641
642     #[inline(always)]
643     fn ne(&self, other: &Rc<T>) -> bool { **self != **other }
644 }
645
646 #[stable(feature = "rust1", since = "1.0.0")]
647 #[cfg(not(stage0))]
648 impl<T: ?Sized + PartialEq> PartialEq for Rc<T> {
649     /// Equality for two `Rc<T>`s.
650     ///
651     /// Two `Rc<T>`s are equal if their inner value are equal.
652     ///
653     /// # Examples
654     ///
655     /// ```
656     /// use std::rc::Rc;
657     ///
658     /// let five = Rc::new(5);
659     ///
660     /// five == Rc::new(5);
661     /// ```
662     #[inline(always)]
663     fn eq(&self, other: &Rc<T>) -> bool { **self == **other }
664
665     /// Inequality for two `Rc<T>`s.
666     ///
667     /// Two `Rc<T>`s are unequal if their inner value are unequal.
668     ///
669     /// # Examples
670     ///
671     /// ```
672     /// use std::rc::Rc;
673     ///
674     /// let five = Rc::new(5);
675     ///
676     /// five != Rc::new(5);
677     /// ```
678     #[inline(always)]
679     fn ne(&self, other: &Rc<T>) -> bool { **self != **other }
680 }
681
682 #[stable(feature = "rust1", since = "1.0.0")]
683 #[cfg(stage0)]
684 impl<T: Eq> Eq for Rc<T> {}
685 #[stable(feature = "rust1", since = "1.0.0")]
686 #[cfg(not(stage0))]
687 impl<T: ?Sized + Eq> Eq for Rc<T> {}
688
689 #[stable(feature = "rust1", since = "1.0.0")]
690 #[cfg(stage0)]
691 impl<T: PartialOrd> PartialOrd for Rc<T> {
692     #[inline(always)]
693     fn partial_cmp(&self, other: &Rc<T>) -> Option<Ordering> {
694         (**self).partial_cmp(&**other)
695     }
696
697     #[inline(always)]
698     fn lt(&self, other: &Rc<T>) -> bool { **self < **other }
699
700     #[inline(always)]
701     fn le(&self, other: &Rc<T>) -> bool { **self <= **other }
702
703     #[inline(always)]
704     fn gt(&self, other: &Rc<T>) -> bool { **self > **other }
705
706     #[inline(always)]
707     fn ge(&self, other: &Rc<T>) -> bool { **self >= **other }
708 }
709 #[stable(feature = "rust1", since = "1.0.0")]
710 #[cfg(not(stage0))]
711 impl<T: ?Sized + PartialOrd> PartialOrd for Rc<T> {
712     /// Partial comparison for two `Rc<T>`s.
713     ///
714     /// The two are compared by calling `partial_cmp()` on their inner values.
715     ///
716     /// # Examples
717     ///
718     /// ```
719     /// use std::rc::Rc;
720     ///
721     /// let five = Rc::new(5);
722     ///
723     /// five.partial_cmp(&Rc::new(5));
724     /// ```
725     #[inline(always)]
726     fn partial_cmp(&self, other: &Rc<T>) -> Option<Ordering> {
727         (**self).partial_cmp(&**other)
728     }
729
730     /// Less-than comparison for two `Rc<T>`s.
731     ///
732     /// The two are compared by calling `<` on their inner values.
733     ///
734     /// # Examples
735     ///
736     /// ```
737     /// use std::rc::Rc;
738     ///
739     /// let five = Rc::new(5);
740     ///
741     /// five < Rc::new(5);
742     /// ```
743     #[inline(always)]
744     fn lt(&self, other: &Rc<T>) -> bool { **self < **other }
745
746     /// 'Less-than or equal to' comparison for two `Rc<T>`s.
747     ///
748     /// The two are compared by calling `<=` on their inner values.
749     ///
750     /// # Examples
751     ///
752     /// ```
753     /// use std::rc::Rc;
754     ///
755     /// let five = Rc::new(5);
756     ///
757     /// five <= Rc::new(5);
758     /// ```
759     #[inline(always)]
760     fn le(&self, other: &Rc<T>) -> bool { **self <= **other }
761
762     /// Greater-than comparison for two `Rc<T>`s.
763     ///
764     /// The two are compared by calling `>` on their inner values.
765     ///
766     /// # Examples
767     ///
768     /// ```
769     /// use std::rc::Rc;
770     ///
771     /// let five = Rc::new(5);
772     ///
773     /// five > Rc::new(5);
774     /// ```
775     #[inline(always)]
776     fn gt(&self, other: &Rc<T>) -> bool { **self > **other }
777
778     /// 'Greater-than or equal to' comparison for two `Rc<T>`s.
779     ///
780     /// The two are compared by calling `>=` on their inner values.
781     ///
782     /// # Examples
783     ///
784     /// ```
785     /// use std::rc::Rc;
786     ///
787     /// let five = Rc::new(5);
788     ///
789     /// five >= Rc::new(5);
790     /// ```
791     #[inline(always)]
792     fn ge(&self, other: &Rc<T>) -> bool { **self >= **other }
793 }
794
795 #[stable(feature = "rust1", since = "1.0.0")]
796 #[cfg(stage0)]
797 impl<T: Ord> Ord for Rc<T> {
798     #[inline]
799     fn cmp(&self, other: &Rc<T>) -> Ordering { (**self).cmp(&**other) }
800 }
801 #[stable(feature = "rust1", since = "1.0.0")]
802 #[cfg(not(stage0))]
803 impl<T: ?Sized + Ord> Ord for Rc<T> {
804     /// Comparison for two `Rc<T>`s.
805     ///
806     /// The two are compared by calling `cmp()` on their inner values.
807     ///
808     /// # Examples
809     ///
810     /// ```
811     /// use std::rc::Rc;
812     ///
813     /// let five = Rc::new(5);
814     ///
815     /// five.partial_cmp(&Rc::new(5));
816     /// ```
817     #[inline]
818     fn cmp(&self, other: &Rc<T>) -> Ordering { (**self).cmp(&**other) }
819 }
820
821 #[cfg(stage0)]
822 #[stable(feature = "rust1", since = "1.0.0")]
823 impl<T: Hash> Hash for Rc<T> {
824     fn hash<H: Hasher>(&self, state: &mut H) {
825         (**self).hash(state);
826     }
827 }
828 #[cfg(not(stage0))]
829 #[stable(feature = "rust1", since = "1.0.0")]
830 impl<T: ?Sized+Hash> Hash for Rc<T> {
831     fn hash<H: Hasher>(&self, state: &mut H) {
832         (**self).hash(state);
833     }
834 }
835
836 #[cfg(stage0)]
837 #[stable(feature = "rust1", since = "1.0.0")]
838 impl<T: fmt::Display> fmt::Display for Rc<T> {
839     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
840         fmt::Display::fmt(&**self, f)
841     }
842 }
843 #[cfg(not(stage0))]
844 #[stable(feature = "rust1", since = "1.0.0")]
845 impl<T: ?Sized+fmt::Display> fmt::Display for Rc<T> {
846     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
847         fmt::Display::fmt(&**self, f)
848     }
849 }
850
851 #[cfg(stage0)]
852 #[stable(feature = "rust1", since = "1.0.0")]
853 impl<T: fmt::Debug> fmt::Debug for Rc<T> {
854     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
855         fmt::Debug::fmt(&**self, f)
856     }
857 }
858 #[cfg(not(stage0))]
859 #[stable(feature = "rust1", since = "1.0.0")]
860 impl<T: ?Sized+fmt::Debug> fmt::Debug for Rc<T> {
861     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
862         fmt::Debug::fmt(&**self, f)
863     }
864 }
865
866 #[stable(feature = "rust1", since = "1.0.0")]
867 impl<T> fmt::Pointer for Rc<T> {
868     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
869         fmt::Pointer::fmt(&*self._ptr, f)
870     }
871 }
872
873 /// A weak version of `Rc<T>`.
874 ///
875 /// Weak references do not count when determining if the inner value should be
876 /// dropped.
877 ///
878 /// See the [module level documentation](./index.html) for more.
879 #[cfg(stage0)]
880 #[unsafe_no_drop_flag]
881 #[unstable(feature = "alloc",
882            reason = "Weak pointers may not belong in this module.")]
883 pub struct Weak<T> {
884     // FIXME #12808: strange names to try to avoid interfering with
885     // field accesses of the contained type via Deref
886     _ptr: NonZero<*mut RcBox<T>>,
887 }
888 #[cfg(not(stage0))]
889 #[unsafe_no_drop_flag]
890 #[unstable(feature = "alloc",
891            reason = "Weak pointers may not belong in this module.")]
892 pub struct Weak<T: ?Sized> {
893     // FIXME #12808: strange names to try to avoid interfering with
894     // field accesses of the contained type via Deref
895     _ptr: NonZero<*mut RcBox<T>>,
896 }
897
898 #[cfg(stage0)]
899 impl<T> !marker::Send for Weak<T> {}
900 #[cfg(not(stage0))]
901 impl<T: ?Sized> !marker::Send for Weak<T> {}
902
903 #[cfg(stage0)]
904 impl<T> !marker::Sync for Weak<T> {}
905 #[cfg(not(stage0))]
906 impl<T: ?Sized> !marker::Sync for Weak<T> {}
907
908
909 #[cfg(stage0)]
910 #[unstable(feature = "alloc",
911            reason = "Weak pointers may not belong in this module.")]
912 impl<T> Weak<T> {
913
914     /// Upgrades a weak reference to a strong reference.
915     ///
916     /// Upgrades the `Weak<T>` reference to an `Rc<T>`, if possible.
917     ///
918     /// Returns `None` if there were no strong references and the data was
919     /// destroyed.
920     ///
921     /// # Examples
922     ///
923     /// ```
924     /// # #![feature(alloc)]
925     /// use std::rc::Rc;
926     ///
927     /// let five = Rc::new(5);
928     ///
929     /// let weak_five = five.downgrade();
930     ///
931     /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
932     /// ```
933     pub fn upgrade(&self) -> Option<Rc<T>> {
934         if self.strong() == 0 {
935             None
936         } else {
937             self.inc_strong();
938             Some(Rc { _ptr: self._ptr })
939         }
940     }
941 }
942 #[cfg(not(stage0))]
943 #[unstable(feature = "alloc",
944            reason = "Weak pointers may not belong in this module.")]
945 impl<T: ?Sized> Weak<T> {
946
947     /// Upgrades a weak reference to a strong reference.
948     ///
949     /// Upgrades the `Weak<T>` reference to an `Rc<T>`, if possible.
950     ///
951     /// Returns `None` if there were no strong references and the data was
952     /// destroyed.
953     ///
954     /// # Examples
955     ///
956     /// ```
957     /// # #![feature(alloc)]
958     /// use std::rc::Rc;
959     ///
960     /// let five = Rc::new(5);
961     ///
962     /// let weak_five = five.downgrade();
963     ///
964     /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
965     /// ```
966     pub fn upgrade(&self) -> Option<Rc<T>> {
967         if self.strong() == 0 {
968             None
969         } else {
970             self.inc_strong();
971             Some(Rc { _ptr: self._ptr })
972         }
973     }
974 }
975
976 #[cfg(stage0)]
977 #[stable(feature = "rust1", since = "1.0.0")]
978 impl<T> Drop for Weak<T> {
979     /// Drops the `Weak<T>`.
980     ///
981     /// This will decrement the weak reference count.
982     ///
983     /// # Examples
984     ///
985     /// ```
986     /// # #![feature(alloc)]
987     /// use std::rc::Rc;
988     ///
989     /// {
990     ///     let five = Rc::new(5);
991     ///     let weak_five = five.downgrade();
992     ///
993     ///     // stuff
994     ///
995     ///     drop(weak_five); // explicit drop
996     /// }
997     /// {
998     ///     let five = Rc::new(5);
999     ///     let weak_five = five.downgrade();
1000     ///
1001     ///     // stuff
1002     ///
1003     /// } // implicit drop
1004     /// ```
1005     fn drop(&mut self) {
1006         unsafe {
1007             let ptr = *self._ptr;
1008             if !ptr.is_null() && ptr as usize != mem::POST_DROP_USIZE {
1009                 self.dec_weak();
1010                 // the weak count starts at 1, and will only go to zero if all
1011                 // the strong pointers have disappeared.
1012                 if self.weak() == 0 {
1013                     deallocate(ptr as *mut u8, size_of::<RcBox<T>>(),
1014                                min_align_of::<RcBox<T>>())
1015                 }
1016             }
1017         }
1018     }
1019 }
1020
1021 #[cfg(not(stage0))]
1022 #[stable(feature = "rust1", since = "1.0.0")]
1023 impl<T: ?Sized> Drop for Weak<T> {
1024     /// Drops the `Weak<T>`.
1025     ///
1026     /// This will decrement the weak reference count.
1027     ///
1028     /// # Examples
1029     ///
1030     /// ```
1031     /// # #![feature(alloc)]
1032     /// use std::rc::Rc;
1033     ///
1034     /// {
1035     ///     let five = Rc::new(5);
1036     ///     let weak_five = five.downgrade();
1037     ///
1038     ///     // stuff
1039     ///
1040     ///     drop(weak_five); // explicit drop
1041     /// }
1042     /// {
1043     ///     let five = Rc::new(5);
1044     ///     let weak_five = five.downgrade();
1045     ///
1046     ///     // stuff
1047     ///
1048     /// } // implicit drop
1049     /// ```
1050     fn drop(&mut self) {
1051         unsafe {
1052             let ptr = *self._ptr;
1053             if !(*(&ptr as *const _ as *const *const ())).is_null() &&
1054                ptr as usize != mem::POST_DROP_USIZE {
1055                 self.dec_weak();
1056                 // the weak count starts at 1, and will only go to zero if all
1057                 // the strong pointers have disappeared.
1058                 if self.weak() == 0 {
1059                     deallocate(ptr as *mut u8, size_of_val(&*ptr),
1060                                min_align_of_val(&*ptr))
1061                 }
1062             }
1063         }
1064     }
1065 }
1066
1067 #[cfg(stage0)]
1068 #[unstable(feature = "alloc",
1069            reason = "Weak pointers may not belong in this module.")]
1070 impl<T> Clone for Weak<T> {
1071
1072     /// Makes a clone of the `Weak<T>`.
1073     ///
1074     /// This increases the weak reference count.
1075     ///
1076     /// # Examples
1077     ///
1078     /// ```
1079     /// # #![feature(alloc)]
1080     /// use std::rc::Rc;
1081     ///
1082     /// let weak_five = Rc::new(5).downgrade();
1083     ///
1084     /// weak_five.clone();
1085     /// ```
1086     #[inline]
1087     fn clone(&self) -> Weak<T> {
1088         self.inc_weak();
1089         Weak { _ptr: self._ptr }
1090     }
1091 }
1092 #[cfg(not(stage0))]
1093 #[unstable(feature = "alloc",
1094            reason = "Weak pointers may not belong in this module.")]
1095 impl<T: ?Sized> Clone for Weak<T> {
1096
1097     /// Makes a clone of the `Weak<T>`.
1098     ///
1099     /// This increases the weak reference count.
1100     ///
1101     /// # Examples
1102     ///
1103     /// ```
1104     /// # #![feature(alloc)]
1105     /// use std::rc::Rc;
1106     ///
1107     /// let weak_five = Rc::new(5).downgrade();
1108     ///
1109     /// weak_five.clone();
1110     /// ```
1111     #[inline]
1112     fn clone(&self) -> Weak<T> {
1113         self.inc_weak();
1114         Weak { _ptr: self._ptr }
1115     }
1116 }
1117
1118 #[cfg(stage0)]
1119 #[stable(feature = "rust1", since = "1.0.0")]
1120 impl<T: fmt::Debug> fmt::Debug for Weak<T> {
1121     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1122         write!(f, "(Weak)")
1123     }
1124 }
1125 #[cfg(not(stage0))]
1126 #[stable(feature = "rust1", since = "1.0.0")]
1127 impl<T: ?Sized+fmt::Debug> fmt::Debug for Weak<T> {
1128     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1129         write!(f, "(Weak)")
1130     }
1131 }
1132
1133 #[cfg(stage0)]
1134 #[doc(hidden)]
1135 trait RcBoxPtr<T> {
1136     fn inner(&self) -> &RcBox<T>;
1137
1138     #[inline]
1139     fn strong(&self) -> usize { self.inner().strong.get() }
1140
1141     #[inline]
1142     fn inc_strong(&self) { self.inner().strong.set(self.strong() + 1); }
1143
1144     #[inline]
1145     fn dec_strong(&self) { self.inner().strong.set(self.strong() - 1); }
1146
1147     #[inline]
1148     fn weak(&self) -> usize { self.inner().weak.get() }
1149
1150     #[inline]
1151     fn inc_weak(&self) { self.inner().weak.set(self.weak() + 1); }
1152
1153     #[inline]
1154     fn dec_weak(&self) { self.inner().weak.set(self.weak() - 1); }
1155 }
1156 #[cfg(not(stage0))]
1157 #[doc(hidden)]
1158 trait RcBoxPtr<T: ?Sized> {
1159     fn inner(&self) -> &RcBox<T>;
1160
1161     #[inline]
1162     fn strong(&self) -> usize { self.inner().strong.get() }
1163
1164     #[inline]
1165     fn inc_strong(&self) { self.inner().strong.set(self.strong() + 1); }
1166
1167     #[inline]
1168     fn dec_strong(&self) { self.inner().strong.set(self.strong() - 1); }
1169
1170     #[inline]
1171     fn weak(&self) -> usize { self.inner().weak.get() }
1172
1173     #[inline]
1174     fn inc_weak(&self) { self.inner().weak.set(self.weak() + 1); }
1175
1176     #[inline]
1177     fn dec_weak(&self) { self.inner().weak.set(self.weak() - 1); }
1178 }
1179
1180 #[cfg(stage0)]
1181 impl<T> RcBoxPtr<T> for Rc<T> {
1182     #[inline(always)]
1183     fn inner(&self) -> &RcBox<T> {
1184         unsafe {
1185             // Safe to assume this here, as if it weren't true, we'd be breaking
1186             // the contract anyway.
1187             // This allows the null check to be elided in the destructor if we
1188             // manipulated the reference count in the same function.
1189             assume(!(*(&self._ptr as *const _ as *const *const ())).is_null());
1190             &(**self._ptr)
1191         }
1192     }
1193 }
1194 #[cfg(not(stage0))]
1195 impl<T: ?Sized> RcBoxPtr<T> for Rc<T> {
1196     #[inline(always)]
1197     fn inner(&self) -> &RcBox<T> {
1198         unsafe {
1199             // Safe to assume this here, as if it weren't true, we'd be breaking
1200             // the contract anyway.
1201             // This allows the null check to be elided in the destructor if we
1202             // manipulated the reference count in the same function.
1203             assume(!(*(&self._ptr as *const _ as *const *const ())).is_null());
1204             &(**self._ptr)
1205         }
1206     }
1207 }
1208
1209 #[cfg(stage0)]
1210 impl<T> RcBoxPtr<T> for Weak<T> {
1211     #[inline(always)]
1212     fn inner(&self) -> &RcBox<T> {
1213         unsafe {
1214             // Safe to assume this here, as if it weren't true, we'd be breaking
1215             // the contract anyway.
1216             // This allows the null check to be elided in the destructor if we
1217             // manipulated the reference count in the same function.
1218             assume(!(*(&self._ptr as *const _ as *const *const ())).is_null());
1219             &(**self._ptr)
1220         }
1221     }
1222 }
1223 #[cfg(not(stage0))]
1224 impl<T: ?Sized> RcBoxPtr<T> for Weak<T> {
1225     #[inline(always)]
1226     fn inner(&self) -> &RcBox<T> {
1227         unsafe {
1228             // Safe to assume this here, as if it weren't true, we'd be breaking
1229             // the contract anyway.
1230             // This allows the null check to be elided in the destructor if we
1231             // manipulated the reference count in the same function.
1232             assume(!(*(&self._ptr as *const _ as *const *const ())).is_null());
1233             &(**self._ptr)
1234         }
1235     }
1236 }
1237
1238 #[cfg(test)]
1239 mod tests {
1240     use super::{Rc, Weak, weak_count, strong_count};
1241     use std::boxed::Box;
1242     use std::cell::RefCell;
1243     use std::option::Option;
1244     use std::option::Option::{Some, None};
1245     use std::result::Result::{Err, Ok};
1246     use std::mem::drop;
1247     use std::clone::Clone;
1248
1249     #[test]
1250     fn test_clone() {
1251         let x = Rc::new(RefCell::new(5));
1252         let y = x.clone();
1253         *x.borrow_mut() = 20;
1254         assert_eq!(*y.borrow(), 20);
1255     }
1256
1257     #[test]
1258     fn test_simple() {
1259         let x = Rc::new(5);
1260         assert_eq!(*x, 5);
1261     }
1262
1263     #[test]
1264     fn test_simple_clone() {
1265         let x = Rc::new(5);
1266         let y = x.clone();
1267         assert_eq!(*x, 5);
1268         assert_eq!(*y, 5);
1269     }
1270
1271     #[test]
1272     fn test_destructor() {
1273         let x: Rc<Box<_>> = Rc::new(box 5);
1274         assert_eq!(**x, 5);
1275     }
1276
1277     #[test]
1278     fn test_live() {
1279         let x = Rc::new(5);
1280         let y = x.downgrade();
1281         assert!(y.upgrade().is_some());
1282     }
1283
1284     #[test]
1285     fn test_dead() {
1286         let x = Rc::new(5);
1287         let y = x.downgrade();
1288         drop(x);
1289         assert!(y.upgrade().is_none());
1290     }
1291
1292     #[test]
1293     fn weak_self_cyclic() {
1294         struct Cycle {
1295             x: RefCell<Option<Weak<Cycle>>>
1296         }
1297
1298         let a = Rc::new(Cycle { x: RefCell::new(None) });
1299         let b = a.clone().downgrade();
1300         *a.x.borrow_mut() = Some(b);
1301
1302         // hopefully we don't double-free (or leak)...
1303     }
1304
1305     #[test]
1306     fn is_unique() {
1307         let x = Rc::new(3);
1308         assert!(super::is_unique(&x));
1309         let y = x.clone();
1310         assert!(!super::is_unique(&x));
1311         drop(y);
1312         assert!(super::is_unique(&x));
1313         let w = x.downgrade();
1314         assert!(!super::is_unique(&x));
1315         drop(w);
1316         assert!(super::is_unique(&x));
1317     }
1318
1319     #[test]
1320     fn test_strong_count() {
1321         let a = Rc::new(0u32);
1322         assert!(strong_count(&a) == 1);
1323         let w = a.downgrade();
1324         assert!(strong_count(&a) == 1);
1325         let b = w.upgrade().expect("upgrade of live rc failed");
1326         assert!(strong_count(&b) == 2);
1327         assert!(strong_count(&a) == 2);
1328         drop(w);
1329         drop(a);
1330         assert!(strong_count(&b) == 1);
1331         let c = b.clone();
1332         assert!(strong_count(&b) == 2);
1333         assert!(strong_count(&c) == 2);
1334     }
1335
1336     #[test]
1337     fn test_weak_count() {
1338         let a = Rc::new(0u32);
1339         assert!(strong_count(&a) == 1);
1340         assert!(weak_count(&a) == 0);
1341         let w = a.downgrade();
1342         assert!(strong_count(&a) == 1);
1343         assert!(weak_count(&a) == 1);
1344         drop(w);
1345         assert!(strong_count(&a) == 1);
1346         assert!(weak_count(&a) == 0);
1347         let c = a.clone();
1348         assert!(strong_count(&a) == 2);
1349         assert!(weak_count(&a) == 0);
1350         drop(c);
1351     }
1352
1353     #[test]
1354     fn try_unwrap() {
1355         let x = Rc::new(3);
1356         assert_eq!(super::try_unwrap(x), Ok(3));
1357         let x = Rc::new(4);
1358         let _y = x.clone();
1359         assert_eq!(super::try_unwrap(x), Err(Rc::new(4)));
1360         let x = Rc::new(5);
1361         let _w = x.downgrade();
1362         assert_eq!(super::try_unwrap(x), Err(Rc::new(5)));
1363     }
1364
1365     #[test]
1366     fn get_mut() {
1367         let mut x = Rc::new(3);
1368         *super::get_mut(&mut x).unwrap() = 4;
1369         assert_eq!(*x, 4);
1370         let y = x.clone();
1371         assert!(super::get_mut(&mut x).is_none());
1372         drop(y);
1373         assert!(super::get_mut(&mut x).is_some());
1374         let _w = x.downgrade();
1375         assert!(super::get_mut(&mut x).is_none());
1376     }
1377
1378     #[test]
1379     fn test_cowrc_clone_make_unique() {
1380         let mut cow0 = Rc::new(75);
1381         let mut cow1 = cow0.clone();
1382         let mut cow2 = cow1.clone();
1383
1384         assert!(75 == *cow0.make_unique());
1385         assert!(75 == *cow1.make_unique());
1386         assert!(75 == *cow2.make_unique());
1387
1388         *cow0.make_unique() += 1;
1389         *cow1.make_unique() += 2;
1390         *cow2.make_unique() += 3;
1391
1392         assert!(76 == *cow0);
1393         assert!(77 == *cow1);
1394         assert!(78 == *cow2);
1395
1396         // none should point to the same backing memory
1397         assert!(*cow0 != *cow1);
1398         assert!(*cow0 != *cow2);
1399         assert!(*cow1 != *cow2);
1400     }
1401
1402     #[test]
1403     fn test_cowrc_clone_unique2() {
1404         let mut cow0 = Rc::new(75);
1405         let cow1 = cow0.clone();
1406         let cow2 = cow1.clone();
1407
1408         assert!(75 == *cow0);
1409         assert!(75 == *cow1);
1410         assert!(75 == *cow2);
1411
1412         *cow0.make_unique() += 1;
1413
1414         assert!(76 == *cow0);
1415         assert!(75 == *cow1);
1416         assert!(75 == *cow2);
1417
1418         // cow1 and cow2 should share the same contents
1419         // cow0 should have a unique reference
1420         assert!(*cow0 != *cow1);
1421         assert!(*cow0 != *cow2);
1422         assert!(*cow1 == *cow2);
1423     }
1424
1425     #[test]
1426     fn test_cowrc_clone_weak() {
1427         let mut cow0 = Rc::new(75);
1428         let cow1_weak = cow0.downgrade();
1429
1430         assert!(75 == *cow0);
1431         assert!(75 == *cow1_weak.upgrade().unwrap());
1432
1433         *cow0.make_unique() += 1;
1434
1435         assert!(76 == *cow0);
1436         assert!(cow1_weak.upgrade().is_none());
1437     }
1438
1439     #[test]
1440     fn test_show() {
1441         let foo = Rc::new(75);
1442         assert_eq!(format!("{:?}", foo), "75");
1443     }
1444
1445     #[test]
1446     fn test_unsized() {
1447         let foo: Rc<[i32]> = Rc::new([1, 2, 3]);
1448         assert_eq!(foo, foo.clone());
1449     }
1450 }