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