]> git.proxmox.com Git - rustc.git/blob - src/liballoc/rc.rs
New upstream version 1.13.0+dfsg1
[rustc.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.
14 //!
15 //! The type [`Rc<T>`][rc] provides shared ownership of a value, allocated
16 //! in the heap. Invoking [`clone`][clone] on `Rc` produces a new pointer
17 //! to the same value in the heap. When the last `Rc` pointer to a given
18 //! value is destroyed, the pointed-to value is also destroyed.
19 //!
20 //! Shared pointers in Rust disallow mutation by default, and `Rc` is no
21 //! exception. If you need to mutate through an `Rc`, use [`Cell`][cell] or
22 //! [`RefCell`][refcell].
23 //!
24 //! `Rc` uses non-atomic reference counting. This means that overhead is very
25 //! low, but an `Rc` cannot be sent between threads, and consequently `Rc`
26 //! does not implement [`Send`][send]. As a result, the Rust compiler
27 //! will check *at compile time* that you are not sending `Rc`s between
28 //! threads. If you need multi-threaded, atomic reference counting, use
29 //! [`sync::Arc`][arc].
30 //!
31 //! The [`downgrade`][downgrade] method can be used to create a non-owning
32 //! [`Weak`][weak] pointer. A `Weak` pointer can be [`upgrade`][upgrade]d
33 //! to an `Rc`, but this will return [`None`][option] if the value has
34 //! already been dropped.
35 //!
36 //! A cycle between `Rc` pointers will never be deallocated. For this reason,
37 //! `Weak` is used to break cycles. For example, a tree could have strong
38 //! `Rc` pointers from parent nodes to children, and `Weak` pointers from
39 //! children back to their parents.
40 //!
41 //! `Rc<T>` automatically dereferences to `T` (via the [`Deref`][deref] trait),
42 //! so you can call `T`'s methods on a value of type `Rc<T>`. To avoid name
43 //! clashes with `T`'s methods, the methods of `Rc<T>` itself are [associated
44 //! functions][assoc], called using function-like syntax:
45 //!
46 //! ```
47 //! # use std::rc::Rc;
48 //! # let my_rc = Rc::new(());
49 //! Rc::downgrade(&my_rc);
50 //! ```
51 //!
52 //! `Weak<T>` does not auto-dereference to `T`, because the value may have
53 //! already been destroyed.
54 //!
55 //! [rc]: struct.Rc.html
56 //! [weak]: struct.Weak.html
57 //! [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
58 //! [cell]: ../../std/cell/struct.Cell.html
59 //! [refcell]: ../../std/cell/struct.RefCell.html
60 //! [send]: ../../std/marker/trait.Send.html
61 //! [arc]: ../../std/sync/struct.Arc.html
62 //! [deref]: ../../std/ops/trait.Deref.html
63 //! [downgrade]: struct.Rc.html#method.downgrade
64 //! [upgrade]: struct.Weak.html#method.upgrade
65 //! [option]: ../../std/option/enum.Option.html
66 //! [assoc]: ../../book/method-syntax.html#associated-functions
67 //!
68 //! # Examples
69 //!
70 //! Consider a scenario where a set of `Gadget`s are owned by a given `Owner`.
71 //! We want to have our `Gadget`s point to their `Owner`. We can't do this with
72 //! unique ownership, because more than one gadget may belong to the same
73 //! `Owner`. `Rc` allows us to share an `Owner` between multiple `Gadget`s,
74 //! and have the `Owner` remain allocated as long as any `Gadget` points at it.
75 //!
76 //! ```
77 //! use std::rc::Rc;
78 //!
79 //! struct Owner {
80 //! name: String,
81 //! // ...other fields
82 //! }
83 //!
84 //! struct Gadget {
85 //! id: i32,
86 //! owner: Rc<Owner>,
87 //! // ...other fields
88 //! }
89 //!
90 //! fn main() {
91 //! // Create a reference-counted `Owner`.
92 //! let gadget_owner: Rc<Owner> = Rc::new(
93 //! Owner {
94 //! name: "Gadget Man".to_string(),
95 //! }
96 //! );
97 //!
98 //! // Create `Gadget`s belonging to `gadget_owner`. Cloning the `Rc<Owner>`
99 //! // value gives us a new pointer to the same `Owner` value, incrementing
100 //! // the reference count in the process.
101 //! let gadget1 = Gadget {
102 //! id: 1,
103 //! owner: gadget_owner.clone(),
104 //! };
105 //! let gadget2 = Gadget {
106 //! id: 2,
107 //! owner: gadget_owner.clone(),
108 //! };
109 //!
110 //! // Dispose of our local variable `gadget_owner`.
111 //! drop(gadget_owner);
112 //!
113 //! // Despite dropping `gadget_owner`, we're still able to print out the name
114 //! // of the `Owner` of the `Gadget`s. This is because we've only dropped a
115 //! // single `Rc<Owner>`, not the `Owner` it points to. As long as there are
116 //! // other `Rc<Owner>` values pointing at the same `Owner`, it will remain
117 //! // allocated. The field projection `gadget1.owner.name` works because
118 //! // `Rc<Owner>` automatically dereferences to `Owner`.
119 //! println!("Gadget {} owned by {}", gadget1.id, gadget1.owner.name);
120 //! println!("Gadget {} owned by {}", gadget2.id, gadget2.owner.name);
121 //!
122 //! // At the end of the function, `gadget1` and `gadget2` are destroyed, and
123 //! // with them the last counted references to our `Owner`. Gadget Man now
124 //! // gets destroyed as well.
125 //! }
126 //! ```
127 //!
128 //! If our requirements change, and we also need to be able to traverse from
129 //! `Owner` to `Gadget`, we will run into problems. An `Rc` pointer from `Owner`
130 //! to `Gadget` introduces a cycle between the values. This means that their
131 //! reference counts can never reach 0, and the values will remain allocated
132 //! forever: a memory leak. In order to get around this, we can use `Weak`
133 //! pointers.
134 //!
135 //! Rust actually makes it somewhat difficult to produce this loop in the first
136 //! place. In order to end up with two values that point at each other, one of
137 //! them needs to be mutable. This is difficult because `Rc` enforces
138 //! memory safety by only giving out shared references to the value it wraps,
139 //! and these don't allow direct mutation. We need to wrap the part of the
140 //! value we wish to mutate in a [`RefCell`][refcell], which provides *interior
141 //! mutability*: a method to achieve mutability through a shared reference.
142 //! `RefCell` enforces Rust's borrowing rules at runtime.
143 //!
144 //! ```
145 //! use std::rc::Rc;
146 //! use std::rc::Weak;
147 //! use std::cell::RefCell;
148 //!
149 //! struct Owner {
150 //! name: String,
151 //! gadgets: RefCell<Vec<Weak<Gadget>>>,
152 //! // ...other fields
153 //! }
154 //!
155 //! struct Gadget {
156 //! id: i32,
157 //! owner: Rc<Owner>,
158 //! // ...other fields
159 //! }
160 //!
161 //! fn main() {
162 //! // Create a reference-counted `Owner`. Note that we've put the `Owner`'s
163 //! // vector of `Gadget`s inside a `RefCell` so that we can mutate it through
164 //! // a shared reference.
165 //! let gadget_owner: Rc<Owner> = Rc::new(
166 //! Owner {
167 //! name: "Gadget Man".to_string(),
168 //! gadgets: RefCell::new(vec![]),
169 //! }
170 //! );
171 //!
172 //! // Create `Gadget`s belonging to `gadget_owner`, as before.
173 //! let gadget1 = Rc::new(
174 //! Gadget {
175 //! id: 1,
176 //! owner: gadget_owner.clone(),
177 //! }
178 //! );
179 //! let gadget2 = Rc::new(
180 //! Gadget {
181 //! id: 2,
182 //! owner: gadget_owner.clone(),
183 //! }
184 //! );
185 //!
186 //! // Add the `Gadget`s to their `Owner`.
187 //! {
188 //! let mut gadgets = gadget_owner.gadgets.borrow_mut();
189 //! gadgets.push(Rc::downgrade(&gadget1));
190 //! gadgets.push(Rc::downgrade(&gadget2));
191 //!
192 //! // `RefCell` dynamic borrow ends here.
193 //! }
194 //!
195 //! // Iterate over our `Gadget`s, printing their details out.
196 //! for gadget_weak in gadget_owner.gadgets.borrow().iter() {
197 //!
198 //! // `gadget_weak` is a `Weak<Gadget>`. Since `Weak` pointers can't
199 //! // guarantee the value is still allocated, we need to call
200 //! // `upgrade`, which returns an `Option<Rc<Gadget>>`.
201 //! //
202 //! // In this case we know the value still exists, so we simply
203 //! // `unwrap` the `Option`. In a more complicated program, you might
204 //! // need graceful error handling for a `None` result.
205 //!
206 //! let gadget = gadget_weak.upgrade().unwrap();
207 //! println!("Gadget {} owned by {}", gadget.id, gadget.owner.name);
208 //! }
209 //!
210 //! // At the end of the function, `gadget_owner`, `gadget1`, and `gadget2`
211 //! // are destroyed. There are now no strong (`Rc`) pointers to the
212 //! // gadgets, so they are destroyed. This zeroes the reference count on
213 //! // Gadget Man, so he gets destroyed as well.
214 //! }
215 //! ```
216
217 #![stable(feature = "rust1", since = "1.0.0")]
218
219 #[cfg(not(test))]
220 use boxed::Box;
221 #[cfg(test)]
222 use std::boxed::Box;
223
224 use core::borrow;
225 use core::cell::Cell;
226 use core::cmp::Ordering;
227 use core::fmt;
228 use core::hash::{Hash, Hasher};
229 use core::intrinsics::{abort, assume};
230 use core::marker;
231 use core::marker::Unsize;
232 use core::mem::{self, align_of_val, forget, size_of_val, uninitialized};
233 use core::ops::Deref;
234 use core::ops::CoerceUnsized;
235 use core::ptr::{self, Shared};
236 use core::convert::From;
237
238 use heap::deallocate;
239
240 struct RcBox<T: ?Sized> {
241 strong: Cell<usize>,
242 weak: Cell<usize>,
243 value: T,
244 }
245
246
247 /// A single-threaded reference-counting pointer.
248 ///
249 /// See the [module-level documentation](./index.html) for more details.
250 ///
251 /// The inherent methods of `Rc` are all associated functions, which means
252 /// that you have to call them as e.g. `Rc::get_mut(&value)` instead of
253 /// `value.get_mut()`. This avoids conflicts with methods of the inner
254 /// type `T`.
255 #[cfg_attr(stage0, unsafe_no_drop_flag)]
256 #[stable(feature = "rust1", since = "1.0.0")]
257 pub struct Rc<T: ?Sized> {
258 ptr: Shared<RcBox<T>>,
259 }
260
261 #[stable(feature = "rust1", since = "1.0.0")]
262 impl<T: ?Sized> !marker::Send for Rc<T> {}
263 #[stable(feature = "rust1", since = "1.0.0")]
264 impl<T: ?Sized> !marker::Sync for Rc<T> {}
265
266 #[unstable(feature = "coerce_unsized", issue = "27732")]
267 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Rc<U>> for Rc<T> {}
268
269 impl<T> Rc<T> {
270 /// Constructs a new `Rc<T>`.
271 ///
272 /// # Examples
273 ///
274 /// ```
275 /// use std::rc::Rc;
276 ///
277 /// let five = Rc::new(5);
278 /// ```
279 #[stable(feature = "rust1", since = "1.0.0")]
280 pub fn new(value: T) -> Rc<T> {
281 unsafe {
282 Rc {
283 // there is an implicit weak pointer owned by all the strong
284 // pointers, which ensures that the weak destructor never frees
285 // the allocation while the strong destructor is running, even
286 // if the weak pointer is stored inside the strong one.
287 ptr: Shared::new(Box::into_raw(box RcBox {
288 strong: Cell::new(1),
289 weak: Cell::new(1),
290 value: value,
291 })),
292 }
293 }
294 }
295
296 /// Returns the contained value, if the `Rc` has exactly one strong reference.
297 ///
298 /// Otherwise, an `Err` is returned with the same `Rc` that was passed in.
299 ///
300 /// This will succeed even if there are outstanding weak references.
301 ///
302 /// # Examples
303 ///
304 /// ```
305 /// use std::rc::Rc;
306 ///
307 /// let x = Rc::new(3);
308 /// assert_eq!(Rc::try_unwrap(x), Ok(3));
309 ///
310 /// let x = Rc::new(4);
311 /// let _y = x.clone();
312 /// assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4);
313 /// ```
314 #[inline]
315 #[stable(feature = "rc_unique", since = "1.4.0")]
316 pub fn try_unwrap(this: Self) -> Result<T, Self> {
317 if Rc::would_unwrap(&this) {
318 unsafe {
319 let val = ptr::read(&*this); // copy the contained object
320
321 // Indicate to Weaks that they can't be promoted by decrememting
322 // the strong count, and then remove the implicit "strong weak"
323 // pointer while also handling drop logic by just crafting a
324 // fake Weak.
325 this.dec_strong();
326 let _weak = Weak { ptr: this.ptr };
327 forget(this);
328 Ok(val)
329 }
330 } else {
331 Err(this)
332 }
333 }
334
335 /// Checks whether `Rc::try_unwrap` would return `Ok`.
336 ///
337 /// # Examples
338 ///
339 /// ```
340 /// #![feature(rc_would_unwrap)]
341 ///
342 /// use std::rc::Rc;
343 ///
344 /// let x = Rc::new(3);
345 /// assert!(Rc::would_unwrap(&x));
346 /// assert_eq!(Rc::try_unwrap(x), Ok(3));
347 ///
348 /// let x = Rc::new(4);
349 /// let _y = x.clone();
350 /// assert!(!Rc::would_unwrap(&x));
351 /// assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4);
352 /// ```
353 #[unstable(feature = "rc_would_unwrap",
354 reason = "just added for niche usecase",
355 issue = "28356")]
356 pub fn would_unwrap(this: &Self) -> bool {
357 Rc::strong_count(&this) == 1
358 }
359 }
360
361 impl<T: ?Sized> Rc<T> {
362 /// Creates a new [`Weak`][weak] pointer to this value.
363 ///
364 /// [weak]: struct.Weak.html
365 ///
366 /// # Examples
367 ///
368 /// ```
369 /// use std::rc::Rc;
370 ///
371 /// let five = Rc::new(5);
372 ///
373 /// let weak_five = Rc::downgrade(&five);
374 /// ```
375 #[stable(feature = "rc_weak", since = "1.4.0")]
376 pub fn downgrade(this: &Self) -> Weak<T> {
377 this.inc_weak();
378 Weak { ptr: this.ptr }
379 }
380
381 /// Gets the number of [`Weak`][weak] pointers to this value.
382 ///
383 /// [weak]: struct.Weak.html
384 ///
385 /// # Examples
386 ///
387 /// ```
388 /// #![feature(rc_counts)]
389 ///
390 /// use std::rc::Rc;
391 ///
392 /// let five = Rc::new(5);
393 /// let _weak_five = Rc::downgrade(&five);
394 ///
395 /// assert_eq!(1, Rc::weak_count(&five));
396 /// ```
397 #[inline]
398 #[unstable(feature = "rc_counts", reason = "not clearly useful",
399 issue = "28356")]
400 pub fn weak_count(this: &Self) -> usize {
401 this.weak() - 1
402 }
403
404 /// Gets the number of strong (`Rc`) pointers to this value.
405 ///
406 /// # Examples
407 ///
408 /// ```
409 /// #![feature(rc_counts)]
410 ///
411 /// use std::rc::Rc;
412 ///
413 /// let five = Rc::new(5);
414 /// let _also_five = five.clone();
415 ///
416 /// assert_eq!(2, Rc::strong_count(&five));
417 /// ```
418 #[inline]
419 #[unstable(feature = "rc_counts", reason = "not clearly useful",
420 issue = "28356")]
421 pub fn strong_count(this: &Self) -> usize {
422 this.strong()
423 }
424
425 /// Returns true if there are no other `Rc` or [`Weak`][weak] pointers to
426 /// this inner value.
427 ///
428 /// [weak]: struct.Weak.html
429 ///
430 /// # Examples
431 ///
432 /// ```
433 /// #![feature(rc_counts)]
434 ///
435 /// use std::rc::Rc;
436 ///
437 /// let five = Rc::new(5);
438 ///
439 /// assert!(Rc::is_unique(&five));
440 /// ```
441 #[inline]
442 #[unstable(feature = "rc_counts", reason = "uniqueness has unclear meaning",
443 issue = "28356")]
444 pub fn is_unique(this: &Self) -> bool {
445 Rc::weak_count(this) == 0 && Rc::strong_count(this) == 1
446 }
447
448 /// Returns a mutable reference to the inner value, if there are
449 /// no other `Rc` or [`Weak`][weak] pointers to the same value.
450 ///
451 /// Returns [`None`][option] otherwise, because it is not safe to
452 /// mutate a shared value.
453 ///
454 /// See also [`make_mut`][make_mut], which will [`clone`][clone]
455 /// the inner value when it's shared.
456 ///
457 /// [weak]: struct.Weak.html
458 /// [option]: ../../std/option/enum.Option.html
459 /// [make_mut]: struct.Rc.html#method.make_mut
460 /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
461 ///
462 /// # Examples
463 ///
464 /// ```
465 /// use std::rc::Rc;
466 ///
467 /// let mut x = Rc::new(3);
468 /// *Rc::get_mut(&mut x).unwrap() = 4;
469 /// assert_eq!(*x, 4);
470 ///
471 /// let _y = x.clone();
472 /// assert!(Rc::get_mut(&mut x).is_none());
473 /// ```
474 #[inline]
475 #[stable(feature = "rc_unique", since = "1.4.0")]
476 pub fn get_mut(this: &mut Self) -> Option<&mut T> {
477 if Rc::is_unique(this) {
478 let inner = unsafe { &mut **this.ptr };
479 Some(&mut inner.value)
480 } else {
481 None
482 }
483 }
484
485 #[inline]
486 #[unstable(feature = "ptr_eq",
487 reason = "newly added",
488 issue = "36497")]
489 /// Returns true if the two `Rc`s point to the same value (not
490 /// just values that compare as equal).
491 ///
492 /// # Examples
493 ///
494 /// ```
495 /// #![feature(ptr_eq)]
496 ///
497 /// use std::rc::Rc;
498 ///
499 /// let five = Rc::new(5);
500 /// let same_five = five.clone();
501 /// let other_five = Rc::new(5);
502 ///
503 /// assert!(Rc::ptr_eq(&five, &same_five));
504 /// assert!(!Rc::ptr_eq(&five, &other_five));
505 /// ```
506 pub fn ptr_eq(this: &Self, other: &Self) -> bool {
507 let this_ptr: *const RcBox<T> = *this.ptr;
508 let other_ptr: *const RcBox<T> = *other.ptr;
509 this_ptr == other_ptr
510 }
511 }
512
513 impl<T: Clone> Rc<T> {
514 /// Makes a mutable reference into the given `Rc`.
515 ///
516 /// If there are other `Rc` or [`Weak`][weak] pointers to the same value,
517 /// then `make_mut` will invoke [`clone`][clone] on the inner value to
518 /// ensure unique ownership. This is also referred to as clone-on-write.
519 ///
520 /// See also [`get_mut`][get_mut], which will fail rather than cloning.
521 ///
522 /// [weak]: struct.Weak.html
523 /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
524 /// [get_mut]: struct.Rc.html#method.get_mut
525 ///
526 /// # Examples
527 ///
528 /// ```
529 /// use std::rc::Rc;
530 ///
531 /// let mut data = Rc::new(5);
532 ///
533 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
534 /// let mut other_data = data.clone(); // Won't clone inner data
535 /// *Rc::make_mut(&mut data) += 1; // Clones inner data
536 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
537 /// *Rc::make_mut(&mut other_data) *= 2; // Won't clone anything
538 ///
539 /// // Now `data` and `other_data` point to different values.
540 /// assert_eq!(*data, 8);
541 /// assert_eq!(*other_data, 12);
542 /// ```
543 #[inline]
544 #[stable(feature = "rc_unique", since = "1.4.0")]
545 pub fn make_mut(this: &mut Self) -> &mut T {
546 if Rc::strong_count(this) != 1 {
547 // Gotta clone the data, there are other Rcs
548 *this = Rc::new((**this).clone())
549 } else if Rc::weak_count(this) != 0 {
550 // Can just steal the data, all that's left is Weaks
551 unsafe {
552 let mut swap = Rc::new(ptr::read(&(**this.ptr).value));
553 mem::swap(this, &mut swap);
554 swap.dec_strong();
555 // Remove implicit strong-weak ref (no need to craft a fake
556 // Weak here -- we know other Weaks can clean up for us)
557 swap.dec_weak();
558 forget(swap);
559 }
560 }
561 // This unsafety is ok because we're guaranteed that the pointer
562 // returned is the *only* pointer that will ever be returned to T. Our
563 // reference count is guaranteed to be 1 at this point, and we required
564 // the `Rc<T>` itself to be `mut`, so we're returning the only possible
565 // reference to the inner value.
566 let inner = unsafe { &mut **this.ptr };
567 &mut inner.value
568 }
569 }
570
571 #[stable(feature = "rust1", since = "1.0.0")]
572 impl<T: ?Sized> Deref for Rc<T> {
573 type Target = T;
574
575 #[inline(always)]
576 fn deref(&self) -> &T {
577 &self.inner().value
578 }
579 }
580
581 #[stable(feature = "rust1", since = "1.0.0")]
582 impl<T: ?Sized> Drop for Rc<T> {
583 /// Drops the `Rc`.
584 ///
585 /// This will decrement the strong reference count. If the strong reference
586 /// count reaches zero then the only other references (if any) are `Weak`,
587 /// so we `drop` the inner value.
588 ///
589 /// # Examples
590 ///
591 /// ```
592 /// use std::rc::Rc;
593 ///
594 /// struct Foo;
595 ///
596 /// impl Drop for Foo {
597 /// fn drop(&mut self) {
598 /// println!("dropped!");
599 /// }
600 /// }
601 ///
602 /// let foo = Rc::new(Foo);
603 /// let foo2 = foo.clone();
604 ///
605 /// drop(foo); // Doesn't print anything
606 /// drop(foo2); // Prints "dropped!"
607 /// ```
608 #[unsafe_destructor_blind_to_params]
609 fn drop(&mut self) {
610 unsafe {
611 let ptr = *self.ptr;
612
613 self.dec_strong();
614 if self.strong() == 0 {
615 // destroy the contained object
616 ptr::drop_in_place(&mut (*ptr).value);
617
618 // remove the implicit "strong weak" pointer now that we've
619 // destroyed the contents.
620 self.dec_weak();
621
622 if self.weak() == 0 {
623 deallocate(ptr as *mut u8, size_of_val(&*ptr), align_of_val(&*ptr))
624 }
625 }
626 }
627 }
628 }
629
630 #[stable(feature = "rust1", since = "1.0.0")]
631 impl<T: ?Sized> Clone for Rc<T> {
632 /// Makes a clone of the `Rc` pointer.
633 ///
634 /// This creates another pointer to the same inner value, increasing the
635 /// strong reference count.
636 ///
637 /// # Examples
638 ///
639 /// ```
640 /// use std::rc::Rc;
641 ///
642 /// let five = Rc::new(5);
643 ///
644 /// five.clone();
645 /// ```
646 #[inline]
647 fn clone(&self) -> Rc<T> {
648 self.inc_strong();
649 Rc { ptr: self.ptr }
650 }
651 }
652
653 #[stable(feature = "rust1", since = "1.0.0")]
654 impl<T: Default> Default for Rc<T> {
655 /// Creates a new `Rc<T>`, with the `Default` value for `T`.
656 ///
657 /// # Examples
658 ///
659 /// ```
660 /// use std::rc::Rc;
661 ///
662 /// let x: Rc<i32> = Default::default();
663 /// assert_eq!(*x, 0);
664 /// ```
665 #[inline]
666 fn default() -> Rc<T> {
667 Rc::new(Default::default())
668 }
669 }
670
671 #[stable(feature = "rust1", since = "1.0.0")]
672 impl<T: ?Sized + PartialEq> PartialEq for Rc<T> {
673 /// Equality for two `Rc`s.
674 ///
675 /// Two `Rc`s are equal if their inner values are equal.
676 ///
677 /// # Examples
678 ///
679 /// ```
680 /// use std::rc::Rc;
681 ///
682 /// let five = Rc::new(5);
683 ///
684 /// assert!(five == Rc::new(5));
685 /// ```
686 #[inline(always)]
687 fn eq(&self, other: &Rc<T>) -> bool {
688 **self == **other
689 }
690
691 /// Inequality for two `Rc`s.
692 ///
693 /// Two `Rc`s are unequal if their inner values are unequal.
694 ///
695 /// # Examples
696 ///
697 /// ```
698 /// use std::rc::Rc;
699 ///
700 /// let five = Rc::new(5);
701 ///
702 /// assert!(five != Rc::new(6));
703 /// ```
704 #[inline(always)]
705 fn ne(&self, other: &Rc<T>) -> bool {
706 **self != **other
707 }
708 }
709
710 #[stable(feature = "rust1", since = "1.0.0")]
711 impl<T: ?Sized + Eq> Eq for Rc<T> {}
712
713 #[stable(feature = "rust1", since = "1.0.0")]
714 impl<T: ?Sized + PartialOrd> PartialOrd for Rc<T> {
715 /// Partial comparison for two `Rc`s.
716 ///
717 /// The two are compared by calling `partial_cmp()` on their inner values.
718 ///
719 /// # Examples
720 ///
721 /// ```
722 /// use std::rc::Rc;
723 /// use std::cmp::Ordering;
724 ///
725 /// let five = Rc::new(5);
726 ///
727 /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&Rc::new(6)));
728 /// ```
729 #[inline(always)]
730 fn partial_cmp(&self, other: &Rc<T>) -> Option<Ordering> {
731 (**self).partial_cmp(&**other)
732 }
733
734 /// Less-than comparison for two `Rc`s.
735 ///
736 /// The two are compared by calling `<` on their inner values.
737 ///
738 /// # Examples
739 ///
740 /// ```
741 /// use std::rc::Rc;
742 ///
743 /// let five = Rc::new(5);
744 ///
745 /// assert!(five < Rc::new(6));
746 /// ```
747 #[inline(always)]
748 fn lt(&self, other: &Rc<T>) -> bool {
749 **self < **other
750 }
751
752 /// 'Less than or equal to' comparison for two `Rc`s.
753 ///
754 /// The two are compared by calling `<=` on their inner values.
755 ///
756 /// # Examples
757 ///
758 /// ```
759 /// use std::rc::Rc;
760 ///
761 /// let five = Rc::new(5);
762 ///
763 /// assert!(five <= Rc::new(5));
764 /// ```
765 #[inline(always)]
766 fn le(&self, other: &Rc<T>) -> bool {
767 **self <= **other
768 }
769
770 /// Greater-than comparison for two `Rc`s.
771 ///
772 /// The two are compared by calling `>` on their inner values.
773 ///
774 /// # Examples
775 ///
776 /// ```
777 /// use std::rc::Rc;
778 ///
779 /// let five = Rc::new(5);
780 ///
781 /// assert!(five > Rc::new(4));
782 /// ```
783 #[inline(always)]
784 fn gt(&self, other: &Rc<T>) -> bool {
785 **self > **other
786 }
787
788 /// 'Greater than or equal to' comparison for two `Rc`s.
789 ///
790 /// The two are compared by calling `>=` on their inner values.
791 ///
792 /// # Examples
793 ///
794 /// ```
795 /// use std::rc::Rc;
796 ///
797 /// let five = Rc::new(5);
798 ///
799 /// assert!(five >= Rc::new(5));
800 /// ```
801 #[inline(always)]
802 fn ge(&self, other: &Rc<T>) -> bool {
803 **self >= **other
804 }
805 }
806
807 #[stable(feature = "rust1", since = "1.0.0")]
808 impl<T: ?Sized + Ord> Ord for Rc<T> {
809 /// Comparison for two `Rc`s.
810 ///
811 /// The two are compared by calling `cmp()` on their inner values.
812 ///
813 /// # Examples
814 ///
815 /// ```
816 /// use std::rc::Rc;
817 /// use std::cmp::Ordering;
818 ///
819 /// let five = Rc::new(5);
820 ///
821 /// assert_eq!(Ordering::Less, five.cmp(&Rc::new(6)));
822 /// ```
823 #[inline]
824 fn cmp(&self, other: &Rc<T>) -> Ordering {
825 (**self).cmp(&**other)
826 }
827 }
828
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 #[stable(feature = "rust1", since = "1.0.0")]
837 impl<T: ?Sized + fmt::Display> fmt::Display for Rc<T> {
838 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
839 fmt::Display::fmt(&**self, f)
840 }
841 }
842
843 #[stable(feature = "rust1", since = "1.0.0")]
844 impl<T: ?Sized + fmt::Debug> fmt::Debug for Rc<T> {
845 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
846 fmt::Debug::fmt(&**self, f)
847 }
848 }
849
850 #[stable(feature = "rust1", since = "1.0.0")]
851 impl<T: ?Sized> fmt::Pointer for Rc<T> {
852 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
853 fmt::Pointer::fmt(&*self.ptr, f)
854 }
855 }
856
857 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
858 impl<T> From<T> for Rc<T> {
859 fn from(t: T) -> Self {
860 Rc::new(t)
861 }
862 }
863
864 /// A weak version of [`Rc`][rc].
865 ///
866 /// `Weak` pointers do not count towards determining if the inner value
867 /// should be dropped.
868 ///
869 /// The typical way to obtain a `Weak` pointer is to call
870 /// [`Rc::downgrade`][downgrade].
871 ///
872 /// See the [module-level documentation](./index.html) for more details.
873 ///
874 /// [rc]: struct.Rc.html
875 /// [downgrade]: struct.Rc.html#method.downgrade
876 #[cfg_attr(stage0, unsafe_no_drop_flag)]
877 #[stable(feature = "rc_weak", since = "1.4.0")]
878 pub struct Weak<T: ?Sized> {
879 ptr: Shared<RcBox<T>>,
880 }
881
882 #[stable(feature = "rc_weak", since = "1.4.0")]
883 impl<T: ?Sized> !marker::Send for Weak<T> {}
884 #[stable(feature = "rc_weak", since = "1.4.0")]
885 impl<T: ?Sized> !marker::Sync for Weak<T> {}
886
887 #[unstable(feature = "coerce_unsized", issue = "27732")]
888 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {}
889
890 impl<T> Weak<T> {
891 /// Constructs a new `Weak<T>`, without an accompanying instance of `T`.
892 ///
893 /// This allocates memory for `T`, but does not initialize it. Calling
894 /// [`upgrade`][upgrade] on the return value always gives
895 /// [`None`][option].
896 ///
897 /// [upgrade]: struct.Weak.html#method.upgrade
898 /// [option]: ../../std/option/enum.Option.html
899 ///
900 /// # Examples
901 ///
902 /// ```
903 /// use std::rc::Weak;
904 ///
905 /// let empty: Weak<i64> = Weak::new();
906 /// assert!(empty.upgrade().is_none());
907 /// ```
908 #[stable(feature = "downgraded_weak", since = "1.10.0")]
909 pub fn new() -> Weak<T> {
910 unsafe {
911 Weak {
912 ptr: Shared::new(Box::into_raw(box RcBox {
913 strong: Cell::new(0),
914 weak: Cell::new(1),
915 value: uninitialized(),
916 })),
917 }
918 }
919 }
920 }
921
922 impl<T: ?Sized> Weak<T> {
923 /// Upgrades the `Weak` pointer to an [`Rc`][rc], if possible.
924 ///
925 /// Returns [`None`][option] if the strong count has reached zero and the
926 /// inner value was destroyed.
927 ///
928 /// [rc]: struct.Rc.html
929 /// [option]: ../../std/option/enum.Option.html
930 ///
931 /// # Examples
932 ///
933 /// ```
934 /// use std::rc::Rc;
935 ///
936 /// let five = Rc::new(5);
937 ///
938 /// let weak_five = Rc::downgrade(&five);
939 ///
940 /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
941 /// assert!(strong_five.is_some());
942 ///
943 /// // Destroy all strong pointers.
944 /// drop(strong_five);
945 /// drop(five);
946 ///
947 /// assert!(weak_five.upgrade().is_none());
948 /// ```
949 #[stable(feature = "rc_weak", since = "1.4.0")]
950 pub fn upgrade(&self) -> Option<Rc<T>> {
951 if self.strong() == 0 {
952 None
953 } else {
954 self.inc_strong();
955 Some(Rc { ptr: self.ptr })
956 }
957 }
958 }
959
960 #[stable(feature = "rc_weak", since = "1.4.0")]
961 impl<T: ?Sized> Drop for Weak<T> {
962 /// Drops the `Weak` pointer.
963 ///
964 /// This will decrement the weak reference count.
965 ///
966 /// # Examples
967 ///
968 /// ```
969 /// use std::rc::Rc;
970 ///
971 /// struct Foo;
972 ///
973 /// impl Drop for Foo {
974 /// fn drop(&mut self) {
975 /// println!("dropped!");
976 /// }
977 /// }
978 ///
979 /// let foo = Rc::new(Foo);
980 /// let weak_foo = Rc::downgrade(&foo);
981 /// let other_weak_foo = weak_foo.clone();
982 ///
983 /// drop(weak_foo); // Doesn't print anything
984 /// drop(foo); // Prints "dropped!"
985 ///
986 /// assert!(other_weak_foo.upgrade().is_none());
987 /// ```
988 fn drop(&mut self) {
989 unsafe {
990 let ptr = *self.ptr;
991
992 self.dec_weak();
993 // the weak count starts at 1, and will only go to zero if all
994 // the strong pointers have disappeared.
995 if self.weak() == 0 {
996 deallocate(ptr as *mut u8, size_of_val(&*ptr), align_of_val(&*ptr))
997 }
998 }
999 }
1000 }
1001
1002 #[stable(feature = "rc_weak", since = "1.4.0")]
1003 impl<T: ?Sized> Clone for Weak<T> {
1004 /// Makes a clone of the `Weak` pointer.
1005 ///
1006 /// This creates another pointer to the same inner value, increasing the
1007 /// weak reference count.
1008 ///
1009 /// # Examples
1010 ///
1011 /// ```
1012 /// use std::rc::Rc;
1013 ///
1014 /// let weak_five = Rc::downgrade(&Rc::new(5));
1015 ///
1016 /// weak_five.clone();
1017 /// ```
1018 #[inline]
1019 fn clone(&self) -> Weak<T> {
1020 self.inc_weak();
1021 Weak { ptr: self.ptr }
1022 }
1023 }
1024
1025 #[stable(feature = "rc_weak", since = "1.4.0")]
1026 impl<T: ?Sized + fmt::Debug> fmt::Debug for Weak<T> {
1027 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1028 write!(f, "(Weak)")
1029 }
1030 }
1031
1032 #[stable(feature = "downgraded_weak", since = "1.10.0")]
1033 impl<T> Default for Weak<T> {
1034 /// Constructs a new `Weak<T>`, without an accompanying instance of `T`.
1035 ///
1036 /// This allocates memory for `T`, but does not initialize it. Calling
1037 /// [`upgrade`][upgrade] on the return value always gives
1038 /// [`None`][option].
1039 ///
1040 /// [upgrade]: struct.Weak.html#method.upgrade
1041 /// [option]: ../../std/option/enum.Option.html
1042 ///
1043 /// # Examples
1044 ///
1045 /// ```
1046 /// use std::rc::Weak;
1047 ///
1048 /// let empty: Weak<i64> = Default::default();
1049 /// assert!(empty.upgrade().is_none());
1050 /// ```
1051 fn default() -> Weak<T> {
1052 Weak::new()
1053 }
1054 }
1055
1056 // NOTE: We checked_add here to deal with mem::forget safety. In particular
1057 // if you mem::forget Rcs (or Weaks), the ref-count can overflow, and then
1058 // you can free the allocation while outstanding Rcs (or Weaks) exist.
1059 // We abort because this is such a degenerate scenario that we don't care about
1060 // what happens -- no real program should ever experience this.
1061 //
1062 // This should have negligible overhead since you don't actually need to
1063 // clone these much in Rust thanks to ownership and move-semantics.
1064
1065 #[doc(hidden)]
1066 trait RcBoxPtr<T: ?Sized> {
1067 fn inner(&self) -> &RcBox<T>;
1068
1069 #[inline]
1070 fn strong(&self) -> usize {
1071 self.inner().strong.get()
1072 }
1073
1074 #[inline]
1075 fn inc_strong(&self) {
1076 self.inner().strong.set(self.strong().checked_add(1).unwrap_or_else(|| unsafe { abort() }));
1077 }
1078
1079 #[inline]
1080 fn dec_strong(&self) {
1081 self.inner().strong.set(self.strong() - 1);
1082 }
1083
1084 #[inline]
1085 fn weak(&self) -> usize {
1086 self.inner().weak.get()
1087 }
1088
1089 #[inline]
1090 fn inc_weak(&self) {
1091 self.inner().weak.set(self.weak().checked_add(1).unwrap_or_else(|| unsafe { abort() }));
1092 }
1093
1094 #[inline]
1095 fn dec_weak(&self) {
1096 self.inner().weak.set(self.weak() - 1);
1097 }
1098 }
1099
1100 impl<T: ?Sized> RcBoxPtr<T> for Rc<T> {
1101 #[inline(always)]
1102 fn inner(&self) -> &RcBox<T> {
1103 unsafe {
1104 // Safe to assume this here, as if it weren't true, we'd be breaking
1105 // the contract anyway.
1106 // This allows the null check to be elided in the destructor if we
1107 // manipulated the reference count in the same function.
1108 assume(!(*(&self.ptr as *const _ as *const *const ())).is_null());
1109 &(**self.ptr)
1110 }
1111 }
1112 }
1113
1114 impl<T: ?Sized> RcBoxPtr<T> for Weak<T> {
1115 #[inline(always)]
1116 fn inner(&self) -> &RcBox<T> {
1117 unsafe {
1118 // Safe to assume this here, as if it weren't true, we'd be breaking
1119 // the contract anyway.
1120 // This allows the null check to be elided in the destructor if we
1121 // manipulated the reference count in the same function.
1122 assume(!(*(&self.ptr as *const _ as *const *const ())).is_null());
1123 &(**self.ptr)
1124 }
1125 }
1126 }
1127
1128 #[cfg(test)]
1129 mod tests {
1130 use super::{Rc, Weak};
1131 use std::boxed::Box;
1132 use std::cell::RefCell;
1133 use std::option::Option;
1134 use std::option::Option::{None, Some};
1135 use std::result::Result::{Err, Ok};
1136 use std::mem::drop;
1137 use std::clone::Clone;
1138 use std::convert::From;
1139
1140 #[test]
1141 fn test_clone() {
1142 let x = Rc::new(RefCell::new(5));
1143 let y = x.clone();
1144 *x.borrow_mut() = 20;
1145 assert_eq!(*y.borrow(), 20);
1146 }
1147
1148 #[test]
1149 fn test_simple() {
1150 let x = Rc::new(5);
1151 assert_eq!(*x, 5);
1152 }
1153
1154 #[test]
1155 fn test_simple_clone() {
1156 let x = Rc::new(5);
1157 let y = x.clone();
1158 assert_eq!(*x, 5);
1159 assert_eq!(*y, 5);
1160 }
1161
1162 #[test]
1163 fn test_destructor() {
1164 let x: Rc<Box<_>> = Rc::new(box 5);
1165 assert_eq!(**x, 5);
1166 }
1167
1168 #[test]
1169 fn test_live() {
1170 let x = Rc::new(5);
1171 let y = Rc::downgrade(&x);
1172 assert!(y.upgrade().is_some());
1173 }
1174
1175 #[test]
1176 fn test_dead() {
1177 let x = Rc::new(5);
1178 let y = Rc::downgrade(&x);
1179 drop(x);
1180 assert!(y.upgrade().is_none());
1181 }
1182
1183 #[test]
1184 fn weak_self_cyclic() {
1185 struct Cycle {
1186 x: RefCell<Option<Weak<Cycle>>>,
1187 }
1188
1189 let a = Rc::new(Cycle { x: RefCell::new(None) });
1190 let b = Rc::downgrade(&a.clone());
1191 *a.x.borrow_mut() = Some(b);
1192
1193 // hopefully we don't double-free (or leak)...
1194 }
1195
1196 #[test]
1197 fn is_unique() {
1198 let x = Rc::new(3);
1199 assert!(Rc::is_unique(&x));
1200 let y = x.clone();
1201 assert!(!Rc::is_unique(&x));
1202 drop(y);
1203 assert!(Rc::is_unique(&x));
1204 let w = Rc::downgrade(&x);
1205 assert!(!Rc::is_unique(&x));
1206 drop(w);
1207 assert!(Rc::is_unique(&x));
1208 }
1209
1210 #[test]
1211 fn test_strong_count() {
1212 let a = Rc::new(0);
1213 assert!(Rc::strong_count(&a) == 1);
1214 let w = Rc::downgrade(&a);
1215 assert!(Rc::strong_count(&a) == 1);
1216 let b = w.upgrade().expect("upgrade of live rc failed");
1217 assert!(Rc::strong_count(&b) == 2);
1218 assert!(Rc::strong_count(&a) == 2);
1219 drop(w);
1220 drop(a);
1221 assert!(Rc::strong_count(&b) == 1);
1222 let c = b.clone();
1223 assert!(Rc::strong_count(&b) == 2);
1224 assert!(Rc::strong_count(&c) == 2);
1225 }
1226
1227 #[test]
1228 fn test_weak_count() {
1229 let a = Rc::new(0);
1230 assert!(Rc::strong_count(&a) == 1);
1231 assert!(Rc::weak_count(&a) == 0);
1232 let w = Rc::downgrade(&a);
1233 assert!(Rc::strong_count(&a) == 1);
1234 assert!(Rc::weak_count(&a) == 1);
1235 drop(w);
1236 assert!(Rc::strong_count(&a) == 1);
1237 assert!(Rc::weak_count(&a) == 0);
1238 let c = a.clone();
1239 assert!(Rc::strong_count(&a) == 2);
1240 assert!(Rc::weak_count(&a) == 0);
1241 drop(c);
1242 }
1243
1244 #[test]
1245 fn try_unwrap() {
1246 let x = Rc::new(3);
1247 assert_eq!(Rc::try_unwrap(x), Ok(3));
1248 let x = Rc::new(4);
1249 let _y = x.clone();
1250 assert_eq!(Rc::try_unwrap(x), Err(Rc::new(4)));
1251 let x = Rc::new(5);
1252 let _w = Rc::downgrade(&x);
1253 assert_eq!(Rc::try_unwrap(x), Ok(5));
1254 }
1255
1256 #[test]
1257 fn get_mut() {
1258 let mut x = Rc::new(3);
1259 *Rc::get_mut(&mut x).unwrap() = 4;
1260 assert_eq!(*x, 4);
1261 let y = x.clone();
1262 assert!(Rc::get_mut(&mut x).is_none());
1263 drop(y);
1264 assert!(Rc::get_mut(&mut x).is_some());
1265 let _w = Rc::downgrade(&x);
1266 assert!(Rc::get_mut(&mut x).is_none());
1267 }
1268
1269 #[test]
1270 fn test_cowrc_clone_make_unique() {
1271 let mut cow0 = Rc::new(75);
1272 let mut cow1 = cow0.clone();
1273 let mut cow2 = cow1.clone();
1274
1275 assert!(75 == *Rc::make_mut(&mut cow0));
1276 assert!(75 == *Rc::make_mut(&mut cow1));
1277 assert!(75 == *Rc::make_mut(&mut cow2));
1278
1279 *Rc::make_mut(&mut cow0) += 1;
1280 *Rc::make_mut(&mut cow1) += 2;
1281 *Rc::make_mut(&mut cow2) += 3;
1282
1283 assert!(76 == *cow0);
1284 assert!(77 == *cow1);
1285 assert!(78 == *cow2);
1286
1287 // none should point to the same backing memory
1288 assert!(*cow0 != *cow1);
1289 assert!(*cow0 != *cow2);
1290 assert!(*cow1 != *cow2);
1291 }
1292
1293 #[test]
1294 fn test_cowrc_clone_unique2() {
1295 let mut cow0 = Rc::new(75);
1296 let cow1 = cow0.clone();
1297 let cow2 = cow1.clone();
1298
1299 assert!(75 == *cow0);
1300 assert!(75 == *cow1);
1301 assert!(75 == *cow2);
1302
1303 *Rc::make_mut(&mut cow0) += 1;
1304
1305 assert!(76 == *cow0);
1306 assert!(75 == *cow1);
1307 assert!(75 == *cow2);
1308
1309 // cow1 and cow2 should share the same contents
1310 // cow0 should have a unique reference
1311 assert!(*cow0 != *cow1);
1312 assert!(*cow0 != *cow2);
1313 assert!(*cow1 == *cow2);
1314 }
1315
1316 #[test]
1317 fn test_cowrc_clone_weak() {
1318 let mut cow0 = Rc::new(75);
1319 let cow1_weak = Rc::downgrade(&cow0);
1320
1321 assert!(75 == *cow0);
1322 assert!(75 == *cow1_weak.upgrade().unwrap());
1323
1324 *Rc::make_mut(&mut cow0) += 1;
1325
1326 assert!(76 == *cow0);
1327 assert!(cow1_weak.upgrade().is_none());
1328 }
1329
1330 #[test]
1331 fn test_show() {
1332 let foo = Rc::new(75);
1333 assert_eq!(format!("{:?}", foo), "75");
1334 }
1335
1336 #[test]
1337 fn test_unsized() {
1338 let foo: Rc<[i32]> = Rc::new([1, 2, 3]);
1339 assert_eq!(foo, foo.clone());
1340 }
1341
1342 #[test]
1343 fn test_from_owned() {
1344 let foo = 123;
1345 let foo_rc = Rc::from(foo);
1346 assert!(123 == *foo_rc);
1347 }
1348
1349 #[test]
1350 fn test_new_weak() {
1351 let foo: Weak<usize> = Weak::new();
1352 assert!(foo.upgrade().is_none());
1353 }
1354
1355 #[test]
1356 fn test_ptr_eq() {
1357 let five = Rc::new(5);
1358 let same_five = five.clone();
1359 let other_five = Rc::new(5);
1360
1361 assert!(Rc::ptr_eq(&five, &same_five));
1362 assert!(!Rc::ptr_eq(&five, &other_five));
1363 }
1364 }
1365
1366 #[stable(feature = "rust1", since = "1.0.0")]
1367 impl<T: ?Sized> borrow::Borrow<T> for Rc<T> {
1368 fn borrow(&self) -> &T {
1369 &**self
1370 }
1371 }
1372
1373 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1374 impl<T: ?Sized> AsRef<T> for Rc<T> {
1375 fn as_ref(&self) -> &T {
1376 &**self
1377 }
1378 }