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