]> git.lizzy.rs Git - rust.git/blob - src/liballoc/rc.rs
Remove recommendation about idiomatic syntax for Arc::Clone
[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 #[cfg(test)]
256 mod tests;
257
258 struct RcBox<T: ?Sized> {
259     strong: Cell<usize>,
260     weak: Cell<usize>,
261     value: T,
262 }
263
264 /// A single-threaded reference-counting pointer. 'Rc' stands for 'Reference
265 /// Counted'.
266 ///
267 /// See the [module-level documentation](./index.html) for more details.
268 ///
269 /// The inherent methods of `Rc` are all associated functions, which means
270 /// that you have to call them as e.g., [`Rc::get_mut(&mut value)`][get_mut] instead of
271 /// `value.get_mut()`. This avoids conflicts with methods of the inner
272 /// type `T`.
273 ///
274 /// [get_mut]: #method.get_mut
275 #[cfg_attr(not(test), lang = "rc")]
276 #[stable(feature = "rust1", since = "1.0.0")]
277 pub struct Rc<T: ?Sized> {
278     ptr: NonNull<RcBox<T>>,
279     phantom: PhantomData<T>,
280 }
281
282 #[stable(feature = "rust1", since = "1.0.0")]
283 impl<T: ?Sized> !marker::Send for Rc<T> {}
284 #[stable(feature = "rust1", since = "1.0.0")]
285 impl<T: ?Sized> !marker::Sync for Rc<T> {}
286
287 #[unstable(feature = "coerce_unsized", issue = "27732")]
288 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Rc<U>> for Rc<T> {}
289
290 #[unstable(feature = "dispatch_from_dyn", issue = "0")]
291 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Rc<U>> for Rc<T> {}
292
293 impl<T: ?Sized> Rc<T> {
294     fn from_inner(ptr: NonNull<RcBox<T>>) -> Self {
295         Self {
296             ptr,
297             phantom: PhantomData,
298         }
299     }
300
301     unsafe fn from_ptr(ptr: *mut RcBox<T>) -> Self {
302         Self::from_inner(NonNull::new_unchecked(ptr))
303     }
304 }
305
306 impl<T> Rc<T> {
307     /// Constructs a new `Rc<T>`.
308     ///
309     /// # Examples
310     ///
311     /// ```
312     /// use std::rc::Rc;
313     ///
314     /// let five = Rc::new(5);
315     /// ```
316     #[stable(feature = "rust1", since = "1.0.0")]
317     pub fn new(value: T) -> Rc<T> {
318         // There is an implicit weak pointer owned by all the strong
319         // pointers, which ensures that the weak destructor never frees
320         // the allocation while the strong destructor is running, even
321         // if the weak pointer is stored inside the strong one.
322         Self::from_inner(Box::into_raw_non_null(box RcBox {
323             strong: Cell::new(1),
324             weak: Cell::new(1),
325             value,
326         }))
327     }
328
329     /// Constructs a new `Pin<Rc<T>>`. If `T` does not implement `Unpin`, then
330     /// `value` will be pinned in memory and unable to be moved.
331     #[stable(feature = "pin", since = "1.33.0")]
332     pub fn pin(value: T) -> Pin<Rc<T>> {
333         unsafe { Pin::new_unchecked(Rc::new(value)) }
334     }
335
336     /// Returns the contained value, if the `Rc` has exactly one strong reference.
337     ///
338     /// Otherwise, an [`Err`][result] is returned with the same `Rc` that was
339     /// passed in.
340     ///
341     /// This will succeed even if there are outstanding weak references.
342     ///
343     /// [result]: ../../std/result/enum.Result.html
344     ///
345     /// # Examples
346     ///
347     /// ```
348     /// use std::rc::Rc;
349     ///
350     /// let x = Rc::new(3);
351     /// assert_eq!(Rc::try_unwrap(x), Ok(3));
352     ///
353     /// let x = Rc::new(4);
354     /// let _y = Rc::clone(&x);
355     /// assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4);
356     /// ```
357     #[inline]
358     #[stable(feature = "rc_unique", since = "1.4.0")]
359     pub fn try_unwrap(this: Self) -> Result<T, Self> {
360         if Rc::strong_count(&this) == 1 {
361             unsafe {
362                 let val = ptr::read(&*this); // copy the contained object
363
364                 // Indicate to Weaks that they can't be promoted by decrementing
365                 // the strong count, and then remove the implicit "strong weak"
366                 // pointer while also handling drop logic by just crafting a
367                 // fake Weak.
368                 this.dec_strong();
369                 let _weak = Weak { ptr: this.ptr };
370                 forget(this);
371                 Ok(val)
372             }
373         } else {
374             Err(this)
375         }
376     }
377 }
378
379 impl<T: ?Sized> Rc<T> {
380     /// Consumes the `Rc`, returning the wrapped pointer.
381     ///
382     /// To avoid a memory leak the pointer must be converted back to an `Rc` using
383     /// [`Rc::from_raw`][from_raw].
384     ///
385     /// [from_raw]: struct.Rc.html#method.from_raw
386     ///
387     /// # Examples
388     ///
389     /// ```
390     /// use std::rc::Rc;
391     ///
392     /// let x = Rc::new("hello".to_owned());
393     /// let x_ptr = Rc::into_raw(x);
394     /// assert_eq!(unsafe { &*x_ptr }, "hello");
395     /// ```
396     #[stable(feature = "rc_raw", since = "1.17.0")]
397     pub fn into_raw(this: Self) -> *const T {
398         let ptr: *const T = &*this;
399         mem::forget(this);
400         ptr
401     }
402
403     /// Constructs an `Rc` from a raw pointer.
404     ///
405     /// The raw pointer must have been previously returned by a call to a
406     /// [`Rc::into_raw`][into_raw].
407     ///
408     /// This function is unsafe because improper use may lead to memory problems. For example, a
409     /// double-free may occur if the function is called twice on the same raw pointer.
410     ///
411     /// [into_raw]: struct.Rc.html#method.into_raw
412     ///
413     /// # Examples
414     ///
415     /// ```
416     /// use std::rc::Rc;
417     ///
418     /// let x = Rc::new("hello".to_owned());
419     /// let x_ptr = Rc::into_raw(x);
420     ///
421     /// unsafe {
422     ///     // Convert back to an `Rc` to prevent leak.
423     ///     let x = Rc::from_raw(x_ptr);
424     ///     assert_eq!(&*x, "hello");
425     ///
426     ///     // Further calls to `Rc::from_raw(x_ptr)` would be memory unsafe.
427     /// }
428     ///
429     /// // The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling!
430     /// ```
431     #[stable(feature = "rc_raw", since = "1.17.0")]
432     pub unsafe fn from_raw(ptr: *const T) -> Self {
433         let offset = data_offset(ptr);
434
435         // Reverse the offset to find the original RcBox.
436         let fake_ptr = ptr as *mut RcBox<T>;
437         let rc_ptr = set_data_ptr(fake_ptr, (ptr as *mut u8).offset(-offset));
438
439         Self::from_ptr(rc_ptr)
440     }
441
442     /// Consumes the `Rc`, returning the wrapped pointer as `NonNull<T>`.
443     ///
444     /// # Examples
445     ///
446     /// ```
447     /// #![feature(rc_into_raw_non_null)]
448     ///
449     /// use std::rc::Rc;
450     ///
451     /// let x = Rc::new("hello".to_owned());
452     /// let ptr = Rc::into_raw_non_null(x);
453     /// let deref = unsafe { ptr.as_ref() };
454     /// assert_eq!(deref, "hello");
455     /// ```
456     #[unstable(feature = "rc_into_raw_non_null", issue = "47336")]
457     #[inline]
458     pub fn into_raw_non_null(this: Self) -> NonNull<T> {
459         // safe because Rc guarantees its pointer is non-null
460         unsafe { NonNull::new_unchecked(Rc::into_raw(this) as *mut _) }
461     }
462
463     /// Creates a new [`Weak`][weak] pointer to this value.
464     ///
465     /// [weak]: struct.Weak.html
466     ///
467     /// # Examples
468     ///
469     /// ```
470     /// use std::rc::Rc;
471     ///
472     /// let five = Rc::new(5);
473     ///
474     /// let weak_five = Rc::downgrade(&five);
475     /// ```
476     #[stable(feature = "rc_weak", since = "1.4.0")]
477     pub fn downgrade(this: &Self) -> Weak<T> {
478         this.inc_weak();
479         // Make sure we do not create a dangling Weak
480         debug_assert!(!is_dangling(this.ptr));
481         Weak { ptr: this.ptr }
482     }
483
484     /// Gets the number of [`Weak`][weak] pointers to this value.
485     ///
486     /// [weak]: struct.Weak.html
487     ///
488     /// # Examples
489     ///
490     /// ```
491     /// use std::rc::Rc;
492     ///
493     /// let five = Rc::new(5);
494     /// let _weak_five = Rc::downgrade(&five);
495     ///
496     /// assert_eq!(1, Rc::weak_count(&five));
497     /// ```
498     #[inline]
499     #[stable(feature = "rc_counts", since = "1.15.0")]
500     pub fn weak_count(this: &Self) -> usize {
501         this.weak() - 1
502     }
503
504     /// Gets the number of strong (`Rc`) pointers to this value.
505     ///
506     /// # Examples
507     ///
508     /// ```
509     /// use std::rc::Rc;
510     ///
511     /// let five = Rc::new(5);
512     /// let _also_five = Rc::clone(&five);
513     ///
514     /// assert_eq!(2, Rc::strong_count(&five));
515     /// ```
516     #[inline]
517     #[stable(feature = "rc_counts", since = "1.15.0")]
518     pub fn strong_count(this: &Self) -> usize {
519         this.strong()
520     }
521
522     /// Returns `true` if there are no other `Rc` or [`Weak`][weak] pointers to
523     /// this inner value.
524     ///
525     /// [weak]: struct.Weak.html
526     #[inline]
527     fn is_unique(this: &Self) -> bool {
528         Rc::weak_count(this) == 0 && Rc::strong_count(this) == 1
529     }
530
531     /// Returns a mutable reference to the inner value, if there are
532     /// no other `Rc` or [`Weak`][weak] pointers to the same value.
533     ///
534     /// Returns [`None`] otherwise, because it is not safe to
535     /// mutate a shared value.
536     ///
537     /// See also [`make_mut`][make_mut], which will [`clone`][clone]
538     /// the inner value when it's shared.
539     ///
540     /// [weak]: struct.Weak.html
541     /// [`None`]: ../../std/option/enum.Option.html#variant.None
542     /// [make_mut]: struct.Rc.html#method.make_mut
543     /// [clone]: ../../std/clone/trait.Clone.html#tymethod.clone
544     ///
545     /// # Examples
546     ///
547     /// ```
548     /// use std::rc::Rc;
549     ///
550     /// let mut x = Rc::new(3);
551     /// *Rc::get_mut(&mut x).unwrap() = 4;
552     /// assert_eq!(*x, 4);
553     ///
554     /// let _y = Rc::clone(&x);
555     /// assert!(Rc::get_mut(&mut x).is_none());
556     /// ```
557     #[inline]
558     #[stable(feature = "rc_unique", since = "1.4.0")]
559     pub fn get_mut(this: &mut Self) -> Option<&mut T> {
560         if Rc::is_unique(this) {
561             unsafe {
562                 Some(&mut this.ptr.as_mut().value)
563             }
564         } else {
565             None
566         }
567     }
568
569     #[inline]
570     #[stable(feature = "ptr_eq", since = "1.17.0")]
571     /// Returns `true` if the two `Rc`s point to the same value (not
572     /// just values that compare as equal).
573     ///
574     /// # Examples
575     ///
576     /// ```
577     /// use std::rc::Rc;
578     ///
579     /// let five = Rc::new(5);
580     /// let same_five = Rc::clone(&five);
581     /// let other_five = Rc::new(5);
582     ///
583     /// assert!(Rc::ptr_eq(&five, &same_five));
584     /// assert!(!Rc::ptr_eq(&five, &other_five));
585     /// ```
586     pub fn ptr_eq(this: &Self, other: &Self) -> bool {
587         this.ptr.as_ptr() == other.ptr.as_ptr()
588     }
589 }
590
591 impl<T: Clone> Rc<T> {
592     /// Makes a mutable reference into the given `Rc`.
593     ///
594     /// If there are other `Rc` pointers to the same value, then `make_mut` will
595     /// [`clone`] the inner value to ensure unique ownership.  This is also
596     /// referred to as clone-on-write.
597     ///
598     /// If there are no other `Rc` pointers to this value, then [`Weak`]
599     /// pointers to this value will be dissassociated.
600     ///
601     /// See also [`get_mut`], which will fail rather than cloning.
602     ///
603     /// [`Weak`]: struct.Weak.html
604     /// [`clone`]: ../../std/clone/trait.Clone.html#tymethod.clone
605     /// [`get_mut`]: struct.Rc.html#method.get_mut
606     ///
607     /// # Examples
608     ///
609     /// ```
610     /// use std::rc::Rc;
611     ///
612     /// let mut data = Rc::new(5);
613     ///
614     /// *Rc::make_mut(&mut data) += 1;        // Won't clone anything
615     /// let mut other_data = Rc::clone(&data);    // Won't clone inner data
616     /// *Rc::make_mut(&mut data) += 1;        // Clones inner data
617     /// *Rc::make_mut(&mut data) += 1;        // Won't clone anything
618     /// *Rc::make_mut(&mut other_data) *= 2;  // Won't clone anything
619     ///
620     /// // Now `data` and `other_data` point to different values.
621     /// assert_eq!(*data, 8);
622     /// assert_eq!(*other_data, 12);
623     /// ```
624     ///
625     /// [`Weak`] pointers will be dissassociated:
626     ///
627     /// ```
628     /// use std::rc::Rc;
629     ///
630     /// let mut data = Rc::new(75);
631     /// let weak = Rc::downgrade(&data);
632     ///
633     /// assert!(75 == *data);
634     /// assert!(75 == *weak.upgrade().unwrap());
635     ///
636     /// *Rc::make_mut(&mut data) += 1;
637     ///
638     /// assert!(76 == *data);
639     /// assert!(weak.upgrade().is_none());
640     /// ```
641     #[inline]
642     #[stable(feature = "rc_unique", since = "1.4.0")]
643     pub fn make_mut(this: &mut Self) -> &mut T {
644         if Rc::strong_count(this) != 1 {
645             // Gotta clone the data, there are other Rcs
646             *this = Rc::new((**this).clone())
647         } else if Rc::weak_count(this) != 0 {
648             // Can just steal the data, all that's left is Weaks
649             unsafe {
650                 let mut swap = Rc::new(ptr::read(&this.ptr.as_ref().value));
651                 mem::swap(this, &mut swap);
652                 swap.dec_strong();
653                 // Remove implicit strong-weak ref (no need to craft a fake
654                 // Weak here -- we know other Weaks can clean up for us)
655                 swap.dec_weak();
656                 forget(swap);
657             }
658         }
659         // This unsafety is ok because we're guaranteed that the pointer
660         // returned is the *only* pointer that will ever be returned to T. Our
661         // reference count is guaranteed to be 1 at this point, and we required
662         // the `Rc<T>` itself to be `mut`, so we're returning the only possible
663         // reference to the inner value.
664         unsafe {
665             &mut this.ptr.as_mut().value
666         }
667     }
668 }
669
670 impl Rc<dyn Any> {
671     #[inline]
672     #[stable(feature = "rc_downcast", since = "1.29.0")]
673     /// Attempt to downcast the `Rc<dyn Any>` to a concrete type.
674     ///
675     /// # Examples
676     ///
677     /// ```
678     /// use std::any::Any;
679     /// use std::rc::Rc;
680     ///
681     /// fn print_if_string(value: Rc<dyn Any>) {
682     ///     if let Ok(string) = value.downcast::<String>() {
683     ///         println!("String ({}): {}", string.len(), string);
684     ///     }
685     /// }
686     ///
687     /// fn main() {
688     ///     let my_string = "Hello World".to_string();
689     ///     print_if_string(Rc::new(my_string));
690     ///     print_if_string(Rc::new(0i8));
691     /// }
692     /// ```
693     pub fn downcast<T: Any>(self) -> Result<Rc<T>, Rc<dyn Any>> {
694         if (*self).is::<T>() {
695             let ptr = self.ptr.cast::<RcBox<T>>();
696             forget(self);
697             Ok(Rc::from_inner(ptr))
698         } else {
699             Err(self)
700         }
701     }
702 }
703
704 impl<T: ?Sized> Rc<T> {
705     /// Allocates an `RcBox<T>` with sufficient space for
706     /// an unsized value where the value has the layout provided.
707     ///
708     /// The function `mem_to_rcbox` is called with the data pointer
709     /// and must return back a (potentially fat)-pointer for the `RcBox<T>`.
710     unsafe fn allocate_for_unsized(
711         value_layout: Layout,
712         mem_to_rcbox: impl FnOnce(*mut u8) -> *mut RcBox<T>
713     ) -> *mut RcBox<T> {
714         // Calculate layout using the given value layout.
715         // Previously, layout was calculated on the expression
716         // `&*(ptr as *const RcBox<T>)`, but this created a misaligned
717         // reference (see #54908).
718         let layout = Layout::new::<RcBox<()>>()
719             .extend(value_layout).unwrap().0
720             .pad_to_align().unwrap();
721
722         // Allocate for the layout.
723         let mem = Global.alloc(layout)
724             .unwrap_or_else(|_| handle_alloc_error(layout));
725
726         // Initialize the RcBox
727         let inner = mem_to_rcbox(mem.as_ptr());
728         debug_assert_eq!(Layout::for_value(&*inner), layout);
729
730         ptr::write(&mut (*inner).strong, Cell::new(1));
731         ptr::write(&mut (*inner).weak, Cell::new(1));
732
733         inner
734     }
735
736     /// Allocates an `RcBox<T>` with sufficient space for an unsized value
737     unsafe fn allocate_for_ptr(ptr: *const T) -> *mut RcBox<T> {
738         // Allocate for the `RcBox<T>` using the given value.
739         Self::allocate_for_unsized(
740             Layout::for_value(&*ptr),
741             |mem| set_data_ptr(ptr as *mut T, mem) as *mut RcBox<T>,
742         )
743     }
744
745     fn from_box(v: Box<T>) -> Rc<T> {
746         unsafe {
747             let box_unique = Box::into_unique(v);
748             let bptr = box_unique.as_ptr();
749
750             let value_size = size_of_val(&*bptr);
751             let ptr = Self::allocate_for_ptr(bptr);
752
753             // Copy value as bytes
754             ptr::copy_nonoverlapping(
755                 bptr as *const T as *const u8,
756                 &mut (*ptr).value as *mut _ as *mut u8,
757                 value_size);
758
759             // Free the allocation without dropping its contents
760             box_free(box_unique);
761
762             Self::from_ptr(ptr)
763         }
764     }
765 }
766
767 impl<T> Rc<[T]> {
768     /// Allocates an `RcBox<[T]>` with the given length.
769     unsafe fn allocate_for_slice(len: usize) -> *mut RcBox<[T]> {
770         Self::allocate_for_unsized(
771             Layout::array::<T>(len).unwrap(),
772             |mem| ptr::slice_from_raw_parts_mut(mem as *mut T, len) as *mut RcBox<[T]>,
773         )
774     }
775 }
776
777 /// Sets the data pointer of a `?Sized` raw pointer.
778 ///
779 /// For a slice/trait object, this sets the `data` field and leaves the rest
780 /// unchanged. For a sized raw pointer, this simply sets the pointer.
781 unsafe fn set_data_ptr<T: ?Sized, U>(mut ptr: *mut T, data: *mut U) -> *mut T {
782     ptr::write(&mut ptr as *mut _ as *mut *mut u8, data as *mut u8);
783     ptr
784 }
785
786 impl<T> Rc<[T]> {
787     /// Copy elements from slice into newly allocated Rc<[T]>
788     ///
789     /// Unsafe because the caller must either take ownership or bind `T: Copy`
790     unsafe fn copy_from_slice(v: &[T]) -> Rc<[T]> {
791         let ptr = Self::allocate_for_slice(v.len());
792
793         ptr::copy_nonoverlapping(
794             v.as_ptr(),
795             &mut (*ptr).value as *mut [T] as *mut T,
796             v.len());
797
798         Self::from_ptr(ptr)
799     }
800
801     /// Constructs an `Rc<[T]>` from an iterator known to be of a certain size.
802     ///
803     /// Behavior is undefined should the size be wrong.
804     unsafe fn from_iter_exact(iter: impl iter::Iterator<Item = T>, len: usize) -> Rc<[T]> {
805         // Panic guard while cloning T elements.
806         // In the event of a panic, elements that have been written
807         // into the new RcBox will be dropped, then the memory freed.
808         struct Guard<T> {
809             mem: NonNull<u8>,
810             elems: *mut T,
811             layout: Layout,
812             n_elems: usize,
813         }
814
815         impl<T> Drop for Guard<T> {
816             fn drop(&mut self) {
817                 unsafe {
818                     let slice = from_raw_parts_mut(self.elems, self.n_elems);
819                     ptr::drop_in_place(slice);
820
821                     Global.dealloc(self.mem, self.layout);
822                 }
823             }
824         }
825
826         let ptr = Self::allocate_for_slice(len);
827
828         let mem = ptr as *mut _ as *mut u8;
829         let layout = Layout::for_value(&*ptr);
830
831         // Pointer to first element
832         let elems = &mut (*ptr).value as *mut [T] as *mut T;
833
834         let mut guard = Guard {
835             mem: NonNull::new_unchecked(mem),
836             elems,
837             layout,
838             n_elems: 0,
839         };
840
841         for (i, item) in iter.enumerate() {
842             ptr::write(elems.add(i), item);
843             guard.n_elems += 1;
844         }
845
846         // All clear. Forget the guard so it doesn't free the new RcBox.
847         forget(guard);
848
849         Self::from_ptr(ptr)
850     }
851 }
852
853 /// Specialization trait used for `From<&[T]>`.
854 trait RcFromSlice<T> {
855     fn from_slice(slice: &[T]) -> Self;
856 }
857
858 impl<T: Clone> RcFromSlice<T> for Rc<[T]> {
859     #[inline]
860     default fn from_slice(v: &[T]) -> Self {
861         unsafe {
862             Self::from_iter_exact(v.iter().cloned(), v.len())
863         }
864     }
865 }
866
867 impl<T: Copy> RcFromSlice<T> for Rc<[T]> {
868     #[inline]
869     fn from_slice(v: &[T]) -> Self {
870         unsafe { Rc::copy_from_slice(v) }
871     }
872 }
873
874 #[stable(feature = "rust1", since = "1.0.0")]
875 impl<T: ?Sized> Deref for Rc<T> {
876     type Target = T;
877
878     #[inline(always)]
879     fn deref(&self) -> &T {
880         &self.inner().value
881     }
882 }
883
884 #[unstable(feature = "receiver_trait", issue = "0")]
885 impl<T: ?Sized> Receiver for Rc<T> {}
886
887 #[stable(feature = "rust1", since = "1.0.0")]
888 unsafe impl<#[may_dangle] T: ?Sized> Drop for Rc<T> {
889     /// Drops the `Rc`.
890     ///
891     /// This will decrement the strong reference count. If the strong reference
892     /// count reaches zero then the only other references (if any) are
893     /// [`Weak`], so we `drop` the inner value.
894     ///
895     /// # Examples
896     ///
897     /// ```
898     /// use std::rc::Rc;
899     ///
900     /// struct Foo;
901     ///
902     /// impl Drop for Foo {
903     ///     fn drop(&mut self) {
904     ///         println!("dropped!");
905     ///     }
906     /// }
907     ///
908     /// let foo  = Rc::new(Foo);
909     /// let foo2 = Rc::clone(&foo);
910     ///
911     /// drop(foo);    // Doesn't print anything
912     /// drop(foo2);   // Prints "dropped!"
913     /// ```
914     ///
915     /// [`Weak`]: ../../std/rc/struct.Weak.html
916     fn drop(&mut self) {
917         unsafe {
918             self.dec_strong();
919             if self.strong() == 0 {
920                 // destroy the contained object
921                 ptr::drop_in_place(self.ptr.as_mut());
922
923                 // remove the implicit "strong weak" pointer now that we've
924                 // destroyed the contents.
925                 self.dec_weak();
926
927                 if self.weak() == 0 {
928                     Global.dealloc(self.ptr.cast(), Layout::for_value(self.ptr.as_ref()));
929                 }
930             }
931         }
932     }
933 }
934
935 #[stable(feature = "rust1", since = "1.0.0")]
936 impl<T: ?Sized> Clone for Rc<T> {
937     /// Makes a clone of the `Rc` pointer.
938     ///
939     /// This creates another pointer to the same inner value, increasing the
940     /// strong reference count.
941     ///
942     /// # Examples
943     ///
944     /// ```
945     /// use std::rc::Rc;
946     ///
947     /// let five = Rc::new(5);
948     ///
949     /// let _ = Rc::clone(&five);
950     /// ```
951     #[inline]
952     fn clone(&self) -> Rc<T> {
953         self.inc_strong();
954         Self::from_inner(self.ptr)
955     }
956 }
957
958 #[stable(feature = "rust1", since = "1.0.0")]
959 impl<T: Default> Default for Rc<T> {
960     /// Creates a new `Rc<T>`, with the `Default` value for `T`.
961     ///
962     /// # Examples
963     ///
964     /// ```
965     /// use std::rc::Rc;
966     ///
967     /// let x: Rc<i32> = Default::default();
968     /// assert_eq!(*x, 0);
969     /// ```
970     #[inline]
971     fn default() -> Rc<T> {
972         Rc::new(Default::default())
973     }
974 }
975
976 #[stable(feature = "rust1", since = "1.0.0")]
977 trait RcEqIdent<T: ?Sized + PartialEq> {
978     fn eq(&self, other: &Rc<T>) -> bool;
979     fn ne(&self, other: &Rc<T>) -> bool;
980 }
981
982 #[stable(feature = "rust1", since = "1.0.0")]
983 impl<T: ?Sized + PartialEq> RcEqIdent<T> for Rc<T> {
984     #[inline]
985     default fn eq(&self, other: &Rc<T>) -> bool {
986         **self == **other
987     }
988
989     #[inline]
990     default fn ne(&self, other: &Rc<T>) -> bool {
991         **self != **other
992     }
993 }
994
995 /// We're doing this specialization here, and not as a more general optimization on `&T`, because it
996 /// would otherwise add a cost to all equality checks on refs. We assume that `Rc`s are used to
997 /// store large values, that are slow to clone, but also heavy to check for equality, causing this
998 /// cost to pay off more easily. It's also more likely to have two `Rc` clones, that point to
999 /// the same value, than two `&T`s.
1000 #[stable(feature = "rust1", since = "1.0.0")]
1001 impl<T: ?Sized + Eq> RcEqIdent<T> for Rc<T> {
1002     #[inline]
1003     fn eq(&self, other: &Rc<T>) -> bool {
1004         Rc::ptr_eq(self, other) || **self == **other
1005     }
1006
1007     #[inline]
1008     fn ne(&self, other: &Rc<T>) -> bool {
1009         !Rc::ptr_eq(self, other) && **self != **other
1010     }
1011 }
1012
1013 #[stable(feature = "rust1", since = "1.0.0")]
1014 impl<T: ?Sized + PartialEq> PartialEq for Rc<T> {
1015     /// Equality for two `Rc`s.
1016     ///
1017     /// Two `Rc`s are equal if their inner values are equal.
1018     ///
1019     /// If `T` also implements `Eq`, two `Rc`s that point to the same value are
1020     /// always equal.
1021     ///
1022     /// # Examples
1023     ///
1024     /// ```
1025     /// use std::rc::Rc;
1026     ///
1027     /// let five = Rc::new(5);
1028     ///
1029     /// assert!(five == Rc::new(5));
1030     /// ```
1031     #[inline]
1032     fn eq(&self, other: &Rc<T>) -> bool {
1033         RcEqIdent::eq(self, other)
1034     }
1035
1036     /// Inequality for two `Rc`s.
1037     ///
1038     /// Two `Rc`s are unequal if their inner values are unequal.
1039     ///
1040     /// If `T` also implements `Eq`, two `Rc`s that point to the same value are
1041     /// never unequal.
1042     ///
1043     /// # Examples
1044     ///
1045     /// ```
1046     /// use std::rc::Rc;
1047     ///
1048     /// let five = Rc::new(5);
1049     ///
1050     /// assert!(five != Rc::new(6));
1051     /// ```
1052     #[inline]
1053     fn ne(&self, other: &Rc<T>) -> bool {
1054         RcEqIdent::ne(self, other)
1055     }
1056 }
1057
1058 #[stable(feature = "rust1", since = "1.0.0")]
1059 impl<T: ?Sized + Eq> Eq for Rc<T> {}
1060
1061 #[stable(feature = "rust1", since = "1.0.0")]
1062 impl<T: ?Sized + PartialOrd> PartialOrd for Rc<T> {
1063     /// Partial comparison for two `Rc`s.
1064     ///
1065     /// The two are compared by calling `partial_cmp()` on their inner values.
1066     ///
1067     /// # Examples
1068     ///
1069     /// ```
1070     /// use std::rc::Rc;
1071     /// use std::cmp::Ordering;
1072     ///
1073     /// let five = Rc::new(5);
1074     ///
1075     /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&Rc::new(6)));
1076     /// ```
1077     #[inline(always)]
1078     fn partial_cmp(&self, other: &Rc<T>) -> Option<Ordering> {
1079         (**self).partial_cmp(&**other)
1080     }
1081
1082     /// Less-than comparison for two `Rc`s.
1083     ///
1084     /// The two are compared by calling `<` on their inner values.
1085     ///
1086     /// # Examples
1087     ///
1088     /// ```
1089     /// use std::rc::Rc;
1090     ///
1091     /// let five = Rc::new(5);
1092     ///
1093     /// assert!(five < Rc::new(6));
1094     /// ```
1095     #[inline(always)]
1096     fn lt(&self, other: &Rc<T>) -> bool {
1097         **self < **other
1098     }
1099
1100     /// 'Less than or equal to' comparison for two `Rc`s.
1101     ///
1102     /// The two are compared by calling `<=` on their inner values.
1103     ///
1104     /// # Examples
1105     ///
1106     /// ```
1107     /// use std::rc::Rc;
1108     ///
1109     /// let five = Rc::new(5);
1110     ///
1111     /// assert!(five <= Rc::new(5));
1112     /// ```
1113     #[inline(always)]
1114     fn le(&self, other: &Rc<T>) -> bool {
1115         **self <= **other
1116     }
1117
1118     /// Greater-than comparison for two `Rc`s.
1119     ///
1120     /// The two are compared by calling `>` on their inner values.
1121     ///
1122     /// # Examples
1123     ///
1124     /// ```
1125     /// use std::rc::Rc;
1126     ///
1127     /// let five = Rc::new(5);
1128     ///
1129     /// assert!(five > Rc::new(4));
1130     /// ```
1131     #[inline(always)]
1132     fn gt(&self, other: &Rc<T>) -> bool {
1133         **self > **other
1134     }
1135
1136     /// 'Greater than or equal to' comparison for two `Rc`s.
1137     ///
1138     /// The two are compared by calling `>=` on their inner values.
1139     ///
1140     /// # Examples
1141     ///
1142     /// ```
1143     /// use std::rc::Rc;
1144     ///
1145     /// let five = Rc::new(5);
1146     ///
1147     /// assert!(five >= Rc::new(5));
1148     /// ```
1149     #[inline(always)]
1150     fn ge(&self, other: &Rc<T>) -> bool {
1151         **self >= **other
1152     }
1153 }
1154
1155 #[stable(feature = "rust1", since = "1.0.0")]
1156 impl<T: ?Sized + Ord> Ord for Rc<T> {
1157     /// Comparison for two `Rc`s.
1158     ///
1159     /// The two are compared by calling `cmp()` on their inner values.
1160     ///
1161     /// # Examples
1162     ///
1163     /// ```
1164     /// use std::rc::Rc;
1165     /// use std::cmp::Ordering;
1166     ///
1167     /// let five = Rc::new(5);
1168     ///
1169     /// assert_eq!(Ordering::Less, five.cmp(&Rc::new(6)));
1170     /// ```
1171     #[inline]
1172     fn cmp(&self, other: &Rc<T>) -> Ordering {
1173         (**self).cmp(&**other)
1174     }
1175 }
1176
1177 #[stable(feature = "rust1", since = "1.0.0")]
1178 impl<T: ?Sized + Hash> Hash for Rc<T> {
1179     fn hash<H: Hasher>(&self, state: &mut H) {
1180         (**self).hash(state);
1181     }
1182 }
1183
1184 #[stable(feature = "rust1", since = "1.0.0")]
1185 impl<T: ?Sized + fmt::Display> fmt::Display for Rc<T> {
1186     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1187         fmt::Display::fmt(&**self, f)
1188     }
1189 }
1190
1191 #[stable(feature = "rust1", since = "1.0.0")]
1192 impl<T: ?Sized + fmt::Debug> fmt::Debug for Rc<T> {
1193     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1194         fmt::Debug::fmt(&**self, f)
1195     }
1196 }
1197
1198 #[stable(feature = "rust1", since = "1.0.0")]
1199 impl<T: ?Sized> fmt::Pointer for Rc<T> {
1200     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1201         fmt::Pointer::fmt(&(&**self as *const T), f)
1202     }
1203 }
1204
1205 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
1206 impl<T> From<T> for Rc<T> {
1207     fn from(t: T) -> Self {
1208         Rc::new(t)
1209     }
1210 }
1211
1212 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1213 impl<T: Clone> From<&[T]> for Rc<[T]> {
1214     #[inline]
1215     fn from(v: &[T]) -> Rc<[T]> {
1216         <Self as RcFromSlice<T>>::from_slice(v)
1217     }
1218 }
1219
1220 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1221 impl From<&str> for Rc<str> {
1222     #[inline]
1223     fn from(v: &str) -> Rc<str> {
1224         let rc = Rc::<[u8]>::from(v.as_bytes());
1225         unsafe { Rc::from_raw(Rc::into_raw(rc) as *const str) }
1226     }
1227 }
1228
1229 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1230 impl From<String> for Rc<str> {
1231     #[inline]
1232     fn from(v: String) -> Rc<str> {
1233         Rc::from(&v[..])
1234     }
1235 }
1236
1237 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1238 impl<T: ?Sized> From<Box<T>> for Rc<T> {
1239     #[inline]
1240     fn from(v: Box<T>) -> Rc<T> {
1241         Rc::from_box(v)
1242     }
1243 }
1244
1245 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1246 impl<T> From<Vec<T>> for Rc<[T]> {
1247     #[inline]
1248     fn from(mut v: Vec<T>) -> Rc<[T]> {
1249         unsafe {
1250             let rc = Rc::copy_from_slice(&v);
1251
1252             // Allow the Vec to free its memory, but not destroy its contents
1253             v.set_len(0);
1254
1255             rc
1256         }
1257     }
1258 }
1259
1260 #[stable(feature = "shared_from_iter", since = "1.37.0")]
1261 impl<T> iter::FromIterator<T> for Rc<[T]> {
1262     /// Takes each element in the `Iterator` and collects it into an `Rc<[T]>`.
1263     ///
1264     /// # Performance characteristics
1265     ///
1266     /// ## The general case
1267     ///
1268     /// In the general case, collecting into `Rc<[T]>` is done by first
1269     /// collecting into a `Vec<T>`. That is, when writing the following:
1270     ///
1271     /// ```rust
1272     /// # use std::rc::Rc;
1273     /// let evens: Rc<[u8]> = (0..10).filter(|&x| x % 2 == 0).collect();
1274     /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]);
1275     /// ```
1276     ///
1277     /// this behaves as if we wrote:
1278     ///
1279     /// ```rust
1280     /// # use std::rc::Rc;
1281     /// let evens: Rc<[u8]> = (0..10).filter(|&x| x % 2 == 0)
1282     ///     .collect::<Vec<_>>() // The first set of allocations happens here.
1283     ///     .into(); // A second allocation for `Rc<[T]>` happens here.
1284     /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]);
1285     /// ```
1286     ///
1287     /// This will allocate as many times as needed for constructing the `Vec<T>`
1288     /// and then it will allocate once for turning the `Vec<T>` into the `Rc<[T]>`.
1289     ///
1290     /// ## Iterators of known length
1291     ///
1292     /// When your `Iterator` implements `TrustedLen` and is of an exact size,
1293     /// a single allocation will be made for the `Rc<[T]>`. For example:
1294     ///
1295     /// ```rust
1296     /// # use std::rc::Rc;
1297     /// let evens: Rc<[u8]> = (0..10).collect(); // Just a single allocation happens here.
1298     /// # assert_eq!(&*evens, &*(0..10).collect::<Vec<_>>());
1299     /// ```
1300     fn from_iter<I: iter::IntoIterator<Item = T>>(iter: I) -> Self {
1301         RcFromIter::from_iter(iter.into_iter())
1302     }
1303 }
1304
1305 /// Specialization trait used for collecting into `Rc<[T]>`.
1306 trait RcFromIter<T, I> {
1307     fn from_iter(iter: I) -> Self;
1308 }
1309
1310 impl<T, I: Iterator<Item = T>> RcFromIter<T, I> for Rc<[T]> {
1311     default fn from_iter(iter: I) -> Self {
1312         iter.collect::<Vec<T>>().into()
1313     }
1314 }
1315
1316 impl<T, I: iter::TrustedLen<Item = T>> RcFromIter<T, I> for Rc<[T]>  {
1317     default fn from_iter(iter: I) -> Self {
1318         // This is the case for a `TrustedLen` iterator.
1319         let (low, high) = iter.size_hint();
1320         if let Some(high) = high {
1321             debug_assert_eq!(
1322                 low, high,
1323                 "TrustedLen iterator's size hint is not exact: {:?}",
1324                 (low, high)
1325             );
1326
1327             unsafe {
1328                 // SAFETY: We need to ensure that the iterator has an exact length and we have.
1329                 Rc::from_iter_exact(iter, low)
1330             }
1331         } else {
1332             // Fall back to normal implementation.
1333             iter.collect::<Vec<T>>().into()
1334         }
1335     }
1336 }
1337
1338 impl<'a, T: 'a + Clone> RcFromIter<&'a T, slice::Iter<'a, T>> for Rc<[T]> {
1339     fn from_iter(iter: slice::Iter<'a, T>) -> Self {
1340         // Delegate to `impl<T: Clone> From<&[T]> for Rc<[T]>`.
1341         //
1342         // In the case that `T: Copy`, we get to use `ptr::copy_nonoverlapping`
1343         // which is even more performant.
1344         //
1345         // In the fall-back case we have `T: Clone`. This is still better
1346         // than the `TrustedLen` implementation as slices have a known length
1347         // and so we get to avoid calling `size_hint` and avoid the branching.
1348         iter.as_slice().into()
1349     }
1350 }
1351
1352 /// `Weak` is a version of [`Rc`] that holds a non-owning reference to the
1353 /// managed value. The value is accessed by calling [`upgrade`] on the `Weak`
1354 /// pointer, which returns an [`Option`]`<`[`Rc`]`<T>>`.
1355 ///
1356 /// Since a `Weak` reference does not count towards ownership, it will not
1357 /// prevent the inner value from being dropped, and `Weak` itself makes no
1358 /// guarantees about the value still being present and may return [`None`]
1359 /// when [`upgrade`]d.
1360 ///
1361 /// A `Weak` pointer is useful for keeping a temporary reference to the value
1362 /// within [`Rc`] without extending its lifetime. It is also used to prevent
1363 /// circular references between [`Rc`] pointers, since mutual owning references
1364 /// would never allow either [`Rc`] to be dropped. For example, a tree could
1365 /// have strong [`Rc`] pointers from parent nodes to children, and `Weak`
1366 /// pointers from children back to their parents.
1367 ///
1368 /// The typical way to obtain a `Weak` pointer is to call [`Rc::downgrade`].
1369 ///
1370 /// [`Rc`]: struct.Rc.html
1371 /// [`Rc::downgrade`]: struct.Rc.html#method.downgrade
1372 /// [`upgrade`]: struct.Weak.html#method.upgrade
1373 /// [`Option`]: ../../std/option/enum.Option.html
1374 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1375 #[stable(feature = "rc_weak", since = "1.4.0")]
1376 pub struct Weak<T: ?Sized> {
1377     // This is a `NonNull` to allow optimizing the size of this type in enums,
1378     // but it is not necessarily a valid pointer.
1379     // `Weak::new` sets this to `usize::MAX` so that it doesn’t need
1380     // to allocate space on the heap.  That's not a value a real pointer
1381     // will ever have because RcBox has alignment at least 2.
1382     ptr: NonNull<RcBox<T>>,
1383 }
1384
1385 #[stable(feature = "rc_weak", since = "1.4.0")]
1386 impl<T: ?Sized> !marker::Send for Weak<T> {}
1387 #[stable(feature = "rc_weak", since = "1.4.0")]
1388 impl<T: ?Sized> !marker::Sync for Weak<T> {}
1389
1390 #[unstable(feature = "coerce_unsized", issue = "27732")]
1391 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {}
1392
1393 #[unstable(feature = "dispatch_from_dyn", issue = "0")]
1394 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Weak<U>> for Weak<T> {}
1395
1396 impl<T> Weak<T> {
1397     /// Constructs a new `Weak<T>`, without allocating any memory.
1398     /// Calling [`upgrade`] on the return value always gives [`None`].
1399     ///
1400     /// [`upgrade`]: #method.upgrade
1401     /// [`None`]: ../../std/option/enum.Option.html
1402     ///
1403     /// # Examples
1404     ///
1405     /// ```
1406     /// use std::rc::Weak;
1407     ///
1408     /// let empty: Weak<i64> = Weak::new();
1409     /// assert!(empty.upgrade().is_none());
1410     /// ```
1411     #[stable(feature = "downgraded_weak", since = "1.10.0")]
1412     pub fn new() -> Weak<T> {
1413         Weak {
1414             ptr: NonNull::new(usize::MAX as *mut RcBox<T>).expect("MAX is not 0"),
1415         }
1416     }
1417
1418     /// Returns a raw pointer to the object `T` pointed to by this `Weak<T>`.
1419     ///
1420     /// It is up to the caller to ensure that the object is still alive when accessing it through
1421     /// the pointer.
1422     ///
1423     /// The pointer may be [`null`] or be dangling in case the object has already been destroyed.
1424     ///
1425     /// # Examples
1426     ///
1427     /// ```
1428     /// #![feature(weak_into_raw)]
1429     ///
1430     /// use std::rc::Rc;
1431     /// use std::ptr;
1432     ///
1433     /// let strong = Rc::new("hello".to_owned());
1434     /// let weak = Rc::downgrade(&strong);
1435     /// // Both point to the same object
1436     /// assert!(ptr::eq(&*strong, weak.as_raw()));
1437     /// // The strong here keeps it alive, so we can still access the object.
1438     /// assert_eq!("hello", unsafe { &*weak.as_raw() });
1439     ///
1440     /// drop(strong);
1441     /// // But not any more. We can do weak.as_raw(), but accessing the pointer would lead to
1442     /// // undefined behaviour.
1443     /// // assert_eq!("hello", unsafe { &*weak.as_raw() });
1444     /// ```
1445     ///
1446     /// [`null`]: ../../std/ptr/fn.null.html
1447     #[unstable(feature = "weak_into_raw", issue = "60728")]
1448     pub fn as_raw(&self) -> *const T {
1449         match self.inner() {
1450             None => ptr::null(),
1451             Some(inner) => {
1452                 let offset = data_offset_sized::<T>();
1453                 let ptr = inner as *const RcBox<T>;
1454                 // Note: while the pointer we create may already point to dropped value, the
1455                 // allocation still lives (it must hold the weak point as long as we are alive).
1456                 // Therefore, the offset is OK to do, it won't get out of the allocation.
1457                 let ptr = unsafe { (ptr as *const u8).offset(offset) };
1458                 ptr as *const T
1459             }
1460         }
1461     }
1462
1463     /// Consumes the `Weak<T>` and turns it into a raw pointer.
1464     ///
1465     /// This converts the weak pointer into a raw pointer, preserving the original weak count. It
1466     /// can be turned back into the `Weak<T>` with [`from_raw`].
1467     ///
1468     /// The same restrictions of accessing the target of the pointer as with
1469     /// [`as_raw`] apply.
1470     ///
1471     /// # Examples
1472     ///
1473     /// ```
1474     /// #![feature(weak_into_raw)]
1475     ///
1476     /// use std::rc::{Rc, Weak};
1477     ///
1478     /// let strong = Rc::new("hello".to_owned());
1479     /// let weak = Rc::downgrade(&strong);
1480     /// let raw = weak.into_raw();
1481     ///
1482     /// assert_eq!(1, Rc::weak_count(&strong));
1483     /// assert_eq!("hello", unsafe { &*raw });
1484     ///
1485     /// drop(unsafe { Weak::from_raw(raw) });
1486     /// assert_eq!(0, Rc::weak_count(&strong));
1487     /// ```
1488     ///
1489     /// [`from_raw`]: struct.Weak.html#method.from_raw
1490     /// [`as_raw`]: struct.Weak.html#method.as_raw
1491     #[unstable(feature = "weak_into_raw", issue = "60728")]
1492     pub fn into_raw(self) -> *const T {
1493         let result = self.as_raw();
1494         mem::forget(self);
1495         result
1496     }
1497
1498     /// Converts a raw pointer previously created by [`into_raw`] back into `Weak<T>`.
1499     ///
1500     /// This can be used to safely get a strong reference (by calling [`upgrade`]
1501     /// later) or to deallocate the weak count by dropping the `Weak<T>`.
1502     ///
1503     /// It takes ownership of one weak count. In case a [`null`] is passed, a dangling [`Weak`] is
1504     /// returned.
1505     ///
1506     /// # Safety
1507     ///
1508     /// The pointer must represent one valid weak count. In other words, it must point to `T` which
1509     /// is or *was* managed by an [`Rc`] and the weak count of that [`Rc`] must not have reached
1510     /// 0. It is allowed for the strong count to be 0.
1511     ///
1512     /// # Examples
1513     ///
1514     /// ```
1515     /// #![feature(weak_into_raw)]
1516     ///
1517     /// use std::rc::{Rc, Weak};
1518     ///
1519     /// let strong = Rc::new("hello".to_owned());
1520     ///
1521     /// let raw_1 = Rc::downgrade(&strong).into_raw();
1522     /// let raw_2 = Rc::downgrade(&strong).into_raw();
1523     ///
1524     /// assert_eq!(2, Rc::weak_count(&strong));
1525     ///
1526     /// assert_eq!("hello", &*unsafe { Weak::from_raw(raw_1) }.upgrade().unwrap());
1527     /// assert_eq!(1, Rc::weak_count(&strong));
1528     ///
1529     /// drop(strong);
1530     ///
1531     /// // Decrement the last weak count.
1532     /// assert!(unsafe { Weak::from_raw(raw_2) }.upgrade().is_none());
1533     /// ```
1534     ///
1535     /// [`null`]: ../../std/ptr/fn.null.html
1536     /// [`into_raw`]: struct.Weak.html#method.into_raw
1537     /// [`upgrade`]: struct.Weak.html#method.upgrade
1538     /// [`Rc`]: struct.Rc.html
1539     /// [`Weak`]: struct.Weak.html
1540     #[unstable(feature = "weak_into_raw", issue = "60728")]
1541     pub unsafe fn from_raw(ptr: *const T) -> Self {
1542         if ptr.is_null() {
1543             Self::new()
1544         } else {
1545             // See Rc::from_raw for details
1546             let offset = data_offset(ptr);
1547             let fake_ptr = ptr as *mut RcBox<T>;
1548             let ptr = set_data_ptr(fake_ptr, (ptr as *mut u8).offset(-offset));
1549             Weak {
1550                 ptr: NonNull::new(ptr).expect("Invalid pointer passed to from_raw"),
1551             }
1552         }
1553     }
1554 }
1555
1556 pub(crate) fn is_dangling<T: ?Sized>(ptr: NonNull<T>) -> bool {
1557     let address = ptr.as_ptr() as *mut () as usize;
1558     address == usize::MAX
1559 }
1560
1561 impl<T: ?Sized> Weak<T> {
1562     /// Attempts to upgrade the `Weak` pointer to an [`Rc`], extending
1563     /// the lifetime of the value if successful.
1564     ///
1565     /// Returns [`None`] if the value has since been dropped.
1566     ///
1567     /// [`Rc`]: struct.Rc.html
1568     /// [`None`]: ../../std/option/enum.Option.html
1569     ///
1570     /// # Examples
1571     ///
1572     /// ```
1573     /// use std::rc::Rc;
1574     ///
1575     /// let five = Rc::new(5);
1576     ///
1577     /// let weak_five = Rc::downgrade(&five);
1578     ///
1579     /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
1580     /// assert!(strong_five.is_some());
1581     ///
1582     /// // Destroy all strong pointers.
1583     /// drop(strong_five);
1584     /// drop(five);
1585     ///
1586     /// assert!(weak_five.upgrade().is_none());
1587     /// ```
1588     #[stable(feature = "rc_weak", since = "1.4.0")]
1589     pub fn upgrade(&self) -> Option<Rc<T>> {
1590         let inner = self.inner()?;
1591         if inner.strong() == 0 {
1592             None
1593         } else {
1594             inner.inc_strong();
1595             Some(Rc::from_inner(self.ptr))
1596         }
1597     }
1598
1599     /// Gets the number of strong (`Rc`) pointers pointing to this value.
1600     ///
1601     /// If `self` was created using [`Weak::new`], this will return 0.
1602     ///
1603     /// [`Weak::new`]: #method.new
1604     #[unstable(feature = "weak_counts", issue = "57977")]
1605     pub fn strong_count(&self) -> usize {
1606         if let Some(inner) = self.inner() {
1607             inner.strong()
1608         } else {
1609             0
1610         }
1611     }
1612
1613     /// Gets the number of `Weak` pointers pointing to this value.
1614     ///
1615     /// If `self` was created using [`Weak::new`], this will return `None`. If
1616     /// not, the returned value is at least 1, since `self` still points to the
1617     /// value.
1618     ///
1619     /// [`Weak::new`]: #method.new
1620     #[unstable(feature = "weak_counts", issue = "57977")]
1621     pub fn weak_count(&self) -> Option<usize> {
1622         self.inner().map(|inner| {
1623             if inner.strong() > 0 {
1624                 inner.weak() - 1  // subtract the implicit weak ptr
1625             } else {
1626                 inner.weak()
1627             }
1628         })
1629     }
1630
1631     /// Returns `None` when the pointer is dangling and there is no allocated `RcBox`
1632     /// (i.e., when this `Weak` was created by `Weak::new`).
1633     #[inline]
1634     fn inner(&self) -> Option<&RcBox<T>> {
1635         if is_dangling(self.ptr) {
1636             None
1637         } else {
1638             Some(unsafe { self.ptr.as_ref() })
1639         }
1640     }
1641
1642     /// Returns `true` if the two `Weak`s point to the same value (not just values
1643     /// that compare as equal).
1644     ///
1645     /// # Notes
1646     ///
1647     /// Since this compares pointers it means that `Weak::new()` will equal each
1648     /// other, even though they don't point to any value.
1649     ///
1650     /// # Examples
1651     ///
1652     /// ```
1653     /// #![feature(weak_ptr_eq)]
1654     /// use std::rc::Rc;
1655     ///
1656     /// let first_rc = Rc::new(5);
1657     /// let first = Rc::downgrade(&first_rc);
1658     /// let second = Rc::downgrade(&first_rc);
1659     ///
1660     /// assert!(first.ptr_eq(&second));
1661     ///
1662     /// let third_rc = Rc::new(5);
1663     /// let third = Rc::downgrade(&third_rc);
1664     ///
1665     /// assert!(!first.ptr_eq(&third));
1666     /// ```
1667     ///
1668     /// Comparing `Weak::new`.
1669     ///
1670     /// ```
1671     /// #![feature(weak_ptr_eq)]
1672     /// use std::rc::{Rc, Weak};
1673     ///
1674     /// let first = Weak::new();
1675     /// let second = Weak::new();
1676     /// assert!(first.ptr_eq(&second));
1677     ///
1678     /// let third_rc = Rc::new(());
1679     /// let third = Rc::downgrade(&third_rc);
1680     /// assert!(!first.ptr_eq(&third));
1681     /// ```
1682     #[inline]
1683     #[unstable(feature = "weak_ptr_eq", issue = "55981")]
1684     pub fn ptr_eq(&self, other: &Self) -> bool {
1685         self.ptr.as_ptr() == other.ptr.as_ptr()
1686     }
1687 }
1688
1689 #[stable(feature = "rc_weak", since = "1.4.0")]
1690 impl<T: ?Sized> Drop for Weak<T> {
1691     /// Drops the `Weak` pointer.
1692     ///
1693     /// # Examples
1694     ///
1695     /// ```
1696     /// use std::rc::{Rc, Weak};
1697     ///
1698     /// struct Foo;
1699     ///
1700     /// impl Drop for Foo {
1701     ///     fn drop(&mut self) {
1702     ///         println!("dropped!");
1703     ///     }
1704     /// }
1705     ///
1706     /// let foo = Rc::new(Foo);
1707     /// let weak_foo = Rc::downgrade(&foo);
1708     /// let other_weak_foo = Weak::clone(&weak_foo);
1709     ///
1710     /// drop(weak_foo);   // Doesn't print anything
1711     /// drop(foo);        // Prints "dropped!"
1712     ///
1713     /// assert!(other_weak_foo.upgrade().is_none());
1714     /// ```
1715     fn drop(&mut self) {
1716         if let Some(inner) = self.inner() {
1717             inner.dec_weak();
1718             // the weak count starts at 1, and will only go to zero if all
1719             // the strong pointers have disappeared.
1720             if inner.weak() == 0 {
1721                 unsafe {
1722                     Global.dealloc(self.ptr.cast(), Layout::for_value(self.ptr.as_ref()));
1723                 }
1724             }
1725         }
1726     }
1727 }
1728
1729 #[stable(feature = "rc_weak", since = "1.4.0")]
1730 impl<T: ?Sized> Clone for Weak<T> {
1731     /// Makes a clone of the `Weak` pointer that points to the same value.
1732     ///
1733     /// # Examples
1734     ///
1735     /// ```
1736     /// use std::rc::{Rc, Weak};
1737     ///
1738     /// let weak_five = Rc::downgrade(&Rc::new(5));
1739     ///
1740     /// let _ = Weak::clone(&weak_five);
1741     /// ```
1742     #[inline]
1743     fn clone(&self) -> Weak<T> {
1744         if let Some(inner) = self.inner() {
1745             inner.inc_weak()
1746         }
1747         Weak { ptr: self.ptr }
1748     }
1749 }
1750
1751 #[stable(feature = "rc_weak", since = "1.4.0")]
1752 impl<T: ?Sized + fmt::Debug> fmt::Debug for Weak<T> {
1753     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1754         write!(f, "(Weak)")
1755     }
1756 }
1757
1758 #[stable(feature = "downgraded_weak", since = "1.10.0")]
1759 impl<T> Default for Weak<T> {
1760     /// Constructs a new `Weak<T>`, allocating memory for `T` without initializing
1761     /// it. Calling [`upgrade`] on the return value always gives [`None`].
1762     ///
1763     /// [`None`]: ../../std/option/enum.Option.html
1764     /// [`upgrade`]: ../../std/rc/struct.Weak.html#method.upgrade
1765     ///
1766     /// # Examples
1767     ///
1768     /// ```
1769     /// use std::rc::Weak;
1770     ///
1771     /// let empty: Weak<i64> = Default::default();
1772     /// assert!(empty.upgrade().is_none());
1773     /// ```
1774     fn default() -> Weak<T> {
1775         Weak::new()
1776     }
1777 }
1778
1779 // NOTE: We checked_add here to deal with mem::forget safely. In particular
1780 // if you mem::forget Rcs (or Weaks), the ref-count can overflow, and then
1781 // you can free the allocation while outstanding Rcs (or Weaks) exist.
1782 // We abort because this is such a degenerate scenario that we don't care about
1783 // what happens -- no real program should ever experience this.
1784 //
1785 // This should have negligible overhead since you don't actually need to
1786 // clone these much in Rust thanks to ownership and move-semantics.
1787
1788 #[doc(hidden)]
1789 trait RcBoxPtr<T: ?Sized> {
1790     fn inner(&self) -> &RcBox<T>;
1791
1792     #[inline]
1793     fn strong(&self) -> usize {
1794         self.inner().strong.get()
1795     }
1796
1797     #[inline]
1798     fn inc_strong(&self) {
1799         let strong = self.strong();
1800
1801         // We want to abort on overflow instead of dropping the value.
1802         // The reference count will never be zero when this is called;
1803         // nevertheless, we insert an abort here to hint LLVM at
1804         // an otherwise missed optimization.
1805         if strong == 0 || strong == usize::max_value() {
1806             unsafe { abort(); }
1807         }
1808         self.inner().strong.set(strong + 1);
1809     }
1810
1811     #[inline]
1812     fn dec_strong(&self) {
1813         self.inner().strong.set(self.strong() - 1);
1814     }
1815
1816     #[inline]
1817     fn weak(&self) -> usize {
1818         self.inner().weak.get()
1819     }
1820
1821     #[inline]
1822     fn inc_weak(&self) {
1823         let weak = self.weak();
1824
1825         // We want to abort on overflow instead of dropping the value.
1826         // The reference count will never be zero when this is called;
1827         // nevertheless, we insert an abort here to hint LLVM at
1828         // an otherwise missed optimization.
1829         if weak == 0 || weak == usize::max_value() {
1830             unsafe { abort(); }
1831         }
1832         self.inner().weak.set(weak + 1);
1833     }
1834
1835     #[inline]
1836     fn dec_weak(&self) {
1837         self.inner().weak.set(self.weak() - 1);
1838     }
1839 }
1840
1841 impl<T: ?Sized> RcBoxPtr<T> for Rc<T> {
1842     #[inline(always)]
1843     fn inner(&self) -> &RcBox<T> {
1844         unsafe {
1845             self.ptr.as_ref()
1846         }
1847     }
1848 }
1849
1850 impl<T: ?Sized> RcBoxPtr<T> for RcBox<T> {
1851     #[inline(always)]
1852     fn inner(&self) -> &RcBox<T> {
1853         self
1854     }
1855 }
1856
1857 #[stable(feature = "rust1", since = "1.0.0")]
1858 impl<T: ?Sized> borrow::Borrow<T> for Rc<T> {
1859     fn borrow(&self) -> &T {
1860         &**self
1861     }
1862 }
1863
1864 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1865 impl<T: ?Sized> AsRef<T> for Rc<T> {
1866     fn as_ref(&self) -> &T {
1867         &**self
1868     }
1869 }
1870
1871 #[stable(feature = "pin", since = "1.33.0")]
1872 impl<T: ?Sized> Unpin for Rc<T> { }
1873
1874 unsafe fn data_offset<T: ?Sized>(ptr: *const T) -> isize {
1875     // Align the unsized value to the end of the `RcBox`.
1876     // Because it is ?Sized, it will always be the last field in memory.
1877     data_offset_align(align_of_val(&*ptr))
1878 }
1879
1880 /// Computes the offset of the data field within `RcBox`.
1881 ///
1882 /// Unlike [`data_offset`], this doesn't need the pointer, but it works only on `T: Sized`.
1883 fn data_offset_sized<T>() -> isize {
1884     data_offset_align(align_of::<T>())
1885 }
1886
1887 #[inline]
1888 fn data_offset_align(align: usize) -> isize {
1889     let layout = Layout::new::<RcBox<()>>();
1890     (layout.size() + layout.padding_needed_for(align)) as isize
1891 }