]> git.proxmox.com Git - rustc.git/blob - library/alloc/src/rc.rs
New upstream version 1.68.2+dfsg1
[rustc.git] / library / alloc / src / 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 allocation in the heap. When the last [`Rc`] pointer to a
7 //! given allocation is destroyed, the value stored in that allocation (often
8 //! referred to as "inner value") is also dropped.
9 //!
10 //! Shared references in Rust disallow mutation by default, and [`Rc`]
11 //! is no exception: you cannot generally obtain a mutable reference to
12 //! something inside an [`Rc`]. If you need mutability, put a [`Cell`]
13 //! or [`RefCell`] inside the [`Rc`]; see [an example of mutability
14 //! inside an `Rc`][mutability].
15 //!
16 //! [`Rc`] uses non-atomic reference counting. This means that overhead is very
17 //! low, but an [`Rc`] cannot be sent between threads, and consequently [`Rc`]
18 //! does not implement [`Send`][send]. As a result, the Rust compiler
19 //! will check *at compile time* that you are not sending [`Rc`]s between
20 //! threads. If you need multi-threaded, atomic reference counting, use
21 //! [`sync::Arc`][arc].
22 //!
23 //! The [`downgrade`][downgrade] method can be used to create a non-owning
24 //! [`Weak`] pointer. A [`Weak`] pointer can be [`upgrade`][upgrade]d
25 //! to an [`Rc`], but this will return [`None`] if the value stored in the allocation has
26 //! already been dropped. In other words, `Weak` pointers do not keep the value
27 //! inside the allocation alive; however, they *do* keep the allocation
28 //! (the backing store for the inner value) alive.
29 //!
30 //! A cycle between [`Rc`] pointers will never be deallocated. For this reason,
31 //! [`Weak`] is used to break cycles. For example, a tree could have strong
32 //! [`Rc`] pointers from parent nodes to children, and [`Weak`] pointers from
33 //! children back to their parents.
34 //!
35 //! `Rc<T>` automatically dereferences to `T` (via the [`Deref`] trait),
36 //! so you can call `T`'s methods on a value of type [`Rc<T>`][`Rc`]. To avoid name
37 //! clashes with `T`'s methods, the methods of [`Rc<T>`][`Rc`] itself are associated
38 //! functions, called using [fully qualified syntax]:
39 //!
40 //! ```
41 //! use std::rc::Rc;
42 //!
43 //! let my_rc = Rc::new(());
44 //! let my_weak = Rc::downgrade(&my_rc);
45 //! ```
46 //!
47 //! `Rc<T>`'s implementations of traits like `Clone` may also be called using
48 //! fully qualified syntax. Some people prefer to use fully qualified syntax,
49 //! while others prefer using method-call syntax.
50 //!
51 //! ```
52 //! use std::rc::Rc;
53 //!
54 //! let rc = Rc::new(());
55 //! // Method-call syntax
56 //! let rc2 = rc.clone();
57 //! // Fully qualified syntax
58 //! let rc3 = Rc::clone(&rc);
59 //! ```
60 //!
61 //! [`Weak<T>`][`Weak`] does not auto-dereference to `T`, because the inner value may have
62 //! already been dropped.
63 //!
64 //! # Cloning references
65 //!
66 //! Creating a new reference to the same allocation as an existing reference counted pointer
67 //! is done using the `Clone` trait implemented for [`Rc<T>`][`Rc`] and [`Weak<T>`][`Weak`].
68 //!
69 //! ```
70 //! use std::rc::Rc;
71 //!
72 //! let foo = Rc::new(vec![1.0, 2.0, 3.0]);
73 //! // The two syntaxes below are equivalent.
74 //! let a = foo.clone();
75 //! let b = Rc::clone(&foo);
76 //! // a and b both point to the same memory location as foo.
77 //! ```
78 //!
79 //! The `Rc::clone(&from)` syntax is the most idiomatic because it conveys more explicitly
80 //! the meaning of the code. In the example above, this syntax makes it easier to see that
81 //! this code is creating a new reference rather than copying the whole content of foo.
82 //!
83 //! # Examples
84 //!
85 //! Consider a scenario where a set of `Gadget`s are owned by a given `Owner`.
86 //! We want to have our `Gadget`s point to their `Owner`. We can't do this with
87 //! unique ownership, because more than one gadget may belong to the same
88 //! `Owner`. [`Rc`] allows us to share an `Owner` between multiple `Gadget`s,
89 //! and have the `Owner` remain allocated as long as any `Gadget` points at it.
90 //!
91 //! ```
92 //! use std::rc::Rc;
93 //!
94 //! struct Owner {
95 //! name: String,
96 //! // ...other fields
97 //! }
98 //!
99 //! struct Gadget {
100 //! id: i32,
101 //! owner: Rc<Owner>,
102 //! // ...other fields
103 //! }
104 //!
105 //! fn main() {
106 //! // Create a reference-counted `Owner`.
107 //! let gadget_owner: Rc<Owner> = Rc::new(
108 //! Owner {
109 //! name: "Gadget Man".to_string(),
110 //! }
111 //! );
112 //!
113 //! // Create `Gadget`s belonging to `gadget_owner`. Cloning the `Rc<Owner>`
114 //! // gives us a new pointer to the same `Owner` allocation, incrementing
115 //! // the reference count in the process.
116 //! let gadget1 = Gadget {
117 //! id: 1,
118 //! owner: Rc::clone(&gadget_owner),
119 //! };
120 //! let gadget2 = Gadget {
121 //! id: 2,
122 //! owner: Rc::clone(&gadget_owner),
123 //! };
124 //!
125 //! // Dispose of our local variable `gadget_owner`.
126 //! drop(gadget_owner);
127 //!
128 //! // Despite dropping `gadget_owner`, we're still able to print out the name
129 //! // of the `Owner` of the `Gadget`s. This is because we've only dropped a
130 //! // single `Rc<Owner>`, not the `Owner` it points to. As long as there are
131 //! // other `Rc<Owner>` pointing at the same `Owner` allocation, it will remain
132 //! // live. The field projection `gadget1.owner.name` works because
133 //! // `Rc<Owner>` automatically dereferences to `Owner`.
134 //! println!("Gadget {} owned by {}", gadget1.id, gadget1.owner.name);
135 //! println!("Gadget {} owned by {}", gadget2.id, gadget2.owner.name);
136 //!
137 //! // At the end of the function, `gadget1` and `gadget2` are destroyed, and
138 //! // with them the last counted references to our `Owner`. Gadget Man now
139 //! // gets destroyed as well.
140 //! }
141 //! ```
142 //!
143 //! If our requirements change, and we also need to be able to traverse from
144 //! `Owner` to `Gadget`, we will run into problems. An [`Rc`] pointer from `Owner`
145 //! to `Gadget` introduces a cycle. This means that their
146 //! reference counts can never reach 0, and the allocation will never be destroyed:
147 //! a memory leak. In order to get around this, we can use [`Weak`]
148 //! pointers.
149 //!
150 //! Rust actually makes it somewhat difficult to produce this loop in the first
151 //! place. In order to end up with two values that point at each other, one of
152 //! them needs to be mutable. This is difficult because [`Rc`] enforces
153 //! memory safety by only giving out shared references to the value it wraps,
154 //! and these don't allow direct mutation. We need to wrap the part of the
155 //! value we wish to mutate in a [`RefCell`], which provides *interior
156 //! mutability*: a method to achieve mutability through a shared reference.
157 //! [`RefCell`] enforces Rust's borrowing rules at runtime.
158 //!
159 //! ```
160 //! use std::rc::Rc;
161 //! use std::rc::Weak;
162 //! use std::cell::RefCell;
163 //!
164 //! struct Owner {
165 //! name: String,
166 //! gadgets: RefCell<Vec<Weak<Gadget>>>,
167 //! // ...other fields
168 //! }
169 //!
170 //! struct Gadget {
171 //! id: i32,
172 //! owner: Rc<Owner>,
173 //! // ...other fields
174 //! }
175 //!
176 //! fn main() {
177 //! // Create a reference-counted `Owner`. Note that we've put the `Owner`'s
178 //! // vector of `Gadget`s inside a `RefCell` so that we can mutate it through
179 //! // a shared reference.
180 //! let gadget_owner: Rc<Owner> = Rc::new(
181 //! Owner {
182 //! name: "Gadget Man".to_string(),
183 //! gadgets: RefCell::new(vec![]),
184 //! }
185 //! );
186 //!
187 //! // Create `Gadget`s belonging to `gadget_owner`, as before.
188 //! let gadget1 = Rc::new(
189 //! Gadget {
190 //! id: 1,
191 //! owner: Rc::clone(&gadget_owner),
192 //! }
193 //! );
194 //! let gadget2 = Rc::new(
195 //! Gadget {
196 //! id: 2,
197 //! owner: Rc::clone(&gadget_owner),
198 //! }
199 //! );
200 //!
201 //! // Add the `Gadget`s to their `Owner`.
202 //! {
203 //! let mut gadgets = gadget_owner.gadgets.borrow_mut();
204 //! gadgets.push(Rc::downgrade(&gadget1));
205 //! gadgets.push(Rc::downgrade(&gadget2));
206 //!
207 //! // `RefCell` dynamic borrow ends here.
208 //! }
209 //!
210 //! // Iterate over our `Gadget`s, printing their details out.
211 //! for gadget_weak in gadget_owner.gadgets.borrow().iter() {
212 //!
213 //! // `gadget_weak` is a `Weak<Gadget>`. Since `Weak` pointers can't
214 //! // guarantee the allocation still exists, we need to call
215 //! // `upgrade`, which returns an `Option<Rc<Gadget>>`.
216 //! //
217 //! // In this case we know the allocation still exists, so we simply
218 //! // `unwrap` the `Option`. In a more complicated program, you might
219 //! // need graceful error handling for a `None` result.
220 //!
221 //! let gadget = gadget_weak.upgrade().unwrap();
222 //! println!("Gadget {} owned by {}", gadget.id, gadget.owner.name);
223 //! }
224 //!
225 //! // At the end of the function, `gadget_owner`, `gadget1`, and `gadget2`
226 //! // are destroyed. There are now no strong (`Rc`) pointers to the
227 //! // gadgets, so they are destroyed. This zeroes the reference count on
228 //! // Gadget Man, so he gets destroyed as well.
229 //! }
230 //! ```
231 //!
232 //! [clone]: Clone::clone
233 //! [`Cell`]: core::cell::Cell
234 //! [`RefCell`]: core::cell::RefCell
235 //! [send]: core::marker::Send
236 //! [arc]: crate::sync::Arc
237 //! [`Deref`]: core::ops::Deref
238 //! [downgrade]: Rc::downgrade
239 //! [upgrade]: Weak::upgrade
240 //! [mutability]: core::cell#introducing-mutability-inside-of-something-immutable
241 //! [fully qualified syntax]: https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#fully-qualified-syntax-for-disambiguation-calling-methods-with-the-same-name
242
243 #![stable(feature = "rust1", since = "1.0.0")]
244
245 #[cfg(not(test))]
246 use crate::boxed::Box;
247 #[cfg(test)]
248 use std::boxed::Box;
249
250 use core::any::Any;
251 use core::borrow;
252 use core::cell::Cell;
253 use core::cmp::Ordering;
254 use core::convert::{From, TryFrom};
255 use core::fmt;
256 use core::hash::{Hash, Hasher};
257 use core::intrinsics::abort;
258 #[cfg(not(no_global_oom_handling))]
259 use core::iter;
260 use core::marker::{self, PhantomData, Unpin, Unsize};
261 #[cfg(not(no_global_oom_handling))]
262 use core::mem::size_of_val;
263 use core::mem::{self, align_of_val_raw, forget};
264 use core::ops::{CoerceUnsized, Deref, DispatchFromDyn, Receiver};
265 use core::panic::{RefUnwindSafe, UnwindSafe};
266 #[cfg(not(no_global_oom_handling))]
267 use core::pin::Pin;
268 use core::ptr::{self, NonNull};
269 #[cfg(not(no_global_oom_handling))]
270 use core::slice::from_raw_parts_mut;
271
272 #[cfg(not(no_global_oom_handling))]
273 use crate::alloc::handle_alloc_error;
274 #[cfg(not(no_global_oom_handling))]
275 use crate::alloc::{box_free, WriteCloneIntoRaw};
276 use crate::alloc::{AllocError, Allocator, Global, Layout};
277 use crate::borrow::{Cow, ToOwned};
278 #[cfg(not(no_global_oom_handling))]
279 use crate::string::String;
280 #[cfg(not(no_global_oom_handling))]
281 use crate::vec::Vec;
282
283 #[cfg(test)]
284 mod tests;
285
286 // This is repr(C) to future-proof against possible field-reordering, which
287 // would interfere with otherwise safe [into|from]_raw() of transmutable
288 // inner types.
289 #[repr(C)]
290 struct RcBox<T: ?Sized> {
291 strong: Cell<usize>,
292 weak: Cell<usize>,
293 value: T,
294 }
295
296 /// Calculate layout for `RcBox<T>` using the inner value's layout
297 fn rcbox_layout_for_value_layout(layout: Layout) -> Layout {
298 // Calculate layout using the given value layout.
299 // Previously, layout was calculated on the expression
300 // `&*(ptr as *const RcBox<T>)`, but this created a misaligned
301 // reference (see #54908).
302 Layout::new::<RcBox<()>>().extend(layout).unwrap().0.pad_to_align()
303 }
304
305 /// A single-threaded reference-counting pointer. 'Rc' stands for 'Reference
306 /// Counted'.
307 ///
308 /// See the [module-level documentation](./index.html) for more details.
309 ///
310 /// The inherent methods of `Rc` are all associated functions, which means
311 /// that you have to call them as e.g., [`Rc::get_mut(&mut value)`][get_mut] instead of
312 /// `value.get_mut()`. This avoids conflicts with methods of the inner type `T`.
313 ///
314 /// [get_mut]: Rc::get_mut
315 #[cfg_attr(not(test), rustc_diagnostic_item = "Rc")]
316 #[stable(feature = "rust1", since = "1.0.0")]
317 #[rustc_insignificant_dtor]
318 pub struct Rc<T: ?Sized> {
319 ptr: NonNull<RcBox<T>>,
320 phantom: PhantomData<RcBox<T>>,
321 }
322
323 #[stable(feature = "rust1", since = "1.0.0")]
324 impl<T: ?Sized> !marker::Send for Rc<T> {}
325
326 // Note that this negative impl isn't strictly necessary for correctness,
327 // as `Rc` transitively contains a `Cell`, which is itself `!Sync`.
328 // However, given how important `Rc`'s `!Sync`-ness is,
329 // having an explicit negative impl is nice for documentation purposes
330 // and results in nicer error messages.
331 #[stable(feature = "rust1", since = "1.0.0")]
332 impl<T: ?Sized> !marker::Sync for Rc<T> {}
333
334 #[stable(feature = "catch_unwind", since = "1.9.0")]
335 impl<T: RefUnwindSafe + ?Sized> UnwindSafe for Rc<T> {}
336 #[stable(feature = "rc_ref_unwind_safe", since = "1.58.0")]
337 impl<T: RefUnwindSafe + ?Sized> RefUnwindSafe for Rc<T> {}
338
339 #[unstable(feature = "coerce_unsized", issue = "18598")]
340 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Rc<U>> for Rc<T> {}
341
342 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
343 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Rc<U>> for Rc<T> {}
344
345 impl<T: ?Sized> Rc<T> {
346 #[inline(always)]
347 fn inner(&self) -> &RcBox<T> {
348 // This unsafety is ok because while this Rc is alive we're guaranteed
349 // that the inner pointer is valid.
350 unsafe { self.ptr.as_ref() }
351 }
352
353 unsafe fn from_inner(ptr: NonNull<RcBox<T>>) -> Self {
354 Self { ptr, phantom: PhantomData }
355 }
356
357 unsafe fn from_ptr(ptr: *mut RcBox<T>) -> Self {
358 unsafe { Self::from_inner(NonNull::new_unchecked(ptr)) }
359 }
360 }
361
362 impl<T> Rc<T> {
363 /// Constructs a new `Rc<T>`.
364 ///
365 /// # Examples
366 ///
367 /// ```
368 /// use std::rc::Rc;
369 ///
370 /// let five = Rc::new(5);
371 /// ```
372 #[cfg(not(no_global_oom_handling))]
373 #[stable(feature = "rust1", since = "1.0.0")]
374 pub fn new(value: T) -> Rc<T> {
375 // There is an implicit weak pointer owned by all the strong
376 // pointers, which ensures that the weak destructor never frees
377 // the allocation while the strong destructor is running, even
378 // if the weak pointer is stored inside the strong one.
379 unsafe {
380 Self::from_inner(
381 Box::leak(Box::new(RcBox { strong: Cell::new(1), weak: Cell::new(1), value }))
382 .into(),
383 )
384 }
385 }
386
387 /// Constructs a new `Rc<T>` while giving you a `Weak<T>` to the allocation,
388 /// to allow you to construct a `T` which holds a weak pointer to itself.
389 ///
390 /// Generally, a structure circularly referencing itself, either directly or
391 /// indirectly, should not hold a strong reference to itself to prevent a memory leak.
392 /// Using this function, you get access to the weak pointer during the
393 /// initialization of `T`, before the `Rc<T>` is created, such that you can
394 /// clone and store it inside the `T`.
395 ///
396 /// `new_cyclic` first allocates the managed allocation for the `Rc<T>`,
397 /// then calls your closure, giving it a `Weak<T>` to this allocation,
398 /// and only afterwards completes the construction of the `Rc<T>` by placing
399 /// the `T` returned from your closure into the allocation.
400 ///
401 /// Since the new `Rc<T>` is not fully-constructed until `Rc<T>::new_cyclic`
402 /// returns, calling [`upgrade`] on the weak reference inside your closure will
403 /// fail and result in a `None` value.
404 ///
405 /// # Panics
406 ///
407 /// If `data_fn` panics, the panic is propagated to the caller, and the
408 /// temporary [`Weak<T>`] is dropped normally.
409 ///
410 /// # Examples
411 ///
412 /// ```
413 /// # #![allow(dead_code)]
414 /// use std::rc::{Rc, Weak};
415 ///
416 /// struct Gadget {
417 /// me: Weak<Gadget>,
418 /// }
419 ///
420 /// impl Gadget {
421 /// /// Construct a reference counted Gadget.
422 /// fn new() -> Rc<Self> {
423 /// // `me` is a `Weak<Gadget>` pointing at the new allocation of the
424 /// // `Rc` we're constructing.
425 /// Rc::new_cyclic(|me| {
426 /// // Create the actual struct here.
427 /// Gadget { me: me.clone() }
428 /// })
429 /// }
430 ///
431 /// /// Return a reference counted pointer to Self.
432 /// fn me(&self) -> Rc<Self> {
433 /// self.me.upgrade().unwrap()
434 /// }
435 /// }
436 /// ```
437 /// [`upgrade`]: Weak::upgrade
438 #[cfg(not(no_global_oom_handling))]
439 #[stable(feature = "arc_new_cyclic", since = "1.60.0")]
440 pub fn new_cyclic<F>(data_fn: F) -> Rc<T>
441 where
442 F: FnOnce(&Weak<T>) -> T,
443 {
444 // Construct the inner in the "uninitialized" state with a single
445 // weak reference.
446 let uninit_ptr: NonNull<_> = Box::leak(Box::new(RcBox {
447 strong: Cell::new(0),
448 weak: Cell::new(1),
449 value: mem::MaybeUninit::<T>::uninit(),
450 }))
451 .into();
452
453 let init_ptr: NonNull<RcBox<T>> = uninit_ptr.cast();
454
455 let weak = Weak { ptr: init_ptr };
456
457 // It's important we don't give up ownership of the weak pointer, or
458 // else the memory might be freed by the time `data_fn` returns. If
459 // we really wanted to pass ownership, we could create an additional
460 // weak pointer for ourselves, but this would result in additional
461 // updates to the weak reference count which might not be necessary
462 // otherwise.
463 let data = data_fn(&weak);
464
465 let strong = unsafe {
466 let inner = init_ptr.as_ptr();
467 ptr::write(ptr::addr_of_mut!((*inner).value), data);
468
469 let prev_value = (*inner).strong.get();
470 debug_assert_eq!(prev_value, 0, "No prior strong references should exist");
471 (*inner).strong.set(1);
472
473 Rc::from_inner(init_ptr)
474 };
475
476 // Strong references should collectively own a shared weak reference,
477 // so don't run the destructor for our old weak reference.
478 mem::forget(weak);
479 strong
480 }
481
482 /// Constructs a new `Rc` with uninitialized contents.
483 ///
484 /// # Examples
485 ///
486 /// ```
487 /// #![feature(new_uninit)]
488 /// #![feature(get_mut_unchecked)]
489 ///
490 /// use std::rc::Rc;
491 ///
492 /// let mut five = Rc::<u32>::new_uninit();
493 ///
494 /// // Deferred initialization:
495 /// Rc::get_mut(&mut five).unwrap().write(5);
496 ///
497 /// let five = unsafe { five.assume_init() };
498 ///
499 /// assert_eq!(*five, 5)
500 /// ```
501 #[cfg(not(no_global_oom_handling))]
502 #[unstable(feature = "new_uninit", issue = "63291")]
503 #[must_use]
504 pub fn new_uninit() -> Rc<mem::MaybeUninit<T>> {
505 unsafe {
506 Rc::from_ptr(Rc::allocate_for_layout(
507 Layout::new::<T>(),
508 |layout| Global.allocate(layout),
509 |mem| mem as *mut RcBox<mem::MaybeUninit<T>>,
510 ))
511 }
512 }
513
514 /// Constructs a new `Rc` with uninitialized contents, with the memory
515 /// being filled with `0` bytes.
516 ///
517 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and
518 /// incorrect usage of this method.
519 ///
520 /// # Examples
521 ///
522 /// ```
523 /// #![feature(new_uninit)]
524 ///
525 /// use std::rc::Rc;
526 ///
527 /// let zero = Rc::<u32>::new_zeroed();
528 /// let zero = unsafe { zero.assume_init() };
529 ///
530 /// assert_eq!(*zero, 0)
531 /// ```
532 ///
533 /// [zeroed]: mem::MaybeUninit::zeroed
534 #[cfg(not(no_global_oom_handling))]
535 #[unstable(feature = "new_uninit", issue = "63291")]
536 #[must_use]
537 pub fn new_zeroed() -> Rc<mem::MaybeUninit<T>> {
538 unsafe {
539 Rc::from_ptr(Rc::allocate_for_layout(
540 Layout::new::<T>(),
541 |layout| Global.allocate_zeroed(layout),
542 |mem| mem as *mut RcBox<mem::MaybeUninit<T>>,
543 ))
544 }
545 }
546
547 /// Constructs a new `Rc<T>`, returning an error if the allocation fails
548 ///
549 /// # Examples
550 ///
551 /// ```
552 /// #![feature(allocator_api)]
553 /// use std::rc::Rc;
554 ///
555 /// let five = Rc::try_new(5);
556 /// # Ok::<(), std::alloc::AllocError>(())
557 /// ```
558 #[unstable(feature = "allocator_api", issue = "32838")]
559 pub fn try_new(value: T) -> Result<Rc<T>, AllocError> {
560 // There is an implicit weak pointer owned by all the strong
561 // pointers, which ensures that the weak destructor never frees
562 // the allocation while the strong destructor is running, even
563 // if the weak pointer is stored inside the strong one.
564 unsafe {
565 Ok(Self::from_inner(
566 Box::leak(Box::try_new(RcBox { strong: Cell::new(1), weak: Cell::new(1), value })?)
567 .into(),
568 ))
569 }
570 }
571
572 /// Constructs a new `Rc` with uninitialized contents, returning an error if the allocation fails
573 ///
574 /// # Examples
575 ///
576 /// ```
577 /// #![feature(allocator_api, new_uninit)]
578 /// #![feature(get_mut_unchecked)]
579 ///
580 /// use std::rc::Rc;
581 ///
582 /// let mut five = Rc::<u32>::try_new_uninit()?;
583 ///
584 /// // Deferred initialization:
585 /// Rc::get_mut(&mut five).unwrap().write(5);
586 ///
587 /// let five = unsafe { five.assume_init() };
588 ///
589 /// assert_eq!(*five, 5);
590 /// # Ok::<(), std::alloc::AllocError>(())
591 /// ```
592 #[unstable(feature = "allocator_api", issue = "32838")]
593 // #[unstable(feature = "new_uninit", issue = "63291")]
594 pub fn try_new_uninit() -> Result<Rc<mem::MaybeUninit<T>>, AllocError> {
595 unsafe {
596 Ok(Rc::from_ptr(Rc::try_allocate_for_layout(
597 Layout::new::<T>(),
598 |layout| Global.allocate(layout),
599 |mem| mem as *mut RcBox<mem::MaybeUninit<T>>,
600 )?))
601 }
602 }
603
604 /// Constructs a new `Rc` with uninitialized contents, with the memory
605 /// being filled with `0` bytes, returning an error if the allocation fails
606 ///
607 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and
608 /// incorrect usage of this method.
609 ///
610 /// # Examples
611 ///
612 /// ```
613 /// #![feature(allocator_api, new_uninit)]
614 ///
615 /// use std::rc::Rc;
616 ///
617 /// let zero = Rc::<u32>::try_new_zeroed()?;
618 /// let zero = unsafe { zero.assume_init() };
619 ///
620 /// assert_eq!(*zero, 0);
621 /// # Ok::<(), std::alloc::AllocError>(())
622 /// ```
623 ///
624 /// [zeroed]: mem::MaybeUninit::zeroed
625 #[unstable(feature = "allocator_api", issue = "32838")]
626 //#[unstable(feature = "new_uninit", issue = "63291")]
627 pub fn try_new_zeroed() -> Result<Rc<mem::MaybeUninit<T>>, AllocError> {
628 unsafe {
629 Ok(Rc::from_ptr(Rc::try_allocate_for_layout(
630 Layout::new::<T>(),
631 |layout| Global.allocate_zeroed(layout),
632 |mem| mem as *mut RcBox<mem::MaybeUninit<T>>,
633 )?))
634 }
635 }
636 /// Constructs a new `Pin<Rc<T>>`. If `T` does not implement `Unpin`, then
637 /// `value` will be pinned in memory and unable to be moved.
638 #[cfg(not(no_global_oom_handling))]
639 #[stable(feature = "pin", since = "1.33.0")]
640 #[must_use]
641 pub fn pin(value: T) -> Pin<Rc<T>> {
642 unsafe { Pin::new_unchecked(Rc::new(value)) }
643 }
644
645 /// Returns the inner value, if the `Rc` has exactly one strong reference.
646 ///
647 /// Otherwise, an [`Err`] is returned with the same `Rc` that was
648 /// passed in.
649 ///
650 /// This will succeed even if there are outstanding weak references.
651 ///
652 /// # Examples
653 ///
654 /// ```
655 /// use std::rc::Rc;
656 ///
657 /// let x = Rc::new(3);
658 /// assert_eq!(Rc::try_unwrap(x), Ok(3));
659 ///
660 /// let x = Rc::new(4);
661 /// let _y = Rc::clone(&x);
662 /// assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4);
663 /// ```
664 #[inline]
665 #[stable(feature = "rc_unique", since = "1.4.0")]
666 pub fn try_unwrap(this: Self) -> Result<T, Self> {
667 if Rc::strong_count(&this) == 1 {
668 unsafe {
669 let val = ptr::read(&*this); // copy the contained object
670
671 // Indicate to Weaks that they can't be promoted by decrementing
672 // the strong count, and then remove the implicit "strong weak"
673 // pointer while also handling drop logic by just crafting a
674 // fake Weak.
675 this.inner().dec_strong();
676 let _weak = Weak { ptr: this.ptr };
677 forget(this);
678 Ok(val)
679 }
680 } else {
681 Err(this)
682 }
683 }
684 }
685
686 impl<T> Rc<[T]> {
687 /// Constructs a new reference-counted slice with uninitialized contents.
688 ///
689 /// # Examples
690 ///
691 /// ```
692 /// #![feature(new_uninit)]
693 /// #![feature(get_mut_unchecked)]
694 ///
695 /// use std::rc::Rc;
696 ///
697 /// let mut values = Rc::<[u32]>::new_uninit_slice(3);
698 ///
699 /// // Deferred initialization:
700 /// let data = Rc::get_mut(&mut values).unwrap();
701 /// data[0].write(1);
702 /// data[1].write(2);
703 /// data[2].write(3);
704 ///
705 /// let values = unsafe { values.assume_init() };
706 ///
707 /// assert_eq!(*values, [1, 2, 3])
708 /// ```
709 #[cfg(not(no_global_oom_handling))]
710 #[unstable(feature = "new_uninit", issue = "63291")]
711 #[must_use]
712 pub fn new_uninit_slice(len: usize) -> Rc<[mem::MaybeUninit<T>]> {
713 unsafe { Rc::from_ptr(Rc::allocate_for_slice(len)) }
714 }
715
716 /// Constructs a new reference-counted slice with uninitialized contents, with the memory being
717 /// filled with `0` bytes.
718 ///
719 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and
720 /// incorrect usage of this method.
721 ///
722 /// # Examples
723 ///
724 /// ```
725 /// #![feature(new_uninit)]
726 ///
727 /// use std::rc::Rc;
728 ///
729 /// let values = Rc::<[u32]>::new_zeroed_slice(3);
730 /// let values = unsafe { values.assume_init() };
731 ///
732 /// assert_eq!(*values, [0, 0, 0])
733 /// ```
734 ///
735 /// [zeroed]: mem::MaybeUninit::zeroed
736 #[cfg(not(no_global_oom_handling))]
737 #[unstable(feature = "new_uninit", issue = "63291")]
738 #[must_use]
739 pub fn new_zeroed_slice(len: usize) -> Rc<[mem::MaybeUninit<T>]> {
740 unsafe {
741 Rc::from_ptr(Rc::allocate_for_layout(
742 Layout::array::<T>(len).unwrap(),
743 |layout| Global.allocate_zeroed(layout),
744 |mem| {
745 ptr::slice_from_raw_parts_mut(mem as *mut T, len)
746 as *mut RcBox<[mem::MaybeUninit<T>]>
747 },
748 ))
749 }
750 }
751 }
752
753 impl<T> Rc<mem::MaybeUninit<T>> {
754 /// Converts to `Rc<T>`.
755 ///
756 /// # Safety
757 ///
758 /// As with [`MaybeUninit::assume_init`],
759 /// it is up to the caller to guarantee that the inner value
760 /// really is in an initialized state.
761 /// Calling this when the content is not yet fully initialized
762 /// causes immediate undefined behavior.
763 ///
764 /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
765 ///
766 /// # Examples
767 ///
768 /// ```
769 /// #![feature(new_uninit)]
770 /// #![feature(get_mut_unchecked)]
771 ///
772 /// use std::rc::Rc;
773 ///
774 /// let mut five = Rc::<u32>::new_uninit();
775 ///
776 /// // Deferred initialization:
777 /// Rc::get_mut(&mut five).unwrap().write(5);
778 ///
779 /// let five = unsafe { five.assume_init() };
780 ///
781 /// assert_eq!(*five, 5)
782 /// ```
783 #[unstable(feature = "new_uninit", issue = "63291")]
784 #[inline]
785 pub unsafe fn assume_init(self) -> Rc<T> {
786 unsafe { Rc::from_inner(mem::ManuallyDrop::new(self).ptr.cast()) }
787 }
788 }
789
790 impl<T> Rc<[mem::MaybeUninit<T>]> {
791 /// Converts to `Rc<[T]>`.
792 ///
793 /// # Safety
794 ///
795 /// As with [`MaybeUninit::assume_init`],
796 /// it is up to the caller to guarantee that the inner value
797 /// really is in an initialized state.
798 /// Calling this when the content is not yet fully initialized
799 /// causes immediate undefined behavior.
800 ///
801 /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
802 ///
803 /// # Examples
804 ///
805 /// ```
806 /// #![feature(new_uninit)]
807 /// #![feature(get_mut_unchecked)]
808 ///
809 /// use std::rc::Rc;
810 ///
811 /// let mut values = Rc::<[u32]>::new_uninit_slice(3);
812 ///
813 /// // Deferred initialization:
814 /// let data = Rc::get_mut(&mut values).unwrap();
815 /// data[0].write(1);
816 /// data[1].write(2);
817 /// data[2].write(3);
818 ///
819 /// let values = unsafe { values.assume_init() };
820 ///
821 /// assert_eq!(*values, [1, 2, 3])
822 /// ```
823 #[unstable(feature = "new_uninit", issue = "63291")]
824 #[inline]
825 pub unsafe fn assume_init(self) -> Rc<[T]> {
826 unsafe { Rc::from_ptr(mem::ManuallyDrop::new(self).ptr.as_ptr() as _) }
827 }
828 }
829
830 impl<T: ?Sized> Rc<T> {
831 /// Consumes the `Rc`, returning the wrapped pointer.
832 ///
833 /// To avoid a memory leak the pointer must be converted back to an `Rc` using
834 /// [`Rc::from_raw`].
835 ///
836 /// # Examples
837 ///
838 /// ```
839 /// use std::rc::Rc;
840 ///
841 /// let x = Rc::new("hello".to_owned());
842 /// let x_ptr = Rc::into_raw(x);
843 /// assert_eq!(unsafe { &*x_ptr }, "hello");
844 /// ```
845 #[stable(feature = "rc_raw", since = "1.17.0")]
846 pub fn into_raw(this: Self) -> *const T {
847 let ptr = Self::as_ptr(&this);
848 mem::forget(this);
849 ptr
850 }
851
852 /// Provides a raw pointer to the data.
853 ///
854 /// The counts are not affected in any way and the `Rc` is not consumed. The pointer is valid
855 /// for as long there are strong counts in the `Rc`.
856 ///
857 /// # Examples
858 ///
859 /// ```
860 /// use std::rc::Rc;
861 ///
862 /// let x = Rc::new("hello".to_owned());
863 /// let y = Rc::clone(&x);
864 /// let x_ptr = Rc::as_ptr(&x);
865 /// assert_eq!(x_ptr, Rc::as_ptr(&y));
866 /// assert_eq!(unsafe { &*x_ptr }, "hello");
867 /// ```
868 #[stable(feature = "weak_into_raw", since = "1.45.0")]
869 pub fn as_ptr(this: &Self) -> *const T {
870 let ptr: *mut RcBox<T> = NonNull::as_ptr(this.ptr);
871
872 // SAFETY: This cannot go through Deref::deref or Rc::inner because
873 // this is required to retain raw/mut provenance such that e.g. `get_mut` can
874 // write through the pointer after the Rc is recovered through `from_raw`.
875 unsafe { ptr::addr_of_mut!((*ptr).value) }
876 }
877
878 /// Constructs an `Rc<T>` from a raw pointer.
879 ///
880 /// The raw pointer must have been previously returned by a call to
881 /// [`Rc<U>::into_raw`][into_raw] where `U` must have the same size
882 /// and alignment as `T`. This is trivially true if `U` is `T`.
883 /// Note that if `U` is not `T` but has the same size and alignment, this is
884 /// basically like transmuting references of different types. See
885 /// [`mem::transmute`] for more information on what
886 /// restrictions apply in this case.
887 ///
888 /// The user of `from_raw` has to make sure a specific value of `T` is only
889 /// dropped once.
890 ///
891 /// This function is unsafe because improper use may lead to memory unsafety,
892 /// even if the returned `Rc<T>` is never accessed.
893 ///
894 /// [into_raw]: Rc::into_raw
895 ///
896 /// # Examples
897 ///
898 /// ```
899 /// use std::rc::Rc;
900 ///
901 /// let x = Rc::new("hello".to_owned());
902 /// let x_ptr = Rc::into_raw(x);
903 ///
904 /// unsafe {
905 /// // Convert back to an `Rc` to prevent leak.
906 /// let x = Rc::from_raw(x_ptr);
907 /// assert_eq!(&*x, "hello");
908 ///
909 /// // Further calls to `Rc::from_raw(x_ptr)` would be memory-unsafe.
910 /// }
911 ///
912 /// // The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling!
913 /// ```
914 #[stable(feature = "rc_raw", since = "1.17.0")]
915 pub unsafe fn from_raw(ptr: *const T) -> Self {
916 let offset = unsafe { data_offset(ptr) };
917
918 // Reverse the offset to find the original RcBox.
919 let rc_ptr = unsafe { ptr.byte_sub(offset) as *mut RcBox<T> };
920
921 unsafe { Self::from_ptr(rc_ptr) }
922 }
923
924 /// Creates a new [`Weak`] pointer to this allocation.
925 ///
926 /// # Examples
927 ///
928 /// ```
929 /// use std::rc::Rc;
930 ///
931 /// let five = Rc::new(5);
932 ///
933 /// let weak_five = Rc::downgrade(&five);
934 /// ```
935 #[must_use = "this returns a new `Weak` pointer, \
936 without modifying the original `Rc`"]
937 #[stable(feature = "rc_weak", since = "1.4.0")]
938 pub fn downgrade(this: &Self) -> Weak<T> {
939 this.inner().inc_weak();
940 // Make sure we do not create a dangling Weak
941 debug_assert!(!is_dangling(this.ptr.as_ptr()));
942 Weak { ptr: this.ptr }
943 }
944
945 /// Gets the number of [`Weak`] pointers to this allocation.
946 ///
947 /// # Examples
948 ///
949 /// ```
950 /// use std::rc::Rc;
951 ///
952 /// let five = Rc::new(5);
953 /// let _weak_five = Rc::downgrade(&five);
954 ///
955 /// assert_eq!(1, Rc::weak_count(&five));
956 /// ```
957 #[inline]
958 #[stable(feature = "rc_counts", since = "1.15.0")]
959 pub fn weak_count(this: &Self) -> usize {
960 this.inner().weak() - 1
961 }
962
963 /// Gets the number of strong (`Rc`) pointers to this allocation.
964 ///
965 /// # Examples
966 ///
967 /// ```
968 /// use std::rc::Rc;
969 ///
970 /// let five = Rc::new(5);
971 /// let _also_five = Rc::clone(&five);
972 ///
973 /// assert_eq!(2, Rc::strong_count(&five));
974 /// ```
975 #[inline]
976 #[stable(feature = "rc_counts", since = "1.15.0")]
977 pub fn strong_count(this: &Self) -> usize {
978 this.inner().strong()
979 }
980
981 /// Increments the strong reference count on the `Rc<T>` associated with the
982 /// provided pointer by one.
983 ///
984 /// # Safety
985 ///
986 /// The pointer must have been obtained through `Rc::into_raw`, and the
987 /// associated `Rc` instance must be valid (i.e. the strong count must be at
988 /// least 1) for the duration of this method.
989 ///
990 /// # Examples
991 ///
992 /// ```
993 /// use std::rc::Rc;
994 ///
995 /// let five = Rc::new(5);
996 ///
997 /// unsafe {
998 /// let ptr = Rc::into_raw(five);
999 /// Rc::increment_strong_count(ptr);
1000 ///
1001 /// let five = Rc::from_raw(ptr);
1002 /// assert_eq!(2, Rc::strong_count(&five));
1003 /// }
1004 /// ```
1005 #[inline]
1006 #[stable(feature = "rc_mutate_strong_count", since = "1.53.0")]
1007 pub unsafe fn increment_strong_count(ptr: *const T) {
1008 // Retain Rc, but don't touch refcount by wrapping in ManuallyDrop
1009 let rc = unsafe { mem::ManuallyDrop::new(Rc::<T>::from_raw(ptr)) };
1010 // Now increase refcount, but don't drop new refcount either
1011 let _rc_clone: mem::ManuallyDrop<_> = rc.clone();
1012 }
1013
1014 /// Decrements the strong reference count on the `Rc<T>` associated with the
1015 /// provided pointer by one.
1016 ///
1017 /// # Safety
1018 ///
1019 /// The pointer must have been obtained through `Rc::into_raw`, and the
1020 /// associated `Rc` instance must be valid (i.e. the strong count must be at
1021 /// least 1) when invoking this method. This method can be used to release
1022 /// the final `Rc` and backing storage, but **should not** be called after
1023 /// the final `Rc` has been released.
1024 ///
1025 /// # Examples
1026 ///
1027 /// ```
1028 /// use std::rc::Rc;
1029 ///
1030 /// let five = Rc::new(5);
1031 ///
1032 /// unsafe {
1033 /// let ptr = Rc::into_raw(five);
1034 /// Rc::increment_strong_count(ptr);
1035 ///
1036 /// let five = Rc::from_raw(ptr);
1037 /// assert_eq!(2, Rc::strong_count(&five));
1038 /// Rc::decrement_strong_count(ptr);
1039 /// assert_eq!(1, Rc::strong_count(&five));
1040 /// }
1041 /// ```
1042 #[inline]
1043 #[stable(feature = "rc_mutate_strong_count", since = "1.53.0")]
1044 pub unsafe fn decrement_strong_count(ptr: *const T) {
1045 unsafe { mem::drop(Rc::from_raw(ptr)) };
1046 }
1047
1048 /// Returns `true` if there are no other `Rc` or [`Weak`] pointers to
1049 /// this allocation.
1050 #[inline]
1051 fn is_unique(this: &Self) -> bool {
1052 Rc::weak_count(this) == 0 && Rc::strong_count(this) == 1
1053 }
1054
1055 /// Returns a mutable reference into the given `Rc`, if there are
1056 /// no other `Rc` or [`Weak`] pointers to the same allocation.
1057 ///
1058 /// Returns [`None`] otherwise, because it is not safe to
1059 /// mutate a shared value.
1060 ///
1061 /// See also [`make_mut`][make_mut], which will [`clone`][clone]
1062 /// the inner value when there are other `Rc` pointers.
1063 ///
1064 /// [make_mut]: Rc::make_mut
1065 /// [clone]: Clone::clone
1066 ///
1067 /// # Examples
1068 ///
1069 /// ```
1070 /// use std::rc::Rc;
1071 ///
1072 /// let mut x = Rc::new(3);
1073 /// *Rc::get_mut(&mut x).unwrap() = 4;
1074 /// assert_eq!(*x, 4);
1075 ///
1076 /// let _y = Rc::clone(&x);
1077 /// assert!(Rc::get_mut(&mut x).is_none());
1078 /// ```
1079 #[inline]
1080 #[stable(feature = "rc_unique", since = "1.4.0")]
1081 pub fn get_mut(this: &mut Self) -> Option<&mut T> {
1082 if Rc::is_unique(this) { unsafe { Some(Rc::get_mut_unchecked(this)) } } else { None }
1083 }
1084
1085 /// Returns a mutable reference into the given `Rc`,
1086 /// without any check.
1087 ///
1088 /// See also [`get_mut`], which is safe and does appropriate checks.
1089 ///
1090 /// [`get_mut`]: Rc::get_mut
1091 ///
1092 /// # Safety
1093 ///
1094 /// If any other `Rc` or [`Weak`] pointers to the same allocation exist, then
1095 /// they must be must not be dereferenced or have active borrows for the duration
1096 /// of the returned borrow, and their inner type must be exactly the same as the
1097 /// inner type of this Rc (including lifetimes). This is trivially the case if no
1098 /// such pointers exist, for example immediately after `Rc::new`.
1099 ///
1100 /// # Examples
1101 ///
1102 /// ```
1103 /// #![feature(get_mut_unchecked)]
1104 ///
1105 /// use std::rc::Rc;
1106 ///
1107 /// let mut x = Rc::new(String::new());
1108 /// unsafe {
1109 /// Rc::get_mut_unchecked(&mut x).push_str("foo")
1110 /// }
1111 /// assert_eq!(*x, "foo");
1112 /// ```
1113 /// Other `Rc` pointers to the same allocation must be to the same type.
1114 /// ```no_run
1115 /// #![feature(get_mut_unchecked)]
1116 ///
1117 /// use std::rc::Rc;
1118 ///
1119 /// let x: Rc<str> = Rc::from("Hello, world!");
1120 /// let mut y: Rc<[u8]> = x.clone().into();
1121 /// unsafe {
1122 /// // this is Undefined Behavior, because x's inner type is str, not [u8]
1123 /// Rc::get_mut_unchecked(&mut y).fill(0xff); // 0xff is invalid in UTF-8
1124 /// }
1125 /// println!("{}", &*x); // Invalid UTF-8 in a str
1126 /// ```
1127 /// Other `Rc` pointers to the same allocation must be to the exact same type, including lifetimes.
1128 /// ```no_run
1129 /// #![feature(get_mut_unchecked)]
1130 ///
1131 /// use std::rc::Rc;
1132 ///
1133 /// let x: Rc<&str> = Rc::new("Hello, world!");
1134 /// {
1135 /// let s = String::from("Oh, no!");
1136 /// let mut y: Rc<&str> = x.clone().into();
1137 /// unsafe {
1138 /// // this is Undefined Behavior, because x's inner type
1139 /// // is &'long str, not &'short str
1140 /// *Rc::get_mut_unchecked(&mut y) = &s;
1141 /// }
1142 /// }
1143 /// println!("{}", &*x); // Use-after-free
1144 /// ```
1145 #[inline]
1146 #[unstable(feature = "get_mut_unchecked", issue = "63292")]
1147 pub unsafe fn get_mut_unchecked(this: &mut Self) -> &mut T {
1148 // We are careful to *not* create a reference covering the "count" fields, as
1149 // this would conflict with accesses to the reference counts (e.g. by `Weak`).
1150 unsafe { &mut (*this.ptr.as_ptr()).value }
1151 }
1152
1153 #[inline]
1154 #[stable(feature = "ptr_eq", since = "1.17.0")]
1155 /// Returns `true` if the two `Rc`s point to the same allocation in a vein similar to
1156 /// [`ptr::eq`]. See [that function][`ptr::eq`] for caveats when comparing `dyn Trait` pointers.
1157 ///
1158 /// # Examples
1159 ///
1160 /// ```
1161 /// use std::rc::Rc;
1162 ///
1163 /// let five = Rc::new(5);
1164 /// let same_five = Rc::clone(&five);
1165 /// let other_five = Rc::new(5);
1166 ///
1167 /// assert!(Rc::ptr_eq(&five, &same_five));
1168 /// assert!(!Rc::ptr_eq(&five, &other_five));
1169 /// ```
1170 pub fn ptr_eq(this: &Self, other: &Self) -> bool {
1171 this.ptr.as_ptr() == other.ptr.as_ptr()
1172 }
1173 }
1174
1175 impl<T: Clone> Rc<T> {
1176 /// Makes a mutable reference into the given `Rc`.
1177 ///
1178 /// If there are other `Rc` pointers to the same allocation, then `make_mut` will
1179 /// [`clone`] the inner value to a new allocation to ensure unique ownership. This is also
1180 /// referred to as clone-on-write.
1181 ///
1182 /// However, if there are no other `Rc` pointers to this allocation, but some [`Weak`]
1183 /// pointers, then the [`Weak`] pointers will be disassociated and the inner value will not
1184 /// be cloned.
1185 ///
1186 /// See also [`get_mut`], which will fail rather than cloning the inner value
1187 /// or disassociating [`Weak`] pointers.
1188 ///
1189 /// [`clone`]: Clone::clone
1190 /// [`get_mut`]: Rc::get_mut
1191 ///
1192 /// # Examples
1193 ///
1194 /// ```
1195 /// use std::rc::Rc;
1196 ///
1197 /// let mut data = Rc::new(5);
1198 ///
1199 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
1200 /// let mut other_data = Rc::clone(&data); // Won't clone inner data
1201 /// *Rc::make_mut(&mut data) += 1; // Clones inner data
1202 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
1203 /// *Rc::make_mut(&mut other_data) *= 2; // Won't clone anything
1204 ///
1205 /// // Now `data` and `other_data` point to different allocations.
1206 /// assert_eq!(*data, 8);
1207 /// assert_eq!(*other_data, 12);
1208 /// ```
1209 ///
1210 /// [`Weak`] pointers will be disassociated:
1211 ///
1212 /// ```
1213 /// use std::rc::Rc;
1214 ///
1215 /// let mut data = Rc::new(75);
1216 /// let weak = Rc::downgrade(&data);
1217 ///
1218 /// assert!(75 == *data);
1219 /// assert!(75 == *weak.upgrade().unwrap());
1220 ///
1221 /// *Rc::make_mut(&mut data) += 1;
1222 ///
1223 /// assert!(76 == *data);
1224 /// assert!(weak.upgrade().is_none());
1225 /// ```
1226 #[cfg(not(no_global_oom_handling))]
1227 #[inline]
1228 #[stable(feature = "rc_unique", since = "1.4.0")]
1229 pub fn make_mut(this: &mut Self) -> &mut T {
1230 if Rc::strong_count(this) != 1 {
1231 // Gotta clone the data, there are other Rcs.
1232 // Pre-allocate memory to allow writing the cloned value directly.
1233 let mut rc = Self::new_uninit();
1234 unsafe {
1235 let data = Rc::get_mut_unchecked(&mut rc);
1236 (**this).write_clone_into_raw(data.as_mut_ptr());
1237 *this = rc.assume_init();
1238 }
1239 } else if Rc::weak_count(this) != 0 {
1240 // Can just steal the data, all that's left is Weaks
1241 let mut rc = Self::new_uninit();
1242 unsafe {
1243 let data = Rc::get_mut_unchecked(&mut rc);
1244 data.as_mut_ptr().copy_from_nonoverlapping(&**this, 1);
1245
1246 this.inner().dec_strong();
1247 // Remove implicit strong-weak ref (no need to craft a fake
1248 // Weak here -- we know other Weaks can clean up for us)
1249 this.inner().dec_weak();
1250 ptr::write(this, rc.assume_init());
1251 }
1252 }
1253 // This unsafety is ok because we're guaranteed that the pointer
1254 // returned is the *only* pointer that will ever be returned to T. Our
1255 // reference count is guaranteed to be 1 at this point, and we required
1256 // the `Rc<T>` itself to be `mut`, so we're returning the only possible
1257 // reference to the allocation.
1258 unsafe { &mut this.ptr.as_mut().value }
1259 }
1260
1261 /// If we have the only reference to `T` then unwrap it. Otherwise, clone `T` and return the
1262 /// clone.
1263 ///
1264 /// Assuming `rc_t` is of type `Rc<T>`, this function is functionally equivalent to
1265 /// `(*rc_t).clone()`, but will avoid cloning the inner value where possible.
1266 ///
1267 /// # Examples
1268 ///
1269 /// ```
1270 /// #![feature(arc_unwrap_or_clone)]
1271 /// # use std::{ptr, rc::Rc};
1272 /// let inner = String::from("test");
1273 /// let ptr = inner.as_ptr();
1274 ///
1275 /// let rc = Rc::new(inner);
1276 /// let inner = Rc::unwrap_or_clone(rc);
1277 /// // The inner value was not cloned
1278 /// assert!(ptr::eq(ptr, inner.as_ptr()));
1279 ///
1280 /// let rc = Rc::new(inner);
1281 /// let rc2 = rc.clone();
1282 /// let inner = Rc::unwrap_or_clone(rc);
1283 /// // Because there were 2 references, we had to clone the inner value.
1284 /// assert!(!ptr::eq(ptr, inner.as_ptr()));
1285 /// // `rc2` is the last reference, so when we unwrap it we get back
1286 /// // the original `String`.
1287 /// let inner = Rc::unwrap_or_clone(rc2);
1288 /// assert!(ptr::eq(ptr, inner.as_ptr()));
1289 /// ```
1290 #[inline]
1291 #[unstable(feature = "arc_unwrap_or_clone", issue = "93610")]
1292 pub fn unwrap_or_clone(this: Self) -> T {
1293 Rc::try_unwrap(this).unwrap_or_else(|rc| (*rc).clone())
1294 }
1295 }
1296
1297 impl Rc<dyn Any> {
1298 /// Attempt to downcast the `Rc<dyn Any>` to a concrete type.
1299 ///
1300 /// # Examples
1301 ///
1302 /// ```
1303 /// use std::any::Any;
1304 /// use std::rc::Rc;
1305 ///
1306 /// fn print_if_string(value: Rc<dyn Any>) {
1307 /// if let Ok(string) = value.downcast::<String>() {
1308 /// println!("String ({}): {}", string.len(), string);
1309 /// }
1310 /// }
1311 ///
1312 /// let my_string = "Hello World".to_string();
1313 /// print_if_string(Rc::new(my_string));
1314 /// print_if_string(Rc::new(0i8));
1315 /// ```
1316 #[inline]
1317 #[stable(feature = "rc_downcast", since = "1.29.0")]
1318 pub fn downcast<T: Any>(self) -> Result<Rc<T>, Rc<dyn Any>> {
1319 if (*self).is::<T>() {
1320 unsafe {
1321 let ptr = self.ptr.cast::<RcBox<T>>();
1322 forget(self);
1323 Ok(Rc::from_inner(ptr))
1324 }
1325 } else {
1326 Err(self)
1327 }
1328 }
1329
1330 /// Downcasts the `Rc<dyn Any>` to a concrete type.
1331 ///
1332 /// For a safe alternative see [`downcast`].
1333 ///
1334 /// # Examples
1335 ///
1336 /// ```
1337 /// #![feature(downcast_unchecked)]
1338 ///
1339 /// use std::any::Any;
1340 /// use std::rc::Rc;
1341 ///
1342 /// let x: Rc<dyn Any> = Rc::new(1_usize);
1343 ///
1344 /// unsafe {
1345 /// assert_eq!(*x.downcast_unchecked::<usize>(), 1);
1346 /// }
1347 /// ```
1348 ///
1349 /// # Safety
1350 ///
1351 /// The contained value must be of type `T`. Calling this method
1352 /// with the incorrect type is *undefined behavior*.
1353 ///
1354 ///
1355 /// [`downcast`]: Self::downcast
1356 #[inline]
1357 #[unstable(feature = "downcast_unchecked", issue = "90850")]
1358 pub unsafe fn downcast_unchecked<T: Any>(self) -> Rc<T> {
1359 unsafe {
1360 let ptr = self.ptr.cast::<RcBox<T>>();
1361 mem::forget(self);
1362 Rc::from_inner(ptr)
1363 }
1364 }
1365 }
1366
1367 impl<T: ?Sized> Rc<T> {
1368 /// Allocates an `RcBox<T>` with sufficient space for
1369 /// a possibly-unsized inner value where the value has the layout provided.
1370 ///
1371 /// The function `mem_to_rcbox` is called with the data pointer
1372 /// and must return back a (potentially fat)-pointer for the `RcBox<T>`.
1373 #[cfg(not(no_global_oom_handling))]
1374 unsafe fn allocate_for_layout(
1375 value_layout: Layout,
1376 allocate: impl FnOnce(Layout) -> Result<NonNull<[u8]>, AllocError>,
1377 mem_to_rcbox: impl FnOnce(*mut u8) -> *mut RcBox<T>,
1378 ) -> *mut RcBox<T> {
1379 let layout = rcbox_layout_for_value_layout(value_layout);
1380 unsafe {
1381 Rc::try_allocate_for_layout(value_layout, allocate, mem_to_rcbox)
1382 .unwrap_or_else(|_| handle_alloc_error(layout))
1383 }
1384 }
1385
1386 /// Allocates an `RcBox<T>` with sufficient space for
1387 /// a possibly-unsized inner value where the value has the layout provided,
1388 /// returning an error if allocation fails.
1389 ///
1390 /// The function `mem_to_rcbox` is called with the data pointer
1391 /// and must return back a (potentially fat)-pointer for the `RcBox<T>`.
1392 #[inline]
1393 unsafe fn try_allocate_for_layout(
1394 value_layout: Layout,
1395 allocate: impl FnOnce(Layout) -> Result<NonNull<[u8]>, AllocError>,
1396 mem_to_rcbox: impl FnOnce(*mut u8) -> *mut RcBox<T>,
1397 ) -> Result<*mut RcBox<T>, AllocError> {
1398 let layout = rcbox_layout_for_value_layout(value_layout);
1399
1400 // Allocate for the layout.
1401 let ptr = allocate(layout)?;
1402
1403 // Initialize the RcBox
1404 let inner = mem_to_rcbox(ptr.as_non_null_ptr().as_ptr());
1405 unsafe {
1406 debug_assert_eq!(Layout::for_value(&*inner), layout);
1407
1408 ptr::write(&mut (*inner).strong, Cell::new(1));
1409 ptr::write(&mut (*inner).weak, Cell::new(1));
1410 }
1411
1412 Ok(inner)
1413 }
1414
1415 /// Allocates an `RcBox<T>` with sufficient space for an unsized inner value
1416 #[cfg(not(no_global_oom_handling))]
1417 unsafe fn allocate_for_ptr(ptr: *const T) -> *mut RcBox<T> {
1418 // Allocate for the `RcBox<T>` using the given value.
1419 unsafe {
1420 Self::allocate_for_layout(
1421 Layout::for_value(&*ptr),
1422 |layout| Global.allocate(layout),
1423 |mem| mem.with_metadata_of(ptr as *const RcBox<T>),
1424 )
1425 }
1426 }
1427
1428 #[cfg(not(no_global_oom_handling))]
1429 fn from_box(v: Box<T>) -> Rc<T> {
1430 unsafe {
1431 let (box_unique, alloc) = Box::into_unique(v);
1432 let bptr = box_unique.as_ptr();
1433
1434 let value_size = size_of_val(&*bptr);
1435 let ptr = Self::allocate_for_ptr(bptr);
1436
1437 // Copy value as bytes
1438 ptr::copy_nonoverlapping(
1439 bptr as *const T as *const u8,
1440 &mut (*ptr).value as *mut _ as *mut u8,
1441 value_size,
1442 );
1443
1444 // Free the allocation without dropping its contents
1445 box_free(box_unique, alloc);
1446
1447 Self::from_ptr(ptr)
1448 }
1449 }
1450 }
1451
1452 impl<T> Rc<[T]> {
1453 /// Allocates an `RcBox<[T]>` with the given length.
1454 #[cfg(not(no_global_oom_handling))]
1455 unsafe fn allocate_for_slice(len: usize) -> *mut RcBox<[T]> {
1456 unsafe {
1457 Self::allocate_for_layout(
1458 Layout::array::<T>(len).unwrap(),
1459 |layout| Global.allocate(layout),
1460 |mem| ptr::slice_from_raw_parts_mut(mem as *mut T, len) as *mut RcBox<[T]>,
1461 )
1462 }
1463 }
1464
1465 /// Copy elements from slice into newly allocated `Rc<[T]>`
1466 ///
1467 /// Unsafe because the caller must either take ownership or bind `T: Copy`
1468 #[cfg(not(no_global_oom_handling))]
1469 unsafe fn copy_from_slice(v: &[T]) -> Rc<[T]> {
1470 unsafe {
1471 let ptr = Self::allocate_for_slice(v.len());
1472 ptr::copy_nonoverlapping(v.as_ptr(), &mut (*ptr).value as *mut [T] as *mut T, v.len());
1473 Self::from_ptr(ptr)
1474 }
1475 }
1476
1477 /// Constructs an `Rc<[T]>` from an iterator known to be of a certain size.
1478 ///
1479 /// Behavior is undefined should the size be wrong.
1480 #[cfg(not(no_global_oom_handling))]
1481 unsafe fn from_iter_exact(iter: impl iter::Iterator<Item = T>, len: usize) -> Rc<[T]> {
1482 // Panic guard while cloning T elements.
1483 // In the event of a panic, elements that have been written
1484 // into the new RcBox will be dropped, then the memory freed.
1485 struct Guard<T> {
1486 mem: NonNull<u8>,
1487 elems: *mut T,
1488 layout: Layout,
1489 n_elems: usize,
1490 }
1491
1492 impl<T> Drop for Guard<T> {
1493 fn drop(&mut self) {
1494 unsafe {
1495 let slice = from_raw_parts_mut(self.elems, self.n_elems);
1496 ptr::drop_in_place(slice);
1497
1498 Global.deallocate(self.mem, self.layout);
1499 }
1500 }
1501 }
1502
1503 unsafe {
1504 let ptr = Self::allocate_for_slice(len);
1505
1506 let mem = ptr as *mut _ as *mut u8;
1507 let layout = Layout::for_value(&*ptr);
1508
1509 // Pointer to first element
1510 let elems = &mut (*ptr).value as *mut [T] as *mut T;
1511
1512 let mut guard = Guard { mem: NonNull::new_unchecked(mem), elems, layout, n_elems: 0 };
1513
1514 for (i, item) in iter.enumerate() {
1515 ptr::write(elems.add(i), item);
1516 guard.n_elems += 1;
1517 }
1518
1519 // All clear. Forget the guard so it doesn't free the new RcBox.
1520 forget(guard);
1521
1522 Self::from_ptr(ptr)
1523 }
1524 }
1525 }
1526
1527 /// Specialization trait used for `From<&[T]>`.
1528 trait RcFromSlice<T> {
1529 fn from_slice(slice: &[T]) -> Self;
1530 }
1531
1532 #[cfg(not(no_global_oom_handling))]
1533 impl<T: Clone> RcFromSlice<T> for Rc<[T]> {
1534 #[inline]
1535 default fn from_slice(v: &[T]) -> Self {
1536 unsafe { Self::from_iter_exact(v.iter().cloned(), v.len()) }
1537 }
1538 }
1539
1540 #[cfg(not(no_global_oom_handling))]
1541 impl<T: Copy> RcFromSlice<T> for Rc<[T]> {
1542 #[inline]
1543 fn from_slice(v: &[T]) -> Self {
1544 unsafe { Rc::copy_from_slice(v) }
1545 }
1546 }
1547
1548 #[stable(feature = "rust1", since = "1.0.0")]
1549 impl<T: ?Sized> Deref for Rc<T> {
1550 type Target = T;
1551
1552 #[inline(always)]
1553 fn deref(&self) -> &T {
1554 &self.inner().value
1555 }
1556 }
1557
1558 #[unstable(feature = "receiver_trait", issue = "none")]
1559 impl<T: ?Sized> Receiver for Rc<T> {}
1560
1561 #[stable(feature = "rust1", since = "1.0.0")]
1562 unsafe impl<#[may_dangle] T: ?Sized> Drop for Rc<T> {
1563 /// Drops the `Rc`.
1564 ///
1565 /// This will decrement the strong reference count. If the strong reference
1566 /// count reaches zero then the only other references (if any) are
1567 /// [`Weak`], so we `drop` the inner value.
1568 ///
1569 /// # Examples
1570 ///
1571 /// ```
1572 /// use std::rc::Rc;
1573 ///
1574 /// struct Foo;
1575 ///
1576 /// impl Drop for Foo {
1577 /// fn drop(&mut self) {
1578 /// println!("dropped!");
1579 /// }
1580 /// }
1581 ///
1582 /// let foo = Rc::new(Foo);
1583 /// let foo2 = Rc::clone(&foo);
1584 ///
1585 /// drop(foo); // Doesn't print anything
1586 /// drop(foo2); // Prints "dropped!"
1587 /// ```
1588 fn drop(&mut self) {
1589 unsafe {
1590 self.inner().dec_strong();
1591 if self.inner().strong() == 0 {
1592 // destroy the contained object
1593 ptr::drop_in_place(Self::get_mut_unchecked(self));
1594
1595 // remove the implicit "strong weak" pointer now that we've
1596 // destroyed the contents.
1597 self.inner().dec_weak();
1598
1599 if self.inner().weak() == 0 {
1600 Global.deallocate(self.ptr.cast(), Layout::for_value(self.ptr.as_ref()));
1601 }
1602 }
1603 }
1604 }
1605 }
1606
1607 #[stable(feature = "rust1", since = "1.0.0")]
1608 impl<T: ?Sized> Clone for Rc<T> {
1609 /// Makes a clone of the `Rc` pointer.
1610 ///
1611 /// This creates another pointer to the same allocation, increasing the
1612 /// strong reference count.
1613 ///
1614 /// # Examples
1615 ///
1616 /// ```
1617 /// use std::rc::Rc;
1618 ///
1619 /// let five = Rc::new(5);
1620 ///
1621 /// let _ = Rc::clone(&five);
1622 /// ```
1623 #[inline]
1624 fn clone(&self) -> Rc<T> {
1625 unsafe {
1626 self.inner().inc_strong();
1627 Self::from_inner(self.ptr)
1628 }
1629 }
1630 }
1631
1632 #[cfg(not(no_global_oom_handling))]
1633 #[stable(feature = "rust1", since = "1.0.0")]
1634 impl<T: Default> Default for Rc<T> {
1635 /// Creates a new `Rc<T>`, with the `Default` value for `T`.
1636 ///
1637 /// # Examples
1638 ///
1639 /// ```
1640 /// use std::rc::Rc;
1641 ///
1642 /// let x: Rc<i32> = Default::default();
1643 /// assert_eq!(*x, 0);
1644 /// ```
1645 #[inline]
1646 fn default() -> Rc<T> {
1647 Rc::new(Default::default())
1648 }
1649 }
1650
1651 #[stable(feature = "rust1", since = "1.0.0")]
1652 trait RcEqIdent<T: ?Sized + PartialEq> {
1653 fn eq(&self, other: &Rc<T>) -> bool;
1654 fn ne(&self, other: &Rc<T>) -> bool;
1655 }
1656
1657 #[stable(feature = "rust1", since = "1.0.0")]
1658 impl<T: ?Sized + PartialEq> RcEqIdent<T> for Rc<T> {
1659 #[inline]
1660 default fn eq(&self, other: &Rc<T>) -> bool {
1661 **self == **other
1662 }
1663
1664 #[inline]
1665 default fn ne(&self, other: &Rc<T>) -> bool {
1666 **self != **other
1667 }
1668 }
1669
1670 // Hack to allow specializing on `Eq` even though `Eq` has a method.
1671 #[rustc_unsafe_specialization_marker]
1672 pub(crate) trait MarkerEq: PartialEq<Self> {}
1673
1674 impl<T: Eq> MarkerEq for T {}
1675
1676 /// We're doing this specialization here, and not as a more general optimization on `&T`, because it
1677 /// would otherwise add a cost to all equality checks on refs. We assume that `Rc`s are used to
1678 /// store large values, that are slow to clone, but also heavy to check for equality, causing this
1679 /// cost to pay off more easily. It's also more likely to have two `Rc` clones, that point to
1680 /// the same value, than two `&T`s.
1681 ///
1682 /// We can only do this when `T: Eq` as a `PartialEq` might be deliberately irreflexive.
1683 #[stable(feature = "rust1", since = "1.0.0")]
1684 impl<T: ?Sized + MarkerEq> RcEqIdent<T> for Rc<T> {
1685 #[inline]
1686 fn eq(&self, other: &Rc<T>) -> bool {
1687 Rc::ptr_eq(self, other) || **self == **other
1688 }
1689
1690 #[inline]
1691 fn ne(&self, other: &Rc<T>) -> bool {
1692 !Rc::ptr_eq(self, other) && **self != **other
1693 }
1694 }
1695
1696 #[stable(feature = "rust1", since = "1.0.0")]
1697 impl<T: ?Sized + PartialEq> PartialEq for Rc<T> {
1698 /// Equality for two `Rc`s.
1699 ///
1700 /// Two `Rc`s are equal if their inner values are equal, even if they are
1701 /// stored in different allocation.
1702 ///
1703 /// If `T` also implements `Eq` (implying reflexivity of equality),
1704 /// two `Rc`s that point to the same allocation are
1705 /// always equal.
1706 ///
1707 /// # Examples
1708 ///
1709 /// ```
1710 /// use std::rc::Rc;
1711 ///
1712 /// let five = Rc::new(5);
1713 ///
1714 /// assert!(five == Rc::new(5));
1715 /// ```
1716 #[inline]
1717 fn eq(&self, other: &Rc<T>) -> bool {
1718 RcEqIdent::eq(self, other)
1719 }
1720
1721 /// Inequality for two `Rc`s.
1722 ///
1723 /// Two `Rc`s are unequal if their inner values are unequal.
1724 ///
1725 /// If `T` also implements `Eq` (implying reflexivity of equality),
1726 /// two `Rc`s that point to the same allocation are
1727 /// never unequal.
1728 ///
1729 /// # Examples
1730 ///
1731 /// ```
1732 /// use std::rc::Rc;
1733 ///
1734 /// let five = Rc::new(5);
1735 ///
1736 /// assert!(five != Rc::new(6));
1737 /// ```
1738 #[inline]
1739 fn ne(&self, other: &Rc<T>) -> bool {
1740 RcEqIdent::ne(self, other)
1741 }
1742 }
1743
1744 #[stable(feature = "rust1", since = "1.0.0")]
1745 impl<T: ?Sized + Eq> Eq for Rc<T> {}
1746
1747 #[stable(feature = "rust1", since = "1.0.0")]
1748 impl<T: ?Sized + PartialOrd> PartialOrd for Rc<T> {
1749 /// Partial comparison for two `Rc`s.
1750 ///
1751 /// The two are compared by calling `partial_cmp()` on their inner values.
1752 ///
1753 /// # Examples
1754 ///
1755 /// ```
1756 /// use std::rc::Rc;
1757 /// use std::cmp::Ordering;
1758 ///
1759 /// let five = Rc::new(5);
1760 ///
1761 /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&Rc::new(6)));
1762 /// ```
1763 #[inline(always)]
1764 fn partial_cmp(&self, other: &Rc<T>) -> Option<Ordering> {
1765 (**self).partial_cmp(&**other)
1766 }
1767
1768 /// Less-than comparison for two `Rc`s.
1769 ///
1770 /// The two are compared by calling `<` on their inner values.
1771 ///
1772 /// # Examples
1773 ///
1774 /// ```
1775 /// use std::rc::Rc;
1776 ///
1777 /// let five = Rc::new(5);
1778 ///
1779 /// assert!(five < Rc::new(6));
1780 /// ```
1781 #[inline(always)]
1782 fn lt(&self, other: &Rc<T>) -> bool {
1783 **self < **other
1784 }
1785
1786 /// 'Less than or equal to' comparison for two `Rc`s.
1787 ///
1788 /// The two are compared by calling `<=` on their inner values.
1789 ///
1790 /// # Examples
1791 ///
1792 /// ```
1793 /// use std::rc::Rc;
1794 ///
1795 /// let five = Rc::new(5);
1796 ///
1797 /// assert!(five <= Rc::new(5));
1798 /// ```
1799 #[inline(always)]
1800 fn le(&self, other: &Rc<T>) -> bool {
1801 **self <= **other
1802 }
1803
1804 /// Greater-than comparison for two `Rc`s.
1805 ///
1806 /// The two are compared by calling `>` on their inner values.
1807 ///
1808 /// # Examples
1809 ///
1810 /// ```
1811 /// use std::rc::Rc;
1812 ///
1813 /// let five = Rc::new(5);
1814 ///
1815 /// assert!(five > Rc::new(4));
1816 /// ```
1817 #[inline(always)]
1818 fn gt(&self, other: &Rc<T>) -> bool {
1819 **self > **other
1820 }
1821
1822 /// 'Greater than or equal to' comparison for two `Rc`s.
1823 ///
1824 /// The two are compared by calling `>=` on their inner values.
1825 ///
1826 /// # Examples
1827 ///
1828 /// ```
1829 /// use std::rc::Rc;
1830 ///
1831 /// let five = Rc::new(5);
1832 ///
1833 /// assert!(five >= Rc::new(5));
1834 /// ```
1835 #[inline(always)]
1836 fn ge(&self, other: &Rc<T>) -> bool {
1837 **self >= **other
1838 }
1839 }
1840
1841 #[stable(feature = "rust1", since = "1.0.0")]
1842 impl<T: ?Sized + Ord> Ord for Rc<T> {
1843 /// Comparison for two `Rc`s.
1844 ///
1845 /// The two are compared by calling `cmp()` on their inner values.
1846 ///
1847 /// # Examples
1848 ///
1849 /// ```
1850 /// use std::rc::Rc;
1851 /// use std::cmp::Ordering;
1852 ///
1853 /// let five = Rc::new(5);
1854 ///
1855 /// assert_eq!(Ordering::Less, five.cmp(&Rc::new(6)));
1856 /// ```
1857 #[inline]
1858 fn cmp(&self, other: &Rc<T>) -> Ordering {
1859 (**self).cmp(&**other)
1860 }
1861 }
1862
1863 #[stable(feature = "rust1", since = "1.0.0")]
1864 impl<T: ?Sized + Hash> Hash for Rc<T> {
1865 fn hash<H: Hasher>(&self, state: &mut H) {
1866 (**self).hash(state);
1867 }
1868 }
1869
1870 #[stable(feature = "rust1", since = "1.0.0")]
1871 impl<T: ?Sized + fmt::Display> fmt::Display for Rc<T> {
1872 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1873 fmt::Display::fmt(&**self, f)
1874 }
1875 }
1876
1877 #[stable(feature = "rust1", since = "1.0.0")]
1878 impl<T: ?Sized + fmt::Debug> fmt::Debug for Rc<T> {
1879 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1880 fmt::Debug::fmt(&**self, f)
1881 }
1882 }
1883
1884 #[stable(feature = "rust1", since = "1.0.0")]
1885 impl<T: ?Sized> fmt::Pointer for Rc<T> {
1886 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1887 fmt::Pointer::fmt(&(&**self as *const T), f)
1888 }
1889 }
1890
1891 #[cfg(not(no_global_oom_handling))]
1892 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
1893 impl<T> From<T> for Rc<T> {
1894 /// Converts a generic type `T` into an `Rc<T>`
1895 ///
1896 /// The conversion allocates on the heap and moves `t`
1897 /// from the stack into it.
1898 ///
1899 /// # Example
1900 /// ```rust
1901 /// # use std::rc::Rc;
1902 /// let x = 5;
1903 /// let rc = Rc::new(5);
1904 ///
1905 /// assert_eq!(Rc::from(x), rc);
1906 /// ```
1907 fn from(t: T) -> Self {
1908 Rc::new(t)
1909 }
1910 }
1911
1912 #[cfg(not(no_global_oom_handling))]
1913 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1914 impl<T: Clone> From<&[T]> for Rc<[T]> {
1915 /// Allocate a reference-counted slice and fill it by cloning `v`'s items.
1916 ///
1917 /// # Example
1918 ///
1919 /// ```
1920 /// # use std::rc::Rc;
1921 /// let original: &[i32] = &[1, 2, 3];
1922 /// let shared: Rc<[i32]> = Rc::from(original);
1923 /// assert_eq!(&[1, 2, 3], &shared[..]);
1924 /// ```
1925 #[inline]
1926 fn from(v: &[T]) -> Rc<[T]> {
1927 <Self as RcFromSlice<T>>::from_slice(v)
1928 }
1929 }
1930
1931 #[cfg(not(no_global_oom_handling))]
1932 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1933 impl From<&str> for Rc<str> {
1934 /// Allocate a reference-counted string slice and copy `v` into it.
1935 ///
1936 /// # Example
1937 ///
1938 /// ```
1939 /// # use std::rc::Rc;
1940 /// let shared: Rc<str> = Rc::from("statue");
1941 /// assert_eq!("statue", &shared[..]);
1942 /// ```
1943 #[inline]
1944 fn from(v: &str) -> Rc<str> {
1945 let rc = Rc::<[u8]>::from(v.as_bytes());
1946 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const str) }
1947 }
1948 }
1949
1950 #[cfg(not(no_global_oom_handling))]
1951 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1952 impl From<String> for Rc<str> {
1953 /// Allocate a reference-counted string slice and copy `v` into it.
1954 ///
1955 /// # Example
1956 ///
1957 /// ```
1958 /// # use std::rc::Rc;
1959 /// let original: String = "statue".to_owned();
1960 /// let shared: Rc<str> = Rc::from(original);
1961 /// assert_eq!("statue", &shared[..]);
1962 /// ```
1963 #[inline]
1964 fn from(v: String) -> Rc<str> {
1965 Rc::from(&v[..])
1966 }
1967 }
1968
1969 #[cfg(not(no_global_oom_handling))]
1970 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1971 impl<T: ?Sized> From<Box<T>> for Rc<T> {
1972 /// Move a boxed object to a new, reference counted, allocation.
1973 ///
1974 /// # Example
1975 ///
1976 /// ```
1977 /// # use std::rc::Rc;
1978 /// let original: Box<i32> = Box::new(1);
1979 /// let shared: Rc<i32> = Rc::from(original);
1980 /// assert_eq!(1, *shared);
1981 /// ```
1982 #[inline]
1983 fn from(v: Box<T>) -> Rc<T> {
1984 Rc::from_box(v)
1985 }
1986 }
1987
1988 #[cfg(not(no_global_oom_handling))]
1989 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1990 impl<T> From<Vec<T>> for Rc<[T]> {
1991 /// Allocate a reference-counted slice and move `v`'s items into it.
1992 ///
1993 /// # Example
1994 ///
1995 /// ```
1996 /// # use std::rc::Rc;
1997 /// let original: Box<Vec<i32>> = Box::new(vec![1, 2, 3]);
1998 /// let shared: Rc<Vec<i32>> = Rc::from(original);
1999 /// assert_eq!(vec![1, 2, 3], *shared);
2000 /// ```
2001 #[inline]
2002 fn from(mut v: Vec<T>) -> Rc<[T]> {
2003 unsafe {
2004 let rc = Rc::copy_from_slice(&v);
2005 // Allow the Vec to free its memory, but not destroy its contents
2006 v.set_len(0);
2007 rc
2008 }
2009 }
2010 }
2011
2012 #[stable(feature = "shared_from_cow", since = "1.45.0")]
2013 impl<'a, B> From<Cow<'a, B>> for Rc<B>
2014 where
2015 B: ToOwned + ?Sized,
2016 Rc<B>: From<&'a B> + From<B::Owned>,
2017 {
2018 /// Create a reference-counted pointer from
2019 /// a clone-on-write pointer by copying its content.
2020 ///
2021 /// # Example
2022 ///
2023 /// ```rust
2024 /// # use std::rc::Rc;
2025 /// # use std::borrow::Cow;
2026 /// let cow: Cow<str> = Cow::Borrowed("eggplant");
2027 /// let shared: Rc<str> = Rc::from(cow);
2028 /// assert_eq!("eggplant", &shared[..]);
2029 /// ```
2030 #[inline]
2031 fn from(cow: Cow<'a, B>) -> Rc<B> {
2032 match cow {
2033 Cow::Borrowed(s) => Rc::from(s),
2034 Cow::Owned(s) => Rc::from(s),
2035 }
2036 }
2037 }
2038
2039 #[stable(feature = "shared_from_str", since = "1.62.0")]
2040 impl From<Rc<str>> for Rc<[u8]> {
2041 /// Converts a reference-counted string slice into a byte slice.
2042 ///
2043 /// # Example
2044 ///
2045 /// ```
2046 /// # use std::rc::Rc;
2047 /// let string: Rc<str> = Rc::from("eggplant");
2048 /// let bytes: Rc<[u8]> = Rc::from(string);
2049 /// assert_eq!("eggplant".as_bytes(), bytes.as_ref());
2050 /// ```
2051 #[inline]
2052 fn from(rc: Rc<str>) -> Self {
2053 // SAFETY: `str` has the same layout as `[u8]`.
2054 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const [u8]) }
2055 }
2056 }
2057
2058 #[stable(feature = "boxed_slice_try_from", since = "1.43.0")]
2059 impl<T, const N: usize> TryFrom<Rc<[T]>> for Rc<[T; N]> {
2060 type Error = Rc<[T]>;
2061
2062 fn try_from(boxed_slice: Rc<[T]>) -> Result<Self, Self::Error> {
2063 if boxed_slice.len() == N {
2064 Ok(unsafe { Rc::from_raw(Rc::into_raw(boxed_slice) as *mut [T; N]) })
2065 } else {
2066 Err(boxed_slice)
2067 }
2068 }
2069 }
2070
2071 #[cfg(not(no_global_oom_handling))]
2072 #[stable(feature = "shared_from_iter", since = "1.37.0")]
2073 impl<T> iter::FromIterator<T> for Rc<[T]> {
2074 /// Takes each element in the `Iterator` and collects it into an `Rc<[T]>`.
2075 ///
2076 /// # Performance characteristics
2077 ///
2078 /// ## The general case
2079 ///
2080 /// In the general case, collecting into `Rc<[T]>` is done by first
2081 /// collecting into a `Vec<T>`. That is, when writing the following:
2082 ///
2083 /// ```rust
2084 /// # use std::rc::Rc;
2085 /// let evens: Rc<[u8]> = (0..10).filter(|&x| x % 2 == 0).collect();
2086 /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]);
2087 /// ```
2088 ///
2089 /// this behaves as if we wrote:
2090 ///
2091 /// ```rust
2092 /// # use std::rc::Rc;
2093 /// let evens: Rc<[u8]> = (0..10).filter(|&x| x % 2 == 0)
2094 /// .collect::<Vec<_>>() // The first set of allocations happens here.
2095 /// .into(); // A second allocation for `Rc<[T]>` happens here.
2096 /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]);
2097 /// ```
2098 ///
2099 /// This will allocate as many times as needed for constructing the `Vec<T>`
2100 /// and then it will allocate once for turning the `Vec<T>` into the `Rc<[T]>`.
2101 ///
2102 /// ## Iterators of known length
2103 ///
2104 /// When your `Iterator` implements `TrustedLen` and is of an exact size,
2105 /// a single allocation will be made for the `Rc<[T]>`. For example:
2106 ///
2107 /// ```rust
2108 /// # use std::rc::Rc;
2109 /// let evens: Rc<[u8]> = (0..10).collect(); // Just a single allocation happens here.
2110 /// # assert_eq!(&*evens, &*(0..10).collect::<Vec<_>>());
2111 /// ```
2112 fn from_iter<I: iter::IntoIterator<Item = T>>(iter: I) -> Self {
2113 ToRcSlice::to_rc_slice(iter.into_iter())
2114 }
2115 }
2116
2117 /// Specialization trait used for collecting into `Rc<[T]>`.
2118 #[cfg(not(no_global_oom_handling))]
2119 trait ToRcSlice<T>: Iterator<Item = T> + Sized {
2120 fn to_rc_slice(self) -> Rc<[T]>;
2121 }
2122
2123 #[cfg(not(no_global_oom_handling))]
2124 impl<T, I: Iterator<Item = T>> ToRcSlice<T> for I {
2125 default fn to_rc_slice(self) -> Rc<[T]> {
2126 self.collect::<Vec<T>>().into()
2127 }
2128 }
2129
2130 #[cfg(not(no_global_oom_handling))]
2131 impl<T, I: iter::TrustedLen<Item = T>> ToRcSlice<T> for I {
2132 fn to_rc_slice(self) -> Rc<[T]> {
2133 // This is the case for a `TrustedLen` iterator.
2134 let (low, high) = self.size_hint();
2135 if let Some(high) = high {
2136 debug_assert_eq!(
2137 low,
2138 high,
2139 "TrustedLen iterator's size hint is not exact: {:?}",
2140 (low, high)
2141 );
2142
2143 unsafe {
2144 // SAFETY: We need to ensure that the iterator has an exact length and we have.
2145 Rc::from_iter_exact(self, low)
2146 }
2147 } else {
2148 // TrustedLen contract guarantees that `upper_bound == `None` implies an iterator
2149 // length exceeding `usize::MAX`.
2150 // The default implementation would collect into a vec which would panic.
2151 // Thus we panic here immediately without invoking `Vec` code.
2152 panic!("capacity overflow");
2153 }
2154 }
2155 }
2156
2157 /// `Weak` is a version of [`Rc`] that holds a non-owning reference to the
2158 /// managed allocation. The allocation is accessed by calling [`upgrade`] on the `Weak`
2159 /// pointer, which returns an <code>[Option]<[Rc]\<T>></code>.
2160 ///
2161 /// Since a `Weak` reference does not count towards ownership, it will not
2162 /// prevent the value stored in the allocation from being dropped, and `Weak` itself makes no
2163 /// guarantees about the value still being present. Thus it may return [`None`]
2164 /// when [`upgrade`]d. Note however that a `Weak` reference *does* prevent the allocation
2165 /// itself (the backing store) from being deallocated.
2166 ///
2167 /// A `Weak` pointer is useful for keeping a temporary reference to the allocation
2168 /// managed by [`Rc`] without preventing its inner value from being dropped. It is also used to
2169 /// prevent circular references between [`Rc`] pointers, since mutual owning references
2170 /// would never allow either [`Rc`] to be dropped. For example, a tree could
2171 /// have strong [`Rc`] pointers from parent nodes to children, and `Weak`
2172 /// pointers from children back to their parents.
2173 ///
2174 /// The typical way to obtain a `Weak` pointer is to call [`Rc::downgrade`].
2175 ///
2176 /// [`upgrade`]: Weak::upgrade
2177 #[stable(feature = "rc_weak", since = "1.4.0")]
2178 pub struct Weak<T: ?Sized> {
2179 // This is a `NonNull` to allow optimizing the size of this type in enums,
2180 // but it is not necessarily a valid pointer.
2181 // `Weak::new` sets this to `usize::MAX` so that it doesn’t need
2182 // to allocate space on the heap. That's not a value a real pointer
2183 // will ever have because RcBox has alignment at least 2.
2184 // This is only possible when `T: Sized`; unsized `T` never dangle.
2185 ptr: NonNull<RcBox<T>>,
2186 }
2187
2188 #[stable(feature = "rc_weak", since = "1.4.0")]
2189 impl<T: ?Sized> !marker::Send for Weak<T> {}
2190 #[stable(feature = "rc_weak", since = "1.4.0")]
2191 impl<T: ?Sized> !marker::Sync for Weak<T> {}
2192
2193 #[unstable(feature = "coerce_unsized", issue = "18598")]
2194 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {}
2195
2196 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
2197 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Weak<U>> for Weak<T> {}
2198
2199 impl<T> Weak<T> {
2200 /// Constructs a new `Weak<T>`, without allocating any memory.
2201 /// Calling [`upgrade`] on the return value always gives [`None`].
2202 ///
2203 /// [`upgrade`]: Weak::upgrade
2204 ///
2205 /// # Examples
2206 ///
2207 /// ```
2208 /// use std::rc::Weak;
2209 ///
2210 /// let empty: Weak<i64> = Weak::new();
2211 /// assert!(empty.upgrade().is_none());
2212 /// ```
2213 #[stable(feature = "downgraded_weak", since = "1.10.0")]
2214 #[rustc_const_unstable(feature = "const_weak_new", issue = "95091", reason = "recently added")]
2215 #[must_use]
2216 pub const fn new() -> Weak<T> {
2217 Weak { ptr: unsafe { NonNull::new_unchecked(ptr::invalid_mut::<RcBox<T>>(usize::MAX)) } }
2218 }
2219 }
2220
2221 pub(crate) fn is_dangling<T: ?Sized>(ptr: *mut T) -> bool {
2222 (ptr as *mut ()).addr() == usize::MAX
2223 }
2224
2225 /// Helper type to allow accessing the reference counts without
2226 /// making any assertions about the data field.
2227 struct WeakInner<'a> {
2228 weak: &'a Cell<usize>,
2229 strong: &'a Cell<usize>,
2230 }
2231
2232 impl<T: ?Sized> Weak<T> {
2233 /// Returns a raw pointer to the object `T` pointed to by this `Weak<T>`.
2234 ///
2235 /// The pointer is valid only if there are some strong references. The pointer may be dangling,
2236 /// unaligned or even [`null`] otherwise.
2237 ///
2238 /// # Examples
2239 ///
2240 /// ```
2241 /// use std::rc::Rc;
2242 /// use std::ptr;
2243 ///
2244 /// let strong = Rc::new("hello".to_owned());
2245 /// let weak = Rc::downgrade(&strong);
2246 /// // Both point to the same object
2247 /// assert!(ptr::eq(&*strong, weak.as_ptr()));
2248 /// // The strong here keeps it alive, so we can still access the object.
2249 /// assert_eq!("hello", unsafe { &*weak.as_ptr() });
2250 ///
2251 /// drop(strong);
2252 /// // But not any more. We can do weak.as_ptr(), but accessing the pointer would lead to
2253 /// // undefined behaviour.
2254 /// // assert_eq!("hello", unsafe { &*weak.as_ptr() });
2255 /// ```
2256 ///
2257 /// [`null`]: ptr::null
2258 #[must_use]
2259 #[stable(feature = "rc_as_ptr", since = "1.45.0")]
2260 pub fn as_ptr(&self) -> *const T {
2261 let ptr: *mut RcBox<T> = NonNull::as_ptr(self.ptr);
2262
2263 if is_dangling(ptr) {
2264 // If the pointer is dangling, we return the sentinel directly. This cannot be
2265 // a valid payload address, as the payload is at least as aligned as RcBox (usize).
2266 ptr as *const T
2267 } else {
2268 // SAFETY: if is_dangling returns false, then the pointer is dereferenceable.
2269 // The payload may be dropped at this point, and we have to maintain provenance,
2270 // so use raw pointer manipulation.
2271 unsafe { ptr::addr_of_mut!((*ptr).value) }
2272 }
2273 }
2274
2275 /// Consumes the `Weak<T>` and turns it into a raw pointer.
2276 ///
2277 /// This converts the weak pointer into a raw pointer, while still preserving the ownership of
2278 /// one weak reference (the weak count is not modified by this operation). It can be turned
2279 /// back into the `Weak<T>` with [`from_raw`].
2280 ///
2281 /// The same restrictions of accessing the target of the pointer as with
2282 /// [`as_ptr`] apply.
2283 ///
2284 /// # Examples
2285 ///
2286 /// ```
2287 /// use std::rc::{Rc, Weak};
2288 ///
2289 /// let strong = Rc::new("hello".to_owned());
2290 /// let weak = Rc::downgrade(&strong);
2291 /// let raw = weak.into_raw();
2292 ///
2293 /// assert_eq!(1, Rc::weak_count(&strong));
2294 /// assert_eq!("hello", unsafe { &*raw });
2295 ///
2296 /// drop(unsafe { Weak::from_raw(raw) });
2297 /// assert_eq!(0, Rc::weak_count(&strong));
2298 /// ```
2299 ///
2300 /// [`from_raw`]: Weak::from_raw
2301 /// [`as_ptr`]: Weak::as_ptr
2302 #[must_use = "`self` will be dropped if the result is not used"]
2303 #[stable(feature = "weak_into_raw", since = "1.45.0")]
2304 pub fn into_raw(self) -> *const T {
2305 let result = self.as_ptr();
2306 mem::forget(self);
2307 result
2308 }
2309
2310 /// Converts a raw pointer previously created by [`into_raw`] back into `Weak<T>`.
2311 ///
2312 /// This can be used to safely get a strong reference (by calling [`upgrade`]
2313 /// later) or to deallocate the weak count by dropping the `Weak<T>`.
2314 ///
2315 /// It takes ownership of one weak reference (with the exception of pointers created by [`new`],
2316 /// as these don't own anything; the method still works on them).
2317 ///
2318 /// # Safety
2319 ///
2320 /// The pointer must have originated from the [`into_raw`] and must still own its potential
2321 /// weak reference.
2322 ///
2323 /// It is allowed for the strong count to be 0 at the time of calling this. Nevertheless, this
2324 /// takes ownership of one weak reference currently represented as a raw pointer (the weak
2325 /// count is not modified by this operation) and therefore it must be paired with a previous
2326 /// call to [`into_raw`].
2327 ///
2328 /// # Examples
2329 ///
2330 /// ```
2331 /// use std::rc::{Rc, Weak};
2332 ///
2333 /// let strong = Rc::new("hello".to_owned());
2334 ///
2335 /// let raw_1 = Rc::downgrade(&strong).into_raw();
2336 /// let raw_2 = Rc::downgrade(&strong).into_raw();
2337 ///
2338 /// assert_eq!(2, Rc::weak_count(&strong));
2339 ///
2340 /// assert_eq!("hello", &*unsafe { Weak::from_raw(raw_1) }.upgrade().unwrap());
2341 /// assert_eq!(1, Rc::weak_count(&strong));
2342 ///
2343 /// drop(strong);
2344 ///
2345 /// // Decrement the last weak count.
2346 /// assert!(unsafe { Weak::from_raw(raw_2) }.upgrade().is_none());
2347 /// ```
2348 ///
2349 /// [`into_raw`]: Weak::into_raw
2350 /// [`upgrade`]: Weak::upgrade
2351 /// [`new`]: Weak::new
2352 #[stable(feature = "weak_into_raw", since = "1.45.0")]
2353 pub unsafe fn from_raw(ptr: *const T) -> Self {
2354 // See Weak::as_ptr for context on how the input pointer is derived.
2355
2356 let ptr = if is_dangling(ptr as *mut T) {
2357 // This is a dangling Weak.
2358 ptr as *mut RcBox<T>
2359 } else {
2360 // Otherwise, we're guaranteed the pointer came from a nondangling Weak.
2361 // SAFETY: data_offset is safe to call, as ptr references a real (potentially dropped) T.
2362 let offset = unsafe { data_offset(ptr) };
2363 // Thus, we reverse the offset to get the whole RcBox.
2364 // SAFETY: the pointer originated from a Weak, so this offset is safe.
2365 unsafe { ptr.byte_sub(offset) as *mut RcBox<T> }
2366 };
2367
2368 // SAFETY: we now have recovered the original Weak pointer, so can create the Weak.
2369 Weak { ptr: unsafe { NonNull::new_unchecked(ptr) } }
2370 }
2371
2372 /// Attempts to upgrade the `Weak` pointer to an [`Rc`], delaying
2373 /// dropping of the inner value if successful.
2374 ///
2375 /// Returns [`None`] if the inner value has since been dropped.
2376 ///
2377 /// # Examples
2378 ///
2379 /// ```
2380 /// use std::rc::Rc;
2381 ///
2382 /// let five = Rc::new(5);
2383 ///
2384 /// let weak_five = Rc::downgrade(&five);
2385 ///
2386 /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
2387 /// assert!(strong_five.is_some());
2388 ///
2389 /// // Destroy all strong pointers.
2390 /// drop(strong_five);
2391 /// drop(five);
2392 ///
2393 /// assert!(weak_five.upgrade().is_none());
2394 /// ```
2395 #[must_use = "this returns a new `Rc`, \
2396 without modifying the original weak pointer"]
2397 #[stable(feature = "rc_weak", since = "1.4.0")]
2398 pub fn upgrade(&self) -> Option<Rc<T>> {
2399 let inner = self.inner()?;
2400
2401 if inner.strong() == 0 {
2402 None
2403 } else {
2404 unsafe {
2405 inner.inc_strong();
2406 Some(Rc::from_inner(self.ptr))
2407 }
2408 }
2409 }
2410
2411 /// Gets the number of strong (`Rc`) pointers pointing to this allocation.
2412 ///
2413 /// If `self` was created using [`Weak::new`], this will return 0.
2414 #[must_use]
2415 #[stable(feature = "weak_counts", since = "1.41.0")]
2416 pub fn strong_count(&self) -> usize {
2417 if let Some(inner) = self.inner() { inner.strong() } else { 0 }
2418 }
2419
2420 /// Gets the number of `Weak` pointers pointing to this allocation.
2421 ///
2422 /// If no strong pointers remain, this will return zero.
2423 #[must_use]
2424 #[stable(feature = "weak_counts", since = "1.41.0")]
2425 pub fn weak_count(&self) -> usize {
2426 self.inner()
2427 .map(|inner| {
2428 if inner.strong() > 0 {
2429 inner.weak() - 1 // subtract the implicit weak ptr
2430 } else {
2431 0
2432 }
2433 })
2434 .unwrap_or(0)
2435 }
2436
2437 /// Returns `None` when the pointer is dangling and there is no allocated `RcBox`,
2438 /// (i.e., when this `Weak` was created by `Weak::new`).
2439 #[inline]
2440 fn inner(&self) -> Option<WeakInner<'_>> {
2441 if is_dangling(self.ptr.as_ptr()) {
2442 None
2443 } else {
2444 // We are careful to *not* create a reference covering the "data" field, as
2445 // the field may be mutated concurrently (for example, if the last `Rc`
2446 // is dropped, the data field will be dropped in-place).
2447 Some(unsafe {
2448 let ptr = self.ptr.as_ptr();
2449 WeakInner { strong: &(*ptr).strong, weak: &(*ptr).weak }
2450 })
2451 }
2452 }
2453
2454 /// Returns `true` if the two `Weak`s point to the same allocation similar to [`ptr::eq`], or if
2455 /// both don't point to any allocation (because they were created with `Weak::new()`). See [that
2456 /// function][`ptr::eq`] for caveats when comparing `dyn Trait` pointers.
2457 ///
2458 /// # Notes
2459 ///
2460 /// Since this compares pointers it means that `Weak::new()` will equal each
2461 /// other, even though they don't point to any allocation.
2462 ///
2463 /// # Examples
2464 ///
2465 /// ```
2466 /// use std::rc::Rc;
2467 ///
2468 /// let first_rc = Rc::new(5);
2469 /// let first = Rc::downgrade(&first_rc);
2470 /// let second = Rc::downgrade(&first_rc);
2471 ///
2472 /// assert!(first.ptr_eq(&second));
2473 ///
2474 /// let third_rc = Rc::new(5);
2475 /// let third = Rc::downgrade(&third_rc);
2476 ///
2477 /// assert!(!first.ptr_eq(&third));
2478 /// ```
2479 ///
2480 /// Comparing `Weak::new`.
2481 ///
2482 /// ```
2483 /// use std::rc::{Rc, Weak};
2484 ///
2485 /// let first = Weak::new();
2486 /// let second = Weak::new();
2487 /// assert!(first.ptr_eq(&second));
2488 ///
2489 /// let third_rc = Rc::new(());
2490 /// let third = Rc::downgrade(&third_rc);
2491 /// assert!(!first.ptr_eq(&third));
2492 /// ```
2493 #[inline]
2494 #[must_use]
2495 #[stable(feature = "weak_ptr_eq", since = "1.39.0")]
2496 pub fn ptr_eq(&self, other: &Self) -> bool {
2497 self.ptr.as_ptr() == other.ptr.as_ptr()
2498 }
2499 }
2500
2501 #[stable(feature = "rc_weak", since = "1.4.0")]
2502 unsafe impl<#[may_dangle] T: ?Sized> Drop for Weak<T> {
2503 /// Drops the `Weak` pointer.
2504 ///
2505 /// # Examples
2506 ///
2507 /// ```
2508 /// use std::rc::{Rc, Weak};
2509 ///
2510 /// struct Foo;
2511 ///
2512 /// impl Drop for Foo {
2513 /// fn drop(&mut self) {
2514 /// println!("dropped!");
2515 /// }
2516 /// }
2517 ///
2518 /// let foo = Rc::new(Foo);
2519 /// let weak_foo = Rc::downgrade(&foo);
2520 /// let other_weak_foo = Weak::clone(&weak_foo);
2521 ///
2522 /// drop(weak_foo); // Doesn't print anything
2523 /// drop(foo); // Prints "dropped!"
2524 ///
2525 /// assert!(other_weak_foo.upgrade().is_none());
2526 /// ```
2527 fn drop(&mut self) {
2528 let inner = if let Some(inner) = self.inner() { inner } else { return };
2529
2530 inner.dec_weak();
2531 // the weak count starts at 1, and will only go to zero if all
2532 // the strong pointers have disappeared.
2533 if inner.weak() == 0 {
2534 unsafe {
2535 Global.deallocate(self.ptr.cast(), Layout::for_value_raw(self.ptr.as_ptr()));
2536 }
2537 }
2538 }
2539 }
2540
2541 #[stable(feature = "rc_weak", since = "1.4.0")]
2542 impl<T: ?Sized> Clone for Weak<T> {
2543 /// Makes a clone of the `Weak` pointer that points to the same allocation.
2544 ///
2545 /// # Examples
2546 ///
2547 /// ```
2548 /// use std::rc::{Rc, Weak};
2549 ///
2550 /// let weak_five = Rc::downgrade(&Rc::new(5));
2551 ///
2552 /// let _ = Weak::clone(&weak_five);
2553 /// ```
2554 #[inline]
2555 fn clone(&self) -> Weak<T> {
2556 if let Some(inner) = self.inner() {
2557 inner.inc_weak()
2558 }
2559 Weak { ptr: self.ptr }
2560 }
2561 }
2562
2563 #[stable(feature = "rc_weak", since = "1.4.0")]
2564 impl<T: ?Sized> fmt::Debug for Weak<T> {
2565 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2566 write!(f, "(Weak)")
2567 }
2568 }
2569
2570 #[stable(feature = "downgraded_weak", since = "1.10.0")]
2571 impl<T> Default for Weak<T> {
2572 /// Constructs a new `Weak<T>`, without allocating any memory.
2573 /// Calling [`upgrade`] on the return value always gives [`None`].
2574 ///
2575 /// [`upgrade`]: Weak::upgrade
2576 ///
2577 /// # Examples
2578 ///
2579 /// ```
2580 /// use std::rc::Weak;
2581 ///
2582 /// let empty: Weak<i64> = Default::default();
2583 /// assert!(empty.upgrade().is_none());
2584 /// ```
2585 fn default() -> Weak<T> {
2586 Weak::new()
2587 }
2588 }
2589
2590 // NOTE: We checked_add here to deal with mem::forget safely. In particular
2591 // if you mem::forget Rcs (or Weaks), the ref-count can overflow, and then
2592 // you can free the allocation while outstanding Rcs (or Weaks) exist.
2593 // We abort because this is such a degenerate scenario that we don't care about
2594 // what happens -- no real program should ever experience this.
2595 //
2596 // This should have negligible overhead since you don't actually need to
2597 // clone these much in Rust thanks to ownership and move-semantics.
2598
2599 #[doc(hidden)]
2600 trait RcInnerPtr {
2601 fn weak_ref(&self) -> &Cell<usize>;
2602 fn strong_ref(&self) -> &Cell<usize>;
2603
2604 #[inline]
2605 fn strong(&self) -> usize {
2606 self.strong_ref().get()
2607 }
2608
2609 #[inline]
2610 fn inc_strong(&self) {
2611 let strong = self.strong();
2612
2613 // We insert an `assume` here to hint LLVM at an otherwise
2614 // missed optimization.
2615 // SAFETY: The reference count will never be zero when this is
2616 // called.
2617 unsafe {
2618 core::intrinsics::assume(strong != 0);
2619 }
2620
2621 let strong = strong.wrapping_add(1);
2622 self.strong_ref().set(strong);
2623
2624 // We want to abort on overflow instead of dropping the value.
2625 // Checking for overflow after the store instead of before
2626 // allows for slightly better code generation.
2627 if core::intrinsics::unlikely(strong == 0) {
2628 abort();
2629 }
2630 }
2631
2632 #[inline]
2633 fn dec_strong(&self) {
2634 self.strong_ref().set(self.strong() - 1);
2635 }
2636
2637 #[inline]
2638 fn weak(&self) -> usize {
2639 self.weak_ref().get()
2640 }
2641
2642 #[inline]
2643 fn inc_weak(&self) {
2644 let weak = self.weak();
2645
2646 // We insert an `assume` here to hint LLVM at an otherwise
2647 // missed optimization.
2648 // SAFETY: The reference count will never be zero when this is
2649 // called.
2650 unsafe {
2651 core::intrinsics::assume(weak != 0);
2652 }
2653
2654 let weak = weak.wrapping_add(1);
2655 self.weak_ref().set(weak);
2656
2657 // We want to abort on overflow instead of dropping the value.
2658 // Checking for overflow after the store instead of before
2659 // allows for slightly better code generation.
2660 if core::intrinsics::unlikely(weak == 0) {
2661 abort();
2662 }
2663 }
2664
2665 #[inline]
2666 fn dec_weak(&self) {
2667 self.weak_ref().set(self.weak() - 1);
2668 }
2669 }
2670
2671 impl<T: ?Sized> RcInnerPtr for RcBox<T> {
2672 #[inline(always)]
2673 fn weak_ref(&self) -> &Cell<usize> {
2674 &self.weak
2675 }
2676
2677 #[inline(always)]
2678 fn strong_ref(&self) -> &Cell<usize> {
2679 &self.strong
2680 }
2681 }
2682
2683 impl<'a> RcInnerPtr for WeakInner<'a> {
2684 #[inline(always)]
2685 fn weak_ref(&self) -> &Cell<usize> {
2686 self.weak
2687 }
2688
2689 #[inline(always)]
2690 fn strong_ref(&self) -> &Cell<usize> {
2691 self.strong
2692 }
2693 }
2694
2695 #[stable(feature = "rust1", since = "1.0.0")]
2696 impl<T: ?Sized> borrow::Borrow<T> for Rc<T> {
2697 fn borrow(&self) -> &T {
2698 &**self
2699 }
2700 }
2701
2702 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
2703 impl<T: ?Sized> AsRef<T> for Rc<T> {
2704 fn as_ref(&self) -> &T {
2705 &**self
2706 }
2707 }
2708
2709 #[stable(feature = "pin", since = "1.33.0")]
2710 impl<T: ?Sized> Unpin for Rc<T> {}
2711
2712 /// Get the offset within an `RcBox` for the payload behind a pointer.
2713 ///
2714 /// # Safety
2715 ///
2716 /// The pointer must point to (and have valid metadata for) a previously
2717 /// valid instance of T, but the T is allowed to be dropped.
2718 unsafe fn data_offset<T: ?Sized>(ptr: *const T) -> usize {
2719 // Align the unsized value to the end of the RcBox.
2720 // Because RcBox is repr(C), it will always be the last field in memory.
2721 // SAFETY: since the only unsized types possible are slices, trait objects,
2722 // and extern types, the input safety requirement is currently enough to
2723 // satisfy the requirements of align_of_val_raw; this is an implementation
2724 // detail of the language that must not be relied upon outside of std.
2725 unsafe { data_offset_align(align_of_val_raw(ptr)) }
2726 }
2727
2728 #[inline]
2729 fn data_offset_align(align: usize) -> usize {
2730 let layout = Layout::new::<RcBox<()>>();
2731 layout.size() + layout.padding_needed_for(align)
2732 }