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