]> git.lizzy.rs Git - rust.git/blob - src/liballoc/rc.rs
Improve how warnings are displayed
[rust.git] / src / liballoc / rc.rs
1 // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 #![allow(deprecated)]
12
13 //! Single-threaded reference-counting pointers. 'Rc' stands for 'Reference
14 //! Counted'.
15 //!
16 //! The type [`Rc<T>`][`Rc`] provides shared ownership of a value of type `T`,
17 //! allocated in the heap. Invoking [`clone`][clone] on [`Rc`] produces a new
18 //! pointer to the same value in the heap. When the last [`Rc`] pointer to a
19 //! given value is destroyed, the pointed-to value is also destroyed.
20 //!
21 //! Shared references in Rust disallow mutation by default, and [`Rc`]
22 //! is no exception: you cannot obtain a mutable reference to
23 //! something inside an [`Rc`]. If you need mutability, put a [`Cell`]
24 //! or [`RefCell`] inside the [`Rc`]; see [an example of mutability
25 //! inside an Rc][mutability].
26 //!
27 //! [`Rc`] uses non-atomic reference counting. This means that overhead is very
28 //! low, but an [`Rc`] cannot be sent between threads, and consequently [`Rc`]
29 //! does not implement [`Send`][send]. As a result, the Rust compiler
30 //! will check *at compile time* that you are not sending [`Rc`]s between
31 //! threads. If you need multi-threaded, atomic reference counting, use
32 //! [`sync::Arc`][arc].
33 //!
34 //! The [`downgrade`][downgrade] method can be used to create a non-owning
35 //! [`Weak`] pointer. A [`Weak`] pointer can be [`upgrade`][upgrade]d
36 //! to an [`Rc`], but this will return [`None`] if the value has
37 //! already been dropped.
38 //!
39 //! A cycle between [`Rc`] pointers will never be deallocated. For this reason,
40 //! [`Weak`] is used to break cycles. For example, a tree could have strong
41 //! [`Rc`] pointers from parent nodes to children, and [`Weak`] pointers from
42 //! children back to their parents.
43 //!
44 //! `Rc<T>` automatically dereferences to `T` (via the [`Deref`] trait),
45 //! so you can call `T`'s methods on a value of type [`Rc<T>`][`Rc`]. To avoid name
46 //! clashes with `T`'s methods, the methods of [`Rc<T>`][`Rc`] itself are [associated
47 //! functions][assoc], called using function-like syntax:
48 //!
49 //! ```
50 //! use std::rc::Rc;
51 //! let my_rc = Rc::new(());
52 //!
53 //! Rc::downgrade(&my_rc);
54 //! ```
55 //!
56 //! [`Weak<T>`][`Weak`] does not auto-dereference to `T`, because the value may have
57 //! already been destroyed.
58 //!
59 //! # Cloning references
60 //!
61 //! Creating a new reference from an existing reference counted pointer is done using the
62 //! `Clone` trait implemented for [`Rc<T>`][`Rc`] and [`Weak<T>`][`Weak`].
63 //!
64 //! ```
65 //! use std::rc::Rc;
66 //! let foo = Rc::new(vec![1.0, 2.0, 3.0]);
67 //! // The two syntaxes below are equivalent.
68 //! let a = foo.clone();
69 //! let b = Rc::clone(&foo);
70 //! // a and b both point to the same memory location as foo.
71 //! ```
72 //!
73 //! The `Rc::clone(&from)` syntax is the most idiomatic because it conveys more explicitly
74 //! the meaning of the code. In the example above, this syntax makes it easier to see that
75 //! this code is creating a new reference rather than copying the whole content of foo.
76 //!
77 //! # Examples
78 //!
79 //! Consider a scenario where a set of `Gadget`s are owned by a given `Owner`.
80 //! We want to have our `Gadget`s point to their `Owner`. We can't do this with
81 //! unique ownership, because more than one gadget may belong to the same
82 //! `Owner`. [`Rc`] allows us to share an `Owner` between multiple `Gadget`s,
83 //! and have the `Owner` remain allocated as long as any `Gadget` points at it.
84 //!
85 //! ```
86 //! use std::rc::Rc;
87 //!
88 //! struct Owner {
89 //!     name: String,
90 //!     // ...other fields
91 //! }
92 //!
93 //! struct Gadget {
94 //!     id: i32,
95 //!     owner: Rc<Owner>,
96 //!     // ...other fields
97 //! }
98 //!
99 //! fn main() {
100 //!     // Create a reference-counted `Owner`.
101 //!     let gadget_owner: Rc<Owner> = Rc::new(
102 //!         Owner {
103 //!             name: "Gadget Man".to_string(),
104 //!         }
105 //!     );
106 //!
107 //!     // Create `Gadget`s belonging to `gadget_owner`. Cloning the `Rc<Owner>`
108 //!     // value gives us a new pointer to the same `Owner` value, incrementing
109 //!     // the reference count in the process.
110 //!     let gadget1 = Gadget {
111 //!         id: 1,
112 //!         owner: Rc::clone(&gadget_owner),
113 //!     };
114 //!     let gadget2 = Gadget {
115 //!         id: 2,
116 //!         owner: Rc::clone(&gadget_owner),
117 //!     };
118 //!
119 //!     // Dispose of our local variable `gadget_owner`.
120 //!     drop(gadget_owner);
121 //!
122 //!     // Despite dropping `gadget_owner`, we're still able to print out the name
123 //!     // of the `Owner` of the `Gadget`s. This is because we've only dropped a
124 //!     // single `Rc<Owner>`, not the `Owner` it points to. As long as there are
125 //!     // other `Rc<Owner>` values pointing at the same `Owner`, it will remain
126 //!     // allocated. The field projection `gadget1.owner.name` works because
127 //!     // `Rc<Owner>` automatically dereferences to `Owner`.
128 //!     println!("Gadget {} owned by {}", gadget1.id, gadget1.owner.name);
129 //!     println!("Gadget {} owned by {}", gadget2.id, gadget2.owner.name);
130 //!
131 //!     // At the end of the function, `gadget1` and `gadget2` are destroyed, and
132 //!     // with them the last counted references to our `Owner`. Gadget Man now
133 //!     // gets destroyed as well.
134 //! }
135 //! ```
136 //!
137 //! If our requirements change, and we also need to be able to traverse from
138 //! `Owner` to `Gadget`, we will run into problems. An [`Rc`] pointer from `Owner`
139 //! to `Gadget` introduces a cycle between the values. This means that their
140 //! reference counts can never reach 0, and the values will remain allocated
141 //! forever: a memory leak. In order to get around this, we can use [`Weak`]
142 //! pointers.
143 //!
144 //! Rust actually makes it somewhat difficult to produce this loop in the first
145 //! place. In order to end up with two values that point at each other, one of
146 //! them needs to be mutable. This is difficult because [`Rc`] enforces
147 //! memory safety by only giving out shared references to the value it wraps,
148 //! and these don't allow direct mutation. We need to wrap the part of the
149 //! value we wish to mutate in a [`RefCell`], which provides *interior
150 //! mutability*: a method to achieve mutability through a shared reference.
151 //! [`RefCell`] enforces Rust's borrowing rules at runtime.
152 //!
153 //! ```
154 //! use std::rc::Rc;
155 //! use std::rc::Weak;
156 //! use std::cell::RefCell;
157 //!
158 //! struct Owner {
159 //!     name: String,
160 //!     gadgets: RefCell<Vec<Weak<Gadget>>>,
161 //!     // ...other fields
162 //! }
163 //!
164 //! struct Gadget {
165 //!     id: i32,
166 //!     owner: Rc<Owner>,
167 //!     // ...other fields
168 //! }
169 //!
170 //! fn main() {
171 //!     // Create a reference-counted `Owner`. Note that we've put the `Owner`'s
172 //!     // vector of `Gadget`s inside a `RefCell` so that we can mutate it through
173 //!     // a shared reference.
174 //!     let gadget_owner: Rc<Owner> = Rc::new(
175 //!         Owner {
176 //!             name: "Gadget Man".to_string(),
177 //!             gadgets: RefCell::new(vec![]),
178 //!         }
179 //!     );
180 //!
181 //!     // Create `Gadget`s belonging to `gadget_owner`, as before.
182 //!     let gadget1 = Rc::new(
183 //!         Gadget {
184 //!             id: 1,
185 //!             owner: Rc::clone(&gadget_owner),
186 //!         }
187 //!     );
188 //!     let gadget2 = Rc::new(
189 //!         Gadget {
190 //!             id: 2,
191 //!             owner: Rc::clone(&gadget_owner),
192 //!         }
193 //!     );
194 //!
195 //!     // Add the `Gadget`s to their `Owner`.
196 //!     {
197 //!         let mut gadgets = gadget_owner.gadgets.borrow_mut();
198 //!         gadgets.push(Rc::downgrade(&gadget1));
199 //!         gadgets.push(Rc::downgrade(&gadget2));
200 //!
201 //!         // `RefCell` dynamic borrow ends here.
202 //!     }
203 //!
204 //!     // Iterate over our `Gadget`s, printing their details out.
205 //!     for gadget_weak in gadget_owner.gadgets.borrow().iter() {
206 //!
207 //!         // `gadget_weak` is a `Weak<Gadget>`. Since `Weak` pointers can't
208 //!         // guarantee the value is still allocated, we need to call
209 //!         // `upgrade`, which returns an `Option<Rc<Gadget>>`.
210 //!         //
211 //!         // In this case we know the value still exists, so we simply
212 //!         // `unwrap` the `Option`. In a more complicated program, you might
213 //!         // need graceful error handling for a `None` result.
214 //!
215 //!         let gadget = gadget_weak.upgrade().unwrap();
216 //!         println!("Gadget {} owned by {}", gadget.id, gadget.owner.name);
217 //!     }
218 //!
219 //!     // At the end of the function, `gadget_owner`, `gadget1`, and `gadget2`
220 //!     // are destroyed. There are now no strong (`Rc`) pointers to the
221 //!     // gadgets, so they are destroyed. This zeroes the reference count on
222 //!     // Gadget Man, so he gets destroyed as well.
223 //! }
224 //! ```
225 //!
226 //! [`Rc`]: struct.Rc.html
227 //! [`Weak`]: struct.Weak.html
228 //! [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
229 //! [`Cell`]: ../../std/cell/struct.Cell.html
230 //! [`RefCell`]: ../../std/cell/struct.RefCell.html
231 //! [send]: ../../std/marker/trait.Send.html
232 //! [arc]: ../../std/sync/struct.Arc.html
233 //! [`Deref`]: ../../std/ops/trait.Deref.html
234 //! [downgrade]: struct.Rc.html#method.downgrade
235 //! [upgrade]: struct.Weak.html#method.upgrade
236 //! [`None`]: ../../std/option/enum.Option.html#variant.None
237 //! [assoc]: ../../book/first-edition/method-syntax.html#associated-functions
238 //! [mutability]: ../../std/cell/index.html#introducing-mutability-inside-of-something-immutable
239
240 #![stable(feature = "rust1", since = "1.0.0")]
241
242 #[cfg(not(test))]
243 use boxed::Box;
244 #[cfg(test)]
245 use std::boxed::Box;
246
247 use core::any::Any;
248 use core::borrow;
249 use core::cell::Cell;
250 use core::cmp::Ordering;
251 use core::fmt;
252 use core::hash::{Hash, Hasher};
253 use core::intrinsics::abort;
254 use core::marker;
255 use core::marker::Unsize;
256 use core::mem::{self, forget, size_of_val, uninitialized};
257 use core::ops::Deref;
258 use core::ops::CoerceUnsized;
259 use core::ptr::{self, Shared};
260 use core::convert::From;
261
262 use heap::{Heap, Alloc, Layout, box_free};
263 use string::String;
264 use vec::Vec;
265
266 struct RcBox<T: ?Sized> {
267     strong: Cell<usize>,
268     weak: Cell<usize>,
269     value: T,
270 }
271
272 /// A single-threaded reference-counting pointer. 'Rc' stands for 'Reference
273 /// Counted'.
274 ///
275 /// See the [module-level documentation](./index.html) for more details.
276 ///
277 /// The inherent methods of `Rc` are all associated functions, which means
278 /// that you have to call them as e.g. [`Rc::get_mut(&mut value)`][get_mut] instead of
279 /// `value.get_mut()`. This avoids conflicts with methods of the inner
280 /// type `T`.
281 ///
282 /// [get_mut]: #method.get_mut
283 #[stable(feature = "rust1", since = "1.0.0")]
284 pub struct Rc<T: ?Sized> {
285     ptr: Shared<RcBox<T>>,
286 }
287
288 #[stable(feature = "rust1", since = "1.0.0")]
289 impl<T: ?Sized> !marker::Send for Rc<T> {}
290 #[stable(feature = "rust1", since = "1.0.0")]
291 impl<T: ?Sized> !marker::Sync for Rc<T> {}
292
293 #[unstable(feature = "coerce_unsized", issue = "27732")]
294 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Rc<U>> for Rc<T> {}
295
296 impl<T> Rc<T> {
297     /// Constructs a new `Rc<T>`.
298     ///
299     /// # Examples
300     ///
301     /// ```
302     /// use std::rc::Rc;
303     ///
304     /// let five = Rc::new(5);
305     /// ```
306     #[stable(feature = "rust1", since = "1.0.0")]
307     pub fn new(value: T) -> Rc<T> {
308         Rc {
309             // there is an implicit weak pointer owned by all the strong
310             // pointers, which ensures that the weak destructor never frees
311             // the allocation while the strong destructor is running, even
312             // if the weak pointer is stored inside the strong one.
313             ptr: Shared::from(Box::into_unique(box RcBox {
314                 strong: Cell::new(1),
315                 weak: Cell::new(1),
316                 value,
317             })),
318         }
319     }
320
321     /// Returns the contained value, if the `Rc` has exactly one strong reference.
322     ///
323     /// Otherwise, an [`Err`][result] is returned with the same `Rc` that was
324     /// passed in.
325     ///
326     /// This will succeed even if there are outstanding weak references.
327     ///
328     /// [result]: ../../std/result/enum.Result.html
329     ///
330     /// # Examples
331     ///
332     /// ```
333     /// use std::rc::Rc;
334     ///
335     /// let x = Rc::new(3);
336     /// assert_eq!(Rc::try_unwrap(x), Ok(3));
337     ///
338     /// let x = Rc::new(4);
339     /// let _y = Rc::clone(&x);
340     /// assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4);
341     /// ```
342     #[inline]
343     #[stable(feature = "rc_unique", since = "1.4.0")]
344     pub fn try_unwrap(this: Self) -> Result<T, Self> {
345         if Rc::strong_count(&this) == 1 {
346             unsafe {
347                 let val = ptr::read(&*this); // copy the contained object
348
349                 // Indicate to Weaks that they can't be promoted by decrememting
350                 // the strong count, and then remove the implicit "strong weak"
351                 // pointer while also handling drop logic by just crafting a
352                 // fake Weak.
353                 this.dec_strong();
354                 let _weak = Weak { ptr: this.ptr };
355                 forget(this);
356                 Ok(val)
357             }
358         } else {
359             Err(this)
360         }
361     }
362
363     /// Consumes the `Rc`, returning the wrapped pointer.
364     ///
365     /// To avoid a memory leak the pointer must be converted back to an `Rc` using
366     /// [`Rc::from_raw`][from_raw].
367     ///
368     /// [from_raw]: struct.Rc.html#method.from_raw
369     ///
370     /// # Examples
371     ///
372     /// ```
373     /// use std::rc::Rc;
374     ///
375     /// let x = Rc::new(10);
376     /// let x_ptr = Rc::into_raw(x);
377     /// assert_eq!(unsafe { *x_ptr }, 10);
378     /// ```
379     #[stable(feature = "rc_raw", since = "1.17.0")]
380     pub fn into_raw(this: Self) -> *const T {
381         let ptr: *const T = &*this;
382         mem::forget(this);
383         ptr
384     }
385
386     /// Constructs an `Rc` from a raw pointer.
387     ///
388     /// The raw pointer must have been previously returned by a call to a
389     /// [`Rc::into_raw`][into_raw].
390     ///
391     /// This function is unsafe because improper use may lead to memory problems. For example, a
392     /// double-free may occur if the function is called twice on the same raw pointer.
393     ///
394     /// [into_raw]: struct.Rc.html#method.into_raw
395     ///
396     /// # Examples
397     ///
398     /// ```
399     /// use std::rc::Rc;
400     ///
401     /// let x = Rc::new(10);
402     /// let x_ptr = Rc::into_raw(x);
403     ///
404     /// unsafe {
405     ///     // Convert back to an `Rc` to prevent leak.
406     ///     let x = Rc::from_raw(x_ptr);
407     ///     assert_eq!(*x, 10);
408     ///
409     ///     // Further calls to `Rc::from_raw(x_ptr)` would be memory unsafe.
410     /// }
411     ///
412     /// // The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling!
413     /// ```
414     #[stable(feature = "rc_raw", since = "1.17.0")]
415     pub unsafe fn from_raw(ptr: *const T) -> Self {
416         // To find the corresponding pointer to the `RcBox` we need to subtract the offset of the
417         // `value` field from the pointer.
418
419         let ptr = (ptr as *const u8).offset(-offset_of!(RcBox<T>, value));
420         Rc {
421             ptr: Shared::new_unchecked(ptr as *mut u8 as *mut _)
422         }
423     }
424 }
425
426 impl<T: ?Sized> Rc<T> {
427     /// Creates a new [`Weak`][weak] pointer to this value.
428     ///
429     /// [weak]: struct.Weak.html
430     ///
431     /// # Examples
432     ///
433     /// ```
434     /// use std::rc::Rc;
435     ///
436     /// let five = Rc::new(5);
437     ///
438     /// let weak_five = Rc::downgrade(&five);
439     /// ```
440     #[stable(feature = "rc_weak", since = "1.4.0")]
441     pub fn downgrade(this: &Self) -> Weak<T> {
442         this.inc_weak();
443         Weak { ptr: this.ptr }
444     }
445
446     /// Gets the number of [`Weak`][weak] pointers to this value.
447     ///
448     /// [weak]: struct.Weak.html
449     ///
450     /// # Examples
451     ///
452     /// ```
453     /// use std::rc::Rc;
454     ///
455     /// let five = Rc::new(5);
456     /// let _weak_five = Rc::downgrade(&five);
457     ///
458     /// assert_eq!(1, Rc::weak_count(&five));
459     /// ```
460     #[inline]
461     #[stable(feature = "rc_counts", since = "1.15.0")]
462     pub fn weak_count(this: &Self) -> usize {
463         this.weak() - 1
464     }
465
466     /// Gets the number of strong (`Rc`) pointers to this value.
467     ///
468     /// # Examples
469     ///
470     /// ```
471     /// use std::rc::Rc;
472     ///
473     /// let five = Rc::new(5);
474     /// let _also_five = Rc::clone(&five);
475     ///
476     /// assert_eq!(2, Rc::strong_count(&five));
477     /// ```
478     #[inline]
479     #[stable(feature = "rc_counts", since = "1.15.0")]
480     pub fn strong_count(this: &Self) -> usize {
481         this.strong()
482     }
483
484     /// Returns true if there are no other `Rc` or [`Weak`][weak] pointers to
485     /// this inner value.
486     ///
487     /// [weak]: struct.Weak.html
488     #[inline]
489     fn is_unique(this: &Self) -> bool {
490         Rc::weak_count(this) == 0 && Rc::strong_count(this) == 1
491     }
492
493     /// Returns a mutable reference to the inner value, if there are
494     /// no other `Rc` or [`Weak`][weak] pointers to the same value.
495     ///
496     /// Returns [`None`] otherwise, because it is not safe to
497     /// mutate a shared value.
498     ///
499     /// See also [`make_mut`][make_mut], which will [`clone`][clone]
500     /// the inner value when it's shared.
501     ///
502     /// [weak]: struct.Weak.html
503     /// [`None`]: ../../std/option/enum.Option.html#variant.None
504     /// [make_mut]: struct.Rc.html#method.make_mut
505     /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
506     ///
507     /// # Examples
508     ///
509     /// ```
510     /// use std::rc::Rc;
511     ///
512     /// let mut x = Rc::new(3);
513     /// *Rc::get_mut(&mut x).unwrap() = 4;
514     /// assert_eq!(*x, 4);
515     ///
516     /// let _y = Rc::clone(&x);
517     /// assert!(Rc::get_mut(&mut x).is_none());
518     /// ```
519     #[inline]
520     #[stable(feature = "rc_unique", since = "1.4.0")]
521     pub fn get_mut(this: &mut Self) -> Option<&mut T> {
522         if Rc::is_unique(this) {
523             unsafe {
524                 Some(&mut this.ptr.as_mut().value)
525             }
526         } else {
527             None
528         }
529     }
530
531     #[inline]
532     #[stable(feature = "ptr_eq", since = "1.17.0")]
533     /// Returns true if the two `Rc`s point to the same value (not
534     /// just values that compare as equal).
535     ///
536     /// # Examples
537     ///
538     /// ```
539     /// use std::rc::Rc;
540     ///
541     /// let five = Rc::new(5);
542     /// let same_five = Rc::clone(&five);
543     /// let other_five = Rc::new(5);
544     ///
545     /// assert!(Rc::ptr_eq(&five, &same_five));
546     /// assert!(!Rc::ptr_eq(&five, &other_five));
547     /// ```
548     pub fn ptr_eq(this: &Self, other: &Self) -> bool {
549         this.ptr.as_ptr() == other.ptr.as_ptr()
550     }
551 }
552
553 impl<T: Clone> Rc<T> {
554     /// Makes a mutable reference into the given `Rc`.
555     ///
556     /// If there are other `Rc` or [`Weak`][weak] pointers to the same value,
557     /// then `make_mut` will invoke [`clone`][clone] on the inner value to
558     /// ensure unique ownership. This is also referred to as clone-on-write.
559     ///
560     /// See also [`get_mut`][get_mut], which will fail rather than cloning.
561     ///
562     /// [weak]: struct.Weak.html
563     /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
564     /// [get_mut]: struct.Rc.html#method.get_mut
565     ///
566     /// # Examples
567     ///
568     /// ```
569     /// use std::rc::Rc;
570     ///
571     /// let mut data = Rc::new(5);
572     ///
573     /// *Rc::make_mut(&mut data) += 1;        // Won't clone anything
574     /// let mut other_data = Rc::clone(&data);    // Won't clone inner data
575     /// *Rc::make_mut(&mut data) += 1;        // Clones inner data
576     /// *Rc::make_mut(&mut data) += 1;        // Won't clone anything
577     /// *Rc::make_mut(&mut other_data) *= 2;  // Won't clone anything
578     ///
579     /// // Now `data` and `other_data` point to different values.
580     /// assert_eq!(*data, 8);
581     /// assert_eq!(*other_data, 12);
582     /// ```
583     #[inline]
584     #[stable(feature = "rc_unique", since = "1.4.0")]
585     pub fn make_mut(this: &mut Self) -> &mut T {
586         if Rc::strong_count(this) != 1 {
587             // Gotta clone the data, there are other Rcs
588             *this = Rc::new((**this).clone())
589         } else if Rc::weak_count(this) != 0 {
590             // Can just steal the data, all that's left is Weaks
591             unsafe {
592                 let mut swap = Rc::new(ptr::read(&this.ptr.as_ref().value));
593                 mem::swap(this, &mut swap);
594                 swap.dec_strong();
595                 // Remove implicit strong-weak ref (no need to craft a fake
596                 // Weak here -- we know other Weaks can clean up for us)
597                 swap.dec_weak();
598                 forget(swap);
599             }
600         }
601         // This unsafety is ok because we're guaranteed that the pointer
602         // returned is the *only* pointer that will ever be returned to T. Our
603         // reference count is guaranteed to be 1 at this point, and we required
604         // the `Rc<T>` itself to be `mut`, so we're returning the only possible
605         // reference to the inner value.
606         unsafe {
607             &mut this.ptr.as_mut().value
608         }
609     }
610 }
611
612 impl Rc<Any> {
613     #[inline]
614     #[unstable(feature = "rc_downcast", issue = "44608")]
615     /// Attempt to downcast the `Rc<Any>` to a concrete type.
616     ///
617     /// # Examples
618     ///
619     /// ```
620     /// #![feature(rc_downcast)]
621     /// use std::any::Any;
622     /// use std::rc::Rc;
623     ///
624     /// fn print_if_string(value: Rc<Any>) {
625     ///     if let Ok(string) = value.downcast::<String>() {
626     ///         println!("String ({}): {}", string.len(), string);
627     ///     }
628     /// }
629     ///
630     /// fn main() {
631     ///     let my_string = "Hello World".to_string();
632     ///     print_if_string(Rc::new(my_string));
633     ///     print_if_string(Rc::new(0i8));
634     /// }
635     /// ```
636     pub fn downcast<T: Any>(self) -> Result<Rc<T>, Rc<Any>> {
637         if (*self).is::<T>() {
638             // avoid the pointer arithmetic in from_raw
639             unsafe {
640                 let raw: *const RcBox<Any> = self.ptr.as_ptr();
641                 forget(self);
642                 Ok(Rc {
643                     ptr: Shared::new_unchecked(raw as *const RcBox<T> as *mut _),
644                 })
645             }
646         } else {
647             Err(self)
648         }
649     }
650 }
651
652 impl<T: ?Sized> Rc<T> {
653     // Allocates an `RcBox<T>` with sufficient space for an unsized value
654     unsafe fn allocate_for_ptr(ptr: *const T) -> *mut RcBox<T> {
655         // Create a fake RcBox to find allocation size and alignment
656         let fake_ptr = ptr as *mut RcBox<T>;
657
658         let layout = Layout::for_value(&*fake_ptr);
659
660         let mem = Heap.alloc(layout)
661             .unwrap_or_else(|e| Heap.oom(e));
662
663         // Initialize the real RcBox
664         let inner = set_data_ptr(ptr as *mut T, mem) as *mut RcBox<T>;
665
666         ptr::write(&mut (*inner).strong, Cell::new(1));
667         ptr::write(&mut (*inner).weak, Cell::new(1));
668
669         inner
670     }
671
672     fn from_box(v: Box<T>) -> Rc<T> {
673         unsafe {
674             let bptr = Box::into_raw(v);
675
676             let value_size = size_of_val(&*bptr);
677             let ptr = Self::allocate_for_ptr(bptr);
678
679             // Copy value as bytes
680             ptr::copy_nonoverlapping(
681                 bptr as *const T as *const u8,
682                 &mut (*ptr).value as *mut _ as *mut u8,
683                 value_size);
684
685             // Free the allocation without dropping its contents
686             box_free(bptr);
687
688             Rc { ptr: Shared::new_unchecked(ptr) }
689         }
690     }
691 }
692
693 // Sets the data pointer of a `?Sized` raw pointer.
694 //
695 // For a slice/trait object, this sets the `data` field and leaves the rest
696 // unchanged. For a sized raw pointer, this simply sets the pointer.
697 unsafe fn set_data_ptr<T: ?Sized, U>(mut ptr: *mut T, data: *mut U) -> *mut T {
698     ptr::write(&mut ptr as *mut _ as *mut *mut u8, data as *mut u8);
699     ptr
700 }
701
702 impl<T> Rc<[T]> {
703     // Copy elements from slice into newly allocated Rc<[T]>
704     //
705     // Unsafe because the caller must either take ownership or bind `T: Copy`
706     unsafe fn copy_from_slice(v: &[T]) -> Rc<[T]> {
707         let v_ptr = v as *const [T];
708         let ptr = Self::allocate_for_ptr(v_ptr);
709
710         ptr::copy_nonoverlapping(
711             v.as_ptr(),
712             &mut (*ptr).value as *mut [T] as *mut T,
713             v.len());
714
715         Rc { ptr: Shared::new_unchecked(ptr) }
716     }
717 }
718
719 trait RcFromSlice<T> {
720     fn from_slice(slice: &[T]) -> Self;
721 }
722
723 impl<T: Clone> RcFromSlice<T> for Rc<[T]> {
724     #[inline]
725     default fn from_slice(v: &[T]) -> Self {
726         // Panic guard while cloning T elements.
727         // In the event of a panic, elements that have been written
728         // into the new RcBox will be dropped, then the memory freed.
729         struct Guard<T> {
730             mem: *mut u8,
731             elems: *mut T,
732             layout: Layout,
733             n_elems: usize,
734         }
735
736         impl<T> Drop for Guard<T> {
737             fn drop(&mut self) {
738                 use core::slice::from_raw_parts_mut;
739
740                 unsafe {
741                     let slice = from_raw_parts_mut(self.elems, self.n_elems);
742                     ptr::drop_in_place(slice);
743
744                     Heap.dealloc(self.mem, self.layout.clone());
745                 }
746             }
747         }
748
749         unsafe {
750             let v_ptr = v as *const [T];
751             let ptr = Self::allocate_for_ptr(v_ptr);
752
753             let mem = ptr as *mut _ as *mut u8;
754             let layout = Layout::for_value(&*ptr);
755
756             // Pointer to first element
757             let elems = &mut (*ptr).value as *mut [T] as *mut T;
758
759             let mut guard = Guard{
760                 mem: mem,
761                 elems: elems,
762                 layout: layout,
763                 n_elems: 0,
764             };
765
766             for (i, item) in v.iter().enumerate() {
767                 ptr::write(elems.offset(i as isize), item.clone());
768                 guard.n_elems += 1;
769             }
770
771             // All clear. Forget the guard so it doesn't free the new RcBox.
772             forget(guard);
773
774             Rc { ptr: Shared::new_unchecked(ptr) }
775         }
776     }
777 }
778
779 impl<T: Copy> RcFromSlice<T> for Rc<[T]> {
780     #[inline]
781     fn from_slice(v: &[T]) -> Self {
782         unsafe { Rc::copy_from_slice(v) }
783     }
784 }
785
786 #[stable(feature = "rust1", since = "1.0.0")]
787 impl<T: ?Sized> Deref for Rc<T> {
788     type Target = T;
789
790     #[inline(always)]
791     fn deref(&self) -> &T {
792         &self.inner().value
793     }
794 }
795
796 #[stable(feature = "rust1", since = "1.0.0")]
797 unsafe impl<#[may_dangle] T: ?Sized> Drop for Rc<T> {
798     /// Drops the `Rc`.
799     ///
800     /// This will decrement the strong reference count. If the strong reference
801     /// count reaches zero then the only other references (if any) are
802     /// [`Weak`][weak], so we `drop` the inner value.
803     ///
804     /// [weak]: struct.Weak.html
805     ///
806     /// # Examples
807     ///
808     /// ```
809     /// use std::rc::Rc;
810     ///
811     /// struct Foo;
812     ///
813     /// impl Drop for Foo {
814     ///     fn drop(&mut self) {
815     ///         println!("dropped!");
816     ///     }
817     /// }
818     ///
819     /// let foo  = Rc::new(Foo);
820     /// let foo2 = Rc::clone(&foo);
821     ///
822     /// drop(foo);    // Doesn't print anything
823     /// drop(foo2);   // Prints "dropped!"
824     /// ```
825     fn drop(&mut self) {
826         unsafe {
827             let ptr = self.ptr.as_ptr();
828
829             self.dec_strong();
830             if self.strong() == 0 {
831                 // destroy the contained object
832                 ptr::drop_in_place(self.ptr.as_mut());
833
834                 // remove the implicit "strong weak" pointer now that we've
835                 // destroyed the contents.
836                 self.dec_weak();
837
838                 if self.weak() == 0 {
839                     Heap.dealloc(ptr as *mut u8, Layout::for_value(&*ptr));
840                 }
841             }
842         }
843     }
844 }
845
846 #[stable(feature = "rust1", since = "1.0.0")]
847 impl<T: ?Sized> Clone for Rc<T> {
848     /// Makes a clone of the `Rc` pointer.
849     ///
850     /// This creates another pointer to the same inner value, increasing the
851     /// strong reference count.
852     ///
853     /// # Examples
854     ///
855     /// ```
856     /// use std::rc::Rc;
857     ///
858     /// let five = Rc::new(5);
859     ///
860     /// Rc::clone(&five);
861     /// ```
862     #[inline]
863     fn clone(&self) -> Rc<T> {
864         self.inc_strong();
865         Rc { ptr: self.ptr }
866     }
867 }
868
869 #[stable(feature = "rust1", since = "1.0.0")]
870 impl<T: Default> Default for Rc<T> {
871     /// Creates a new `Rc<T>`, with the `Default` value for `T`.
872     ///
873     /// # Examples
874     ///
875     /// ```
876     /// use std::rc::Rc;
877     ///
878     /// let x: Rc<i32> = Default::default();
879     /// assert_eq!(*x, 0);
880     /// ```
881     #[inline]
882     fn default() -> Rc<T> {
883         Rc::new(Default::default())
884     }
885 }
886
887 #[stable(feature = "rust1", since = "1.0.0")]
888 impl<T: ?Sized + PartialEq> PartialEq for Rc<T> {
889     /// Equality for two `Rc`s.
890     ///
891     /// Two `Rc`s are equal if their inner values are equal.
892     ///
893     /// # Examples
894     ///
895     /// ```
896     /// use std::rc::Rc;
897     ///
898     /// let five = Rc::new(5);
899     ///
900     /// assert!(five == Rc::new(5));
901     /// ```
902     #[inline(always)]
903     fn eq(&self, other: &Rc<T>) -> bool {
904         **self == **other
905     }
906
907     /// Inequality for two `Rc`s.
908     ///
909     /// Two `Rc`s are unequal if their inner values are unequal.
910     ///
911     /// # Examples
912     ///
913     /// ```
914     /// use std::rc::Rc;
915     ///
916     /// let five = Rc::new(5);
917     ///
918     /// assert!(five != Rc::new(6));
919     /// ```
920     #[inline(always)]
921     fn ne(&self, other: &Rc<T>) -> bool {
922         **self != **other
923     }
924 }
925
926 #[stable(feature = "rust1", since = "1.0.0")]
927 impl<T: ?Sized + Eq> Eq for Rc<T> {}
928
929 #[stable(feature = "rust1", since = "1.0.0")]
930 impl<T: ?Sized + PartialOrd> PartialOrd for Rc<T> {
931     /// Partial comparison for two `Rc`s.
932     ///
933     /// The two are compared by calling `partial_cmp()` on their inner values.
934     ///
935     /// # Examples
936     ///
937     /// ```
938     /// use std::rc::Rc;
939     /// use std::cmp::Ordering;
940     ///
941     /// let five = Rc::new(5);
942     ///
943     /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&Rc::new(6)));
944     /// ```
945     #[inline(always)]
946     fn partial_cmp(&self, other: &Rc<T>) -> Option<Ordering> {
947         (**self).partial_cmp(&**other)
948     }
949
950     /// Less-than comparison for two `Rc`s.
951     ///
952     /// The two are compared by calling `<` on their inner values.
953     ///
954     /// # Examples
955     ///
956     /// ```
957     /// use std::rc::Rc;
958     ///
959     /// let five = Rc::new(5);
960     ///
961     /// assert!(five < Rc::new(6));
962     /// ```
963     #[inline(always)]
964     fn lt(&self, other: &Rc<T>) -> bool {
965         **self < **other
966     }
967
968     /// 'Less than or equal to' comparison for two `Rc`s.
969     ///
970     /// The two are compared by calling `<=` on their inner values.
971     ///
972     /// # Examples
973     ///
974     /// ```
975     /// use std::rc::Rc;
976     ///
977     /// let five = Rc::new(5);
978     ///
979     /// assert!(five <= Rc::new(5));
980     /// ```
981     #[inline(always)]
982     fn le(&self, other: &Rc<T>) -> bool {
983         **self <= **other
984     }
985
986     /// Greater-than comparison for two `Rc`s.
987     ///
988     /// The two are compared by calling `>` on their inner values.
989     ///
990     /// # Examples
991     ///
992     /// ```
993     /// use std::rc::Rc;
994     ///
995     /// let five = Rc::new(5);
996     ///
997     /// assert!(five > Rc::new(4));
998     /// ```
999     #[inline(always)]
1000     fn gt(&self, other: &Rc<T>) -> bool {
1001         **self > **other
1002     }
1003
1004     /// 'Greater than or equal to' comparison for two `Rc`s.
1005     ///
1006     /// The two are compared by calling `>=` on their inner values.
1007     ///
1008     /// # Examples
1009     ///
1010     /// ```
1011     /// use std::rc::Rc;
1012     ///
1013     /// let five = Rc::new(5);
1014     ///
1015     /// assert!(five >= Rc::new(5));
1016     /// ```
1017     #[inline(always)]
1018     fn ge(&self, other: &Rc<T>) -> bool {
1019         **self >= **other
1020     }
1021 }
1022
1023 #[stable(feature = "rust1", since = "1.0.0")]
1024 impl<T: ?Sized + Ord> Ord for Rc<T> {
1025     /// Comparison for two `Rc`s.
1026     ///
1027     /// The two are compared by calling `cmp()` on their inner values.
1028     ///
1029     /// # Examples
1030     ///
1031     /// ```
1032     /// use std::rc::Rc;
1033     /// use std::cmp::Ordering;
1034     ///
1035     /// let five = Rc::new(5);
1036     ///
1037     /// assert_eq!(Ordering::Less, five.cmp(&Rc::new(6)));
1038     /// ```
1039     #[inline]
1040     fn cmp(&self, other: &Rc<T>) -> Ordering {
1041         (**self).cmp(&**other)
1042     }
1043 }
1044
1045 #[stable(feature = "rust1", since = "1.0.0")]
1046 impl<T: ?Sized + Hash> Hash for Rc<T> {
1047     fn hash<H: Hasher>(&self, state: &mut H) {
1048         (**self).hash(state);
1049     }
1050 }
1051
1052 #[stable(feature = "rust1", since = "1.0.0")]
1053 impl<T: ?Sized + fmt::Display> fmt::Display for Rc<T> {
1054     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1055         fmt::Display::fmt(&**self, f)
1056     }
1057 }
1058
1059 #[stable(feature = "rust1", since = "1.0.0")]
1060 impl<T: ?Sized + fmt::Debug> fmt::Debug for Rc<T> {
1061     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1062         fmt::Debug::fmt(&**self, f)
1063     }
1064 }
1065
1066 #[stable(feature = "rust1", since = "1.0.0")]
1067 impl<T: ?Sized> fmt::Pointer for Rc<T> {
1068     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1069         fmt::Pointer::fmt(&self.ptr, f)
1070     }
1071 }
1072
1073 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
1074 impl<T> From<T> for Rc<T> {
1075     fn from(t: T) -> Self {
1076         Rc::new(t)
1077     }
1078 }
1079
1080 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1081 impl<'a, T: Clone> From<&'a [T]> for Rc<[T]> {
1082     #[inline]
1083     fn from(v: &[T]) -> Rc<[T]> {
1084         <Self as RcFromSlice<T>>::from_slice(v)
1085     }
1086 }
1087
1088 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1089 impl<'a> From<&'a str> for Rc<str> {
1090     #[inline]
1091     fn from(v: &str) -> Rc<str> {
1092         unsafe { mem::transmute(<Rc<[u8]>>::from(v.as_bytes())) }
1093     }
1094 }
1095
1096 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1097 impl From<String> for Rc<str> {
1098     #[inline]
1099     fn from(v: String) -> Rc<str> {
1100         Rc::from(&v[..])
1101     }
1102 }
1103
1104 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1105 impl<T: ?Sized> From<Box<T>> for Rc<T> {
1106     #[inline]
1107     fn from(v: Box<T>) -> Rc<T> {
1108         Rc::from_box(v)
1109     }
1110 }
1111
1112 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1113 impl<T> From<Vec<T>> for Rc<[T]> {
1114     #[inline]
1115     fn from(mut v: Vec<T>) -> Rc<[T]> {
1116         unsafe {
1117             let rc = Rc::copy_from_slice(&v);
1118
1119             // Allow the Vec to free its memory, but not destroy its contents
1120             v.set_len(0);
1121
1122             rc
1123         }
1124     }
1125 }
1126
1127 /// `Weak` is a version of [`Rc`] that holds a non-owning reference to the
1128 /// managed value. The value is accessed by calling [`upgrade`] on the `Weak`
1129 /// pointer, which returns an [`Option`]`<`[`Rc`]`<T>>`.
1130 ///
1131 /// Since a `Weak` reference does not count towards ownership, it will not
1132 /// prevent the inner value from being dropped, and `Weak` itself makes no
1133 /// guarantees about the value still being present and may return [`None`]
1134 /// when [`upgrade`]d.
1135 ///
1136 /// A `Weak` pointer is useful for keeping a temporary reference to the value
1137 /// within [`Rc`] without extending its lifetime. It is also used to prevent
1138 /// circular references between [`Rc`] pointers, since mutual owning references
1139 /// would never allow either [`Rc`] to be dropped. For example, a tree could
1140 /// have strong [`Rc`] pointers from parent nodes to children, and `Weak`
1141 /// pointers from children back to their parents.
1142 ///
1143 /// The typical way to obtain a `Weak` pointer is to call [`Rc::downgrade`].
1144 ///
1145 /// [`Rc`]: struct.Rc.html
1146 /// [`Rc::downgrade`]: struct.Rc.html#method.downgrade
1147 /// [`upgrade`]: struct.Weak.html#method.upgrade
1148 /// [`Option`]: ../../std/option/enum.Option.html
1149 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1150 #[stable(feature = "rc_weak", since = "1.4.0")]
1151 pub struct Weak<T: ?Sized> {
1152     ptr: Shared<RcBox<T>>,
1153 }
1154
1155 #[stable(feature = "rc_weak", since = "1.4.0")]
1156 impl<T: ?Sized> !marker::Send for Weak<T> {}
1157 #[stable(feature = "rc_weak", since = "1.4.0")]
1158 impl<T: ?Sized> !marker::Sync for Weak<T> {}
1159
1160 #[unstable(feature = "coerce_unsized", issue = "27732")]
1161 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {}
1162
1163 impl<T> Weak<T> {
1164     /// Constructs a new `Weak<T>`, allocating memory for `T` without initializing
1165     /// it. Calling [`upgrade`] on the return value always gives [`None`].
1166     ///
1167     /// [`upgrade`]: struct.Weak.html#method.upgrade
1168     /// [`None`]: ../../std/option/enum.Option.html
1169     ///
1170     /// # Examples
1171     ///
1172     /// ```
1173     /// use std::rc::Weak;
1174     ///
1175     /// let empty: Weak<i64> = Weak::new();
1176     /// assert!(empty.upgrade().is_none());
1177     /// ```
1178     #[stable(feature = "downgraded_weak", since = "1.10.0")]
1179     pub fn new() -> Weak<T> {
1180         unsafe {
1181             Weak {
1182                 ptr: Shared::from(Box::into_unique(box RcBox {
1183                     strong: Cell::new(0),
1184                     weak: Cell::new(1),
1185                     value: uninitialized(),
1186                 })),
1187             }
1188         }
1189     }
1190 }
1191
1192 impl<T: ?Sized> Weak<T> {
1193     /// Attempts to upgrade the `Weak` pointer to an [`Rc`], extending
1194     /// the lifetime of the value if successful.
1195     ///
1196     /// Returns [`None`] if the value has since been dropped.
1197     ///
1198     /// [`Rc`]: struct.Rc.html
1199     /// [`None`]: ../../std/option/enum.Option.html
1200     ///
1201     /// # Examples
1202     ///
1203     /// ```
1204     /// use std::rc::Rc;
1205     ///
1206     /// let five = Rc::new(5);
1207     ///
1208     /// let weak_five = Rc::downgrade(&five);
1209     ///
1210     /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
1211     /// assert!(strong_five.is_some());
1212     ///
1213     /// // Destroy all strong pointers.
1214     /// drop(strong_five);
1215     /// drop(five);
1216     ///
1217     /// assert!(weak_five.upgrade().is_none());
1218     /// ```
1219     #[stable(feature = "rc_weak", since = "1.4.0")]
1220     pub fn upgrade(&self) -> Option<Rc<T>> {
1221         if self.strong() == 0 {
1222             None
1223         } else {
1224             self.inc_strong();
1225             Some(Rc { ptr: self.ptr })
1226         }
1227     }
1228 }
1229
1230 #[stable(feature = "rc_weak", since = "1.4.0")]
1231 impl<T: ?Sized> Drop for Weak<T> {
1232     /// Drops the `Weak` pointer.
1233     ///
1234     /// # Examples
1235     ///
1236     /// ```
1237     /// use std::rc::{Rc, Weak};
1238     ///
1239     /// struct Foo;
1240     ///
1241     /// impl Drop for Foo {
1242     ///     fn drop(&mut self) {
1243     ///         println!("dropped!");
1244     ///     }
1245     /// }
1246     ///
1247     /// let foo = Rc::new(Foo);
1248     /// let weak_foo = Rc::downgrade(&foo);
1249     /// let other_weak_foo = Weak::clone(&weak_foo);
1250     ///
1251     /// drop(weak_foo);   // Doesn't print anything
1252     /// drop(foo);        // Prints "dropped!"
1253     ///
1254     /// assert!(other_weak_foo.upgrade().is_none());
1255     /// ```
1256     fn drop(&mut self) {
1257         unsafe {
1258             let ptr = self.ptr.as_ptr();
1259
1260             self.dec_weak();
1261             // the weak count starts at 1, and will only go to zero if all
1262             // the strong pointers have disappeared.
1263             if self.weak() == 0 {
1264                 Heap.dealloc(ptr as *mut u8, Layout::for_value(&*ptr));
1265             }
1266         }
1267     }
1268 }
1269
1270 #[stable(feature = "rc_weak", since = "1.4.0")]
1271 impl<T: ?Sized> Clone for Weak<T> {
1272     /// Makes a clone of the `Weak` pointer that points to the same value.
1273     ///
1274     /// # Examples
1275     ///
1276     /// ```
1277     /// use std::rc::{Rc, Weak};
1278     ///
1279     /// let weak_five = Rc::downgrade(&Rc::new(5));
1280     ///
1281     /// Weak::clone(&weak_five);
1282     /// ```
1283     #[inline]
1284     fn clone(&self) -> Weak<T> {
1285         self.inc_weak();
1286         Weak { ptr: self.ptr }
1287     }
1288 }
1289
1290 #[stable(feature = "rc_weak", since = "1.4.0")]
1291 impl<T: ?Sized + fmt::Debug> fmt::Debug for Weak<T> {
1292     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1293         write!(f, "(Weak)")
1294     }
1295 }
1296
1297 #[stable(feature = "downgraded_weak", since = "1.10.0")]
1298 impl<T> Default for Weak<T> {
1299     /// Constructs a new `Weak<T>`, allocating memory for `T` without initializing
1300     /// it. Calling [`upgrade`] on the return value always gives [`None`].
1301     ///
1302     /// [`upgrade`]: struct.Weak.html#method.upgrade
1303     /// [`None`]: ../../std/option/enum.Option.html
1304     ///
1305     /// # Examples
1306     ///
1307     /// ```
1308     /// use std::rc::Weak;
1309     ///
1310     /// let empty: Weak<i64> = Default::default();
1311     /// assert!(empty.upgrade().is_none());
1312     /// ```
1313     fn default() -> Weak<T> {
1314         Weak::new()
1315     }
1316 }
1317
1318 // NOTE: We checked_add here to deal with mem::forget safety. In particular
1319 // if you mem::forget Rcs (or Weaks), the ref-count can overflow, and then
1320 // you can free the allocation while outstanding Rcs (or Weaks) exist.
1321 // We abort because this is such a degenerate scenario that we don't care about
1322 // what happens -- no real program should ever experience this.
1323 //
1324 // This should have negligible overhead since you don't actually need to
1325 // clone these much in Rust thanks to ownership and move-semantics.
1326
1327 #[doc(hidden)]
1328 trait RcBoxPtr<T: ?Sized> {
1329     fn inner(&self) -> &RcBox<T>;
1330
1331     #[inline]
1332     fn strong(&self) -> usize {
1333         self.inner().strong.get()
1334     }
1335
1336     #[inline]
1337     fn inc_strong(&self) {
1338         self.inner().strong.set(self.strong().checked_add(1).unwrap_or_else(|| unsafe { abort() }));
1339     }
1340
1341     #[inline]
1342     fn dec_strong(&self) {
1343         self.inner().strong.set(self.strong() - 1);
1344     }
1345
1346     #[inline]
1347     fn weak(&self) -> usize {
1348         self.inner().weak.get()
1349     }
1350
1351     #[inline]
1352     fn inc_weak(&self) {
1353         self.inner().weak.set(self.weak().checked_add(1).unwrap_or_else(|| unsafe { abort() }));
1354     }
1355
1356     #[inline]
1357     fn dec_weak(&self) {
1358         self.inner().weak.set(self.weak() - 1);
1359     }
1360 }
1361
1362 impl<T: ?Sized> RcBoxPtr<T> for Rc<T> {
1363     #[inline(always)]
1364     fn inner(&self) -> &RcBox<T> {
1365         unsafe {
1366             self.ptr.as_ref()
1367         }
1368     }
1369 }
1370
1371 impl<T: ?Sized> RcBoxPtr<T> for Weak<T> {
1372     #[inline(always)]
1373     fn inner(&self) -> &RcBox<T> {
1374         unsafe {
1375             self.ptr.as_ref()
1376         }
1377     }
1378 }
1379
1380 #[cfg(test)]
1381 mod tests {
1382     use super::{Rc, Weak};
1383     use std::boxed::Box;
1384     use std::cell::RefCell;
1385     use std::option::Option;
1386     use std::option::Option::{None, Some};
1387     use std::result::Result::{Err, Ok};
1388     use std::mem::drop;
1389     use std::clone::Clone;
1390     use std::convert::From;
1391
1392     #[test]
1393     fn test_clone() {
1394         let x = Rc::new(RefCell::new(5));
1395         let y = x.clone();
1396         *x.borrow_mut() = 20;
1397         assert_eq!(*y.borrow(), 20);
1398     }
1399
1400     #[test]
1401     fn test_simple() {
1402         let x = Rc::new(5);
1403         assert_eq!(*x, 5);
1404     }
1405
1406     #[test]
1407     fn test_simple_clone() {
1408         let x = Rc::new(5);
1409         let y = x.clone();
1410         assert_eq!(*x, 5);
1411         assert_eq!(*y, 5);
1412     }
1413
1414     #[test]
1415     fn test_destructor() {
1416         let x: Rc<Box<_>> = Rc::new(box 5);
1417         assert_eq!(**x, 5);
1418     }
1419
1420     #[test]
1421     fn test_live() {
1422         let x = Rc::new(5);
1423         let y = Rc::downgrade(&x);
1424         assert!(y.upgrade().is_some());
1425     }
1426
1427     #[test]
1428     fn test_dead() {
1429         let x = Rc::new(5);
1430         let y = Rc::downgrade(&x);
1431         drop(x);
1432         assert!(y.upgrade().is_none());
1433     }
1434
1435     #[test]
1436     fn weak_self_cyclic() {
1437         struct Cycle {
1438             x: RefCell<Option<Weak<Cycle>>>,
1439         }
1440
1441         let a = Rc::new(Cycle { x: RefCell::new(None) });
1442         let b = Rc::downgrade(&a.clone());
1443         *a.x.borrow_mut() = Some(b);
1444
1445         // hopefully we don't double-free (or leak)...
1446     }
1447
1448     #[test]
1449     fn is_unique() {
1450         let x = Rc::new(3);
1451         assert!(Rc::is_unique(&x));
1452         let y = x.clone();
1453         assert!(!Rc::is_unique(&x));
1454         drop(y);
1455         assert!(Rc::is_unique(&x));
1456         let w = Rc::downgrade(&x);
1457         assert!(!Rc::is_unique(&x));
1458         drop(w);
1459         assert!(Rc::is_unique(&x));
1460     }
1461
1462     #[test]
1463     fn test_strong_count() {
1464         let a = Rc::new(0);
1465         assert!(Rc::strong_count(&a) == 1);
1466         let w = Rc::downgrade(&a);
1467         assert!(Rc::strong_count(&a) == 1);
1468         let b = w.upgrade().expect("upgrade of live rc failed");
1469         assert!(Rc::strong_count(&b) == 2);
1470         assert!(Rc::strong_count(&a) == 2);
1471         drop(w);
1472         drop(a);
1473         assert!(Rc::strong_count(&b) == 1);
1474         let c = b.clone();
1475         assert!(Rc::strong_count(&b) == 2);
1476         assert!(Rc::strong_count(&c) == 2);
1477     }
1478
1479     #[test]
1480     fn test_weak_count() {
1481         let a = Rc::new(0);
1482         assert!(Rc::strong_count(&a) == 1);
1483         assert!(Rc::weak_count(&a) == 0);
1484         let w = Rc::downgrade(&a);
1485         assert!(Rc::strong_count(&a) == 1);
1486         assert!(Rc::weak_count(&a) == 1);
1487         drop(w);
1488         assert!(Rc::strong_count(&a) == 1);
1489         assert!(Rc::weak_count(&a) == 0);
1490         let c = a.clone();
1491         assert!(Rc::strong_count(&a) == 2);
1492         assert!(Rc::weak_count(&a) == 0);
1493         drop(c);
1494     }
1495
1496     #[test]
1497     fn try_unwrap() {
1498         let x = Rc::new(3);
1499         assert_eq!(Rc::try_unwrap(x), Ok(3));
1500         let x = Rc::new(4);
1501         let _y = x.clone();
1502         assert_eq!(Rc::try_unwrap(x), Err(Rc::new(4)));
1503         let x = Rc::new(5);
1504         let _w = Rc::downgrade(&x);
1505         assert_eq!(Rc::try_unwrap(x), Ok(5));
1506     }
1507
1508     #[test]
1509     fn into_from_raw() {
1510         let x = Rc::new(box "hello");
1511         let y = x.clone();
1512
1513         let x_ptr = Rc::into_raw(x);
1514         drop(y);
1515         unsafe {
1516             assert_eq!(**x_ptr, "hello");
1517
1518             let x = Rc::from_raw(x_ptr);
1519             assert_eq!(**x, "hello");
1520
1521             assert_eq!(Rc::try_unwrap(x).map(|x| *x), Ok("hello"));
1522         }
1523     }
1524
1525     #[test]
1526     fn get_mut() {
1527         let mut x = Rc::new(3);
1528         *Rc::get_mut(&mut x).unwrap() = 4;
1529         assert_eq!(*x, 4);
1530         let y = x.clone();
1531         assert!(Rc::get_mut(&mut x).is_none());
1532         drop(y);
1533         assert!(Rc::get_mut(&mut x).is_some());
1534         let _w = Rc::downgrade(&x);
1535         assert!(Rc::get_mut(&mut x).is_none());
1536     }
1537
1538     #[test]
1539     fn test_cowrc_clone_make_unique() {
1540         let mut cow0 = Rc::new(75);
1541         let mut cow1 = cow0.clone();
1542         let mut cow2 = cow1.clone();
1543
1544         assert!(75 == *Rc::make_mut(&mut cow0));
1545         assert!(75 == *Rc::make_mut(&mut cow1));
1546         assert!(75 == *Rc::make_mut(&mut cow2));
1547
1548         *Rc::make_mut(&mut cow0) += 1;
1549         *Rc::make_mut(&mut cow1) += 2;
1550         *Rc::make_mut(&mut cow2) += 3;
1551
1552         assert!(76 == *cow0);
1553         assert!(77 == *cow1);
1554         assert!(78 == *cow2);
1555
1556         // none should point to the same backing memory
1557         assert!(*cow0 != *cow1);
1558         assert!(*cow0 != *cow2);
1559         assert!(*cow1 != *cow2);
1560     }
1561
1562     #[test]
1563     fn test_cowrc_clone_unique2() {
1564         let mut cow0 = Rc::new(75);
1565         let cow1 = cow0.clone();
1566         let cow2 = cow1.clone();
1567
1568         assert!(75 == *cow0);
1569         assert!(75 == *cow1);
1570         assert!(75 == *cow2);
1571
1572         *Rc::make_mut(&mut cow0) += 1;
1573
1574         assert!(76 == *cow0);
1575         assert!(75 == *cow1);
1576         assert!(75 == *cow2);
1577
1578         // cow1 and cow2 should share the same contents
1579         // cow0 should have a unique reference
1580         assert!(*cow0 != *cow1);
1581         assert!(*cow0 != *cow2);
1582         assert!(*cow1 == *cow2);
1583     }
1584
1585     #[test]
1586     fn test_cowrc_clone_weak() {
1587         let mut cow0 = Rc::new(75);
1588         let cow1_weak = Rc::downgrade(&cow0);
1589
1590         assert!(75 == *cow0);
1591         assert!(75 == *cow1_weak.upgrade().unwrap());
1592
1593         *Rc::make_mut(&mut cow0) += 1;
1594
1595         assert!(76 == *cow0);
1596         assert!(cow1_weak.upgrade().is_none());
1597     }
1598
1599     #[test]
1600     fn test_show() {
1601         let foo = Rc::new(75);
1602         assert_eq!(format!("{:?}", foo), "75");
1603     }
1604
1605     #[test]
1606     fn test_unsized() {
1607         let foo: Rc<[i32]> = Rc::new([1, 2, 3]);
1608         assert_eq!(foo, foo.clone());
1609     }
1610
1611     #[test]
1612     fn test_from_owned() {
1613         let foo = 123;
1614         let foo_rc = Rc::from(foo);
1615         assert!(123 == *foo_rc);
1616     }
1617
1618     #[test]
1619     fn test_new_weak() {
1620         let foo: Weak<usize> = Weak::new();
1621         assert!(foo.upgrade().is_none());
1622     }
1623
1624     #[test]
1625     fn test_ptr_eq() {
1626         let five = Rc::new(5);
1627         let same_five = five.clone();
1628         let other_five = Rc::new(5);
1629
1630         assert!(Rc::ptr_eq(&five, &same_five));
1631         assert!(!Rc::ptr_eq(&five, &other_five));
1632     }
1633
1634     #[test]
1635     fn test_from_str() {
1636         let r: Rc<str> = Rc::from("foo");
1637
1638         assert_eq!(&r[..], "foo");
1639     }
1640
1641     #[test]
1642     fn test_copy_from_slice() {
1643         let s: &[u32] = &[1, 2, 3];
1644         let r: Rc<[u32]> = Rc::from(s);
1645
1646         assert_eq!(&r[..], [1, 2, 3]);
1647     }
1648
1649     #[test]
1650     fn test_clone_from_slice() {
1651         #[derive(Clone, Debug, Eq, PartialEq)]
1652         struct X(u32);
1653
1654         let s: &[X] = &[X(1), X(2), X(3)];
1655         let r: Rc<[X]> = Rc::from(s);
1656
1657         assert_eq!(&r[..], s);
1658     }
1659
1660     #[test]
1661     #[should_panic]
1662     fn test_clone_from_slice_panic() {
1663         use std::string::{String, ToString};
1664
1665         struct Fail(u32, String);
1666
1667         impl Clone for Fail {
1668             fn clone(&self) -> Fail {
1669                 if self.0 == 2 {
1670                     panic!();
1671                 }
1672                 Fail(self.0, self.1.clone())
1673             }
1674         }
1675
1676         let s: &[Fail] = &[
1677             Fail(0, "foo".to_string()),
1678             Fail(1, "bar".to_string()),
1679             Fail(2, "baz".to_string()),
1680         ];
1681
1682         // Should panic, but not cause memory corruption
1683         let _r: Rc<[Fail]> = Rc::from(s);
1684     }
1685
1686     #[test]
1687     fn test_from_box() {
1688         let b: Box<u32> = box 123;
1689         let r: Rc<u32> = Rc::from(b);
1690
1691         assert_eq!(*r, 123);
1692     }
1693
1694     #[test]
1695     fn test_from_box_str() {
1696         use std::string::String;
1697
1698         let s = String::from("foo").into_boxed_str();
1699         let r: Rc<str> = Rc::from(s);
1700
1701         assert_eq!(&r[..], "foo");
1702     }
1703
1704     #[test]
1705     fn test_from_box_slice() {
1706         let s = vec![1, 2, 3].into_boxed_slice();
1707         let r: Rc<[u32]> = Rc::from(s);
1708
1709         assert_eq!(&r[..], [1, 2, 3]);
1710     }
1711
1712     #[test]
1713     fn test_from_box_trait() {
1714         use std::fmt::Display;
1715         use std::string::ToString;
1716
1717         let b: Box<Display> = box 123;
1718         let r: Rc<Display> = Rc::from(b);
1719
1720         assert_eq!(r.to_string(), "123");
1721     }
1722
1723     #[test]
1724     fn test_from_box_trait_zero_sized() {
1725         use std::fmt::Debug;
1726
1727         let b: Box<Debug> = box ();
1728         let r: Rc<Debug> = Rc::from(b);
1729
1730         assert_eq!(format!("{:?}", r), "()");
1731     }
1732
1733     #[test]
1734     fn test_from_vec() {
1735         let v = vec![1, 2, 3];
1736         let r: Rc<[u32]> = Rc::from(v);
1737
1738         assert_eq!(&r[..], [1, 2, 3]);
1739     }
1740
1741     #[test]
1742     fn test_downcast() {
1743         use std::any::Any;
1744
1745         let r1: Rc<Any> = Rc::new(i32::max_value());
1746         let r2: Rc<Any> = Rc::new("abc");
1747
1748         assert!(r1.clone().downcast::<u32>().is_err());
1749
1750         let r1i32 = r1.downcast::<i32>();
1751         assert!(r1i32.is_ok());
1752         assert_eq!(r1i32.unwrap(), Rc::new(i32::max_value()));
1753
1754         assert!(r2.clone().downcast::<i32>().is_err());
1755
1756         let r2str = r2.downcast::<&'static str>();
1757         assert!(r2str.is_ok());
1758         assert_eq!(r2str.unwrap(), Rc::new("abc"));
1759     }
1760 }
1761
1762 #[stable(feature = "rust1", since = "1.0.0")]
1763 impl<T: ?Sized> borrow::Borrow<T> for Rc<T> {
1764     fn borrow(&self) -> &T {
1765         &**self
1766     }
1767 }
1768
1769 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1770 impl<T: ?Sized> AsRef<T> for Rc<T> {
1771     fn as_ref(&self) -> &T {
1772         &**self
1773     }
1774 }