]> git.lizzy.rs Git - rust.git/blob - src/liballoc/rc.rs
Simplify SaveHandler trait
[rust.git] / src / liballoc / rc.rs
1 //! Single-threaded reference-counting pointers. 'Rc' stands for 'Reference
2 //! Counted'.
3 //!
4 //! The type [`Rc<T>`][`Rc`] provides shared ownership of a value of type `T`,
5 //! allocated in the heap. Invoking [`clone`][clone] on [`Rc`] produces a new
6 //! pointer to the same value in the heap. When the last [`Rc`] pointer to a
7 //! given value is destroyed, the pointed-to value is also destroyed.
8 //!
9 //! Shared references in Rust disallow mutation by default, and [`Rc`]
10 //! is no exception: you cannot generally obtain a mutable reference to
11 //! something inside an [`Rc`]. If you need mutability, put a [`Cell`]
12 //! or [`RefCell`] inside the [`Rc`]; see [an example of mutability
13 //! inside an Rc][mutability].
14 //!
15 //! [`Rc`] uses non-atomic reference counting. This means that overhead is very
16 //! low, but an [`Rc`] cannot be sent between threads, and consequently [`Rc`]
17 //! does not implement [`Send`][send]. As a result, the Rust compiler
18 //! will check *at compile time* that you are not sending [`Rc`]s between
19 //! threads. If you need multi-threaded, atomic reference counting, use
20 //! [`sync::Arc`][arc].
21 //!
22 //! The [`downgrade`][downgrade] method can be used to create a non-owning
23 //! [`Weak`] pointer. A [`Weak`] pointer can be [`upgrade`][upgrade]d
24 //! to an [`Rc`], but this will return [`None`] if the value has
25 //! already been dropped.
26 //!
27 //! A cycle between [`Rc`] pointers will never be deallocated. For this reason,
28 //! [`Weak`] is used to break cycles. For example, a tree could have strong
29 //! [`Rc`] pointers from parent nodes to children, and [`Weak`] pointers from
30 //! children back to their parents.
31 //!
32 //! `Rc<T>` automatically dereferences to `T` (via the [`Deref`] trait),
33 //! so you can call `T`'s methods on a value of type [`Rc<T>`][`Rc`]. To avoid name
34 //! clashes with `T`'s methods, the methods of [`Rc<T>`][`Rc`] itself are associated
35 //! functions, called using function-like syntax:
36 //!
37 //! ```
38 //! use std::rc::Rc;
39 //! let my_rc = Rc::new(());
40 //!
41 //! Rc::downgrade(&my_rc);
42 //! ```
43 //!
44 //! [`Weak<T>`][`Weak`] does not auto-dereference to `T`, because the value may have
45 //! already been destroyed.
46 //!
47 //! # Cloning references
48 //!
49 //! Creating a new reference from an existing reference counted pointer is done using the
50 //! `Clone` trait implemented for [`Rc<T>`][`Rc`] and [`Weak<T>`][`Weak`].
51 //!
52 //! ```
53 //! use std::rc::Rc;
54 //! let foo = Rc::new(vec![1.0, 2.0, 3.0]);
55 //! // The two syntaxes below are equivalent.
56 //! let a = foo.clone();
57 //! let b = Rc::clone(&foo);
58 //! // a and b both point to the same memory location as foo.
59 //! ```
60 //!
61 //! The `Rc::clone(&from)` syntax is the most idiomatic because it conveys more explicitly
62 //! the meaning of the code. In the example above, this syntax makes it easier to see that
63 //! this code is creating a new reference rather than copying the whole content of foo.
64 //!
65 //! # Examples
66 //!
67 //! Consider a scenario where a set of `Gadget`s are owned by a given `Owner`.
68 //! We want to have our `Gadget`s point to their `Owner`. We can't do this with
69 //! unique ownership, because more than one gadget may belong to the same
70 //! `Owner`. [`Rc`] allows us to share an `Owner` between multiple `Gadget`s,
71 //! and have the `Owner` remain allocated as long as any `Gadget` points at it.
72 //!
73 //! ```
74 //! use std::rc::Rc;
75 //!
76 //! struct Owner {
77 //!     name: String,
78 //!     // ...other fields
79 //! }
80 //!
81 //! struct Gadget {
82 //!     id: i32,
83 //!     owner: Rc<Owner>,
84 //!     // ...other fields
85 //! }
86 //!
87 //! fn main() {
88 //!     // Create a reference-counted `Owner`.
89 //!     let gadget_owner: Rc<Owner> = Rc::new(
90 //!         Owner {
91 //!             name: "Gadget Man".to_string(),
92 //!         }
93 //!     );
94 //!
95 //!     // Create `Gadget`s belonging to `gadget_owner`. Cloning the `Rc<Owner>`
96 //!     // value gives us a new pointer to the same `Owner` value, incrementing
97 //!     // the reference count in the process.
98 //!     let gadget1 = Gadget {
99 //!         id: 1,
100 //!         owner: Rc::clone(&gadget_owner),
101 //!     };
102 //!     let gadget2 = Gadget {
103 //!         id: 2,
104 //!         owner: Rc::clone(&gadget_owner),
105 //!     };
106 //!
107 //!     // Dispose of our local variable `gadget_owner`.
108 //!     drop(gadget_owner);
109 //!
110 //!     // Despite dropping `gadget_owner`, we're still able to print out the name
111 //!     // of the `Owner` of the `Gadget`s. This is because we've only dropped a
112 //!     // single `Rc<Owner>`, not the `Owner` it points to. As long as there are
113 //!     // other `Rc<Owner>` values pointing at the same `Owner`, it will remain
114 //!     // allocated. The field projection `gadget1.owner.name` works because
115 //!     // `Rc<Owner>` automatically dereferences to `Owner`.
116 //!     println!("Gadget {} owned by {}", gadget1.id, gadget1.owner.name);
117 //!     println!("Gadget {} owned by {}", gadget2.id, gadget2.owner.name);
118 //!
119 //!     // At the end of the function, `gadget1` and `gadget2` are destroyed, and
120 //!     // with them the last counted references to our `Owner`. Gadget Man now
121 //!     // gets destroyed as well.
122 //! }
123 //! ```
124 //!
125 //! If our requirements change, and we also need to be able to traverse from
126 //! `Owner` to `Gadget`, we will run into problems. An [`Rc`] pointer from `Owner`
127 //! to `Gadget` introduces a cycle between the values. This means that their
128 //! reference counts can never reach 0, and the values will remain allocated
129 //! forever: a memory leak. In order to get around this, we can use [`Weak`]
130 //! pointers.
131 //!
132 //! Rust actually makes it somewhat difficult to produce this loop in the first
133 //! place. In order to end up with two values that point at each other, one of
134 //! them needs to be mutable. This is difficult because [`Rc`] enforces
135 //! memory safety by only giving out shared references to the value it wraps,
136 //! and these don't allow direct mutation. We need to wrap the part of the
137 //! value we wish to mutate in a [`RefCell`], which provides *interior
138 //! mutability*: a method to achieve mutability through a shared reference.
139 //! [`RefCell`] enforces Rust's borrowing rules at runtime.
140 //!
141 //! ```
142 //! use std::rc::Rc;
143 //! use std::rc::Weak;
144 //! use std::cell::RefCell;
145 //!
146 //! struct Owner {
147 //!     name: String,
148 //!     gadgets: RefCell<Vec<Weak<Gadget>>>,
149 //!     // ...other fields
150 //! }
151 //!
152 //! struct Gadget {
153 //!     id: i32,
154 //!     owner: Rc<Owner>,
155 //!     // ...other fields
156 //! }
157 //!
158 //! fn main() {
159 //!     // Create a reference-counted `Owner`. Note that we've put the `Owner`'s
160 //!     // vector of `Gadget`s inside a `RefCell` so that we can mutate it through
161 //!     // a shared reference.
162 //!     let gadget_owner: Rc<Owner> = Rc::new(
163 //!         Owner {
164 //!             name: "Gadget Man".to_string(),
165 //!             gadgets: RefCell::new(vec![]),
166 //!         }
167 //!     );
168 //!
169 //!     // Create `Gadget`s belonging to `gadget_owner`, as before.
170 //!     let gadget1 = Rc::new(
171 //!         Gadget {
172 //!             id: 1,
173 //!             owner: Rc::clone(&gadget_owner),
174 //!         }
175 //!     );
176 //!     let gadget2 = Rc::new(
177 //!         Gadget {
178 //!             id: 2,
179 //!             owner: Rc::clone(&gadget_owner),
180 //!         }
181 //!     );
182 //!
183 //!     // Add the `Gadget`s to their `Owner`.
184 //!     {
185 //!         let mut gadgets = gadget_owner.gadgets.borrow_mut();
186 //!         gadgets.push(Rc::downgrade(&gadget1));
187 //!         gadgets.push(Rc::downgrade(&gadget2));
188 //!
189 //!         // `RefCell` dynamic borrow ends here.
190 //!     }
191 //!
192 //!     // Iterate over our `Gadget`s, printing their details out.
193 //!     for gadget_weak in gadget_owner.gadgets.borrow().iter() {
194 //!
195 //!         // `gadget_weak` is a `Weak<Gadget>`. Since `Weak` pointers can't
196 //!         // guarantee the value is still allocated, we need to call
197 //!         // `upgrade`, which returns an `Option<Rc<Gadget>>`.
198 //!         //
199 //!         // In this case we know the value still exists, so we simply
200 //!         // `unwrap` the `Option`. In a more complicated program, you might
201 //!         // need graceful error handling for a `None` result.
202 //!
203 //!         let gadget = gadget_weak.upgrade().unwrap();
204 //!         println!("Gadget {} owned by {}", gadget.id, gadget.owner.name);
205 //!     }
206 //!
207 //!     // At the end of the function, `gadget_owner`, `gadget1`, and `gadget2`
208 //!     // are destroyed. There are now no strong (`Rc`) pointers to the
209 //!     // gadgets, so they are destroyed. This zeroes the reference count on
210 //!     // Gadget Man, so he gets destroyed as well.
211 //! }
212 //! ```
213 //!
214 //! [`Rc`]: struct.Rc.html
215 //! [`Weak`]: struct.Weak.html
216 //! [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
217 //! [`Cell`]: ../../std/cell/struct.Cell.html
218 //! [`RefCell`]: ../../std/cell/struct.RefCell.html
219 //! [send]: ../../std/marker/trait.Send.html
220 //! [arc]: ../../std/sync/struct.Arc.html
221 //! [`Deref`]: ../../std/ops/trait.Deref.html
222 //! [downgrade]: struct.Rc.html#method.downgrade
223 //! [upgrade]: struct.Weak.html#method.upgrade
224 //! [`None`]: ../../std/option/enum.Option.html#variant.None
225 //! [mutability]: ../../std/cell/index.html#introducing-mutability-inside-of-something-immutable
226
227 #![stable(feature = "rust1", since = "1.0.0")]
228
229 #[cfg(not(test))]
230 use crate::boxed::Box;
231 #[cfg(test)]
232 use std::boxed::Box;
233
234 use core::any::Any;
235 use core::borrow;
236 use core::cell::Cell;
237 use core::cmp::Ordering;
238 use core::fmt;
239 use core::hash::{Hash, Hasher};
240 use core::intrinsics::abort;
241 use core::iter;
242 use core::marker::{self, Unpin, Unsize, PhantomData};
243 use core::mem::{self, align_of, align_of_val, forget, size_of_val};
244 use core::ops::{Deref, Receiver, CoerceUnsized, DispatchFromDyn};
245 use core::pin::Pin;
246 use core::ptr::{self, NonNull};
247 use core::slice::{self, from_raw_parts_mut};
248 use core::convert::From;
249 use core::usize;
250
251 use crate::alloc::{Global, Alloc, Layout, box_free, handle_alloc_error};
252 use crate::string::String;
253 use crate::vec::Vec;
254
255 struct RcBox<T: ?Sized> {
256     strong: Cell<usize>,
257     weak: Cell<usize>,
258     value: T,
259 }
260
261 /// A single-threaded reference-counting pointer. 'Rc' stands for 'Reference
262 /// Counted'.
263 ///
264 /// See the [module-level documentation](./index.html) for more details.
265 ///
266 /// The inherent methods of `Rc` are all associated functions, which means
267 /// that you have to call them as e.g., [`Rc::get_mut(&mut value)`][get_mut] instead of
268 /// `value.get_mut()`. This avoids conflicts with methods of the inner
269 /// type `T`.
270 ///
271 /// [get_mut]: #method.get_mut
272 #[cfg_attr(not(test), lang = "rc")]
273 #[stable(feature = "rust1", since = "1.0.0")]
274 pub struct Rc<T: ?Sized> {
275     ptr: NonNull<RcBox<T>>,
276     phantom: PhantomData<T>,
277 }
278
279 #[stable(feature = "rust1", since = "1.0.0")]
280 impl<T: ?Sized> !marker::Send for Rc<T> {}
281 #[stable(feature = "rust1", since = "1.0.0")]
282 impl<T: ?Sized> !marker::Sync for Rc<T> {}
283
284 #[unstable(feature = "coerce_unsized", issue = "27732")]
285 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Rc<U>> for Rc<T> {}
286
287 #[unstable(feature = "dispatch_from_dyn", issue = "0")]
288 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Rc<U>> for Rc<T> {}
289
290 impl<T: ?Sized> Rc<T> {
291     fn from_inner(ptr: NonNull<RcBox<T>>) -> Self {
292         Self {
293             ptr,
294             phantom: PhantomData,
295         }
296     }
297
298     unsafe fn from_ptr(ptr: *mut RcBox<T>) -> Self {
299         Self::from_inner(NonNull::new_unchecked(ptr))
300     }
301 }
302
303 impl<T> Rc<T> {
304     /// Constructs a new `Rc<T>`.
305     ///
306     /// # Examples
307     ///
308     /// ```
309     /// use std::rc::Rc;
310     ///
311     /// let five = Rc::new(5);
312     /// ```
313     #[stable(feature = "rust1", since = "1.0.0")]
314     pub fn new(value: T) -> Rc<T> {
315         // There is an implicit weak pointer owned by all the strong
316         // pointers, which ensures that the weak destructor never frees
317         // the allocation while the strong destructor is running, even
318         // if the weak pointer is stored inside the strong one.
319         Self::from_inner(Box::into_raw_non_null(box RcBox {
320             strong: Cell::new(1),
321             weak: Cell::new(1),
322             value,
323         }))
324     }
325
326     /// Constructs a new `Pin<Rc<T>>`. If `T` does not implement `Unpin`, then
327     /// `value` will be pinned in memory and unable to be moved.
328     #[stable(feature = "pin", since = "1.33.0")]
329     pub fn pin(value: T) -> Pin<Rc<T>> {
330         unsafe { Pin::new_unchecked(Rc::new(value)) }
331     }
332
333     /// Returns the contained value, if the `Rc` has exactly one strong reference.
334     ///
335     /// Otherwise, an [`Err`][result] is returned with the same `Rc` that was
336     /// passed in.
337     ///
338     /// This will succeed even if there are outstanding weak references.
339     ///
340     /// [result]: ../../std/result/enum.Result.html
341     ///
342     /// # Examples
343     ///
344     /// ```
345     /// use std::rc::Rc;
346     ///
347     /// let x = Rc::new(3);
348     /// assert_eq!(Rc::try_unwrap(x), Ok(3));
349     ///
350     /// let x = Rc::new(4);
351     /// let _y = Rc::clone(&x);
352     /// assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4);
353     /// ```
354     #[inline]
355     #[stable(feature = "rc_unique", since = "1.4.0")]
356     pub fn try_unwrap(this: Self) -> Result<T, Self> {
357         if Rc::strong_count(&this) == 1 {
358             unsafe {
359                 let val = ptr::read(&*this); // copy the contained object
360
361                 // Indicate to Weaks that they can't be promoted by decrementing
362                 // the strong count, and then remove the implicit "strong weak"
363                 // pointer while also handling drop logic by just crafting a
364                 // fake Weak.
365                 this.dec_strong();
366                 let _weak = Weak { ptr: this.ptr };
367                 forget(this);
368                 Ok(val)
369             }
370         } else {
371             Err(this)
372         }
373     }
374 }
375
376 impl<T: ?Sized> Rc<T> {
377     /// Consumes the `Rc`, returning the wrapped pointer.
378     ///
379     /// To avoid a memory leak the pointer must be converted back to an `Rc` using
380     /// [`Rc::from_raw`][from_raw].
381     ///
382     /// [from_raw]: struct.Rc.html#method.from_raw
383     ///
384     /// # Examples
385     ///
386     /// ```
387     /// use std::rc::Rc;
388     ///
389     /// let x = Rc::new("hello".to_owned());
390     /// let x_ptr = Rc::into_raw(x);
391     /// assert_eq!(unsafe { &*x_ptr }, "hello");
392     /// ```
393     #[stable(feature = "rc_raw", since = "1.17.0")]
394     pub fn into_raw(this: Self) -> *const T {
395         let ptr: *const T = &*this;
396         mem::forget(this);
397         ptr
398     }
399
400     /// Constructs an `Rc` from a raw pointer.
401     ///
402     /// The raw pointer must have been previously returned by a call to a
403     /// [`Rc::into_raw`][into_raw].
404     ///
405     /// This function is unsafe because improper use may lead to memory problems. For example, a
406     /// double-free may occur if the function is called twice on the same raw pointer.
407     ///
408     /// [into_raw]: struct.Rc.html#method.into_raw
409     ///
410     /// # Examples
411     ///
412     /// ```
413     /// use std::rc::Rc;
414     ///
415     /// let x = Rc::new("hello".to_owned());
416     /// let x_ptr = Rc::into_raw(x);
417     ///
418     /// unsafe {
419     ///     // Convert back to an `Rc` to prevent leak.
420     ///     let x = Rc::from_raw(x_ptr);
421     ///     assert_eq!(&*x, "hello");
422     ///
423     ///     // Further calls to `Rc::from_raw(x_ptr)` would be memory unsafe.
424     /// }
425     ///
426     /// // The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling!
427     /// ```
428     #[stable(feature = "rc_raw", since = "1.17.0")]
429     pub unsafe fn from_raw(ptr: *const T) -> Self {
430         let offset = data_offset(ptr);
431
432         // Reverse the offset to find the original RcBox.
433         let fake_ptr = ptr as *mut RcBox<T>;
434         let rc_ptr = set_data_ptr(fake_ptr, (ptr as *mut u8).offset(-offset));
435
436         Self::from_ptr(rc_ptr)
437     }
438
439     /// Consumes the `Rc`, returning the wrapped pointer as `NonNull<T>`.
440     ///
441     /// # Examples
442     ///
443     /// ```
444     /// #![feature(rc_into_raw_non_null)]
445     ///
446     /// use std::rc::Rc;
447     ///
448     /// let x = Rc::new("hello".to_owned());
449     /// let ptr = Rc::into_raw_non_null(x);
450     /// let deref = unsafe { ptr.as_ref() };
451     /// assert_eq!(deref, "hello");
452     /// ```
453     #[unstable(feature = "rc_into_raw_non_null", issue = "47336")]
454     #[inline]
455     pub fn into_raw_non_null(this: Self) -> NonNull<T> {
456         // safe because Rc guarantees its pointer is non-null
457         unsafe { NonNull::new_unchecked(Rc::into_raw(this) as *mut _) }
458     }
459
460     /// Creates a new [`Weak`][weak] pointer to this value.
461     ///
462     /// [weak]: struct.Weak.html
463     ///
464     /// # Examples
465     ///
466     /// ```
467     /// use std::rc::Rc;
468     ///
469     /// let five = Rc::new(5);
470     ///
471     /// let weak_five = Rc::downgrade(&five);
472     /// ```
473     #[stable(feature = "rc_weak", since = "1.4.0")]
474     pub fn downgrade(this: &Self) -> Weak<T> {
475         this.inc_weak();
476         // Make sure we do not create a dangling Weak
477         debug_assert!(!is_dangling(this.ptr));
478         Weak { ptr: this.ptr }
479     }
480
481     /// Gets the number of [`Weak`][weak] pointers to this value.
482     ///
483     /// [weak]: struct.Weak.html
484     ///
485     /// # Examples
486     ///
487     /// ```
488     /// use std::rc::Rc;
489     ///
490     /// let five = Rc::new(5);
491     /// let _weak_five = Rc::downgrade(&five);
492     ///
493     /// assert_eq!(1, Rc::weak_count(&five));
494     /// ```
495     #[inline]
496     #[stable(feature = "rc_counts", since = "1.15.0")]
497     pub fn weak_count(this: &Self) -> usize {
498         this.weak() - 1
499     }
500
501     /// Gets the number of strong (`Rc`) pointers to this value.
502     ///
503     /// # Examples
504     ///
505     /// ```
506     /// use std::rc::Rc;
507     ///
508     /// let five = Rc::new(5);
509     /// let _also_five = Rc::clone(&five);
510     ///
511     /// assert_eq!(2, Rc::strong_count(&five));
512     /// ```
513     #[inline]
514     #[stable(feature = "rc_counts", since = "1.15.0")]
515     pub fn strong_count(this: &Self) -> usize {
516         this.strong()
517     }
518
519     /// Returns `true` if there are no other `Rc` or [`Weak`][weak] pointers to
520     /// this inner value.
521     ///
522     /// [weak]: struct.Weak.html
523     #[inline]
524     fn is_unique(this: &Self) -> bool {
525         Rc::weak_count(this) == 0 && Rc::strong_count(this) == 1
526     }
527
528     /// Returns a mutable reference to the inner value, if there are
529     /// no other `Rc` or [`Weak`][weak] pointers to the same value.
530     ///
531     /// Returns [`None`] otherwise, because it is not safe to
532     /// mutate a shared value.
533     ///
534     /// See also [`make_mut`][make_mut], which will [`clone`][clone]
535     /// the inner value when it's shared.
536     ///
537     /// [weak]: struct.Weak.html
538     /// [`None`]: ../../std/option/enum.Option.html#variant.None
539     /// [make_mut]: struct.Rc.html#method.make_mut
540     /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
541     ///
542     /// # Examples
543     ///
544     /// ```
545     /// use std::rc::Rc;
546     ///
547     /// let mut x = Rc::new(3);
548     /// *Rc::get_mut(&mut x).unwrap() = 4;
549     /// assert_eq!(*x, 4);
550     ///
551     /// let _y = Rc::clone(&x);
552     /// assert!(Rc::get_mut(&mut x).is_none());
553     /// ```
554     #[inline]
555     #[stable(feature = "rc_unique", since = "1.4.0")]
556     pub fn get_mut(this: &mut Self) -> Option<&mut T> {
557         if Rc::is_unique(this) {
558             unsafe {
559                 Some(&mut this.ptr.as_mut().value)
560             }
561         } else {
562             None
563         }
564     }
565
566     #[inline]
567     #[stable(feature = "ptr_eq", since = "1.17.0")]
568     /// Returns `true` if the two `Rc`s point to the same value (not
569     /// just values that compare as equal).
570     ///
571     /// # Examples
572     ///
573     /// ```
574     /// use std::rc::Rc;
575     ///
576     /// let five = Rc::new(5);
577     /// let same_five = Rc::clone(&five);
578     /// let other_five = Rc::new(5);
579     ///
580     /// assert!(Rc::ptr_eq(&five, &same_five));
581     /// assert!(!Rc::ptr_eq(&five, &other_five));
582     /// ```
583     pub fn ptr_eq(this: &Self, other: &Self) -> bool {
584         this.ptr.as_ptr() == other.ptr.as_ptr()
585     }
586 }
587
588 impl<T: Clone> Rc<T> {
589     /// Makes a mutable reference into the given `Rc`.
590     ///
591     /// If there are other `Rc` pointers to the same value, then `make_mut` will
592     /// [`clone`] the inner value to ensure unique ownership.  This is also
593     /// referred to as clone-on-write.
594     ///
595     /// If there are no other `Rc` pointers to this value, then [`Weak`]
596     /// pointers to this value will be dissassociated.
597     ///
598     /// See also [`get_mut`], which will fail rather than cloning.
599     ///
600     /// [`Weak`]: struct.Weak.html
601     /// [`clone`]: ../../std/clone/trait.Clone.html#tymethod.clone
602     /// [`get_mut`]: struct.Rc.html#method.get_mut
603     ///
604     /// # Examples
605     ///
606     /// ```
607     /// use std::rc::Rc;
608     ///
609     /// let mut data = Rc::new(5);
610     ///
611     /// *Rc::make_mut(&mut data) += 1;        // Won't clone anything
612     /// let mut other_data = Rc::clone(&data);    // Won't clone inner data
613     /// *Rc::make_mut(&mut data) += 1;        // Clones inner data
614     /// *Rc::make_mut(&mut data) += 1;        // Won't clone anything
615     /// *Rc::make_mut(&mut other_data) *= 2;  // Won't clone anything
616     ///
617     /// // Now `data` and `other_data` point to different values.
618     /// assert_eq!(*data, 8);
619     /// assert_eq!(*other_data, 12);
620     /// ```
621     ///
622     /// [`Weak`] pointers will be dissassociated:
623     ///
624     /// ```
625     /// use std::rc::Rc;
626     ///
627     /// let mut data = Rc::new(75);
628     /// let weak = Rc::downgrade(&data);
629     ///
630     /// assert!(75 == *data);
631     /// assert!(75 == *weak.upgrade().unwrap());
632     ///
633     /// *Rc::make_mut(&mut data) += 1;
634     ///
635     /// assert!(76 == *data);
636     /// assert!(weak.upgrade().is_none());
637     /// ```
638     #[inline]
639     #[stable(feature = "rc_unique", since = "1.4.0")]
640     pub fn make_mut(this: &mut Self) -> &mut T {
641         if Rc::strong_count(this) != 1 {
642             // Gotta clone the data, there are other Rcs
643             *this = Rc::new((**this).clone())
644         } else if Rc::weak_count(this) != 0 {
645             // Can just steal the data, all that's left is Weaks
646             unsafe {
647                 let mut swap = Rc::new(ptr::read(&this.ptr.as_ref().value));
648                 mem::swap(this, &mut swap);
649                 swap.dec_strong();
650                 // Remove implicit strong-weak ref (no need to craft a fake
651                 // Weak here -- we know other Weaks can clean up for us)
652                 swap.dec_weak();
653                 forget(swap);
654             }
655         }
656         // This unsafety is ok because we're guaranteed that the pointer
657         // returned is the *only* pointer that will ever be returned to T. Our
658         // reference count is guaranteed to be 1 at this point, and we required
659         // the `Rc<T>` itself to be `mut`, so we're returning the only possible
660         // reference to the inner value.
661         unsafe {
662             &mut this.ptr.as_mut().value
663         }
664     }
665 }
666
667 impl Rc<dyn Any> {
668     #[inline]
669     #[stable(feature = "rc_downcast", since = "1.29.0")]
670     /// Attempt to downcast the `Rc<dyn Any>` to a concrete type.
671     ///
672     /// # Examples
673     ///
674     /// ```
675     /// use std::any::Any;
676     /// use std::rc::Rc;
677     ///
678     /// fn print_if_string(value: Rc<dyn Any>) {
679     ///     if let Ok(string) = value.downcast::<String>() {
680     ///         println!("String ({}): {}", string.len(), string);
681     ///     }
682     /// }
683     ///
684     /// fn main() {
685     ///     let my_string = "Hello World".to_string();
686     ///     print_if_string(Rc::new(my_string));
687     ///     print_if_string(Rc::new(0i8));
688     /// }
689     /// ```
690     pub fn downcast<T: Any>(self) -> Result<Rc<T>, Rc<dyn Any>> {
691         if (*self).is::<T>() {
692             let ptr = self.ptr.cast::<RcBox<T>>();
693             forget(self);
694             Ok(Rc::from_inner(ptr))
695         } else {
696             Err(self)
697         }
698     }
699 }
700
701 impl<T: ?Sized> Rc<T> {
702     /// Allocates an `RcBox<T>` with sufficient space for
703     /// an unsized value where the value has the layout provided.
704     ///
705     /// The function `mem_to_rcbox` is called with the data pointer
706     /// and must return back a (potentially fat)-pointer for the `RcBox<T>`.
707     unsafe fn allocate_for_unsized(
708         value_layout: Layout,
709         mem_to_rcbox: impl FnOnce(*mut u8) -> *mut RcBox<T>
710     ) -> *mut RcBox<T> {
711         // Calculate layout using the given value layout.
712         // Previously, layout was calculated on the expression
713         // `&*(ptr as *const RcBox<T>)`, but this created a misaligned
714         // reference (see #54908).
715         let layout = Layout::new::<RcBox<()>>()
716             .extend(value_layout).unwrap().0
717             .pad_to_align().unwrap();
718
719         // Allocate for the layout.
720         let mem = Global.alloc(layout)
721             .unwrap_or_else(|_| handle_alloc_error(layout));
722
723         // Initialize the RcBox
724         let inner = mem_to_rcbox(mem.as_ptr());
725         debug_assert_eq!(Layout::for_value(&*inner), layout);
726
727         ptr::write(&mut (*inner).strong, Cell::new(1));
728         ptr::write(&mut (*inner).weak, Cell::new(1));
729
730         inner
731     }
732
733     /// Allocates an `RcBox<T>` with sufficient space for an unsized value
734     unsafe fn allocate_for_ptr(ptr: *const T) -> *mut RcBox<T> {
735         // Allocate for the `RcBox<T>` using the given value.
736         Self::allocate_for_unsized(
737             Layout::for_value(&*ptr),
738             |mem| set_data_ptr(ptr as *mut T, mem) as *mut RcBox<T>,
739         )
740     }
741
742     fn from_box(v: Box<T>) -> Rc<T> {
743         unsafe {
744             let box_unique = Box::into_unique(v);
745             let bptr = box_unique.as_ptr();
746
747             let value_size = size_of_val(&*bptr);
748             let ptr = Self::allocate_for_ptr(bptr);
749
750             // Copy value as bytes
751             ptr::copy_nonoverlapping(
752                 bptr as *const T as *const u8,
753                 &mut (*ptr).value as *mut _ as *mut u8,
754                 value_size);
755
756             // Free the allocation without dropping its contents
757             box_free(box_unique);
758
759             Self::from_ptr(ptr)
760         }
761     }
762 }
763
764 impl<T> Rc<[T]> {
765     /// Allocates an `RcBox<[T]>` with the given length.
766     unsafe fn allocate_for_slice(len: usize) -> *mut RcBox<[T]> {
767         Self::allocate_for_unsized(
768             Layout::array::<T>(len).unwrap(),
769             |mem| ptr::slice_from_raw_parts_mut(mem as *mut T, len) as *mut RcBox<[T]>,
770         )
771     }
772 }
773
774 /// Sets the data pointer of a `?Sized` raw pointer.
775 ///
776 /// For a slice/trait object, this sets the `data` field and leaves the rest
777 /// unchanged. For a sized raw pointer, this simply sets the pointer.
778 unsafe fn set_data_ptr<T: ?Sized, U>(mut ptr: *mut T, data: *mut U) -> *mut T {
779     ptr::write(&mut ptr as *mut _ as *mut *mut u8, data as *mut u8);
780     ptr
781 }
782
783 impl<T> Rc<[T]> {
784     /// Copy elements from slice into newly allocated Rc<[T]>
785     ///
786     /// Unsafe because the caller must either take ownership or bind `T: Copy`
787     unsafe fn copy_from_slice(v: &[T]) -> Rc<[T]> {
788         let ptr = Self::allocate_for_slice(v.len());
789
790         ptr::copy_nonoverlapping(
791             v.as_ptr(),
792             &mut (*ptr).value as *mut [T] as *mut T,
793             v.len());
794
795         Self::from_ptr(ptr)
796     }
797
798     /// Constructs an `Rc<[T]>` from an iterator known to be of a certain size.
799     ///
800     /// Behavior is undefined should the size be wrong.
801     unsafe fn from_iter_exact(iter: impl iter::Iterator<Item = T>, len: usize) -> Rc<[T]> {
802         // Panic guard while cloning T elements.
803         // In the event of a panic, elements that have been written
804         // into the new RcBox will be dropped, then the memory freed.
805         struct Guard<T> {
806             mem: NonNull<u8>,
807             elems: *mut T,
808             layout: Layout,
809             n_elems: usize,
810         }
811
812         impl<T> Drop for Guard<T> {
813             fn drop(&mut self) {
814                 unsafe {
815                     let slice = from_raw_parts_mut(self.elems, self.n_elems);
816                     ptr::drop_in_place(slice);
817
818                     Global.dealloc(self.mem, self.layout.clone());
819                 }
820             }
821         }
822
823         let ptr = Self::allocate_for_slice(len);
824
825         let mem = ptr as *mut _ as *mut u8;
826         let layout = Layout::for_value(&*ptr);
827
828         // Pointer to first element
829         let elems = &mut (*ptr).value as *mut [T] as *mut T;
830
831         let mut guard = Guard {
832             mem: NonNull::new_unchecked(mem),
833             elems,
834             layout,
835             n_elems: 0,
836         };
837
838         for (i, item) in iter.enumerate() {
839             ptr::write(elems.add(i), item);
840             guard.n_elems += 1;
841         }
842
843         // All clear. Forget the guard so it doesn't free the new RcBox.
844         forget(guard);
845
846         Self::from_ptr(ptr)
847     }
848 }
849
850 /// Specialization trait used for `From<&[T]>`.
851 trait RcFromSlice<T> {
852     fn from_slice(slice: &[T]) -> Self;
853 }
854
855 impl<T: Clone> RcFromSlice<T> for Rc<[T]> {
856     #[inline]
857     default fn from_slice(v: &[T]) -> Self {
858         unsafe {
859             Self::from_iter_exact(v.iter().cloned(), v.len())
860         }
861     }
862 }
863
864 impl<T: Copy> RcFromSlice<T> for Rc<[T]> {
865     #[inline]
866     fn from_slice(v: &[T]) -> Self {
867         unsafe { Rc::copy_from_slice(v) }
868     }
869 }
870
871 #[stable(feature = "rust1", since = "1.0.0")]
872 impl<T: ?Sized> Deref for Rc<T> {
873     type Target = T;
874
875     #[inline(always)]
876     fn deref(&self) -> &T {
877         &self.inner().value
878     }
879 }
880
881 #[unstable(feature = "receiver_trait", issue = "0")]
882 impl<T: ?Sized> Receiver for Rc<T> {}
883
884 #[stable(feature = "rust1", since = "1.0.0")]
885 unsafe impl<#[may_dangle] T: ?Sized> Drop for Rc<T> {
886     /// Drops the `Rc`.
887     ///
888     /// This will decrement the strong reference count. If the strong reference
889     /// count reaches zero then the only other references (if any) are
890     /// [`Weak`], so we `drop` the inner value.
891     ///
892     /// # Examples
893     ///
894     /// ```
895     /// use std::rc::Rc;
896     ///
897     /// struct Foo;
898     ///
899     /// impl Drop for Foo {
900     ///     fn drop(&mut self) {
901     ///         println!("dropped!");
902     ///     }
903     /// }
904     ///
905     /// let foo  = Rc::new(Foo);
906     /// let foo2 = Rc::clone(&foo);
907     ///
908     /// drop(foo);    // Doesn't print anything
909     /// drop(foo2);   // Prints "dropped!"
910     /// ```
911     ///
912     /// [`Weak`]: ../../std/rc/struct.Weak.html
913     fn drop(&mut self) {
914         unsafe {
915             self.dec_strong();
916             if self.strong() == 0 {
917                 // destroy the contained object
918                 ptr::drop_in_place(self.ptr.as_mut());
919
920                 // remove the implicit "strong weak" pointer now that we've
921                 // destroyed the contents.
922                 self.dec_weak();
923
924                 if self.weak() == 0 {
925                     Global.dealloc(self.ptr.cast(), Layout::for_value(self.ptr.as_ref()));
926                 }
927             }
928         }
929     }
930 }
931
932 #[stable(feature = "rust1", since = "1.0.0")]
933 impl<T: ?Sized> Clone for Rc<T> {
934     /// Makes a clone of the `Rc` pointer.
935     ///
936     /// This creates another pointer to the same inner value, increasing the
937     /// strong reference count.
938     ///
939     /// # Examples
940     ///
941     /// ```
942     /// use std::rc::Rc;
943     ///
944     /// let five = Rc::new(5);
945     ///
946     /// let _ = Rc::clone(&five);
947     /// ```
948     #[inline]
949     fn clone(&self) -> Rc<T> {
950         self.inc_strong();
951         Self::from_inner(self.ptr)
952     }
953 }
954
955 #[stable(feature = "rust1", since = "1.0.0")]
956 impl<T: Default> Default for Rc<T> {
957     /// Creates a new `Rc<T>`, with the `Default` value for `T`.
958     ///
959     /// # Examples
960     ///
961     /// ```
962     /// use std::rc::Rc;
963     ///
964     /// let x: Rc<i32> = Default::default();
965     /// assert_eq!(*x, 0);
966     /// ```
967     #[inline]
968     fn default() -> Rc<T> {
969         Rc::new(Default::default())
970     }
971 }
972
973 #[stable(feature = "rust1", since = "1.0.0")]
974 trait RcEqIdent<T: ?Sized + PartialEq> {
975     fn eq(&self, other: &Rc<T>) -> bool;
976     fn ne(&self, other: &Rc<T>) -> bool;
977 }
978
979 #[stable(feature = "rust1", since = "1.0.0")]
980 impl<T: ?Sized + PartialEq> RcEqIdent<T> for Rc<T> {
981     #[inline]
982     default fn eq(&self, other: &Rc<T>) -> bool {
983         **self == **other
984     }
985
986     #[inline]
987     default fn ne(&self, other: &Rc<T>) -> bool {
988         **self != **other
989     }
990 }
991
992 /// We're doing this specialization here, and not as a more general optimization on `&T`, because it
993 /// would otherwise add a cost to all equality checks on refs. We assume that `Rc`s are used to
994 /// store large values, that are slow to clone, but also heavy to check for equality, causing this
995 /// cost to pay off more easily. It's also more likely to have two `Rc` clones, that point to
996 /// the same value, than two `&T`s.
997 #[stable(feature = "rust1", since = "1.0.0")]
998 impl<T: ?Sized + Eq> RcEqIdent<T> for Rc<T> {
999     #[inline]
1000     fn eq(&self, other: &Rc<T>) -> bool {
1001         Rc::ptr_eq(self, other) || **self == **other
1002     }
1003
1004     #[inline]
1005     fn ne(&self, other: &Rc<T>) -> bool {
1006         !Rc::ptr_eq(self, other) && **self != **other
1007     }
1008 }
1009
1010 #[stable(feature = "rust1", since = "1.0.0")]
1011 impl<T: ?Sized + PartialEq> PartialEq for Rc<T> {
1012     /// Equality for two `Rc`s.
1013     ///
1014     /// Two `Rc`s are equal if their inner values are equal.
1015     ///
1016     /// If `T` also implements `Eq`, two `Rc`s that point to the same value are
1017     /// always equal.
1018     ///
1019     /// # Examples
1020     ///
1021     /// ```
1022     /// use std::rc::Rc;
1023     ///
1024     /// let five = Rc::new(5);
1025     ///
1026     /// assert!(five == Rc::new(5));
1027     /// ```
1028     #[inline]
1029     fn eq(&self, other: &Rc<T>) -> bool {
1030         RcEqIdent::eq(self, other)
1031     }
1032
1033     /// Inequality for two `Rc`s.
1034     ///
1035     /// Two `Rc`s are unequal if their inner values are unequal.
1036     ///
1037     /// If `T` also implements `Eq`, two `Rc`s that point to the same value are
1038     /// never unequal.
1039     ///
1040     /// # Examples
1041     ///
1042     /// ```
1043     /// use std::rc::Rc;
1044     ///
1045     /// let five = Rc::new(5);
1046     ///
1047     /// assert!(five != Rc::new(6));
1048     /// ```
1049     #[inline]
1050     fn ne(&self, other: &Rc<T>) -> bool {
1051         RcEqIdent::ne(self, other)
1052     }
1053 }
1054
1055 #[stable(feature = "rust1", since = "1.0.0")]
1056 impl<T: ?Sized + Eq> Eq for Rc<T> {}
1057
1058 #[stable(feature = "rust1", since = "1.0.0")]
1059 impl<T: ?Sized + PartialOrd> PartialOrd for Rc<T> {
1060     /// Partial comparison for two `Rc`s.
1061     ///
1062     /// The two are compared by calling `partial_cmp()` on their inner values.
1063     ///
1064     /// # Examples
1065     ///
1066     /// ```
1067     /// use std::rc::Rc;
1068     /// use std::cmp::Ordering;
1069     ///
1070     /// let five = Rc::new(5);
1071     ///
1072     /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&Rc::new(6)));
1073     /// ```
1074     #[inline(always)]
1075     fn partial_cmp(&self, other: &Rc<T>) -> Option<Ordering> {
1076         (**self).partial_cmp(&**other)
1077     }
1078
1079     /// Less-than comparison for two `Rc`s.
1080     ///
1081     /// The two are compared by calling `<` on their inner values.
1082     ///
1083     /// # Examples
1084     ///
1085     /// ```
1086     /// use std::rc::Rc;
1087     ///
1088     /// let five = Rc::new(5);
1089     ///
1090     /// assert!(five < Rc::new(6));
1091     /// ```
1092     #[inline(always)]
1093     fn lt(&self, other: &Rc<T>) -> bool {
1094         **self < **other
1095     }
1096
1097     /// 'Less than or equal to' comparison for two `Rc`s.
1098     ///
1099     /// The two are compared by calling `<=` on their inner values.
1100     ///
1101     /// # Examples
1102     ///
1103     /// ```
1104     /// use std::rc::Rc;
1105     ///
1106     /// let five = Rc::new(5);
1107     ///
1108     /// assert!(five <= Rc::new(5));
1109     /// ```
1110     #[inline(always)]
1111     fn le(&self, other: &Rc<T>) -> bool {
1112         **self <= **other
1113     }
1114
1115     /// Greater-than comparison for two `Rc`s.
1116     ///
1117     /// The two are compared by calling `>` on their inner values.
1118     ///
1119     /// # Examples
1120     ///
1121     /// ```
1122     /// use std::rc::Rc;
1123     ///
1124     /// let five = Rc::new(5);
1125     ///
1126     /// assert!(five > Rc::new(4));
1127     /// ```
1128     #[inline(always)]
1129     fn gt(&self, other: &Rc<T>) -> bool {
1130         **self > **other
1131     }
1132
1133     /// 'Greater than or equal to' comparison for two `Rc`s.
1134     ///
1135     /// The two are compared by calling `>=` on their inner values.
1136     ///
1137     /// # Examples
1138     ///
1139     /// ```
1140     /// use std::rc::Rc;
1141     ///
1142     /// let five = Rc::new(5);
1143     ///
1144     /// assert!(five >= Rc::new(5));
1145     /// ```
1146     #[inline(always)]
1147     fn ge(&self, other: &Rc<T>) -> bool {
1148         **self >= **other
1149     }
1150 }
1151
1152 #[stable(feature = "rust1", since = "1.0.0")]
1153 impl<T: ?Sized + Ord> Ord for Rc<T> {
1154     /// Comparison for two `Rc`s.
1155     ///
1156     /// The two are compared by calling `cmp()` on their inner values.
1157     ///
1158     /// # Examples
1159     ///
1160     /// ```
1161     /// use std::rc::Rc;
1162     /// use std::cmp::Ordering;
1163     ///
1164     /// let five = Rc::new(5);
1165     ///
1166     /// assert_eq!(Ordering::Less, five.cmp(&Rc::new(6)));
1167     /// ```
1168     #[inline]
1169     fn cmp(&self, other: &Rc<T>) -> Ordering {
1170         (**self).cmp(&**other)
1171     }
1172 }
1173
1174 #[stable(feature = "rust1", since = "1.0.0")]
1175 impl<T: ?Sized + Hash> Hash for Rc<T> {
1176     fn hash<H: Hasher>(&self, state: &mut H) {
1177         (**self).hash(state);
1178     }
1179 }
1180
1181 #[stable(feature = "rust1", since = "1.0.0")]
1182 impl<T: ?Sized + fmt::Display> fmt::Display for Rc<T> {
1183     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1184         fmt::Display::fmt(&**self, f)
1185     }
1186 }
1187
1188 #[stable(feature = "rust1", since = "1.0.0")]
1189 impl<T: ?Sized + fmt::Debug> fmt::Debug for Rc<T> {
1190     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1191         fmt::Debug::fmt(&**self, f)
1192     }
1193 }
1194
1195 #[stable(feature = "rust1", since = "1.0.0")]
1196 impl<T: ?Sized> fmt::Pointer for Rc<T> {
1197     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1198         fmt::Pointer::fmt(&(&**self as *const T), f)
1199     }
1200 }
1201
1202 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
1203 impl<T> From<T> for Rc<T> {
1204     fn from(t: T) -> Self {
1205         Rc::new(t)
1206     }
1207 }
1208
1209 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1210 impl<T: Clone> From<&[T]> for Rc<[T]> {
1211     #[inline]
1212     fn from(v: &[T]) -> Rc<[T]> {
1213         <Self as RcFromSlice<T>>::from_slice(v)
1214     }
1215 }
1216
1217 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1218 impl From<&str> for Rc<str> {
1219     #[inline]
1220     fn from(v: &str) -> Rc<str> {
1221         let rc = Rc::<[u8]>::from(v.as_bytes());
1222         unsafe { Rc::from_raw(Rc::into_raw(rc) as *const str) }
1223     }
1224 }
1225
1226 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1227 impl From<String> for Rc<str> {
1228     #[inline]
1229     fn from(v: String) -> Rc<str> {
1230         Rc::from(&v[..])
1231     }
1232 }
1233
1234 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1235 impl<T: ?Sized> From<Box<T>> for Rc<T> {
1236     #[inline]
1237     fn from(v: Box<T>) -> Rc<T> {
1238         Rc::from_box(v)
1239     }
1240 }
1241
1242 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1243 impl<T> From<Vec<T>> for Rc<[T]> {
1244     #[inline]
1245     fn from(mut v: Vec<T>) -> Rc<[T]> {
1246         unsafe {
1247             let rc = Rc::copy_from_slice(&v);
1248
1249             // Allow the Vec to free its memory, but not destroy its contents
1250             v.set_len(0);
1251
1252             rc
1253         }
1254     }
1255 }
1256
1257 #[stable(feature = "shared_from_iter", since = "1.37.0")]
1258 impl<T> iter::FromIterator<T> for Rc<[T]> {
1259     /// Takes each element in the `Iterator` and collects it into an `Rc<[T]>`.
1260     ///
1261     /// # Performance characteristics
1262     ///
1263     /// ## The general case
1264     ///
1265     /// In the general case, collecting into `Rc<[T]>` is done by first
1266     /// collecting into a `Vec<T>`. That is, when writing the following:
1267     ///
1268     /// ```rust
1269     /// # use std::rc::Rc;
1270     /// let evens: Rc<[u8]> = (0..10).filter(|&x| x % 2 == 0).collect();
1271     /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]);
1272     /// ```
1273     ///
1274     /// this behaves as if we wrote:
1275     ///
1276     /// ```rust
1277     /// # use std::rc::Rc;
1278     /// let evens: Rc<[u8]> = (0..10).filter(|&x| x % 2 == 0)
1279     ///     .collect::<Vec<_>>() // The first set of allocations happens here.
1280     ///     .into(); // A second allocation for `Rc<[T]>` happens here.
1281     /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]);
1282     /// ```
1283     ///
1284     /// This will allocate as many times as needed for constructing the `Vec<T>`
1285     /// and then it will allocate once for turning the `Vec<T>` into the `Rc<[T]>`.
1286     ///
1287     /// ## Iterators of known length
1288     ///
1289     /// When your `Iterator` implements `TrustedLen` and is of an exact size,
1290     /// a single allocation will be made for the `Rc<[T]>`. For example:
1291     ///
1292     /// ```rust
1293     /// # use std::rc::Rc;
1294     /// let evens: Rc<[u8]> = (0..10).collect(); // Just a single allocation happens here.
1295     /// # assert_eq!(&*evens, &*(0..10).collect::<Vec<_>>());
1296     /// ```
1297     fn from_iter<I: iter::IntoIterator<Item = T>>(iter: I) -> Self {
1298         RcFromIter::from_iter(iter.into_iter())
1299     }
1300 }
1301
1302 /// Specialization trait used for collecting into `Rc<[T]>`.
1303 trait RcFromIter<T, I> {
1304     fn from_iter(iter: I) -> Self;
1305 }
1306
1307 impl<T, I: Iterator<Item = T>> RcFromIter<T, I> for Rc<[T]> {
1308     default fn from_iter(iter: I) -> Self {
1309         iter.collect::<Vec<T>>().into()
1310     }
1311 }
1312
1313 impl<T, I: iter::TrustedLen<Item = T>> RcFromIter<T, I> for Rc<[T]>  {
1314     default fn from_iter(iter: I) -> Self {
1315         // This is the case for a `TrustedLen` iterator.
1316         let (low, high) = iter.size_hint();
1317         if let Some(high) = high {
1318             debug_assert_eq!(
1319                 low, high,
1320                 "TrustedLen iterator's size hint is not exact: {:?}",
1321                 (low, high)
1322             );
1323
1324             unsafe {
1325                 // SAFETY: We need to ensure that the iterator has an exact length and we have.
1326                 Rc::from_iter_exact(iter, low)
1327             }
1328         } else {
1329             // Fall back to normal implementation.
1330             iter.collect::<Vec<T>>().into()
1331         }
1332     }
1333 }
1334
1335 impl<'a, T: 'a + Clone> RcFromIter<&'a T, slice::Iter<'a, T>> for Rc<[T]> {
1336     fn from_iter(iter: slice::Iter<'a, T>) -> Self {
1337         // Delegate to `impl<T: Clone> From<&[T]> for Rc<[T]>`.
1338         //
1339         // In the case that `T: Copy`, we get to use `ptr::copy_nonoverlapping`
1340         // which is even more performant.
1341         //
1342         // In the fall-back case we have `T: Clone`. This is still better
1343         // than the `TrustedLen` implementation as slices have a known length
1344         // and so we get to avoid calling `size_hint` and avoid the branching.
1345         iter.as_slice().into()
1346     }
1347 }
1348
1349 /// `Weak` is a version of [`Rc`] that holds a non-owning reference to the
1350 /// managed value. The value is accessed by calling [`upgrade`] on the `Weak`
1351 /// pointer, which returns an [`Option`]`<`[`Rc`]`<T>>`.
1352 ///
1353 /// Since a `Weak` reference does not count towards ownership, it will not
1354 /// prevent the inner value from being dropped, and `Weak` itself makes no
1355 /// guarantees about the value still being present and may return [`None`]
1356 /// when [`upgrade`]d.
1357 ///
1358 /// A `Weak` pointer is useful for keeping a temporary reference to the value
1359 /// within [`Rc`] without extending its lifetime. It is also used to prevent
1360 /// circular references between [`Rc`] pointers, since mutual owning references
1361 /// would never allow either [`Rc`] to be dropped. For example, a tree could
1362 /// have strong [`Rc`] pointers from parent nodes to children, and `Weak`
1363 /// pointers from children back to their parents.
1364 ///
1365 /// The typical way to obtain a `Weak` pointer is to call [`Rc::downgrade`].
1366 ///
1367 /// [`Rc`]: struct.Rc.html
1368 /// [`Rc::downgrade`]: struct.Rc.html#method.downgrade
1369 /// [`upgrade`]: struct.Weak.html#method.upgrade
1370 /// [`Option`]: ../../std/option/enum.Option.html
1371 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1372 #[stable(feature = "rc_weak", since = "1.4.0")]
1373 pub struct Weak<T: ?Sized> {
1374     // This is a `NonNull` to allow optimizing the size of this type in enums,
1375     // but it is not necessarily a valid pointer.
1376     // `Weak::new` sets this to `usize::MAX` so that it doesn’t need
1377     // to allocate space on the heap.  That's not a value a real pointer
1378     // will ever have because RcBox has alignment at least 2.
1379     ptr: NonNull<RcBox<T>>,
1380 }
1381
1382 #[stable(feature = "rc_weak", since = "1.4.0")]
1383 impl<T: ?Sized> !marker::Send for Weak<T> {}
1384 #[stable(feature = "rc_weak", since = "1.4.0")]
1385 impl<T: ?Sized> !marker::Sync for Weak<T> {}
1386
1387 #[unstable(feature = "coerce_unsized", issue = "27732")]
1388 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {}
1389
1390 #[unstable(feature = "dispatch_from_dyn", issue = "0")]
1391 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Weak<U>> for Weak<T> {}
1392
1393 impl<T> Weak<T> {
1394     /// Constructs a new `Weak<T>`, without allocating any memory.
1395     /// Calling [`upgrade`] on the return value always gives [`None`].
1396     ///
1397     /// [`upgrade`]: #method.upgrade
1398     /// [`None`]: ../../std/option/enum.Option.html
1399     ///
1400     /// # Examples
1401     ///
1402     /// ```
1403     /// use std::rc::Weak;
1404     ///
1405     /// let empty: Weak<i64> = Weak::new();
1406     /// assert!(empty.upgrade().is_none());
1407     /// ```
1408     #[stable(feature = "downgraded_weak", since = "1.10.0")]
1409     pub fn new() -> Weak<T> {
1410         Weak {
1411             ptr: NonNull::new(usize::MAX as *mut RcBox<T>).expect("MAX is not 0"),
1412         }
1413     }
1414
1415     /// Returns a raw pointer to the object `T` pointed to by this `Weak<T>`.
1416     ///
1417     /// It is up to the caller to ensure that the object is still alive when accessing it through
1418     /// the pointer.
1419     ///
1420     /// The pointer may be [`null`] or be dangling in case the object has already been destroyed.
1421     ///
1422     /// # Examples
1423     ///
1424     /// ```
1425     /// #![feature(weak_into_raw)]
1426     ///
1427     /// use std::rc::Rc;
1428     /// use std::ptr;
1429     ///
1430     /// let strong = Rc::new("hello".to_owned());
1431     /// let weak = Rc::downgrade(&strong);
1432     /// // Both point to the same object
1433     /// assert!(ptr::eq(&*strong, weak.as_raw()));
1434     /// // The strong here keeps it alive, so we can still access the object.
1435     /// assert_eq!("hello", unsafe { &*weak.as_raw() });
1436     ///
1437     /// drop(strong);
1438     /// // But not any more. We can do weak.as_raw(), but accessing the pointer would lead to
1439     /// // undefined behaviour.
1440     /// // assert_eq!("hello", unsafe { &*weak.as_raw() });
1441     /// ```
1442     ///
1443     /// [`null`]: ../../std/ptr/fn.null.html
1444     #[unstable(feature = "weak_into_raw", issue = "60728")]
1445     pub fn as_raw(&self) -> *const T {
1446         match self.inner() {
1447             None => ptr::null(),
1448             Some(inner) => {
1449                 let offset = data_offset_sized::<T>();
1450                 let ptr = inner as *const RcBox<T>;
1451                 // Note: while the pointer we create may already point to dropped value, the
1452                 // allocation still lives (it must hold the weak point as long as we are alive).
1453                 // Therefore, the offset is OK to do, it won't get out of the allocation.
1454                 let ptr = unsafe { (ptr as *const u8).offset(offset) };
1455                 ptr as *const T
1456             }
1457         }
1458     }
1459
1460     /// Consumes the `Weak<T>` and turns it into a raw pointer.
1461     ///
1462     /// This converts the weak pointer into a raw pointer, preserving the original weak count. It
1463     /// can be turned back into the `Weak<T>` with [`from_raw`].
1464     ///
1465     /// The same restrictions of accessing the target of the pointer as with
1466     /// [`as_raw`] apply.
1467     ///
1468     /// # Examples
1469     ///
1470     /// ```
1471     /// #![feature(weak_into_raw)]
1472     ///
1473     /// use std::rc::{Rc, Weak};
1474     ///
1475     /// let strong = Rc::new("hello".to_owned());
1476     /// let weak = Rc::downgrade(&strong);
1477     /// let raw = weak.into_raw();
1478     ///
1479     /// assert_eq!(1, Rc::weak_count(&strong));
1480     /// assert_eq!("hello", unsafe { &*raw });
1481     ///
1482     /// drop(unsafe { Weak::from_raw(raw) });
1483     /// assert_eq!(0, Rc::weak_count(&strong));
1484     /// ```
1485     ///
1486     /// [`from_raw`]: struct.Weak.html#method.from_raw
1487     /// [`as_raw`]: struct.Weak.html#method.as_raw
1488     #[unstable(feature = "weak_into_raw", issue = "60728")]
1489     pub fn into_raw(self) -> *const T {
1490         let result = self.as_raw();
1491         mem::forget(self);
1492         result
1493     }
1494
1495     /// Converts a raw pointer previously created by [`into_raw`] back into `Weak<T>`.
1496     ///
1497     /// This can be used to safely get a strong reference (by calling [`upgrade`]
1498     /// later) or to deallocate the weak count by dropping the `Weak<T>`.
1499     ///
1500     /// It takes ownership of one weak count. In case a [`null`] is passed, a dangling [`Weak`] is
1501     /// returned.
1502     ///
1503     /// # Safety
1504     ///
1505     /// The pointer must represent one valid weak count. In other words, it must point to `T` which
1506     /// is or *was* managed by an [`Rc`] and the weak count of that [`Rc`] must not have reached
1507     /// 0. It is allowed for the strong count to be 0.
1508     ///
1509     /// # Examples
1510     ///
1511     /// ```
1512     /// #![feature(weak_into_raw)]
1513     ///
1514     /// use std::rc::{Rc, Weak};
1515     ///
1516     /// let strong = Rc::new("hello".to_owned());
1517     ///
1518     /// let raw_1 = Rc::downgrade(&strong).into_raw();
1519     /// let raw_2 = Rc::downgrade(&strong).into_raw();
1520     ///
1521     /// assert_eq!(2, Rc::weak_count(&strong));
1522     ///
1523     /// assert_eq!("hello", &*unsafe { Weak::from_raw(raw_1) }.upgrade().unwrap());
1524     /// assert_eq!(1, Rc::weak_count(&strong));
1525     ///
1526     /// drop(strong);
1527     ///
1528     /// // Decrement the last weak count.
1529     /// assert!(unsafe { Weak::from_raw(raw_2) }.upgrade().is_none());
1530     /// ```
1531     ///
1532     /// [`null`]: ../../std/ptr/fn.null.html
1533     /// [`into_raw`]: struct.Weak.html#method.into_raw
1534     /// [`upgrade`]: struct.Weak.html#method.upgrade
1535     /// [`Rc`]: struct.Rc.html
1536     /// [`Weak`]: struct.Weak.html
1537     #[unstable(feature = "weak_into_raw", issue = "60728")]
1538     pub unsafe fn from_raw(ptr: *const T) -> Self {
1539         if ptr.is_null() {
1540             Self::new()
1541         } else {
1542             // See Rc::from_raw for details
1543             let offset = data_offset(ptr);
1544             let fake_ptr = ptr as *mut RcBox<T>;
1545             let ptr = set_data_ptr(fake_ptr, (ptr as *mut u8).offset(-offset));
1546             Weak {
1547                 ptr: NonNull::new(ptr).expect("Invalid pointer passed to from_raw"),
1548             }
1549         }
1550     }
1551 }
1552
1553 pub(crate) fn is_dangling<T: ?Sized>(ptr: NonNull<T>) -> bool {
1554     let address = ptr.as_ptr() as *mut () as usize;
1555     address == usize::MAX
1556 }
1557
1558 impl<T: ?Sized> Weak<T> {
1559     /// Attempts to upgrade the `Weak` pointer to an [`Rc`], extending
1560     /// the lifetime of the value if successful.
1561     ///
1562     /// Returns [`None`] if the value has since been dropped.
1563     ///
1564     /// [`Rc`]: struct.Rc.html
1565     /// [`None`]: ../../std/option/enum.Option.html
1566     ///
1567     /// # Examples
1568     ///
1569     /// ```
1570     /// use std::rc::Rc;
1571     ///
1572     /// let five = Rc::new(5);
1573     ///
1574     /// let weak_five = Rc::downgrade(&five);
1575     ///
1576     /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
1577     /// assert!(strong_five.is_some());
1578     ///
1579     /// // Destroy all strong pointers.
1580     /// drop(strong_five);
1581     /// drop(five);
1582     ///
1583     /// assert!(weak_five.upgrade().is_none());
1584     /// ```
1585     #[stable(feature = "rc_weak", since = "1.4.0")]
1586     pub fn upgrade(&self) -> Option<Rc<T>> {
1587         let inner = self.inner()?;
1588         if inner.strong() == 0 {
1589             None
1590         } else {
1591             inner.inc_strong();
1592             Some(Rc::from_inner(self.ptr))
1593         }
1594     }
1595
1596     /// Gets the number of strong (`Rc`) pointers pointing to this value.
1597     ///
1598     /// If `self` was created using [`Weak::new`], this will return 0.
1599     ///
1600     /// [`Weak::new`]: #method.new
1601     #[unstable(feature = "weak_counts", issue = "57977")]
1602     pub fn strong_count(&self) -> usize {
1603         if let Some(inner) = self.inner() {
1604             inner.strong()
1605         } else {
1606             0
1607         }
1608     }
1609
1610     /// Gets the number of `Weak` pointers pointing to this value.
1611     ///
1612     /// If `self` was created using [`Weak::new`], this will return `None`. If
1613     /// not, the returned value is at least 1, since `self` still points to the
1614     /// value.
1615     ///
1616     /// [`Weak::new`]: #method.new
1617     #[unstable(feature = "weak_counts", issue = "57977")]
1618     pub fn weak_count(&self) -> Option<usize> {
1619         self.inner().map(|inner| {
1620             if inner.strong() > 0 {
1621                 inner.weak() - 1  // subtract the implicit weak ptr
1622             } else {
1623                 inner.weak()
1624             }
1625         })
1626     }
1627
1628     /// Returns `None` when the pointer is dangling and there is no allocated `RcBox`
1629     /// (i.e., when this `Weak` was created by `Weak::new`).
1630     #[inline]
1631     fn inner(&self) -> Option<&RcBox<T>> {
1632         if is_dangling(self.ptr) {
1633             None
1634         } else {
1635             Some(unsafe { self.ptr.as_ref() })
1636         }
1637     }
1638
1639     /// Returns `true` if the two `Weak`s point to the same value (not just values
1640     /// that compare as equal).
1641     ///
1642     /// # Notes
1643     ///
1644     /// Since this compares pointers it means that `Weak::new()` will equal each
1645     /// other, even though they don't point to any value.
1646     ///
1647     /// # Examples
1648     ///
1649     /// ```
1650     /// #![feature(weak_ptr_eq)]
1651     /// use std::rc::Rc;
1652     ///
1653     /// let first_rc = Rc::new(5);
1654     /// let first = Rc::downgrade(&first_rc);
1655     /// let second = Rc::downgrade(&first_rc);
1656     ///
1657     /// assert!(first.ptr_eq(&second));
1658     ///
1659     /// let third_rc = Rc::new(5);
1660     /// let third = Rc::downgrade(&third_rc);
1661     ///
1662     /// assert!(!first.ptr_eq(&third));
1663     /// ```
1664     ///
1665     /// Comparing `Weak::new`.
1666     ///
1667     /// ```
1668     /// #![feature(weak_ptr_eq)]
1669     /// use std::rc::{Rc, Weak};
1670     ///
1671     /// let first = Weak::new();
1672     /// let second = Weak::new();
1673     /// assert!(first.ptr_eq(&second));
1674     ///
1675     /// let third_rc = Rc::new(());
1676     /// let third = Rc::downgrade(&third_rc);
1677     /// assert!(!first.ptr_eq(&third));
1678     /// ```
1679     #[inline]
1680     #[unstable(feature = "weak_ptr_eq", issue = "55981")]
1681     pub fn ptr_eq(&self, other: &Self) -> bool {
1682         self.ptr.as_ptr() == other.ptr.as_ptr()
1683     }
1684 }
1685
1686 #[stable(feature = "rc_weak", since = "1.4.0")]
1687 impl<T: ?Sized> Drop for Weak<T> {
1688     /// Drops the `Weak` pointer.
1689     ///
1690     /// # Examples
1691     ///
1692     /// ```
1693     /// use std::rc::{Rc, Weak};
1694     ///
1695     /// struct Foo;
1696     ///
1697     /// impl Drop for Foo {
1698     ///     fn drop(&mut self) {
1699     ///         println!("dropped!");
1700     ///     }
1701     /// }
1702     ///
1703     /// let foo = Rc::new(Foo);
1704     /// let weak_foo = Rc::downgrade(&foo);
1705     /// let other_weak_foo = Weak::clone(&weak_foo);
1706     ///
1707     /// drop(weak_foo);   // Doesn't print anything
1708     /// drop(foo);        // Prints "dropped!"
1709     ///
1710     /// assert!(other_weak_foo.upgrade().is_none());
1711     /// ```
1712     fn drop(&mut self) {
1713         if let Some(inner) = self.inner() {
1714             inner.dec_weak();
1715             // the weak count starts at 1, and will only go to zero if all
1716             // the strong pointers have disappeared.
1717             if inner.weak() == 0 {
1718                 unsafe {
1719                     Global.dealloc(self.ptr.cast(), Layout::for_value(self.ptr.as_ref()));
1720                 }
1721             }
1722         }
1723     }
1724 }
1725
1726 #[stable(feature = "rc_weak", since = "1.4.0")]
1727 impl<T: ?Sized> Clone for Weak<T> {
1728     /// Makes a clone of the `Weak` pointer that points to the same value.
1729     ///
1730     /// # Examples
1731     ///
1732     /// ```
1733     /// use std::rc::{Rc, Weak};
1734     ///
1735     /// let weak_five = Rc::downgrade(&Rc::new(5));
1736     ///
1737     /// let _ = Weak::clone(&weak_five);
1738     /// ```
1739     #[inline]
1740     fn clone(&self) -> Weak<T> {
1741         if let Some(inner) = self.inner() {
1742             inner.inc_weak()
1743         }
1744         Weak { ptr: self.ptr }
1745     }
1746 }
1747
1748 #[stable(feature = "rc_weak", since = "1.4.0")]
1749 impl<T: ?Sized + fmt::Debug> fmt::Debug for Weak<T> {
1750     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1751         write!(f, "(Weak)")
1752     }
1753 }
1754
1755 #[stable(feature = "downgraded_weak", since = "1.10.0")]
1756 impl<T> Default for Weak<T> {
1757     /// Constructs a new `Weak<T>`, allocating memory for `T` without initializing
1758     /// it. Calling [`upgrade`] on the return value always gives [`None`].
1759     ///
1760     /// [`None`]: ../../std/option/enum.Option.html
1761     /// [`upgrade`]: ../../std/rc/struct.Weak.html#method.upgrade
1762     ///
1763     /// # Examples
1764     ///
1765     /// ```
1766     /// use std::rc::Weak;
1767     ///
1768     /// let empty: Weak<i64> = Default::default();
1769     /// assert!(empty.upgrade().is_none());
1770     /// ```
1771     fn default() -> Weak<T> {
1772         Weak::new()
1773     }
1774 }
1775
1776 // NOTE: We checked_add here to deal with mem::forget safely. In particular
1777 // if you mem::forget Rcs (or Weaks), the ref-count can overflow, and then
1778 // you can free the allocation while outstanding Rcs (or Weaks) exist.
1779 // We abort because this is such a degenerate scenario that we don't care about
1780 // what happens -- no real program should ever experience this.
1781 //
1782 // This should have negligible overhead since you don't actually need to
1783 // clone these much in Rust thanks to ownership and move-semantics.
1784
1785 #[doc(hidden)]
1786 trait RcBoxPtr<T: ?Sized> {
1787     fn inner(&self) -> &RcBox<T>;
1788
1789     #[inline]
1790     fn strong(&self) -> usize {
1791         self.inner().strong.get()
1792     }
1793
1794     #[inline]
1795     fn inc_strong(&self) {
1796         let strong = self.strong();
1797
1798         // We want to abort on overflow instead of dropping the value.
1799         // The reference count will never be zero when this is called;
1800         // nevertheless, we insert an abort here to hint LLVM at
1801         // an otherwise missed optimization.
1802         if strong == 0 || strong == usize::max_value() {
1803             unsafe { abort(); }
1804         }
1805         self.inner().strong.set(strong + 1);
1806     }
1807
1808     #[inline]
1809     fn dec_strong(&self) {
1810         self.inner().strong.set(self.strong() - 1);
1811     }
1812
1813     #[inline]
1814     fn weak(&self) -> usize {
1815         self.inner().weak.get()
1816     }
1817
1818     #[inline]
1819     fn inc_weak(&self) {
1820         let weak = self.weak();
1821
1822         // We want to abort on overflow instead of dropping the value.
1823         // The reference count will never be zero when this is called;
1824         // nevertheless, we insert an abort here to hint LLVM at
1825         // an otherwise missed optimization.
1826         if weak == 0 || weak == usize::max_value() {
1827             unsafe { abort(); }
1828         }
1829         self.inner().weak.set(weak + 1);
1830     }
1831
1832     #[inline]
1833     fn dec_weak(&self) {
1834         self.inner().weak.set(self.weak() - 1);
1835     }
1836 }
1837
1838 impl<T: ?Sized> RcBoxPtr<T> for Rc<T> {
1839     #[inline(always)]
1840     fn inner(&self) -> &RcBox<T> {
1841         unsafe {
1842             self.ptr.as_ref()
1843         }
1844     }
1845 }
1846
1847 impl<T: ?Sized> RcBoxPtr<T> for RcBox<T> {
1848     #[inline(always)]
1849     fn inner(&self) -> &RcBox<T> {
1850         self
1851     }
1852 }
1853
1854 #[cfg(test)]
1855 mod tests {
1856     use super::{Rc, Weak};
1857     use std::boxed::Box;
1858     use std::cell::RefCell;
1859     use std::option::Option::{self, None, Some};
1860     use std::result::Result::{Err, Ok};
1861     use std::mem::drop;
1862     use std::clone::Clone;
1863     use std::convert::From;
1864
1865     #[test]
1866     fn test_clone() {
1867         let x = Rc::new(RefCell::new(5));
1868         let y = x.clone();
1869         *x.borrow_mut() = 20;
1870         assert_eq!(*y.borrow(), 20);
1871     }
1872
1873     #[test]
1874     fn test_simple() {
1875         let x = Rc::new(5);
1876         assert_eq!(*x, 5);
1877     }
1878
1879     #[test]
1880     fn test_simple_clone() {
1881         let x = Rc::new(5);
1882         let y = x.clone();
1883         assert_eq!(*x, 5);
1884         assert_eq!(*y, 5);
1885     }
1886
1887     #[test]
1888     fn test_destructor() {
1889         let x: Rc<Box<_>> = Rc::new(box 5);
1890         assert_eq!(**x, 5);
1891     }
1892
1893     #[test]
1894     fn test_live() {
1895         let x = Rc::new(5);
1896         let y = Rc::downgrade(&x);
1897         assert!(y.upgrade().is_some());
1898     }
1899
1900     #[test]
1901     fn test_dead() {
1902         let x = Rc::new(5);
1903         let y = Rc::downgrade(&x);
1904         drop(x);
1905         assert!(y.upgrade().is_none());
1906     }
1907
1908     #[test]
1909     fn weak_self_cyclic() {
1910         struct Cycle {
1911             x: RefCell<Option<Weak<Cycle>>>,
1912         }
1913
1914         let a = Rc::new(Cycle { x: RefCell::new(None) });
1915         let b = Rc::downgrade(&a.clone());
1916         *a.x.borrow_mut() = Some(b);
1917
1918         // hopefully we don't double-free (or leak)...
1919     }
1920
1921     #[test]
1922     fn is_unique() {
1923         let x = Rc::new(3);
1924         assert!(Rc::is_unique(&x));
1925         let y = x.clone();
1926         assert!(!Rc::is_unique(&x));
1927         drop(y);
1928         assert!(Rc::is_unique(&x));
1929         let w = Rc::downgrade(&x);
1930         assert!(!Rc::is_unique(&x));
1931         drop(w);
1932         assert!(Rc::is_unique(&x));
1933     }
1934
1935     #[test]
1936     fn test_strong_count() {
1937         let a = Rc::new(0);
1938         assert!(Rc::strong_count(&a) == 1);
1939         let w = Rc::downgrade(&a);
1940         assert!(Rc::strong_count(&a) == 1);
1941         let b = w.upgrade().expect("upgrade of live rc failed");
1942         assert!(Rc::strong_count(&b) == 2);
1943         assert!(Rc::strong_count(&a) == 2);
1944         drop(w);
1945         drop(a);
1946         assert!(Rc::strong_count(&b) == 1);
1947         let c = b.clone();
1948         assert!(Rc::strong_count(&b) == 2);
1949         assert!(Rc::strong_count(&c) == 2);
1950     }
1951
1952     #[test]
1953     fn test_weak_count() {
1954         let a = Rc::new(0);
1955         assert!(Rc::strong_count(&a) == 1);
1956         assert!(Rc::weak_count(&a) == 0);
1957         let w = Rc::downgrade(&a);
1958         assert!(Rc::strong_count(&a) == 1);
1959         assert!(Rc::weak_count(&a) == 1);
1960         drop(w);
1961         assert!(Rc::strong_count(&a) == 1);
1962         assert!(Rc::weak_count(&a) == 0);
1963         let c = a.clone();
1964         assert!(Rc::strong_count(&a) == 2);
1965         assert!(Rc::weak_count(&a) == 0);
1966         drop(c);
1967     }
1968
1969     #[test]
1970     fn weak_counts() {
1971         assert_eq!(Weak::weak_count(&Weak::<u64>::new()), None);
1972         assert_eq!(Weak::strong_count(&Weak::<u64>::new()), 0);
1973
1974         let a = Rc::new(0);
1975         let w = Rc::downgrade(&a);
1976         assert_eq!(Weak::strong_count(&w), 1);
1977         assert_eq!(Weak::weak_count(&w), Some(1));
1978         let w2 = w.clone();
1979         assert_eq!(Weak::strong_count(&w), 1);
1980         assert_eq!(Weak::weak_count(&w), Some(2));
1981         assert_eq!(Weak::strong_count(&w2), 1);
1982         assert_eq!(Weak::weak_count(&w2), Some(2));
1983         drop(w);
1984         assert_eq!(Weak::strong_count(&w2), 1);
1985         assert_eq!(Weak::weak_count(&w2), Some(1));
1986         let a2 = a.clone();
1987         assert_eq!(Weak::strong_count(&w2), 2);
1988         assert_eq!(Weak::weak_count(&w2), Some(1));
1989         drop(a2);
1990         drop(a);
1991         assert_eq!(Weak::strong_count(&w2), 0);
1992         assert_eq!(Weak::weak_count(&w2), Some(1));
1993         drop(w2);
1994     }
1995
1996     #[test]
1997     fn try_unwrap() {
1998         let x = Rc::new(3);
1999         assert_eq!(Rc::try_unwrap(x), Ok(3));
2000         let x = Rc::new(4);
2001         let _y = x.clone();
2002         assert_eq!(Rc::try_unwrap(x), Err(Rc::new(4)));
2003         let x = Rc::new(5);
2004         let _w = Rc::downgrade(&x);
2005         assert_eq!(Rc::try_unwrap(x), Ok(5));
2006     }
2007
2008     #[test]
2009     fn into_from_raw() {
2010         let x = Rc::new(box "hello");
2011         let y = x.clone();
2012
2013         let x_ptr = Rc::into_raw(x);
2014         drop(y);
2015         unsafe {
2016             assert_eq!(**x_ptr, "hello");
2017
2018             let x = Rc::from_raw(x_ptr);
2019             assert_eq!(**x, "hello");
2020
2021             assert_eq!(Rc::try_unwrap(x).map(|x| *x), Ok("hello"));
2022         }
2023     }
2024
2025     #[test]
2026     fn test_into_from_raw_unsized() {
2027         use std::fmt::Display;
2028         use std::string::ToString;
2029
2030         let rc: Rc<str> = Rc::from("foo");
2031
2032         let ptr = Rc::into_raw(rc.clone());
2033         let rc2 = unsafe { Rc::from_raw(ptr) };
2034
2035         assert_eq!(unsafe { &*ptr }, "foo");
2036         assert_eq!(rc, rc2);
2037
2038         let rc: Rc<dyn Display> = Rc::new(123);
2039
2040         let ptr = Rc::into_raw(rc.clone());
2041         let rc2 = unsafe { Rc::from_raw(ptr) };
2042
2043         assert_eq!(unsafe { &*ptr }.to_string(), "123");
2044         assert_eq!(rc2.to_string(), "123");
2045     }
2046
2047     #[test]
2048     fn get_mut() {
2049         let mut x = Rc::new(3);
2050         *Rc::get_mut(&mut x).unwrap() = 4;
2051         assert_eq!(*x, 4);
2052         let y = x.clone();
2053         assert!(Rc::get_mut(&mut x).is_none());
2054         drop(y);
2055         assert!(Rc::get_mut(&mut x).is_some());
2056         let _w = Rc::downgrade(&x);
2057         assert!(Rc::get_mut(&mut x).is_none());
2058     }
2059
2060     #[test]
2061     fn test_cowrc_clone_make_unique() {
2062         let mut cow0 = Rc::new(75);
2063         let mut cow1 = cow0.clone();
2064         let mut cow2 = cow1.clone();
2065
2066         assert!(75 == *Rc::make_mut(&mut cow0));
2067         assert!(75 == *Rc::make_mut(&mut cow1));
2068         assert!(75 == *Rc::make_mut(&mut cow2));
2069
2070         *Rc::make_mut(&mut cow0) += 1;
2071         *Rc::make_mut(&mut cow1) += 2;
2072         *Rc::make_mut(&mut cow2) += 3;
2073
2074         assert!(76 == *cow0);
2075         assert!(77 == *cow1);
2076         assert!(78 == *cow2);
2077
2078         // none should point to the same backing memory
2079         assert!(*cow0 != *cow1);
2080         assert!(*cow0 != *cow2);
2081         assert!(*cow1 != *cow2);
2082     }
2083
2084     #[test]
2085     fn test_cowrc_clone_unique2() {
2086         let mut cow0 = Rc::new(75);
2087         let cow1 = cow0.clone();
2088         let cow2 = cow1.clone();
2089
2090         assert!(75 == *cow0);
2091         assert!(75 == *cow1);
2092         assert!(75 == *cow2);
2093
2094         *Rc::make_mut(&mut cow0) += 1;
2095
2096         assert!(76 == *cow0);
2097         assert!(75 == *cow1);
2098         assert!(75 == *cow2);
2099
2100         // cow1 and cow2 should share the same contents
2101         // cow0 should have a unique reference
2102         assert!(*cow0 != *cow1);
2103         assert!(*cow0 != *cow2);
2104         assert!(*cow1 == *cow2);
2105     }
2106
2107     #[test]
2108     fn test_cowrc_clone_weak() {
2109         let mut cow0 = Rc::new(75);
2110         let cow1_weak = Rc::downgrade(&cow0);
2111
2112         assert!(75 == *cow0);
2113         assert!(75 == *cow1_weak.upgrade().unwrap());
2114
2115         *Rc::make_mut(&mut cow0) += 1;
2116
2117         assert!(76 == *cow0);
2118         assert!(cow1_weak.upgrade().is_none());
2119     }
2120
2121     #[test]
2122     fn test_show() {
2123         let foo = Rc::new(75);
2124         assert_eq!(format!("{:?}", foo), "75");
2125     }
2126
2127     #[test]
2128     fn test_unsized() {
2129         let foo: Rc<[i32]> = Rc::new([1, 2, 3]);
2130         assert_eq!(foo, foo.clone());
2131     }
2132
2133     #[test]
2134     fn test_from_owned() {
2135         let foo = 123;
2136         let foo_rc = Rc::from(foo);
2137         assert!(123 == *foo_rc);
2138     }
2139
2140     #[test]
2141     fn test_new_weak() {
2142         let foo: Weak<usize> = Weak::new();
2143         assert!(foo.upgrade().is_none());
2144     }
2145
2146     #[test]
2147     fn test_ptr_eq() {
2148         let five = Rc::new(5);
2149         let same_five = five.clone();
2150         let other_five = Rc::new(5);
2151
2152         assert!(Rc::ptr_eq(&five, &same_five));
2153         assert!(!Rc::ptr_eq(&five, &other_five));
2154     }
2155
2156     #[test]
2157     fn test_from_str() {
2158         let r: Rc<str> = Rc::from("foo");
2159
2160         assert_eq!(&r[..], "foo");
2161     }
2162
2163     #[test]
2164     fn test_copy_from_slice() {
2165         let s: &[u32] = &[1, 2, 3];
2166         let r: Rc<[u32]> = Rc::from(s);
2167
2168         assert_eq!(&r[..], [1, 2, 3]);
2169     }
2170
2171     #[test]
2172     fn test_clone_from_slice() {
2173         #[derive(Clone, Debug, Eq, PartialEq)]
2174         struct X(u32);
2175
2176         let s: &[X] = &[X(1), X(2), X(3)];
2177         let r: Rc<[X]> = Rc::from(s);
2178
2179         assert_eq!(&r[..], s);
2180     }
2181
2182     #[test]
2183     #[should_panic]
2184     fn test_clone_from_slice_panic() {
2185         use std::string::{String, ToString};
2186
2187         struct Fail(u32, String);
2188
2189         impl Clone for Fail {
2190             fn clone(&self) -> Fail {
2191                 if self.0 == 2 {
2192                     panic!();
2193                 }
2194                 Fail(self.0, self.1.clone())
2195             }
2196         }
2197
2198         let s: &[Fail] = &[
2199             Fail(0, "foo".to_string()),
2200             Fail(1, "bar".to_string()),
2201             Fail(2, "baz".to_string()),
2202         ];
2203
2204         // Should panic, but not cause memory corruption
2205         let _r: Rc<[Fail]> = Rc::from(s);
2206     }
2207
2208     #[test]
2209     fn test_from_box() {
2210         let b: Box<u32> = box 123;
2211         let r: Rc<u32> = Rc::from(b);
2212
2213         assert_eq!(*r, 123);
2214     }
2215
2216     #[test]
2217     fn test_from_box_str() {
2218         use std::string::String;
2219
2220         let s = String::from("foo").into_boxed_str();
2221         let r: Rc<str> = Rc::from(s);
2222
2223         assert_eq!(&r[..], "foo");
2224     }
2225
2226     #[test]
2227     fn test_from_box_slice() {
2228         let s = vec![1, 2, 3].into_boxed_slice();
2229         let r: Rc<[u32]> = Rc::from(s);
2230
2231         assert_eq!(&r[..], [1, 2, 3]);
2232     }
2233
2234     #[test]
2235     fn test_from_box_trait() {
2236         use std::fmt::Display;
2237         use std::string::ToString;
2238
2239         let b: Box<dyn Display> = box 123;
2240         let r: Rc<dyn Display> = Rc::from(b);
2241
2242         assert_eq!(r.to_string(), "123");
2243     }
2244
2245     #[test]
2246     fn test_from_box_trait_zero_sized() {
2247         use std::fmt::Debug;
2248
2249         let b: Box<dyn Debug> = box ();
2250         let r: Rc<dyn Debug> = Rc::from(b);
2251
2252         assert_eq!(format!("{:?}", r), "()");
2253     }
2254
2255     #[test]
2256     fn test_from_vec() {
2257         let v = vec![1, 2, 3];
2258         let r: Rc<[u32]> = Rc::from(v);
2259
2260         assert_eq!(&r[..], [1, 2, 3]);
2261     }
2262
2263     #[test]
2264     fn test_downcast() {
2265         use std::any::Any;
2266
2267         let r1: Rc<dyn Any> = Rc::new(i32::max_value());
2268         let r2: Rc<dyn Any> = Rc::new("abc");
2269
2270         assert!(r1.clone().downcast::<u32>().is_err());
2271
2272         let r1i32 = r1.downcast::<i32>();
2273         assert!(r1i32.is_ok());
2274         assert_eq!(r1i32.unwrap(), Rc::new(i32::max_value()));
2275
2276         assert!(r2.clone().downcast::<i32>().is_err());
2277
2278         let r2str = r2.downcast::<&'static str>();
2279         assert!(r2str.is_ok());
2280         assert_eq!(r2str.unwrap(), Rc::new("abc"));
2281     }
2282 }
2283
2284 #[stable(feature = "rust1", since = "1.0.0")]
2285 impl<T: ?Sized> borrow::Borrow<T> for Rc<T> {
2286     fn borrow(&self) -> &T {
2287         &**self
2288     }
2289 }
2290
2291 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
2292 impl<T: ?Sized> AsRef<T> for Rc<T> {
2293     fn as_ref(&self) -> &T {
2294         &**self
2295     }
2296 }
2297
2298 #[stable(feature = "pin", since = "1.33.0")]
2299 impl<T: ?Sized> Unpin for Rc<T> { }
2300
2301 unsafe fn data_offset<T: ?Sized>(ptr: *const T) -> isize {
2302     // Align the unsized value to the end of the `RcBox`.
2303     // Because it is ?Sized, it will always be the last field in memory.
2304     data_offset_align(align_of_val(&*ptr))
2305 }
2306
2307 /// Computes the offset of the data field within `RcBox`.
2308 ///
2309 /// Unlike [`data_offset`], this doesn't need the pointer, but it works only on `T: Sized`.
2310 fn data_offset_sized<T>() -> isize {
2311     data_offset_align(align_of::<T>())
2312 }
2313
2314 #[inline]
2315 fn data_offset_align(align: usize) -> isize {
2316     let layout = Layout::new::<RcBox<()>>();
2317     (layout.size() + layout.padding_needed_for(align)) as isize
2318 }