alloc/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`]. 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//! [arc]: crate::sync::Arc
236//! [`Deref`]: core::ops::Deref
237//! [downgrade]: Rc::downgrade
238//! [upgrade]: Weak::upgrade
239//! [mutability]: core::cell#introducing-mutability-inside-of-something-immutable
240//! [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
241
242#![stable(feature = "rust1", since = "1.0.0")]
243
244use core::any::Any;
245use core::cell::{Cell, CloneFromCell};
246#[cfg(not(no_global_oom_handling))]
247use core::clone::CloneToUninit;
248use core::clone::UseCloned;
249use core::cmp::Ordering;
250use core::hash::{Hash, Hasher};
251use core::intrinsics::abort;
252#[cfg(not(no_global_oom_handling))]
253use core::iter;
254use core::marker::{PhantomData, Unsize};
255use core::mem::{self, ManuallyDrop, align_of_val_raw};
256use core::num::NonZeroUsize;
257use core::ops::{CoerceUnsized, Deref, DerefMut, DerefPure, DispatchFromDyn, LegacyReceiver};
258use core::panic::{RefUnwindSafe, UnwindSafe};
259#[cfg(not(no_global_oom_handling))]
260use core::pin::Pin;
261use core::pin::PinCoerceUnsized;
262use core::ptr::{self, NonNull, drop_in_place};
263#[cfg(not(no_global_oom_handling))]
264use core::slice::from_raw_parts_mut;
265use core::{borrow, fmt, hint};
266
267#[cfg(not(no_global_oom_handling))]
268use crate::alloc::handle_alloc_error;
269use crate::alloc::{AllocError, Allocator, Global, Layout};
270use crate::borrow::{Cow, ToOwned};
271use crate::boxed::Box;
272#[cfg(not(no_global_oom_handling))]
273use crate::string::String;
274#[cfg(not(no_global_oom_handling))]
275use crate::vec::Vec;
276
277// This is repr(C) to future-proof against possible field-reordering, which
278// would interfere with otherwise safe [into|from]_raw() of transmutable
279// inner types.
280// repr(align(2)) (forcing alignment to at least 2) is required because usize
281// has 1-byte alignment on AVR.
282#[repr(C, align(2))]
283struct RcInner<T: ?Sized> {
284 strong: Cell<usize>,
285 weak: Cell<usize>,
286 value: T,
287}
288
289/// Calculate layout for `RcInner<T>` using the inner value's layout
290fn rc_inner_layout_for_value_layout(layout: Layout) -> Layout {
291 // Calculate layout using the given value layout.
292 // Previously, layout was calculated on the expression
293 // `&*(ptr as *const RcInner<T>)`, but this created a misaligned
294 // reference (see #54908).
295 Layout::new::<RcInner<()>>().extend(layout).unwrap().0.pad_to_align()
296}
297
298/// A single-threaded reference-counting pointer. 'Rc' stands for 'Reference
299/// Counted'.
300///
301/// See the [module-level documentation](./index.html) for more details.
302///
303/// The inherent methods of `Rc` are all associated functions, which means
304/// that you have to call them as e.g., [`Rc::get_mut(&mut value)`][get_mut] instead of
305/// `value.get_mut()`. This avoids conflicts with methods of the inner type `T`.
306///
307/// [get_mut]: Rc::get_mut
308#[doc(search_unbox)]
309#[rustc_diagnostic_item = "Rc"]
310#[stable(feature = "rust1", since = "1.0.0")]
311#[rustc_insignificant_dtor]
312pub struct Rc<
313 T: ?Sized,
314 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
315> {
316 ptr: NonNull<RcInner<T>>,
317 phantom: PhantomData<RcInner<T>>,
318 alloc: A,
319}
320
321#[stable(feature = "rust1", since = "1.0.0")]
322impl<T: ?Sized, A: Allocator> !Send for Rc<T, A> {}
323
324// Note that this negative impl isn't strictly necessary for correctness,
325// as `Rc` transitively contains a `Cell`, which is itself `!Sync`.
326// However, given how important `Rc`'s `!Sync`-ness is,
327// having an explicit negative impl is nice for documentation purposes
328// and results in nicer error messages.
329#[stable(feature = "rust1", since = "1.0.0")]
330impl<T: ?Sized, A: Allocator> !Sync for Rc<T, A> {}
331
332#[stable(feature = "catch_unwind", since = "1.9.0")]
333impl<T: RefUnwindSafe + ?Sized, A: Allocator + UnwindSafe> UnwindSafe for Rc<T, A> {}
334#[stable(feature = "rc_ref_unwind_safe", since = "1.58.0")]
335impl<T: RefUnwindSafe + ?Sized, A: Allocator + UnwindSafe> RefUnwindSafe for Rc<T, A> {}
336
337#[unstable(feature = "coerce_unsized", issue = "18598")]
338impl<T: ?Sized + Unsize<U>, U: ?Sized, A: Allocator> CoerceUnsized<Rc<U, A>> for Rc<T, A> {}
339
340#[unstable(feature = "dispatch_from_dyn", issue = "none")]
341impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Rc<U>> for Rc<T> {}
342
343// SAFETY: `Rc::clone` doesn't access any `Cell`s which could contain the `Rc` being cloned.
344#[unstable(feature = "cell_get_cloned", issue = "145329")]
345unsafe impl<T: ?Sized> CloneFromCell for Rc<T> {}
346
347impl<T: ?Sized> Rc<T> {
348 #[inline]
349 unsafe fn from_inner(ptr: NonNull<RcInner<T>>) -> Self {
350 unsafe { Self::from_inner_in(ptr, Global) }
351 }
352
353 #[inline]
354 unsafe fn from_ptr(ptr: *mut RcInner<T>) -> Self {
355 unsafe { Self::from_inner(NonNull::new_unchecked(ptr)) }
356 }
357}
358
359impl<T: ?Sized, A: Allocator> Rc<T, A> {
360 #[inline(always)]
361 fn inner(&self) -> &RcInner<T> {
362 // This unsafety is ok because while this Rc is alive we're guaranteed
363 // that the inner pointer is valid.
364 unsafe { self.ptr.as_ref() }
365 }
366
367 #[inline]
368 fn into_inner_with_allocator(this: Self) -> (NonNull<RcInner<T>>, A) {
369 let this = mem::ManuallyDrop::new(this);
370 (this.ptr, unsafe { ptr::read(&this.alloc) })
371 }
372
373 #[inline]
374 unsafe fn from_inner_in(ptr: NonNull<RcInner<T>>, alloc: A) -> Self {
375 Self { ptr, phantom: PhantomData, alloc }
376 }
377
378 #[inline]
379 unsafe fn from_ptr_in(ptr: *mut RcInner<T>, alloc: A) -> Self {
380 unsafe { Self::from_inner_in(NonNull::new_unchecked(ptr), alloc) }
381 }
382
383 // Non-inlined part of `drop`.
384 #[inline(never)]
385 unsafe fn drop_slow(&mut self) {
386 // Reconstruct the "strong weak" pointer and drop it when this
387 // variable goes out of scope. This ensures that the memory is
388 // deallocated even if the destructor of `T` panics.
389 let _weak = Weak { ptr: self.ptr, alloc: &self.alloc };
390
391 // Destroy the contained object.
392 // We cannot use `get_mut_unchecked` here, because `self.alloc` is borrowed.
393 unsafe {
394 ptr::drop_in_place(&mut (*self.ptr.as_ptr()).value);
395 }
396 }
397}
398
399impl<T> Rc<T> {
400 /// Constructs a new `Rc<T>`.
401 ///
402 /// # Examples
403 ///
404 /// ```
405 /// use std::rc::Rc;
406 ///
407 /// let five = Rc::new(5);
408 /// ```
409 #[cfg(not(no_global_oom_handling))]
410 #[stable(feature = "rust1", since = "1.0.0")]
411 pub fn new(value: T) -> Rc<T> {
412 // There is an implicit weak pointer owned by all the strong
413 // pointers, which ensures that the weak destructor never frees
414 // the allocation while the strong destructor is running, even
415 // if the weak pointer is stored inside the strong one.
416 unsafe {
417 Self::from_inner(
418 Box::leak(Box::new(RcInner { strong: Cell::new(1), weak: Cell::new(1), value }))
419 .into(),
420 )
421 }
422 }
423
424 /// Constructs a new `Rc<T>` while giving you a `Weak<T>` to the allocation,
425 /// to allow you to construct a `T` which holds a weak pointer to itself.
426 ///
427 /// Generally, a structure circularly referencing itself, either directly or
428 /// indirectly, should not hold a strong reference to itself to prevent a memory leak.
429 /// Using this function, you get access to the weak pointer during the
430 /// initialization of `T`, before the `Rc<T>` is created, such that you can
431 /// clone and store it inside the `T`.
432 ///
433 /// `new_cyclic` first allocates the managed allocation for the `Rc<T>`,
434 /// then calls your closure, giving it a `Weak<T>` to this allocation,
435 /// and only afterwards completes the construction of the `Rc<T>` by placing
436 /// the `T` returned from your closure into the allocation.
437 ///
438 /// Since the new `Rc<T>` is not fully-constructed until `Rc<T>::new_cyclic`
439 /// returns, calling [`upgrade`] on the weak reference inside your closure will
440 /// fail and result in a `None` value.
441 ///
442 /// # Panics
443 ///
444 /// If `data_fn` panics, the panic is propagated to the caller, and the
445 /// temporary [`Weak<T>`] is dropped normally.
446 ///
447 /// # Examples
448 ///
449 /// ```
450 /// # #![allow(dead_code)]
451 /// use std::rc::{Rc, Weak};
452 ///
453 /// struct Gadget {
454 /// me: Weak<Gadget>,
455 /// }
456 ///
457 /// impl Gadget {
458 /// /// Constructs a reference counted Gadget.
459 /// fn new() -> Rc<Self> {
460 /// // `me` is a `Weak<Gadget>` pointing at the new allocation of the
461 /// // `Rc` we're constructing.
462 /// Rc::new_cyclic(|me| {
463 /// // Create the actual struct here.
464 /// Gadget { me: me.clone() }
465 /// })
466 /// }
467 ///
468 /// /// Returns a reference counted pointer to Self.
469 /// fn me(&self) -> Rc<Self> {
470 /// self.me.upgrade().unwrap()
471 /// }
472 /// }
473 /// ```
474 /// [`upgrade`]: Weak::upgrade
475 #[cfg(not(no_global_oom_handling))]
476 #[stable(feature = "arc_new_cyclic", since = "1.60.0")]
477 pub fn new_cyclic<F>(data_fn: F) -> Rc<T>
478 where
479 F: FnOnce(&Weak<T>) -> T,
480 {
481 Self::new_cyclic_in(data_fn, Global)
482 }
483
484 /// Constructs a new `Rc` with uninitialized contents.
485 ///
486 /// # Examples
487 ///
488 /// ```
489 /// use std::rc::Rc;
490 ///
491 /// let mut five = Rc::<u32>::new_uninit();
492 ///
493 /// // Deferred initialization:
494 /// Rc::get_mut(&mut five).unwrap().write(5);
495 ///
496 /// let five = unsafe { five.assume_init() };
497 ///
498 /// assert_eq!(*five, 5)
499 /// ```
500 #[cfg(not(no_global_oom_handling))]
501 #[stable(feature = "new_uninit", since = "1.82.0")]
502 #[must_use]
503 pub fn new_uninit() -> Rc<mem::MaybeUninit<T>> {
504 unsafe {
505 Rc::from_ptr(Rc::allocate_for_layout(
506 Layout::new::<T>(),
507 |layout| Global.allocate(layout),
508 <*mut u8>::cast,
509 ))
510 }
511 }
512
513 /// Constructs a new `Rc` with uninitialized contents, with the memory
514 /// being filled with `0` bytes.
515 ///
516 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and
517 /// incorrect usage of this method.
518 ///
519 /// # Examples
520 ///
521 /// ```
522 /// use std::rc::Rc;
523 ///
524 /// let zero = Rc::<u32>::new_zeroed();
525 /// let zero = unsafe { zero.assume_init() };
526 ///
527 /// assert_eq!(*zero, 0)
528 /// ```
529 ///
530 /// [zeroed]: mem::MaybeUninit::zeroed
531 #[cfg(not(no_global_oom_handling))]
532 #[stable(feature = "new_zeroed_alloc", since = "CURRENT_RUSTC_VERSION")]
533 #[must_use]
534 pub fn new_zeroed() -> Rc<mem::MaybeUninit<T>> {
535 unsafe {
536 Rc::from_ptr(Rc::allocate_for_layout(
537 Layout::new::<T>(),
538 |layout| Global.allocate_zeroed(layout),
539 <*mut u8>::cast,
540 ))
541 }
542 }
543
544 /// Constructs a new `Rc<T>`, returning an error if the allocation fails
545 ///
546 /// # Examples
547 ///
548 /// ```
549 /// #![feature(allocator_api)]
550 /// use std::rc::Rc;
551 ///
552 /// let five = Rc::try_new(5);
553 /// # Ok::<(), std::alloc::AllocError>(())
554 /// ```
555 #[unstable(feature = "allocator_api", issue = "32838")]
556 pub fn try_new(value: T) -> Result<Rc<T>, AllocError> {
557 // There is an implicit weak pointer owned by all the strong
558 // pointers, which ensures that the weak destructor never frees
559 // the allocation while the strong destructor is running, even
560 // if the weak pointer is stored inside the strong one.
561 unsafe {
562 Ok(Self::from_inner(
563 Box::leak(Box::try_new(RcInner {
564 strong: Cell::new(1),
565 weak: Cell::new(1),
566 value,
567 })?)
568 .into(),
569 ))
570 }
571 }
572
573 /// Constructs a new `Rc` with uninitialized contents, returning an error if the allocation fails
574 ///
575 /// # Examples
576 ///
577 /// ```
578 /// #![feature(allocator_api)]
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 pub fn try_new_uninit() -> Result<Rc<mem::MaybeUninit<T>>, AllocError> {
594 unsafe {
595 Ok(Rc::from_ptr(Rc::try_allocate_for_layout(
596 Layout::new::<T>(),
597 |layout| Global.allocate(layout),
598 <*mut u8>::cast,
599 )?))
600 }
601 }
602
603 /// Constructs a new `Rc` with uninitialized contents, with the memory
604 /// being filled with `0` bytes, returning an error if the allocation fails
605 ///
606 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and
607 /// incorrect usage of this method.
608 ///
609 /// # Examples
610 ///
611 /// ```
612 /// #![feature(allocator_api)]
613 ///
614 /// use std::rc::Rc;
615 ///
616 /// let zero = Rc::<u32>::try_new_zeroed()?;
617 /// let zero = unsafe { zero.assume_init() };
618 ///
619 /// assert_eq!(*zero, 0);
620 /// # Ok::<(), std::alloc::AllocError>(())
621 /// ```
622 ///
623 /// [zeroed]: mem::MaybeUninit::zeroed
624 #[unstable(feature = "allocator_api", issue = "32838")]
625 pub fn try_new_zeroed() -> Result<Rc<mem::MaybeUninit<T>>, AllocError> {
626 unsafe {
627 Ok(Rc::from_ptr(Rc::try_allocate_for_layout(
628 Layout::new::<T>(),
629 |layout| Global.allocate_zeroed(layout),
630 <*mut u8>::cast,
631 )?))
632 }
633 }
634 /// Constructs a new `Pin<Rc<T>>`. If `T` does not implement `Unpin`, then
635 /// `value` will be pinned in memory and unable to be moved.
636 #[cfg(not(no_global_oom_handling))]
637 #[stable(feature = "pin", since = "1.33.0")]
638 #[must_use]
639 pub fn pin(value: T) -> Pin<Rc<T>> {
640 unsafe { Pin::new_unchecked(Rc::new(value)) }
641 }
642}
643
644impl<T, A: Allocator> Rc<T, A> {
645 /// Constructs a new `Rc` in the provided allocator.
646 ///
647 /// # Examples
648 ///
649 /// ```
650 /// #![feature(allocator_api)]
651 /// use std::rc::Rc;
652 /// use std::alloc::System;
653 ///
654 /// let five = Rc::new_in(5, System);
655 /// ```
656 #[cfg(not(no_global_oom_handling))]
657 #[unstable(feature = "allocator_api", issue = "32838")]
658 #[inline]
659 pub fn new_in(value: T, alloc: A) -> Rc<T, A> {
660 // NOTE: Prefer match over unwrap_or_else since closure sometimes not inlineable.
661 // That would make code size bigger.
662 match Self::try_new_in(value, alloc) {
663 Ok(m) => m,
664 Err(_) => handle_alloc_error(Layout::new::<RcInner<T>>()),
665 }
666 }
667
668 /// Constructs a new `Rc` with uninitialized contents in the provided allocator.
669 ///
670 /// # Examples
671 ///
672 /// ```
673 /// #![feature(get_mut_unchecked)]
674 /// #![feature(allocator_api)]
675 ///
676 /// use std::rc::Rc;
677 /// use std::alloc::System;
678 ///
679 /// let mut five = Rc::<u32, _>::new_uninit_in(System);
680 ///
681 /// let five = unsafe {
682 /// // Deferred initialization:
683 /// Rc::get_mut_unchecked(&mut five).as_mut_ptr().write(5);
684 ///
685 /// five.assume_init()
686 /// };
687 ///
688 /// assert_eq!(*five, 5)
689 /// ```
690 #[cfg(not(no_global_oom_handling))]
691 #[unstable(feature = "allocator_api", issue = "32838")]
692 #[inline]
693 pub fn new_uninit_in(alloc: A) -> Rc<mem::MaybeUninit<T>, A> {
694 unsafe {
695 Rc::from_ptr_in(
696 Rc::allocate_for_layout(
697 Layout::new::<T>(),
698 |layout| alloc.allocate(layout),
699 <*mut u8>::cast,
700 ),
701 alloc,
702 )
703 }
704 }
705
706 /// Constructs a new `Rc` with uninitialized contents, with the memory
707 /// being filled with `0` bytes, in the provided allocator.
708 ///
709 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and
710 /// incorrect usage of this method.
711 ///
712 /// # Examples
713 ///
714 /// ```
715 /// #![feature(allocator_api)]
716 ///
717 /// use std::rc::Rc;
718 /// use std::alloc::System;
719 ///
720 /// let zero = Rc::<u32, _>::new_zeroed_in(System);
721 /// let zero = unsafe { zero.assume_init() };
722 ///
723 /// assert_eq!(*zero, 0)
724 /// ```
725 ///
726 /// [zeroed]: mem::MaybeUninit::zeroed
727 #[cfg(not(no_global_oom_handling))]
728 #[unstable(feature = "allocator_api", issue = "32838")]
729 #[inline]
730 pub fn new_zeroed_in(alloc: A) -> Rc<mem::MaybeUninit<T>, A> {
731 unsafe {
732 Rc::from_ptr_in(
733 Rc::allocate_for_layout(
734 Layout::new::<T>(),
735 |layout| alloc.allocate_zeroed(layout),
736 <*mut u8>::cast,
737 ),
738 alloc,
739 )
740 }
741 }
742
743 /// Constructs a new `Rc<T, A>` in the given allocator while giving you a `Weak<T, A>` to the allocation,
744 /// to allow you to construct a `T` which holds a weak pointer to itself.
745 ///
746 /// Generally, a structure circularly referencing itself, either directly or
747 /// indirectly, should not hold a strong reference to itself to prevent a memory leak.
748 /// Using this function, you get access to the weak pointer during the
749 /// initialization of `T`, before the `Rc<T, A>` is created, such that you can
750 /// clone and store it inside the `T`.
751 ///
752 /// `new_cyclic_in` first allocates the managed allocation for the `Rc<T, A>`,
753 /// then calls your closure, giving it a `Weak<T, A>` to this allocation,
754 /// and only afterwards completes the construction of the `Rc<T, A>` by placing
755 /// the `T` returned from your closure into the allocation.
756 ///
757 /// Since the new `Rc<T, A>` is not fully-constructed until `Rc<T, A>::new_cyclic_in`
758 /// returns, calling [`upgrade`] on the weak reference inside your closure will
759 /// fail and result in a `None` value.
760 ///
761 /// # Panics
762 ///
763 /// If `data_fn` panics, the panic is propagated to the caller, and the
764 /// temporary [`Weak<T, A>`] is dropped normally.
765 ///
766 /// # Examples
767 ///
768 /// See [`new_cyclic`].
769 ///
770 /// [`new_cyclic`]: Rc::new_cyclic
771 /// [`upgrade`]: Weak::upgrade
772 #[cfg(not(no_global_oom_handling))]
773 #[unstable(feature = "allocator_api", issue = "32838")]
774 pub fn new_cyclic_in<F>(data_fn: F, alloc: A) -> Rc<T, A>
775 where
776 F: FnOnce(&Weak<T, A>) -> T,
777 {
778 // Construct the inner in the "uninitialized" state with a single
779 // weak reference.
780 let (uninit_raw_ptr, alloc) = Box::into_raw_with_allocator(Box::new_in(
781 RcInner {
782 strong: Cell::new(0),
783 weak: Cell::new(1),
784 value: mem::MaybeUninit::<T>::uninit(),
785 },
786 alloc,
787 ));
788 let uninit_ptr: NonNull<_> = (unsafe { &mut *uninit_raw_ptr }).into();
789 let init_ptr: NonNull<RcInner<T>> = uninit_ptr.cast();
790
791 let weak = Weak { ptr: init_ptr, alloc };
792
793 // It's important we don't give up ownership of the weak pointer, or
794 // else the memory might be freed by the time `data_fn` returns. If
795 // we really wanted to pass ownership, we could create an additional
796 // weak pointer for ourselves, but this would result in additional
797 // updates to the weak reference count which might not be necessary
798 // otherwise.
799 let data = data_fn(&weak);
800
801 let strong = unsafe {
802 let inner = init_ptr.as_ptr();
803 ptr::write(&raw mut (*inner).value, data);
804
805 let prev_value = (*inner).strong.get();
806 debug_assert_eq!(prev_value, 0, "No prior strong references should exist");
807 (*inner).strong.set(1);
808
809 // Strong references should collectively own a shared weak reference,
810 // so don't run the destructor for our old weak reference.
811 // Calling into_raw_with_allocator has the double effect of giving us back the allocator,
812 // and forgetting the weak reference.
813 let alloc = weak.into_raw_with_allocator().1;
814
815 Rc::from_inner_in(init_ptr, alloc)
816 };
817
818 strong
819 }
820
821 /// Constructs a new `Rc<T>` in the provided allocator, returning an error if the allocation
822 /// fails
823 ///
824 /// # Examples
825 ///
826 /// ```
827 /// #![feature(allocator_api)]
828 /// use std::rc::Rc;
829 /// use std::alloc::System;
830 ///
831 /// let five = Rc::try_new_in(5, System);
832 /// # Ok::<(), std::alloc::AllocError>(())
833 /// ```
834 #[unstable(feature = "allocator_api", issue = "32838")]
835 #[inline]
836 pub fn try_new_in(value: T, alloc: A) -> Result<Self, AllocError> {
837 // There is an implicit weak pointer owned by all the strong
838 // pointers, which ensures that the weak destructor never frees
839 // the allocation while the strong destructor is running, even
840 // if the weak pointer is stored inside the strong one.
841 let (ptr, alloc) = Box::into_unique(Box::try_new_in(
842 RcInner { strong: Cell::new(1), weak: Cell::new(1), value },
843 alloc,
844 )?);
845 Ok(unsafe { Self::from_inner_in(ptr.into(), alloc) })
846 }
847
848 /// Constructs a new `Rc` with uninitialized contents, in the provided allocator, returning an
849 /// error if the allocation fails
850 ///
851 /// # Examples
852 ///
853 /// ```
854 /// #![feature(allocator_api)]
855 /// #![feature(get_mut_unchecked)]
856 ///
857 /// use std::rc::Rc;
858 /// use std::alloc::System;
859 ///
860 /// let mut five = Rc::<u32, _>::try_new_uninit_in(System)?;
861 ///
862 /// let five = unsafe {
863 /// // Deferred initialization:
864 /// Rc::get_mut_unchecked(&mut five).as_mut_ptr().write(5);
865 ///
866 /// five.assume_init()
867 /// };
868 ///
869 /// assert_eq!(*five, 5);
870 /// # Ok::<(), std::alloc::AllocError>(())
871 /// ```
872 #[unstable(feature = "allocator_api", issue = "32838")]
873 #[inline]
874 pub fn try_new_uninit_in(alloc: A) -> Result<Rc<mem::MaybeUninit<T>, A>, AllocError> {
875 unsafe {
876 Ok(Rc::from_ptr_in(
877 Rc::try_allocate_for_layout(
878 Layout::new::<T>(),
879 |layout| alloc.allocate(layout),
880 <*mut u8>::cast,
881 )?,
882 alloc,
883 ))
884 }
885 }
886
887 /// Constructs a new `Rc` with uninitialized contents, with the memory
888 /// being filled with `0` bytes, in the provided allocator, returning an error if the allocation
889 /// fails
890 ///
891 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and
892 /// incorrect usage of this method.
893 ///
894 /// # Examples
895 ///
896 /// ```
897 /// #![feature(allocator_api)]
898 ///
899 /// use std::rc::Rc;
900 /// use std::alloc::System;
901 ///
902 /// let zero = Rc::<u32, _>::try_new_zeroed_in(System)?;
903 /// let zero = unsafe { zero.assume_init() };
904 ///
905 /// assert_eq!(*zero, 0);
906 /// # Ok::<(), std::alloc::AllocError>(())
907 /// ```
908 ///
909 /// [zeroed]: mem::MaybeUninit::zeroed
910 #[unstable(feature = "allocator_api", issue = "32838")]
911 #[inline]
912 pub fn try_new_zeroed_in(alloc: A) -> Result<Rc<mem::MaybeUninit<T>, A>, AllocError> {
913 unsafe {
914 Ok(Rc::from_ptr_in(
915 Rc::try_allocate_for_layout(
916 Layout::new::<T>(),
917 |layout| alloc.allocate_zeroed(layout),
918 <*mut u8>::cast,
919 )?,
920 alloc,
921 ))
922 }
923 }
924
925 /// Constructs a new `Pin<Rc<T>>` in the provided allocator. If `T` does not implement `Unpin`, then
926 /// `value` will be pinned in memory and unable to be moved.
927 #[cfg(not(no_global_oom_handling))]
928 #[unstable(feature = "allocator_api", issue = "32838")]
929 #[inline]
930 pub fn pin_in(value: T, alloc: A) -> Pin<Self>
931 where
932 A: 'static,
933 {
934 unsafe { Pin::new_unchecked(Rc::new_in(value, alloc)) }
935 }
936
937 /// Returns the inner value, if the `Rc` has exactly one strong reference.
938 ///
939 /// Otherwise, an [`Err`] is returned with the same `Rc` that was
940 /// passed in.
941 ///
942 /// This will succeed even if there are outstanding weak references.
943 ///
944 /// # Examples
945 ///
946 /// ```
947 /// use std::rc::Rc;
948 ///
949 /// let x = Rc::new(3);
950 /// assert_eq!(Rc::try_unwrap(x), Ok(3));
951 ///
952 /// let x = Rc::new(4);
953 /// let _y = Rc::clone(&x);
954 /// assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4);
955 /// ```
956 #[inline]
957 #[stable(feature = "rc_unique", since = "1.4.0")]
958 pub fn try_unwrap(this: Self) -> Result<T, Self> {
959 if Rc::strong_count(&this) == 1 {
960 let this = ManuallyDrop::new(this);
961
962 let val: T = unsafe { ptr::read(&**this) }; // copy the contained object
963 let alloc: A = unsafe { ptr::read(&this.alloc) }; // copy the allocator
964
965 // Indicate to Weaks that they can't be promoted by decrementing
966 // the strong count, and then remove the implicit "strong weak"
967 // pointer while also handling drop logic by just crafting a
968 // fake Weak.
969 this.inner().dec_strong();
970 let _weak = Weak { ptr: this.ptr, alloc };
971 Ok(val)
972 } else {
973 Err(this)
974 }
975 }
976
977 /// Returns the inner value, if the `Rc` has exactly one strong reference.
978 ///
979 /// Otherwise, [`None`] is returned and the `Rc` is dropped.
980 ///
981 /// This will succeed even if there are outstanding weak references.
982 ///
983 /// If `Rc::into_inner` is called on every clone of this `Rc`,
984 /// it is guaranteed that exactly one of the calls returns the inner value.
985 /// This means in particular that the inner value is not dropped.
986 ///
987 /// [`Rc::try_unwrap`] is conceptually similar to `Rc::into_inner`.
988 /// And while they are meant for different use-cases, `Rc::into_inner(this)`
989 /// is in fact equivalent to <code>[Rc::try_unwrap]\(this).[ok][Result::ok]()</code>.
990 /// (Note that the same kind of equivalence does **not** hold true for
991 /// [`Arc`](crate::sync::Arc), due to race conditions that do not apply to `Rc`!)
992 ///
993 /// # Examples
994 ///
995 /// ```
996 /// use std::rc::Rc;
997 ///
998 /// let x = Rc::new(3);
999 /// assert_eq!(Rc::into_inner(x), Some(3));
1000 ///
1001 /// let x = Rc::new(4);
1002 /// let y = Rc::clone(&x);
1003 ///
1004 /// assert_eq!(Rc::into_inner(y), None);
1005 /// assert_eq!(Rc::into_inner(x), Some(4));
1006 /// ```
1007 #[inline]
1008 #[stable(feature = "rc_into_inner", since = "1.70.0")]
1009 pub fn into_inner(this: Self) -> Option<T> {
1010 Rc::try_unwrap(this).ok()
1011 }
1012}
1013
1014impl<T> Rc<[T]> {
1015 /// Constructs a new reference-counted slice with uninitialized contents.
1016 ///
1017 /// # Examples
1018 ///
1019 /// ```
1020 /// use std::rc::Rc;
1021 ///
1022 /// let mut values = Rc::<[u32]>::new_uninit_slice(3);
1023 ///
1024 /// // Deferred initialization:
1025 /// let data = Rc::get_mut(&mut values).unwrap();
1026 /// data[0].write(1);
1027 /// data[1].write(2);
1028 /// data[2].write(3);
1029 ///
1030 /// let values = unsafe { values.assume_init() };
1031 ///
1032 /// assert_eq!(*values, [1, 2, 3])
1033 /// ```
1034 #[cfg(not(no_global_oom_handling))]
1035 #[stable(feature = "new_uninit", since = "1.82.0")]
1036 #[must_use]
1037 pub fn new_uninit_slice(len: usize) -> Rc<[mem::MaybeUninit<T>]> {
1038 unsafe { Rc::from_ptr(Rc::allocate_for_slice(len)) }
1039 }
1040
1041 /// Constructs a new reference-counted slice with uninitialized contents, with the memory being
1042 /// filled with `0` bytes.
1043 ///
1044 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and
1045 /// incorrect usage of this method.
1046 ///
1047 /// # Examples
1048 ///
1049 /// ```
1050 /// use std::rc::Rc;
1051 ///
1052 /// let values = Rc::<[u32]>::new_zeroed_slice(3);
1053 /// let values = unsafe { values.assume_init() };
1054 ///
1055 /// assert_eq!(*values, [0, 0, 0])
1056 /// ```
1057 ///
1058 /// [zeroed]: mem::MaybeUninit::zeroed
1059 #[cfg(not(no_global_oom_handling))]
1060 #[stable(feature = "new_zeroed_alloc", since = "CURRENT_RUSTC_VERSION")]
1061 #[must_use]
1062 pub fn new_zeroed_slice(len: usize) -> Rc<[mem::MaybeUninit<T>]> {
1063 unsafe {
1064 Rc::from_ptr(Rc::allocate_for_layout(
1065 Layout::array::<T>(len).unwrap(),
1066 |layout| Global.allocate_zeroed(layout),
1067 |mem| {
1068 ptr::slice_from_raw_parts_mut(mem.cast::<T>(), len)
1069 as *mut RcInner<[mem::MaybeUninit<T>]>
1070 },
1071 ))
1072 }
1073 }
1074
1075 /// Converts the reference-counted slice into a reference-counted array.
1076 ///
1077 /// This operation does not reallocate; the underlying array of the slice is simply reinterpreted as an array type.
1078 ///
1079 /// If `N` is not exactly equal to the length of `self`, then this method returns `None`.
1080 #[unstable(feature = "slice_as_array", issue = "133508")]
1081 #[inline]
1082 #[must_use]
1083 pub fn into_array<const N: usize>(self) -> Option<Rc<[T; N]>> {
1084 if self.len() == N {
1085 let ptr = Self::into_raw(self) as *const [T; N];
1086
1087 // SAFETY: The underlying array of a slice has the exact same layout as an actual array `[T; N]` if `N` is equal to the slice's length.
1088 let me = unsafe { Rc::from_raw(ptr) };
1089 Some(me)
1090 } else {
1091 None
1092 }
1093 }
1094}
1095
1096impl<T, A: Allocator> Rc<[T], A> {
1097 /// Constructs a new reference-counted slice with uninitialized contents.
1098 ///
1099 /// # Examples
1100 ///
1101 /// ```
1102 /// #![feature(get_mut_unchecked)]
1103 /// #![feature(allocator_api)]
1104 ///
1105 /// use std::rc::Rc;
1106 /// use std::alloc::System;
1107 ///
1108 /// let mut values = Rc::<[u32], _>::new_uninit_slice_in(3, System);
1109 ///
1110 /// let values = unsafe {
1111 /// // Deferred initialization:
1112 /// Rc::get_mut_unchecked(&mut values)[0].as_mut_ptr().write(1);
1113 /// Rc::get_mut_unchecked(&mut values)[1].as_mut_ptr().write(2);
1114 /// Rc::get_mut_unchecked(&mut values)[2].as_mut_ptr().write(3);
1115 ///
1116 /// values.assume_init()
1117 /// };
1118 ///
1119 /// assert_eq!(*values, [1, 2, 3])
1120 /// ```
1121 #[cfg(not(no_global_oom_handling))]
1122 #[unstable(feature = "allocator_api", issue = "32838")]
1123 #[inline]
1124 pub fn new_uninit_slice_in(len: usize, alloc: A) -> Rc<[mem::MaybeUninit<T>], A> {
1125 unsafe { Rc::from_ptr_in(Rc::allocate_for_slice_in(len, &alloc), alloc) }
1126 }
1127
1128 /// Constructs a new reference-counted slice with uninitialized contents, with the memory being
1129 /// filled with `0` bytes.
1130 ///
1131 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and
1132 /// incorrect usage of this method.
1133 ///
1134 /// # Examples
1135 ///
1136 /// ```
1137 /// #![feature(allocator_api)]
1138 ///
1139 /// use std::rc::Rc;
1140 /// use std::alloc::System;
1141 ///
1142 /// let values = Rc::<[u32], _>::new_zeroed_slice_in(3, System);
1143 /// let values = unsafe { values.assume_init() };
1144 ///
1145 /// assert_eq!(*values, [0, 0, 0])
1146 /// ```
1147 ///
1148 /// [zeroed]: mem::MaybeUninit::zeroed
1149 #[cfg(not(no_global_oom_handling))]
1150 #[unstable(feature = "allocator_api", issue = "32838")]
1151 #[inline]
1152 pub fn new_zeroed_slice_in(len: usize, alloc: A) -> Rc<[mem::MaybeUninit<T>], A> {
1153 unsafe {
1154 Rc::from_ptr_in(
1155 Rc::allocate_for_layout(
1156 Layout::array::<T>(len).unwrap(),
1157 |layout| alloc.allocate_zeroed(layout),
1158 |mem| {
1159 ptr::slice_from_raw_parts_mut(mem.cast::<T>(), len)
1160 as *mut RcInner<[mem::MaybeUninit<T>]>
1161 },
1162 ),
1163 alloc,
1164 )
1165 }
1166 }
1167}
1168
1169impl<T, A: Allocator> Rc<mem::MaybeUninit<T>, A> {
1170 /// Converts to `Rc<T>`.
1171 ///
1172 /// # Safety
1173 ///
1174 /// As with [`MaybeUninit::assume_init`],
1175 /// it is up to the caller to guarantee that the inner value
1176 /// really is in an initialized state.
1177 /// Calling this when the content is not yet fully initialized
1178 /// causes immediate undefined behavior.
1179 ///
1180 /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
1181 ///
1182 /// # Examples
1183 ///
1184 /// ```
1185 /// use std::rc::Rc;
1186 ///
1187 /// let mut five = Rc::<u32>::new_uninit();
1188 ///
1189 /// // Deferred initialization:
1190 /// Rc::get_mut(&mut five).unwrap().write(5);
1191 ///
1192 /// let five = unsafe { five.assume_init() };
1193 ///
1194 /// assert_eq!(*five, 5)
1195 /// ```
1196 #[stable(feature = "new_uninit", since = "1.82.0")]
1197 #[inline]
1198 pub unsafe fn assume_init(self) -> Rc<T, A> {
1199 let (ptr, alloc) = Rc::into_inner_with_allocator(self);
1200 unsafe { Rc::from_inner_in(ptr.cast(), alloc) }
1201 }
1202}
1203
1204impl<T, A: Allocator> Rc<[mem::MaybeUninit<T>], A> {
1205 /// Converts to `Rc<[T]>`.
1206 ///
1207 /// # Safety
1208 ///
1209 /// As with [`MaybeUninit::assume_init`],
1210 /// it is up to the caller to guarantee that the inner value
1211 /// really is in an initialized state.
1212 /// Calling this when the content is not yet fully initialized
1213 /// causes immediate undefined behavior.
1214 ///
1215 /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
1216 ///
1217 /// # Examples
1218 ///
1219 /// ```
1220 /// use std::rc::Rc;
1221 ///
1222 /// let mut values = Rc::<[u32]>::new_uninit_slice(3);
1223 ///
1224 /// // Deferred initialization:
1225 /// let data = Rc::get_mut(&mut values).unwrap();
1226 /// data[0].write(1);
1227 /// data[1].write(2);
1228 /// data[2].write(3);
1229 ///
1230 /// let values = unsafe { values.assume_init() };
1231 ///
1232 /// assert_eq!(*values, [1, 2, 3])
1233 /// ```
1234 #[stable(feature = "new_uninit", since = "1.82.0")]
1235 #[inline]
1236 pub unsafe fn assume_init(self) -> Rc<[T], A> {
1237 let (ptr, alloc) = Rc::into_inner_with_allocator(self);
1238 unsafe { Rc::from_ptr_in(ptr.as_ptr() as _, alloc) }
1239 }
1240}
1241
1242impl<T: ?Sized> Rc<T> {
1243 /// Constructs an `Rc<T>` from a raw pointer.
1244 ///
1245 /// The raw pointer must have been previously returned by a call to
1246 /// [`Rc<U>::into_raw`][into_raw] with the following requirements:
1247 ///
1248 /// * If `U` is sized, it must have the same size and alignment as `T`. This
1249 /// is trivially true if `U` is `T`.
1250 /// * If `U` is unsized, its data pointer must have the same size and
1251 /// alignment as `T`. This is trivially true if `Rc<U>` was constructed
1252 /// through `Rc<T>` and then converted to `Rc<U>` through an [unsized
1253 /// coercion].
1254 ///
1255 /// Note that if `U` or `U`'s data pointer is not `T` but has the same size
1256 /// and alignment, this is basically like transmuting references of
1257 /// different types. See [`mem::transmute`][transmute] for more information
1258 /// on what restrictions apply in this case.
1259 ///
1260 /// The raw pointer must point to a block of memory allocated by the global allocator
1261 ///
1262 /// The user of `from_raw` has to make sure a specific value of `T` is only
1263 /// dropped once.
1264 ///
1265 /// This function is unsafe because improper use may lead to memory unsafety,
1266 /// even if the returned `Rc<T>` is never accessed.
1267 ///
1268 /// [into_raw]: Rc::into_raw
1269 /// [transmute]: core::mem::transmute
1270 /// [unsized coercion]: https://doc.rust-lang.org/reference/type-coercions.html#unsized-coercions
1271 ///
1272 /// # Examples
1273 ///
1274 /// ```
1275 /// use std::rc::Rc;
1276 ///
1277 /// let x = Rc::new("hello".to_owned());
1278 /// let x_ptr = Rc::into_raw(x);
1279 ///
1280 /// unsafe {
1281 /// // Convert back to an `Rc` to prevent leak.
1282 /// let x = Rc::from_raw(x_ptr);
1283 /// assert_eq!(&*x, "hello");
1284 ///
1285 /// // Further calls to `Rc::from_raw(x_ptr)` would be memory-unsafe.
1286 /// }
1287 ///
1288 /// // The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling!
1289 /// ```
1290 ///
1291 /// Convert a slice back into its original array:
1292 ///
1293 /// ```
1294 /// use std::rc::Rc;
1295 ///
1296 /// let x: Rc<[u32]> = Rc::new([1, 2, 3]);
1297 /// let x_ptr: *const [u32] = Rc::into_raw(x);
1298 ///
1299 /// unsafe {
1300 /// let x: Rc<[u32; 3]> = Rc::from_raw(x_ptr.cast::<[u32; 3]>());
1301 /// assert_eq!(&*x, &[1, 2, 3]);
1302 /// }
1303 /// ```
1304 #[inline]
1305 #[stable(feature = "rc_raw", since = "1.17.0")]
1306 pub unsafe fn from_raw(ptr: *const T) -> Self {
1307 unsafe { Self::from_raw_in(ptr, Global) }
1308 }
1309
1310 /// Consumes the `Rc`, returning the wrapped pointer.
1311 ///
1312 /// To avoid a memory leak the pointer must be converted back to an `Rc` using
1313 /// [`Rc::from_raw`].
1314 ///
1315 /// # Examples
1316 ///
1317 /// ```
1318 /// use std::rc::Rc;
1319 ///
1320 /// let x = Rc::new("hello".to_owned());
1321 /// let x_ptr = Rc::into_raw(x);
1322 /// assert_eq!(unsafe { &*x_ptr }, "hello");
1323 /// # // Prevent leaks for Miri.
1324 /// # drop(unsafe { Rc::from_raw(x_ptr) });
1325 /// ```
1326 #[must_use = "losing the pointer will leak memory"]
1327 #[stable(feature = "rc_raw", since = "1.17.0")]
1328 #[rustc_never_returns_null_ptr]
1329 pub fn into_raw(this: Self) -> *const T {
1330 let this = ManuallyDrop::new(this);
1331 Self::as_ptr(&*this)
1332 }
1333
1334 /// Increments the strong reference count on the `Rc<T>` associated with the
1335 /// provided pointer by one.
1336 ///
1337 /// # Safety
1338 ///
1339 /// The pointer must have been obtained through `Rc::into_raw` and must satisfy the
1340 /// same layout requirements specified in [`Rc::from_raw_in`][from_raw_in].
1341 /// The associated `Rc` instance must be valid (i.e. the strong count must be at
1342 /// least 1) for the duration of this method, and `ptr` must point to a block of memory
1343 /// allocated by the global allocator.
1344 ///
1345 /// [from_raw_in]: Rc::from_raw_in
1346 ///
1347 /// # Examples
1348 ///
1349 /// ```
1350 /// use std::rc::Rc;
1351 ///
1352 /// let five = Rc::new(5);
1353 ///
1354 /// unsafe {
1355 /// let ptr = Rc::into_raw(five);
1356 /// Rc::increment_strong_count(ptr);
1357 ///
1358 /// let five = Rc::from_raw(ptr);
1359 /// assert_eq!(2, Rc::strong_count(&five));
1360 /// # // Prevent leaks for Miri.
1361 /// # Rc::decrement_strong_count(ptr);
1362 /// }
1363 /// ```
1364 #[inline]
1365 #[stable(feature = "rc_mutate_strong_count", since = "1.53.0")]
1366 pub unsafe fn increment_strong_count(ptr: *const T) {
1367 unsafe { Self::increment_strong_count_in(ptr, Global) }
1368 }
1369
1370 /// Decrements the strong reference count on the `Rc<T>` associated with the
1371 /// provided pointer by one.
1372 ///
1373 /// # Safety
1374 ///
1375 /// The pointer must have been obtained through `Rc::into_raw`and must satisfy the
1376 /// same layout requirements specified in [`Rc::from_raw_in`][from_raw_in].
1377 /// The associated `Rc` instance must be valid (i.e. the strong count must be at
1378 /// least 1) when invoking this method, and `ptr` must point to a block of memory
1379 /// allocated by the global allocator. This method can be used to release the final `Rc` and
1380 /// backing storage, but **should not** be called after the final `Rc` has been released.
1381 ///
1382 /// [from_raw_in]: Rc::from_raw_in
1383 ///
1384 /// # Examples
1385 ///
1386 /// ```
1387 /// use std::rc::Rc;
1388 ///
1389 /// let five = Rc::new(5);
1390 ///
1391 /// unsafe {
1392 /// let ptr = Rc::into_raw(five);
1393 /// Rc::increment_strong_count(ptr);
1394 ///
1395 /// let five = Rc::from_raw(ptr);
1396 /// assert_eq!(2, Rc::strong_count(&five));
1397 /// Rc::decrement_strong_count(ptr);
1398 /// assert_eq!(1, Rc::strong_count(&five));
1399 /// }
1400 /// ```
1401 #[inline]
1402 #[stable(feature = "rc_mutate_strong_count", since = "1.53.0")]
1403 pub unsafe fn decrement_strong_count(ptr: *const T) {
1404 unsafe { Self::decrement_strong_count_in(ptr, Global) }
1405 }
1406}
1407
1408impl<T: ?Sized, A: Allocator> Rc<T, A> {
1409 /// Returns a reference to the underlying allocator.
1410 ///
1411 /// Note: this is an associated function, which means that you have
1412 /// to call it as `Rc::allocator(&r)` instead of `r.allocator()`. This
1413 /// is so that there is no conflict with a method on the inner type.
1414 #[inline]
1415 #[unstable(feature = "allocator_api", issue = "32838")]
1416 pub fn allocator(this: &Self) -> &A {
1417 &this.alloc
1418 }
1419
1420 /// Consumes the `Rc`, returning the wrapped pointer and allocator.
1421 ///
1422 /// To avoid a memory leak the pointer must be converted back to an `Rc` using
1423 /// [`Rc::from_raw_in`].
1424 ///
1425 /// # Examples
1426 ///
1427 /// ```
1428 /// #![feature(allocator_api)]
1429 /// use std::rc::Rc;
1430 /// use std::alloc::System;
1431 ///
1432 /// let x = Rc::new_in("hello".to_owned(), System);
1433 /// let (ptr, alloc) = Rc::into_raw_with_allocator(x);
1434 /// assert_eq!(unsafe { &*ptr }, "hello");
1435 /// let x = unsafe { Rc::from_raw_in(ptr, alloc) };
1436 /// assert_eq!(&*x, "hello");
1437 /// ```
1438 #[must_use = "losing the pointer will leak memory"]
1439 #[unstable(feature = "allocator_api", issue = "32838")]
1440 pub fn into_raw_with_allocator(this: Self) -> (*const T, A) {
1441 let this = mem::ManuallyDrop::new(this);
1442 let ptr = Self::as_ptr(&this);
1443 // Safety: `this` is ManuallyDrop so the allocator will not be double-dropped
1444 let alloc = unsafe { ptr::read(&this.alloc) };
1445 (ptr, alloc)
1446 }
1447
1448 /// Provides a raw pointer to the data.
1449 ///
1450 /// The counts are not affected in any way and the `Rc` is not consumed. The pointer is valid
1451 /// for as long as there are strong counts in the `Rc`.
1452 ///
1453 /// # Examples
1454 ///
1455 /// ```
1456 /// use std::rc::Rc;
1457 ///
1458 /// let x = Rc::new(0);
1459 /// let y = Rc::clone(&x);
1460 /// let x_ptr = Rc::as_ptr(&x);
1461 /// assert_eq!(x_ptr, Rc::as_ptr(&y));
1462 /// assert_eq!(unsafe { *x_ptr }, 0);
1463 /// ```
1464 #[stable(feature = "weak_into_raw", since = "1.45.0")]
1465 #[rustc_never_returns_null_ptr]
1466 pub fn as_ptr(this: &Self) -> *const T {
1467 let ptr: *mut RcInner<T> = NonNull::as_ptr(this.ptr);
1468
1469 // SAFETY: This cannot go through Deref::deref or Rc::inner because
1470 // this is required to retain raw/mut provenance such that e.g. `get_mut` can
1471 // write through the pointer after the Rc is recovered through `from_raw`.
1472 unsafe { &raw mut (*ptr).value }
1473 }
1474
1475 /// Constructs an `Rc<T, A>` from a raw pointer in the provided allocator.
1476 ///
1477 /// The raw pointer must have been previously returned by a call to [`Rc<U,
1478 /// A>::into_raw`][into_raw] with the following requirements:
1479 ///
1480 /// * If `U` is sized, it must have the same size and alignment as `T`. This
1481 /// is trivially true if `U` is `T`.
1482 /// * If `U` is unsized, its data pointer must have the same size and
1483 /// alignment as `T`. This is trivially true if `Rc<U>` was constructed
1484 /// through `Rc<T>` and then converted to `Rc<U>` through an [unsized
1485 /// coercion].
1486 ///
1487 /// Note that if `U` or `U`'s data pointer is not `T` but has the same size
1488 /// and alignment, this is basically like transmuting references of
1489 /// different types. See [`mem::transmute`][transmute] for more information
1490 /// on what restrictions apply in this case.
1491 ///
1492 /// The raw pointer must point to a block of memory allocated by `alloc`
1493 ///
1494 /// The user of `from_raw` has to make sure a specific value of `T` is only
1495 /// dropped once.
1496 ///
1497 /// This function is unsafe because improper use may lead to memory unsafety,
1498 /// even if the returned `Rc<T>` is never accessed.
1499 ///
1500 /// [into_raw]: Rc::into_raw
1501 /// [transmute]: core::mem::transmute
1502 /// [unsized coercion]: https://doc.rust-lang.org/reference/type-coercions.html#unsized-coercions
1503 ///
1504 /// # Examples
1505 ///
1506 /// ```
1507 /// #![feature(allocator_api)]
1508 ///
1509 /// use std::rc::Rc;
1510 /// use std::alloc::System;
1511 ///
1512 /// let x = Rc::new_in("hello".to_owned(), System);
1513 /// let (x_ptr, _alloc) = Rc::into_raw_with_allocator(x);
1514 ///
1515 /// unsafe {
1516 /// // Convert back to an `Rc` to prevent leak.
1517 /// let x = Rc::from_raw_in(x_ptr, System);
1518 /// assert_eq!(&*x, "hello");
1519 ///
1520 /// // Further calls to `Rc::from_raw(x_ptr)` would be memory-unsafe.
1521 /// }
1522 ///
1523 /// // The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling!
1524 /// ```
1525 ///
1526 /// Convert a slice back into its original array:
1527 ///
1528 /// ```
1529 /// #![feature(allocator_api)]
1530 ///
1531 /// use std::rc::Rc;
1532 /// use std::alloc::System;
1533 ///
1534 /// let x: Rc<[u32], _> = Rc::new_in([1, 2, 3], System);
1535 /// let x_ptr: *const [u32] = Rc::into_raw_with_allocator(x).0;
1536 ///
1537 /// unsafe {
1538 /// let x: Rc<[u32; 3], _> = Rc::from_raw_in(x_ptr.cast::<[u32; 3]>(), System);
1539 /// assert_eq!(&*x, &[1, 2, 3]);
1540 /// }
1541 /// ```
1542 #[unstable(feature = "allocator_api", issue = "32838")]
1543 pub unsafe fn from_raw_in(ptr: *const T, alloc: A) -> Self {
1544 let offset = unsafe { data_offset(ptr) };
1545
1546 // Reverse the offset to find the original RcInner.
1547 let rc_ptr = unsafe { ptr.byte_sub(offset) as *mut RcInner<T> };
1548
1549 unsafe { Self::from_ptr_in(rc_ptr, alloc) }
1550 }
1551
1552 /// Creates a new [`Weak`] pointer to this allocation.
1553 ///
1554 /// # Examples
1555 ///
1556 /// ```
1557 /// use std::rc::Rc;
1558 ///
1559 /// let five = Rc::new(5);
1560 ///
1561 /// let weak_five = Rc::downgrade(&five);
1562 /// ```
1563 #[must_use = "this returns a new `Weak` pointer, \
1564 without modifying the original `Rc`"]
1565 #[stable(feature = "rc_weak", since = "1.4.0")]
1566 pub fn downgrade(this: &Self) -> Weak<T, A>
1567 where
1568 A: Clone,
1569 {
1570 this.inner().inc_weak();
1571 // Make sure we do not create a dangling Weak
1572 debug_assert!(!is_dangling(this.ptr.as_ptr()));
1573 Weak { ptr: this.ptr, alloc: this.alloc.clone() }
1574 }
1575
1576 /// Gets the number of [`Weak`] pointers to this allocation.
1577 ///
1578 /// # Examples
1579 ///
1580 /// ```
1581 /// use std::rc::Rc;
1582 ///
1583 /// let five = Rc::new(5);
1584 /// let _weak_five = Rc::downgrade(&five);
1585 ///
1586 /// assert_eq!(1, Rc::weak_count(&five));
1587 /// ```
1588 #[inline]
1589 #[stable(feature = "rc_counts", since = "1.15.0")]
1590 pub fn weak_count(this: &Self) -> usize {
1591 this.inner().weak() - 1
1592 }
1593
1594 /// Gets the number of strong (`Rc`) pointers to this allocation.
1595 ///
1596 /// # Examples
1597 ///
1598 /// ```
1599 /// use std::rc::Rc;
1600 ///
1601 /// let five = Rc::new(5);
1602 /// let _also_five = Rc::clone(&five);
1603 ///
1604 /// assert_eq!(2, Rc::strong_count(&five));
1605 /// ```
1606 #[inline]
1607 #[stable(feature = "rc_counts", since = "1.15.0")]
1608 pub fn strong_count(this: &Self) -> usize {
1609 this.inner().strong()
1610 }
1611
1612 /// Increments the strong reference count on the `Rc<T>` associated with the
1613 /// provided pointer by one.
1614 ///
1615 /// # Safety
1616 ///
1617 /// The pointer must have been obtained through `Rc::into_raw` and must satisfy the
1618 /// same layout requirements specified in [`Rc::from_raw_in`][from_raw_in].
1619 /// The associated `Rc` instance must be valid (i.e. the strong count must be at
1620 /// least 1) for the duration of this method, and `ptr` must point to a block of memory
1621 /// allocated by `alloc`.
1622 ///
1623 /// [from_raw_in]: Rc::from_raw_in
1624 ///
1625 /// # Examples
1626 ///
1627 /// ```
1628 /// #![feature(allocator_api)]
1629 ///
1630 /// use std::rc::Rc;
1631 /// use std::alloc::System;
1632 ///
1633 /// let five = Rc::new_in(5, System);
1634 ///
1635 /// unsafe {
1636 /// let (ptr, _alloc) = Rc::into_raw_with_allocator(five);
1637 /// Rc::increment_strong_count_in(ptr, System);
1638 ///
1639 /// let five = Rc::from_raw_in(ptr, System);
1640 /// assert_eq!(2, Rc::strong_count(&five));
1641 /// # // Prevent leaks for Miri.
1642 /// # Rc::decrement_strong_count_in(ptr, System);
1643 /// }
1644 /// ```
1645 #[inline]
1646 #[unstable(feature = "allocator_api", issue = "32838")]
1647 pub unsafe fn increment_strong_count_in(ptr: *const T, alloc: A)
1648 where
1649 A: Clone,
1650 {
1651 // Retain Rc, but don't touch refcount by wrapping in ManuallyDrop
1652 let rc = unsafe { mem::ManuallyDrop::new(Rc::<T, A>::from_raw_in(ptr, alloc)) };
1653 // Now increase refcount, but don't drop new refcount either
1654 let _rc_clone: mem::ManuallyDrop<_> = rc.clone();
1655 }
1656
1657 /// Decrements the strong reference count on the `Rc<T>` associated with the
1658 /// provided pointer by one.
1659 ///
1660 /// # Safety
1661 ///
1662 /// The pointer must have been obtained through `Rc::into_raw`and must satisfy the
1663 /// same layout requirements specified in [`Rc::from_raw_in`][from_raw_in].
1664 /// The associated `Rc` instance must be valid (i.e. the strong count must be at
1665 /// least 1) when invoking this method, and `ptr` must point to a block of memory
1666 /// allocated by `alloc`. This method can be used to release the final `Rc` and
1667 /// backing storage, but **should not** be called after the final `Rc` has been released.
1668 ///
1669 /// [from_raw_in]: Rc::from_raw_in
1670 ///
1671 /// # Examples
1672 ///
1673 /// ```
1674 /// #![feature(allocator_api)]
1675 ///
1676 /// use std::rc::Rc;
1677 /// use std::alloc::System;
1678 ///
1679 /// let five = Rc::new_in(5, System);
1680 ///
1681 /// unsafe {
1682 /// let (ptr, _alloc) = Rc::into_raw_with_allocator(five);
1683 /// Rc::increment_strong_count_in(ptr, System);
1684 ///
1685 /// let five = Rc::from_raw_in(ptr, System);
1686 /// assert_eq!(2, Rc::strong_count(&five));
1687 /// Rc::decrement_strong_count_in(ptr, System);
1688 /// assert_eq!(1, Rc::strong_count(&five));
1689 /// }
1690 /// ```
1691 #[inline]
1692 #[unstable(feature = "allocator_api", issue = "32838")]
1693 pub unsafe fn decrement_strong_count_in(ptr: *const T, alloc: A) {
1694 unsafe { drop(Rc::from_raw_in(ptr, alloc)) };
1695 }
1696
1697 /// Returns `true` if there are no other `Rc` or [`Weak`] pointers to
1698 /// this allocation.
1699 #[inline]
1700 fn is_unique(this: &Self) -> bool {
1701 Rc::weak_count(this) == 0 && Rc::strong_count(this) == 1
1702 }
1703
1704 /// Returns a mutable reference into the given `Rc`, if there are
1705 /// no other `Rc` or [`Weak`] pointers to the same allocation.
1706 ///
1707 /// Returns [`None`] otherwise, because it is not safe to
1708 /// mutate a shared value.
1709 ///
1710 /// See also [`make_mut`][make_mut], which will [`clone`][clone]
1711 /// the inner value when there are other `Rc` pointers.
1712 ///
1713 /// [make_mut]: Rc::make_mut
1714 /// [clone]: Clone::clone
1715 ///
1716 /// # Examples
1717 ///
1718 /// ```
1719 /// use std::rc::Rc;
1720 ///
1721 /// let mut x = Rc::new(3);
1722 /// *Rc::get_mut(&mut x).unwrap() = 4;
1723 /// assert_eq!(*x, 4);
1724 ///
1725 /// let _y = Rc::clone(&x);
1726 /// assert!(Rc::get_mut(&mut x).is_none());
1727 /// ```
1728 #[inline]
1729 #[stable(feature = "rc_unique", since = "1.4.0")]
1730 pub fn get_mut(this: &mut Self) -> Option<&mut T> {
1731 if Rc::is_unique(this) { unsafe { Some(Rc::get_mut_unchecked(this)) } } else { None }
1732 }
1733
1734 /// Returns a mutable reference into the given `Rc`,
1735 /// without any check.
1736 ///
1737 /// See also [`get_mut`], which is safe and does appropriate checks.
1738 ///
1739 /// [`get_mut`]: Rc::get_mut
1740 ///
1741 /// # Safety
1742 ///
1743 /// If any other `Rc` or [`Weak`] pointers to the same allocation exist, then
1744 /// they must not be dereferenced or have active borrows for the duration
1745 /// of the returned borrow, and their inner type must be exactly the same as the
1746 /// inner type of this Rc (including lifetimes). This is trivially the case if no
1747 /// such pointers exist, for example immediately after `Rc::new`.
1748 ///
1749 /// # Examples
1750 ///
1751 /// ```
1752 /// #![feature(get_mut_unchecked)]
1753 ///
1754 /// use std::rc::Rc;
1755 ///
1756 /// let mut x = Rc::new(String::new());
1757 /// unsafe {
1758 /// Rc::get_mut_unchecked(&mut x).push_str("foo")
1759 /// }
1760 /// assert_eq!(*x, "foo");
1761 /// ```
1762 /// Other `Rc` pointers to the same allocation must be to the same type.
1763 /// ```no_run
1764 /// #![feature(get_mut_unchecked)]
1765 ///
1766 /// use std::rc::Rc;
1767 ///
1768 /// let x: Rc<str> = Rc::from("Hello, world!");
1769 /// let mut y: Rc<[u8]> = x.clone().into();
1770 /// unsafe {
1771 /// // this is Undefined Behavior, because x's inner type is str, not [u8]
1772 /// Rc::get_mut_unchecked(&mut y).fill(0xff); // 0xff is invalid in UTF-8
1773 /// }
1774 /// println!("{}", &*x); // Invalid UTF-8 in a str
1775 /// ```
1776 /// Other `Rc` pointers to the same allocation must be to the exact same type, including lifetimes.
1777 /// ```no_run
1778 /// #![feature(get_mut_unchecked)]
1779 ///
1780 /// use std::rc::Rc;
1781 ///
1782 /// let x: Rc<&str> = Rc::new("Hello, world!");
1783 /// {
1784 /// let s = String::from("Oh, no!");
1785 /// let mut y: Rc<&str> = x.clone();
1786 /// unsafe {
1787 /// // this is Undefined Behavior, because x's inner type
1788 /// // is &'long str, not &'short str
1789 /// *Rc::get_mut_unchecked(&mut y) = &s;
1790 /// }
1791 /// }
1792 /// println!("{}", &*x); // Use-after-free
1793 /// ```
1794 #[inline]
1795 #[unstable(feature = "get_mut_unchecked", issue = "63292")]
1796 pub unsafe fn get_mut_unchecked(this: &mut Self) -> &mut T {
1797 // We are careful to *not* create a reference covering the "count" fields, as
1798 // this would conflict with accesses to the reference counts (e.g. by `Weak`).
1799 unsafe { &mut (*this.ptr.as_ptr()).value }
1800 }
1801
1802 #[inline]
1803 #[stable(feature = "ptr_eq", since = "1.17.0")]
1804 /// Returns `true` if the two `Rc`s point to the same allocation in a vein similar to
1805 /// [`ptr::eq`]. This function ignores the metadata of `dyn Trait` pointers.
1806 ///
1807 /// # Examples
1808 ///
1809 /// ```
1810 /// use std::rc::Rc;
1811 ///
1812 /// let five = Rc::new(5);
1813 /// let same_five = Rc::clone(&five);
1814 /// let other_five = Rc::new(5);
1815 ///
1816 /// assert!(Rc::ptr_eq(&five, &same_five));
1817 /// assert!(!Rc::ptr_eq(&five, &other_five));
1818 /// ```
1819 pub fn ptr_eq(this: &Self, other: &Self) -> bool {
1820 ptr::addr_eq(this.ptr.as_ptr(), other.ptr.as_ptr())
1821 }
1822}
1823
1824#[cfg(not(no_global_oom_handling))]
1825impl<T: ?Sized + CloneToUninit, A: Allocator + Clone> Rc<T, A> {
1826 /// Makes a mutable reference into the given `Rc`.
1827 ///
1828 /// If there are other `Rc` pointers to the same allocation, then `make_mut` will
1829 /// [`clone`] the inner value to a new allocation to ensure unique ownership. This is also
1830 /// referred to as clone-on-write.
1831 ///
1832 /// However, if there are no other `Rc` pointers to this allocation, but some [`Weak`]
1833 /// pointers, then the [`Weak`] pointers will be disassociated and the inner value will not
1834 /// be cloned.
1835 ///
1836 /// See also [`get_mut`], which will fail rather than cloning the inner value
1837 /// or disassociating [`Weak`] pointers.
1838 ///
1839 /// [`clone`]: Clone::clone
1840 /// [`get_mut`]: Rc::get_mut
1841 ///
1842 /// # Examples
1843 ///
1844 /// ```
1845 /// use std::rc::Rc;
1846 ///
1847 /// let mut data = Rc::new(5);
1848 ///
1849 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
1850 /// let mut other_data = Rc::clone(&data); // Won't clone inner data
1851 /// *Rc::make_mut(&mut data) += 1; // Clones inner data
1852 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
1853 /// *Rc::make_mut(&mut other_data) *= 2; // Won't clone anything
1854 ///
1855 /// // Now `data` and `other_data` point to different allocations.
1856 /// assert_eq!(*data, 8);
1857 /// assert_eq!(*other_data, 12);
1858 /// ```
1859 ///
1860 /// [`Weak`] pointers will be disassociated:
1861 ///
1862 /// ```
1863 /// use std::rc::Rc;
1864 ///
1865 /// let mut data = Rc::new(75);
1866 /// let weak = Rc::downgrade(&data);
1867 ///
1868 /// assert!(75 == *data);
1869 /// assert!(75 == *weak.upgrade().unwrap());
1870 ///
1871 /// *Rc::make_mut(&mut data) += 1;
1872 ///
1873 /// assert!(76 == *data);
1874 /// assert!(weak.upgrade().is_none());
1875 /// ```
1876 #[inline]
1877 #[stable(feature = "rc_unique", since = "1.4.0")]
1878 pub fn make_mut(this: &mut Self) -> &mut T {
1879 let size_of_val = size_of_val::<T>(&**this);
1880
1881 if Rc::strong_count(this) != 1 {
1882 // Gotta clone the data, there are other Rcs.
1883
1884 let this_data_ref: &T = &**this;
1885 // `in_progress` drops the allocation if we panic before finishing initializing it.
1886 let mut in_progress: UniqueRcUninit<T, A> =
1887 UniqueRcUninit::new(this_data_ref, this.alloc.clone());
1888
1889 // Initialize with clone of this.
1890 let initialized_clone = unsafe {
1891 // Clone. If the clone panics, `in_progress` will be dropped and clean up.
1892 this_data_ref.clone_to_uninit(in_progress.data_ptr().cast());
1893 // Cast type of pointer, now that it is initialized.
1894 in_progress.into_rc()
1895 };
1896
1897 // Replace `this` with newly constructed Rc.
1898 *this = initialized_clone;
1899 } else if Rc::weak_count(this) != 0 {
1900 // Can just steal the data, all that's left is Weaks
1901
1902 // We don't need panic-protection like the above branch does, but we might as well
1903 // use the same mechanism.
1904 let mut in_progress: UniqueRcUninit<T, A> =
1905 UniqueRcUninit::new(&**this, this.alloc.clone());
1906 unsafe {
1907 // Initialize `in_progress` with move of **this.
1908 // We have to express this in terms of bytes because `T: ?Sized`; there is no
1909 // operation that just copies a value based on its `size_of_val()`.
1910 ptr::copy_nonoverlapping(
1911 ptr::from_ref(&**this).cast::<u8>(),
1912 in_progress.data_ptr().cast::<u8>(),
1913 size_of_val,
1914 );
1915
1916 this.inner().dec_strong();
1917 // Remove implicit strong-weak ref (no need to craft a fake
1918 // Weak here -- we know other Weaks can clean up for us)
1919 this.inner().dec_weak();
1920 // Replace `this` with newly constructed Rc that has the moved data.
1921 ptr::write(this, in_progress.into_rc());
1922 }
1923 }
1924 // This unsafety is ok because we're guaranteed that the pointer
1925 // returned is the *only* pointer that will ever be returned to T. Our
1926 // reference count is guaranteed to be 1 at this point, and we required
1927 // the `Rc<T>` itself to be `mut`, so we're returning the only possible
1928 // reference to the allocation.
1929 unsafe { &mut this.ptr.as_mut().value }
1930 }
1931}
1932
1933impl<T: Clone, A: Allocator> Rc<T, A> {
1934 /// If we have the only reference to `T` then unwrap it. Otherwise, clone `T` and return the
1935 /// clone.
1936 ///
1937 /// Assuming `rc_t` is of type `Rc<T>`, this function is functionally equivalent to
1938 /// `(*rc_t).clone()`, but will avoid cloning the inner value where possible.
1939 ///
1940 /// # Examples
1941 ///
1942 /// ```
1943 /// # use std::{ptr, rc::Rc};
1944 /// let inner = String::from("test");
1945 /// let ptr = inner.as_ptr();
1946 ///
1947 /// let rc = Rc::new(inner);
1948 /// let inner = Rc::unwrap_or_clone(rc);
1949 /// // The inner value was not cloned
1950 /// assert!(ptr::eq(ptr, inner.as_ptr()));
1951 ///
1952 /// let rc = Rc::new(inner);
1953 /// let rc2 = rc.clone();
1954 /// let inner = Rc::unwrap_or_clone(rc);
1955 /// // Because there were 2 references, we had to clone the inner value.
1956 /// assert!(!ptr::eq(ptr, inner.as_ptr()));
1957 /// // `rc2` is the last reference, so when we unwrap it we get back
1958 /// // the original `String`.
1959 /// let inner = Rc::unwrap_or_clone(rc2);
1960 /// assert!(ptr::eq(ptr, inner.as_ptr()));
1961 /// ```
1962 #[inline]
1963 #[stable(feature = "arc_unwrap_or_clone", since = "1.76.0")]
1964 pub fn unwrap_or_clone(this: Self) -> T {
1965 Rc::try_unwrap(this).unwrap_or_else(|rc| (*rc).clone())
1966 }
1967}
1968
1969impl<A: Allocator> Rc<dyn Any, A> {
1970 /// Attempts to downcast the `Rc<dyn Any>` to a concrete type.
1971 ///
1972 /// # Examples
1973 ///
1974 /// ```
1975 /// use std::any::Any;
1976 /// use std::rc::Rc;
1977 ///
1978 /// fn print_if_string(value: Rc<dyn Any>) {
1979 /// if let Ok(string) = value.downcast::<String>() {
1980 /// println!("String ({}): {}", string.len(), string);
1981 /// }
1982 /// }
1983 ///
1984 /// let my_string = "Hello World".to_string();
1985 /// print_if_string(Rc::new(my_string));
1986 /// print_if_string(Rc::new(0i8));
1987 /// ```
1988 #[inline]
1989 #[stable(feature = "rc_downcast", since = "1.29.0")]
1990 pub fn downcast<T: Any>(self) -> Result<Rc<T, A>, Self> {
1991 if (*self).is::<T>() {
1992 unsafe {
1993 let (ptr, alloc) = Rc::into_inner_with_allocator(self);
1994 Ok(Rc::from_inner_in(ptr.cast(), alloc))
1995 }
1996 } else {
1997 Err(self)
1998 }
1999 }
2000
2001 /// Downcasts the `Rc<dyn Any>` to a concrete type.
2002 ///
2003 /// For a safe alternative see [`downcast`].
2004 ///
2005 /// # Examples
2006 ///
2007 /// ```
2008 /// #![feature(downcast_unchecked)]
2009 ///
2010 /// use std::any::Any;
2011 /// use std::rc::Rc;
2012 ///
2013 /// let x: Rc<dyn Any> = Rc::new(1_usize);
2014 ///
2015 /// unsafe {
2016 /// assert_eq!(*x.downcast_unchecked::<usize>(), 1);
2017 /// }
2018 /// ```
2019 ///
2020 /// # Safety
2021 ///
2022 /// The contained value must be of type `T`. Calling this method
2023 /// with the incorrect type is *undefined behavior*.
2024 ///
2025 ///
2026 /// [`downcast`]: Self::downcast
2027 #[inline]
2028 #[unstable(feature = "downcast_unchecked", issue = "90850")]
2029 pub unsafe fn downcast_unchecked<T: Any>(self) -> Rc<T, A> {
2030 unsafe {
2031 let (ptr, alloc) = Rc::into_inner_with_allocator(self);
2032 Rc::from_inner_in(ptr.cast(), alloc)
2033 }
2034 }
2035}
2036
2037impl<T: ?Sized> Rc<T> {
2038 /// Allocates an `RcInner<T>` with sufficient space for
2039 /// a possibly-unsized inner value where the value has the layout provided.
2040 ///
2041 /// The function `mem_to_rc_inner` is called with the data pointer
2042 /// and must return back a (potentially fat)-pointer for the `RcInner<T>`.
2043 #[cfg(not(no_global_oom_handling))]
2044 unsafe fn allocate_for_layout(
2045 value_layout: Layout,
2046 allocate: impl FnOnce(Layout) -> Result<NonNull<[u8]>, AllocError>,
2047 mem_to_rc_inner: impl FnOnce(*mut u8) -> *mut RcInner<T>,
2048 ) -> *mut RcInner<T> {
2049 let layout = rc_inner_layout_for_value_layout(value_layout);
2050 unsafe {
2051 Rc::try_allocate_for_layout(value_layout, allocate, mem_to_rc_inner)
2052 .unwrap_or_else(|_| handle_alloc_error(layout))
2053 }
2054 }
2055
2056 /// Allocates an `RcInner<T>` with sufficient space for
2057 /// a possibly-unsized inner value where the value has the layout provided,
2058 /// returning an error if allocation fails.
2059 ///
2060 /// The function `mem_to_rc_inner` is called with the data pointer
2061 /// and must return back a (potentially fat)-pointer for the `RcInner<T>`.
2062 #[inline]
2063 unsafe fn try_allocate_for_layout(
2064 value_layout: Layout,
2065 allocate: impl FnOnce(Layout) -> Result<NonNull<[u8]>, AllocError>,
2066 mem_to_rc_inner: impl FnOnce(*mut u8) -> *mut RcInner<T>,
2067 ) -> Result<*mut RcInner<T>, AllocError> {
2068 let layout = rc_inner_layout_for_value_layout(value_layout);
2069
2070 // Allocate for the layout.
2071 let ptr = allocate(layout)?;
2072
2073 // Initialize the RcInner
2074 let inner = mem_to_rc_inner(ptr.as_non_null_ptr().as_ptr());
2075 unsafe {
2076 debug_assert_eq!(Layout::for_value_raw(inner), layout);
2077
2078 (&raw mut (*inner).strong).write(Cell::new(1));
2079 (&raw mut (*inner).weak).write(Cell::new(1));
2080 }
2081
2082 Ok(inner)
2083 }
2084}
2085
2086impl<T: ?Sized, A: Allocator> Rc<T, A> {
2087 /// Allocates an `RcInner<T>` with sufficient space for an unsized inner value
2088 #[cfg(not(no_global_oom_handling))]
2089 unsafe fn allocate_for_ptr_in(ptr: *const T, alloc: &A) -> *mut RcInner<T> {
2090 // Allocate for the `RcInner<T>` using the given value.
2091 unsafe {
2092 Rc::<T>::allocate_for_layout(
2093 Layout::for_value_raw(ptr),
2094 |layout| alloc.allocate(layout),
2095 |mem| mem.with_metadata_of(ptr as *const RcInner<T>),
2096 )
2097 }
2098 }
2099
2100 #[cfg(not(no_global_oom_handling))]
2101 fn from_box_in(src: Box<T, A>) -> Rc<T, A> {
2102 unsafe {
2103 let value_size = size_of_val(&*src);
2104 let ptr = Self::allocate_for_ptr_in(&*src, Box::allocator(&src));
2105
2106 // Copy value as bytes
2107 ptr::copy_nonoverlapping(
2108 (&raw const *src) as *const u8,
2109 (&raw mut (*ptr).value) as *mut u8,
2110 value_size,
2111 );
2112
2113 // Free the allocation without dropping its contents
2114 let (bptr, alloc) = Box::into_raw_with_allocator(src);
2115 let src = Box::from_raw_in(bptr as *mut mem::ManuallyDrop<T>, alloc.by_ref());
2116 drop(src);
2117
2118 Self::from_ptr_in(ptr, alloc)
2119 }
2120 }
2121}
2122
2123impl<T> Rc<[T]> {
2124 /// Allocates an `RcInner<[T]>` with the given length.
2125 #[cfg(not(no_global_oom_handling))]
2126 unsafe fn allocate_for_slice(len: usize) -> *mut RcInner<[T]> {
2127 unsafe {
2128 Self::allocate_for_layout(
2129 Layout::array::<T>(len).unwrap(),
2130 |layout| Global.allocate(layout),
2131 |mem| ptr::slice_from_raw_parts_mut(mem.cast::<T>(), len) as *mut RcInner<[T]>,
2132 )
2133 }
2134 }
2135
2136 /// Copy elements from slice into newly allocated `Rc<[T]>`
2137 ///
2138 /// Unsafe because the caller must either take ownership or bind `T: Copy`
2139 #[cfg(not(no_global_oom_handling))]
2140 unsafe fn copy_from_slice(v: &[T]) -> Rc<[T]> {
2141 unsafe {
2142 let ptr = Self::allocate_for_slice(v.len());
2143 ptr::copy_nonoverlapping(v.as_ptr(), (&raw mut (*ptr).value) as *mut T, v.len());
2144 Self::from_ptr(ptr)
2145 }
2146 }
2147
2148 /// Constructs an `Rc<[T]>` from an iterator known to be of a certain size.
2149 ///
2150 /// Behavior is undefined should the size be wrong.
2151 #[cfg(not(no_global_oom_handling))]
2152 unsafe fn from_iter_exact(iter: impl Iterator<Item = T>, len: usize) -> Rc<[T]> {
2153 // Panic guard while cloning T elements.
2154 // In the event of a panic, elements that have been written
2155 // into the new RcInner will be dropped, then the memory freed.
2156 struct Guard<T> {
2157 mem: NonNull<u8>,
2158 elems: *mut T,
2159 layout: Layout,
2160 n_elems: usize,
2161 }
2162
2163 impl<T> Drop for Guard<T> {
2164 fn drop(&mut self) {
2165 unsafe {
2166 let slice = from_raw_parts_mut(self.elems, self.n_elems);
2167 ptr::drop_in_place(slice);
2168
2169 Global.deallocate(self.mem, self.layout);
2170 }
2171 }
2172 }
2173
2174 unsafe {
2175 let ptr = Self::allocate_for_slice(len);
2176
2177 let mem = ptr as *mut _ as *mut u8;
2178 let layout = Layout::for_value_raw(ptr);
2179
2180 // Pointer to first element
2181 let elems = (&raw mut (*ptr).value) as *mut T;
2182
2183 let mut guard = Guard { mem: NonNull::new_unchecked(mem), elems, layout, n_elems: 0 };
2184
2185 for (i, item) in iter.enumerate() {
2186 ptr::write(elems.add(i), item);
2187 guard.n_elems += 1;
2188 }
2189
2190 // All clear. Forget the guard so it doesn't free the new RcInner.
2191 mem::forget(guard);
2192
2193 Self::from_ptr(ptr)
2194 }
2195 }
2196}
2197
2198impl<T, A: Allocator> Rc<[T], A> {
2199 /// Allocates an `RcInner<[T]>` with the given length.
2200 #[inline]
2201 #[cfg(not(no_global_oom_handling))]
2202 unsafe fn allocate_for_slice_in(len: usize, alloc: &A) -> *mut RcInner<[T]> {
2203 unsafe {
2204 Rc::<[T]>::allocate_for_layout(
2205 Layout::array::<T>(len).unwrap(),
2206 |layout| alloc.allocate(layout),
2207 |mem| ptr::slice_from_raw_parts_mut(mem.cast::<T>(), len) as *mut RcInner<[T]>,
2208 )
2209 }
2210 }
2211}
2212
2213#[cfg(not(no_global_oom_handling))]
2214/// Specialization trait used for `From<&[T]>`.
2215trait RcFromSlice<T> {
2216 fn from_slice(slice: &[T]) -> Self;
2217}
2218
2219#[cfg(not(no_global_oom_handling))]
2220impl<T: Clone> RcFromSlice<T> for Rc<[T]> {
2221 #[inline]
2222 default fn from_slice(v: &[T]) -> Self {
2223 unsafe { Self::from_iter_exact(v.iter().cloned(), v.len()) }
2224 }
2225}
2226
2227#[cfg(not(no_global_oom_handling))]
2228impl<T: Copy> RcFromSlice<T> for Rc<[T]> {
2229 #[inline]
2230 fn from_slice(v: &[T]) -> Self {
2231 unsafe { Rc::copy_from_slice(v) }
2232 }
2233}
2234
2235#[stable(feature = "rust1", since = "1.0.0")]
2236impl<T: ?Sized, A: Allocator> Deref for Rc<T, A> {
2237 type Target = T;
2238
2239 #[inline(always)]
2240 fn deref(&self) -> &T {
2241 &self.inner().value
2242 }
2243}
2244
2245#[unstable(feature = "pin_coerce_unsized_trait", issue = "123430")]
2246unsafe impl<T: ?Sized, A: Allocator> PinCoerceUnsized for Rc<T, A> {}
2247
2248//#[unstable(feature = "unique_rc_arc", issue = "112566")]
2249#[unstable(feature = "pin_coerce_unsized_trait", issue = "123430")]
2250unsafe impl<T: ?Sized, A: Allocator> PinCoerceUnsized for UniqueRc<T, A> {}
2251
2252#[unstable(feature = "pin_coerce_unsized_trait", issue = "123430")]
2253unsafe impl<T: ?Sized, A: Allocator> PinCoerceUnsized for Weak<T, A> {}
2254
2255#[unstable(feature = "deref_pure_trait", issue = "87121")]
2256unsafe impl<T: ?Sized, A: Allocator> DerefPure for Rc<T, A> {}
2257
2258//#[unstable(feature = "unique_rc_arc", issue = "112566")]
2259#[unstable(feature = "deref_pure_trait", issue = "87121")]
2260unsafe impl<T: ?Sized, A: Allocator> DerefPure for UniqueRc<T, A> {}
2261
2262#[unstable(feature = "legacy_receiver_trait", issue = "none")]
2263impl<T: ?Sized> LegacyReceiver for Rc<T> {}
2264
2265#[stable(feature = "rust1", since = "1.0.0")]
2266unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Rc<T, A> {
2267 /// Drops the `Rc`.
2268 ///
2269 /// This will decrement the strong reference count. If the strong reference
2270 /// count reaches zero then the only other references (if any) are
2271 /// [`Weak`], so we `drop` the inner value.
2272 ///
2273 /// # Examples
2274 ///
2275 /// ```
2276 /// use std::rc::Rc;
2277 ///
2278 /// struct Foo;
2279 ///
2280 /// impl Drop for Foo {
2281 /// fn drop(&mut self) {
2282 /// println!("dropped!");
2283 /// }
2284 /// }
2285 ///
2286 /// let foo = Rc::new(Foo);
2287 /// let foo2 = Rc::clone(&foo);
2288 ///
2289 /// drop(foo); // Doesn't print anything
2290 /// drop(foo2); // Prints "dropped!"
2291 /// ```
2292 #[inline]
2293 fn drop(&mut self) {
2294 unsafe {
2295 self.inner().dec_strong();
2296 if self.inner().strong() == 0 {
2297 self.drop_slow();
2298 }
2299 }
2300 }
2301}
2302
2303#[stable(feature = "rust1", since = "1.0.0")]
2304impl<T: ?Sized, A: Allocator + Clone> Clone for Rc<T, A> {
2305 /// Makes a clone of the `Rc` pointer.
2306 ///
2307 /// This creates another pointer to the same allocation, increasing the
2308 /// strong reference count.
2309 ///
2310 /// # Examples
2311 ///
2312 /// ```
2313 /// use std::rc::Rc;
2314 ///
2315 /// let five = Rc::new(5);
2316 ///
2317 /// let _ = Rc::clone(&five);
2318 /// ```
2319 #[inline]
2320 fn clone(&self) -> Self {
2321 unsafe {
2322 self.inner().inc_strong();
2323 Self::from_inner_in(self.ptr, self.alloc.clone())
2324 }
2325 }
2326}
2327
2328#[unstable(feature = "ergonomic_clones", issue = "132290")]
2329impl<T: ?Sized, A: Allocator + Clone> UseCloned for Rc<T, A> {}
2330
2331#[cfg(not(no_global_oom_handling))]
2332#[stable(feature = "rust1", since = "1.0.0")]
2333impl<T: Default> Default for Rc<T> {
2334 /// Creates a new `Rc<T>`, with the `Default` value for `T`.
2335 ///
2336 /// # Examples
2337 ///
2338 /// ```
2339 /// use std::rc::Rc;
2340 ///
2341 /// let x: Rc<i32> = Default::default();
2342 /// assert_eq!(*x, 0);
2343 /// ```
2344 #[inline]
2345 fn default() -> Self {
2346 unsafe {
2347 Self::from_inner(
2348 Box::leak(Box::write(
2349 Box::new_uninit(),
2350 RcInner { strong: Cell::new(1), weak: Cell::new(1), value: T::default() },
2351 ))
2352 .into(),
2353 )
2354 }
2355 }
2356}
2357
2358#[cfg(not(no_global_oom_handling))]
2359#[stable(feature = "more_rc_default_impls", since = "1.80.0")]
2360impl Default for Rc<str> {
2361 /// Creates an empty `str` inside an `Rc`.
2362 ///
2363 /// This may or may not share an allocation with other Rcs on the same thread.
2364 #[inline]
2365 fn default() -> Self {
2366 let rc = Rc::<[u8]>::default();
2367 // `[u8]` has the same layout as `str`.
2368 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const str) }
2369 }
2370}
2371
2372#[cfg(not(no_global_oom_handling))]
2373#[stable(feature = "more_rc_default_impls", since = "1.80.0")]
2374impl<T> Default for Rc<[T]> {
2375 /// Creates an empty `[T]` inside an `Rc`.
2376 ///
2377 /// This may or may not share an allocation with other Rcs on the same thread.
2378 #[inline]
2379 fn default() -> Self {
2380 let arr: [T; 0] = [];
2381 Rc::from(arr)
2382 }
2383}
2384
2385#[cfg(not(no_global_oom_handling))]
2386#[stable(feature = "pin_default_impls", since = "1.91.0")]
2387impl<T> Default for Pin<Rc<T>>
2388where
2389 T: ?Sized,
2390 Rc<T>: Default,
2391{
2392 #[inline]
2393 fn default() -> Self {
2394 unsafe { Pin::new_unchecked(Rc::<T>::default()) }
2395 }
2396}
2397
2398#[stable(feature = "rust1", since = "1.0.0")]
2399trait RcEqIdent<T: ?Sized + PartialEq, A: Allocator> {
2400 fn eq(&self, other: &Rc<T, A>) -> bool;
2401 fn ne(&self, other: &Rc<T, A>) -> bool;
2402}
2403
2404#[stable(feature = "rust1", since = "1.0.0")]
2405impl<T: ?Sized + PartialEq, A: Allocator> RcEqIdent<T, A> for Rc<T, A> {
2406 #[inline]
2407 default fn eq(&self, other: &Rc<T, A>) -> bool {
2408 **self == **other
2409 }
2410
2411 #[inline]
2412 default fn ne(&self, other: &Rc<T, A>) -> bool {
2413 **self != **other
2414 }
2415}
2416
2417// Hack to allow specializing on `Eq` even though `Eq` has a method.
2418#[rustc_unsafe_specialization_marker]
2419pub(crate) trait MarkerEq: PartialEq<Self> {}
2420
2421impl<T: Eq> MarkerEq for T {}
2422
2423/// We're doing this specialization here, and not as a more general optimization on `&T`, because it
2424/// would otherwise add a cost to all equality checks on refs. We assume that `Rc`s are used to
2425/// store large values, that are slow to clone, but also heavy to check for equality, causing this
2426/// cost to pay off more easily. It's also more likely to have two `Rc` clones, that point to
2427/// the same value, than two `&T`s.
2428///
2429/// We can only do this when `T: Eq` as a `PartialEq` might be deliberately irreflexive.
2430#[stable(feature = "rust1", since = "1.0.0")]
2431impl<T: ?Sized + MarkerEq, A: Allocator> RcEqIdent<T, A> for Rc<T, A> {
2432 #[inline]
2433 fn eq(&self, other: &Rc<T, A>) -> bool {
2434 Rc::ptr_eq(self, other) || **self == **other
2435 }
2436
2437 #[inline]
2438 fn ne(&self, other: &Rc<T, A>) -> bool {
2439 !Rc::ptr_eq(self, other) && **self != **other
2440 }
2441}
2442
2443#[stable(feature = "rust1", since = "1.0.0")]
2444impl<T: ?Sized + PartialEq, A: Allocator> PartialEq for Rc<T, A> {
2445 /// Equality for two `Rc`s.
2446 ///
2447 /// Two `Rc`s are equal if their inner values are equal, even if they are
2448 /// stored in different allocation.
2449 ///
2450 /// If `T` also implements `Eq` (implying reflexivity of equality),
2451 /// two `Rc`s that point to the same allocation are
2452 /// always equal.
2453 ///
2454 /// # Examples
2455 ///
2456 /// ```
2457 /// use std::rc::Rc;
2458 ///
2459 /// let five = Rc::new(5);
2460 ///
2461 /// assert!(five == Rc::new(5));
2462 /// ```
2463 #[inline]
2464 fn eq(&self, other: &Rc<T, A>) -> bool {
2465 RcEqIdent::eq(self, other)
2466 }
2467
2468 /// Inequality for two `Rc`s.
2469 ///
2470 /// Two `Rc`s are not equal if their inner values are not equal.
2471 ///
2472 /// If `T` also implements `Eq` (implying reflexivity of equality),
2473 /// two `Rc`s that point to the same allocation are
2474 /// always equal.
2475 ///
2476 /// # Examples
2477 ///
2478 /// ```
2479 /// use std::rc::Rc;
2480 ///
2481 /// let five = Rc::new(5);
2482 ///
2483 /// assert!(five != Rc::new(6));
2484 /// ```
2485 #[inline]
2486 fn ne(&self, other: &Rc<T, A>) -> bool {
2487 RcEqIdent::ne(self, other)
2488 }
2489}
2490
2491#[stable(feature = "rust1", since = "1.0.0")]
2492impl<T: ?Sized + Eq, A: Allocator> Eq for Rc<T, A> {}
2493
2494#[stable(feature = "rust1", since = "1.0.0")]
2495impl<T: ?Sized + PartialOrd, A: Allocator> PartialOrd for Rc<T, A> {
2496 /// Partial comparison for two `Rc`s.
2497 ///
2498 /// The two are compared by calling `partial_cmp()` on their inner values.
2499 ///
2500 /// # Examples
2501 ///
2502 /// ```
2503 /// use std::rc::Rc;
2504 /// use std::cmp::Ordering;
2505 ///
2506 /// let five = Rc::new(5);
2507 ///
2508 /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&Rc::new(6)));
2509 /// ```
2510 #[inline(always)]
2511 fn partial_cmp(&self, other: &Rc<T, A>) -> Option<Ordering> {
2512 (**self).partial_cmp(&**other)
2513 }
2514
2515 /// Less-than comparison for two `Rc`s.
2516 ///
2517 /// The two are compared by calling `<` on their inner values.
2518 ///
2519 /// # Examples
2520 ///
2521 /// ```
2522 /// use std::rc::Rc;
2523 ///
2524 /// let five = Rc::new(5);
2525 ///
2526 /// assert!(five < Rc::new(6));
2527 /// ```
2528 #[inline(always)]
2529 fn lt(&self, other: &Rc<T, A>) -> bool {
2530 **self < **other
2531 }
2532
2533 /// 'Less than or equal to' comparison for two `Rc`s.
2534 ///
2535 /// The two are compared by calling `<=` on their inner values.
2536 ///
2537 /// # Examples
2538 ///
2539 /// ```
2540 /// use std::rc::Rc;
2541 ///
2542 /// let five = Rc::new(5);
2543 ///
2544 /// assert!(five <= Rc::new(5));
2545 /// ```
2546 #[inline(always)]
2547 fn le(&self, other: &Rc<T, A>) -> bool {
2548 **self <= **other
2549 }
2550
2551 /// Greater-than comparison for two `Rc`s.
2552 ///
2553 /// The two are compared by calling `>` on their inner values.
2554 ///
2555 /// # Examples
2556 ///
2557 /// ```
2558 /// use std::rc::Rc;
2559 ///
2560 /// let five = Rc::new(5);
2561 ///
2562 /// assert!(five > Rc::new(4));
2563 /// ```
2564 #[inline(always)]
2565 fn gt(&self, other: &Rc<T, A>) -> bool {
2566 **self > **other
2567 }
2568
2569 /// 'Greater than or equal to' comparison for two `Rc`s.
2570 ///
2571 /// The two are compared by calling `>=` on their inner values.
2572 ///
2573 /// # Examples
2574 ///
2575 /// ```
2576 /// use std::rc::Rc;
2577 ///
2578 /// let five = Rc::new(5);
2579 ///
2580 /// assert!(five >= Rc::new(5));
2581 /// ```
2582 #[inline(always)]
2583 fn ge(&self, other: &Rc<T, A>) -> bool {
2584 **self >= **other
2585 }
2586}
2587
2588#[stable(feature = "rust1", since = "1.0.0")]
2589impl<T: ?Sized + Ord, A: Allocator> Ord for Rc<T, A> {
2590 /// Comparison for two `Rc`s.
2591 ///
2592 /// The two are compared by calling `cmp()` on their inner values.
2593 ///
2594 /// # Examples
2595 ///
2596 /// ```
2597 /// use std::rc::Rc;
2598 /// use std::cmp::Ordering;
2599 ///
2600 /// let five = Rc::new(5);
2601 ///
2602 /// assert_eq!(Ordering::Less, five.cmp(&Rc::new(6)));
2603 /// ```
2604 #[inline]
2605 fn cmp(&self, other: &Rc<T, A>) -> Ordering {
2606 (**self).cmp(&**other)
2607 }
2608}
2609
2610#[stable(feature = "rust1", since = "1.0.0")]
2611impl<T: ?Sized + Hash, A: Allocator> Hash for Rc<T, A> {
2612 fn hash<H: Hasher>(&self, state: &mut H) {
2613 (**self).hash(state);
2614 }
2615}
2616
2617#[stable(feature = "rust1", since = "1.0.0")]
2618impl<T: ?Sized + fmt::Display, A: Allocator> fmt::Display for Rc<T, A> {
2619 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2620 fmt::Display::fmt(&**self, f)
2621 }
2622}
2623
2624#[stable(feature = "rust1", since = "1.0.0")]
2625impl<T: ?Sized + fmt::Debug, A: Allocator> fmt::Debug for Rc<T, A> {
2626 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2627 fmt::Debug::fmt(&**self, f)
2628 }
2629}
2630
2631#[stable(feature = "rust1", since = "1.0.0")]
2632impl<T: ?Sized, A: Allocator> fmt::Pointer for Rc<T, A> {
2633 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2634 fmt::Pointer::fmt(&(&raw const **self), f)
2635 }
2636}
2637
2638#[cfg(not(no_global_oom_handling))]
2639#[stable(feature = "from_for_ptrs", since = "1.6.0")]
2640impl<T> From<T> for Rc<T> {
2641 /// Converts a generic type `T` into an `Rc<T>`
2642 ///
2643 /// The conversion allocates on the heap and moves `t`
2644 /// from the stack into it.
2645 ///
2646 /// # Example
2647 /// ```rust
2648 /// # use std::rc::Rc;
2649 /// let x = 5;
2650 /// let rc = Rc::new(5);
2651 ///
2652 /// assert_eq!(Rc::from(x), rc);
2653 /// ```
2654 fn from(t: T) -> Self {
2655 Rc::new(t)
2656 }
2657}
2658
2659#[cfg(not(no_global_oom_handling))]
2660#[stable(feature = "shared_from_array", since = "1.74.0")]
2661impl<T, const N: usize> From<[T; N]> for Rc<[T]> {
2662 /// Converts a [`[T; N]`](prim@array) into an `Rc<[T]>`.
2663 ///
2664 /// The conversion moves the array into a newly allocated `Rc`.
2665 ///
2666 /// # Example
2667 ///
2668 /// ```
2669 /// # use std::rc::Rc;
2670 /// let original: [i32; 3] = [1, 2, 3];
2671 /// let shared: Rc<[i32]> = Rc::from(original);
2672 /// assert_eq!(&[1, 2, 3], &shared[..]);
2673 /// ```
2674 #[inline]
2675 fn from(v: [T; N]) -> Rc<[T]> {
2676 Rc::<[T; N]>::from(v)
2677 }
2678}
2679
2680#[cfg(not(no_global_oom_handling))]
2681#[stable(feature = "shared_from_slice", since = "1.21.0")]
2682impl<T: Clone> From<&[T]> for Rc<[T]> {
2683 /// Allocates a reference-counted slice and fills it by cloning `v`'s items.
2684 ///
2685 /// # Example
2686 ///
2687 /// ```
2688 /// # use std::rc::Rc;
2689 /// let original: &[i32] = &[1, 2, 3];
2690 /// let shared: Rc<[i32]> = Rc::from(original);
2691 /// assert_eq!(&[1, 2, 3], &shared[..]);
2692 /// ```
2693 #[inline]
2694 fn from(v: &[T]) -> Rc<[T]> {
2695 <Self as RcFromSlice<T>>::from_slice(v)
2696 }
2697}
2698
2699#[cfg(not(no_global_oom_handling))]
2700#[stable(feature = "shared_from_mut_slice", since = "1.84.0")]
2701impl<T: Clone> From<&mut [T]> for Rc<[T]> {
2702 /// Allocates a reference-counted slice and fills it by cloning `v`'s items.
2703 ///
2704 /// # Example
2705 ///
2706 /// ```
2707 /// # use std::rc::Rc;
2708 /// let mut original = [1, 2, 3];
2709 /// let original: &mut [i32] = &mut original;
2710 /// let shared: Rc<[i32]> = Rc::from(original);
2711 /// assert_eq!(&[1, 2, 3], &shared[..]);
2712 /// ```
2713 #[inline]
2714 fn from(v: &mut [T]) -> Rc<[T]> {
2715 Rc::from(&*v)
2716 }
2717}
2718
2719#[cfg(not(no_global_oom_handling))]
2720#[stable(feature = "shared_from_slice", since = "1.21.0")]
2721impl From<&str> for Rc<str> {
2722 /// Allocates a reference-counted string slice and copies `v` into it.
2723 ///
2724 /// # Example
2725 ///
2726 /// ```
2727 /// # use std::rc::Rc;
2728 /// let shared: Rc<str> = Rc::from("statue");
2729 /// assert_eq!("statue", &shared[..]);
2730 /// ```
2731 #[inline]
2732 fn from(v: &str) -> Rc<str> {
2733 let rc = Rc::<[u8]>::from(v.as_bytes());
2734 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const str) }
2735 }
2736}
2737
2738#[cfg(not(no_global_oom_handling))]
2739#[stable(feature = "shared_from_mut_slice", since = "1.84.0")]
2740impl From<&mut str> for Rc<str> {
2741 /// Allocates a reference-counted string slice and copies `v` into it.
2742 ///
2743 /// # Example
2744 ///
2745 /// ```
2746 /// # use std::rc::Rc;
2747 /// let mut original = String::from("statue");
2748 /// let original: &mut str = &mut original;
2749 /// let shared: Rc<str> = Rc::from(original);
2750 /// assert_eq!("statue", &shared[..]);
2751 /// ```
2752 #[inline]
2753 fn from(v: &mut str) -> Rc<str> {
2754 Rc::from(&*v)
2755 }
2756}
2757
2758#[cfg(not(no_global_oom_handling))]
2759#[stable(feature = "shared_from_slice", since = "1.21.0")]
2760impl From<String> for Rc<str> {
2761 /// Allocates a reference-counted string slice and copies `v` into it.
2762 ///
2763 /// # Example
2764 ///
2765 /// ```
2766 /// # use std::rc::Rc;
2767 /// let original: String = "statue".to_owned();
2768 /// let shared: Rc<str> = Rc::from(original);
2769 /// assert_eq!("statue", &shared[..]);
2770 /// ```
2771 #[inline]
2772 fn from(v: String) -> Rc<str> {
2773 Rc::from(&v[..])
2774 }
2775}
2776
2777#[cfg(not(no_global_oom_handling))]
2778#[stable(feature = "shared_from_slice", since = "1.21.0")]
2779impl<T: ?Sized, A: Allocator> From<Box<T, A>> for Rc<T, A> {
2780 /// Move a boxed object to a new, reference counted, allocation.
2781 ///
2782 /// # Example
2783 ///
2784 /// ```
2785 /// # use std::rc::Rc;
2786 /// let original: Box<i32> = Box::new(1);
2787 /// let shared: Rc<i32> = Rc::from(original);
2788 /// assert_eq!(1, *shared);
2789 /// ```
2790 #[inline]
2791 fn from(v: Box<T, A>) -> Rc<T, A> {
2792 Rc::from_box_in(v)
2793 }
2794}
2795
2796#[cfg(not(no_global_oom_handling))]
2797#[stable(feature = "shared_from_slice", since = "1.21.0")]
2798impl<T, A: Allocator> From<Vec<T, A>> for Rc<[T], A> {
2799 /// Allocates a reference-counted slice and moves `v`'s items into it.
2800 ///
2801 /// # Example
2802 ///
2803 /// ```
2804 /// # use std::rc::Rc;
2805 /// let unique: Vec<i32> = vec![1, 2, 3];
2806 /// let shared: Rc<[i32]> = Rc::from(unique);
2807 /// assert_eq!(&[1, 2, 3], &shared[..]);
2808 /// ```
2809 #[inline]
2810 fn from(v: Vec<T, A>) -> Rc<[T], A> {
2811 unsafe {
2812 let (vec_ptr, len, cap, alloc) = v.into_raw_parts_with_alloc();
2813
2814 let rc_ptr = Self::allocate_for_slice_in(len, &alloc);
2815 ptr::copy_nonoverlapping(vec_ptr, (&raw mut (*rc_ptr).value) as *mut T, len);
2816
2817 // Create a `Vec<T, &A>` with length 0, to deallocate the buffer
2818 // without dropping its contents or the allocator
2819 let _ = Vec::from_raw_parts_in(vec_ptr, 0, cap, &alloc);
2820
2821 Self::from_ptr_in(rc_ptr, alloc)
2822 }
2823 }
2824}
2825
2826#[stable(feature = "shared_from_cow", since = "1.45.0")]
2827impl<'a, B> From<Cow<'a, B>> for Rc<B>
2828where
2829 B: ToOwned + ?Sized,
2830 Rc<B>: From<&'a B> + From<B::Owned>,
2831{
2832 /// Creates a reference-counted pointer from a clone-on-write pointer by
2833 /// copying its content.
2834 ///
2835 /// # Example
2836 ///
2837 /// ```rust
2838 /// # use std::rc::Rc;
2839 /// # use std::borrow::Cow;
2840 /// let cow: Cow<'_, str> = Cow::Borrowed("eggplant");
2841 /// let shared: Rc<str> = Rc::from(cow);
2842 /// assert_eq!("eggplant", &shared[..]);
2843 /// ```
2844 #[inline]
2845 fn from(cow: Cow<'a, B>) -> Rc<B> {
2846 match cow {
2847 Cow::Borrowed(s) => Rc::from(s),
2848 Cow::Owned(s) => Rc::from(s),
2849 }
2850 }
2851}
2852
2853#[stable(feature = "shared_from_str", since = "1.62.0")]
2854impl From<Rc<str>> for Rc<[u8]> {
2855 /// Converts a reference-counted string slice into a byte slice.
2856 ///
2857 /// # Example
2858 ///
2859 /// ```
2860 /// # use std::rc::Rc;
2861 /// let string: Rc<str> = Rc::from("eggplant");
2862 /// let bytes: Rc<[u8]> = Rc::from(string);
2863 /// assert_eq!("eggplant".as_bytes(), bytes.as_ref());
2864 /// ```
2865 #[inline]
2866 fn from(rc: Rc<str>) -> Self {
2867 // SAFETY: `str` has the same layout as `[u8]`.
2868 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const [u8]) }
2869 }
2870}
2871
2872#[stable(feature = "boxed_slice_try_from", since = "1.43.0")]
2873impl<T, A: Allocator, const N: usize> TryFrom<Rc<[T], A>> for Rc<[T; N], A> {
2874 type Error = Rc<[T], A>;
2875
2876 fn try_from(boxed_slice: Rc<[T], A>) -> Result<Self, Self::Error> {
2877 if boxed_slice.len() == N {
2878 let (ptr, alloc) = Rc::into_inner_with_allocator(boxed_slice);
2879 Ok(unsafe { Rc::from_inner_in(ptr.cast(), alloc) })
2880 } else {
2881 Err(boxed_slice)
2882 }
2883 }
2884}
2885
2886#[cfg(not(no_global_oom_handling))]
2887#[stable(feature = "shared_from_iter", since = "1.37.0")]
2888impl<T> FromIterator<T> for Rc<[T]> {
2889 /// Takes each element in the `Iterator` and collects it into an `Rc<[T]>`.
2890 ///
2891 /// # Performance characteristics
2892 ///
2893 /// ## The general case
2894 ///
2895 /// In the general case, collecting into `Rc<[T]>` is done by first
2896 /// collecting into a `Vec<T>`. That is, when writing the following:
2897 ///
2898 /// ```rust
2899 /// # use std::rc::Rc;
2900 /// let evens: Rc<[u8]> = (0..10).filter(|&x| x % 2 == 0).collect();
2901 /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]);
2902 /// ```
2903 ///
2904 /// this behaves as if we wrote:
2905 ///
2906 /// ```rust
2907 /// # use std::rc::Rc;
2908 /// let evens: Rc<[u8]> = (0..10).filter(|&x| x % 2 == 0)
2909 /// .collect::<Vec<_>>() // The first set of allocations happens here.
2910 /// .into(); // A second allocation for `Rc<[T]>` happens here.
2911 /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]);
2912 /// ```
2913 ///
2914 /// This will allocate as many times as needed for constructing the `Vec<T>`
2915 /// and then it will allocate once for turning the `Vec<T>` into the `Rc<[T]>`.
2916 ///
2917 /// ## Iterators of known length
2918 ///
2919 /// When your `Iterator` implements `TrustedLen` and is of an exact size,
2920 /// a single allocation will be made for the `Rc<[T]>`. For example:
2921 ///
2922 /// ```rust
2923 /// # use std::rc::Rc;
2924 /// let evens: Rc<[u8]> = (0..10).collect(); // Just a single allocation happens here.
2925 /// # assert_eq!(&*evens, &*(0..10).collect::<Vec<_>>());
2926 /// ```
2927 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
2928 ToRcSlice::to_rc_slice(iter.into_iter())
2929 }
2930}
2931
2932/// Specialization trait used for collecting into `Rc<[T]>`.
2933#[cfg(not(no_global_oom_handling))]
2934trait ToRcSlice<T>: Iterator<Item = T> + Sized {
2935 fn to_rc_slice(self) -> Rc<[T]>;
2936}
2937
2938#[cfg(not(no_global_oom_handling))]
2939impl<T, I: Iterator<Item = T>> ToRcSlice<T> for I {
2940 default fn to_rc_slice(self) -> Rc<[T]> {
2941 self.collect::<Vec<T>>().into()
2942 }
2943}
2944
2945#[cfg(not(no_global_oom_handling))]
2946impl<T, I: iter::TrustedLen<Item = T>> ToRcSlice<T> for I {
2947 fn to_rc_slice(self) -> Rc<[T]> {
2948 // This is the case for a `TrustedLen` iterator.
2949 let (low, high) = self.size_hint();
2950 if let Some(high) = high {
2951 debug_assert_eq!(
2952 low,
2953 high,
2954 "TrustedLen iterator's size hint is not exact: {:?}",
2955 (low, high)
2956 );
2957
2958 unsafe {
2959 // SAFETY: We need to ensure that the iterator has an exact length and we have.
2960 Rc::from_iter_exact(self, low)
2961 }
2962 } else {
2963 // TrustedLen contract guarantees that `upper_bound == None` implies an iterator
2964 // length exceeding `usize::MAX`.
2965 // The default implementation would collect into a vec which would panic.
2966 // Thus we panic here immediately without invoking `Vec` code.
2967 panic!("capacity overflow");
2968 }
2969 }
2970}
2971
2972/// `Weak` is a version of [`Rc`] that holds a non-owning reference to the
2973/// managed allocation.
2974///
2975/// The allocation is accessed by calling [`upgrade`] on the `Weak`
2976/// pointer, which returns an <code>[Option]<[Rc]\<T>></code>.
2977///
2978/// Since a `Weak` reference does not count towards ownership, it will not
2979/// prevent the value stored in the allocation from being dropped, and `Weak` itself makes no
2980/// guarantees about the value still being present. Thus it may return [`None`]
2981/// when [`upgrade`]d. Note however that a `Weak` reference *does* prevent the allocation
2982/// itself (the backing store) from being deallocated.
2983///
2984/// A `Weak` pointer is useful for keeping a temporary reference to the allocation
2985/// managed by [`Rc`] without preventing its inner value from being dropped. It is also used to
2986/// prevent circular references between [`Rc`] pointers, since mutual owning references
2987/// would never allow either [`Rc`] to be dropped. For example, a tree could
2988/// have strong [`Rc`] pointers from parent nodes to children, and `Weak`
2989/// pointers from children back to their parents.
2990///
2991/// The typical way to obtain a `Weak` pointer is to call [`Rc::downgrade`].
2992///
2993/// [`upgrade`]: Weak::upgrade
2994#[stable(feature = "rc_weak", since = "1.4.0")]
2995#[rustc_diagnostic_item = "RcWeak"]
2996pub struct Weak<
2997 T: ?Sized,
2998 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
2999> {
3000 // This is a `NonNull` to allow optimizing the size of this type in enums,
3001 // but it is not necessarily a valid pointer.
3002 // `Weak::new` sets this to `usize::MAX` so that it doesn’t need
3003 // to allocate space on the heap. That's not a value a real pointer
3004 // will ever have because RcInner has alignment at least 2.
3005 ptr: NonNull<RcInner<T>>,
3006 alloc: A,
3007}
3008
3009#[stable(feature = "rc_weak", since = "1.4.0")]
3010impl<T: ?Sized, A: Allocator> !Send for Weak<T, A> {}
3011#[stable(feature = "rc_weak", since = "1.4.0")]
3012impl<T: ?Sized, A: Allocator> !Sync for Weak<T, A> {}
3013
3014#[unstable(feature = "coerce_unsized", issue = "18598")]
3015impl<T: ?Sized + Unsize<U>, U: ?Sized, A: Allocator> CoerceUnsized<Weak<U, A>> for Weak<T, A> {}
3016
3017#[unstable(feature = "dispatch_from_dyn", issue = "none")]
3018impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Weak<U>> for Weak<T> {}
3019
3020// SAFETY: `Weak::clone` doesn't access any `Cell`s which could contain the `Weak` being cloned.
3021#[unstable(feature = "cell_get_cloned", issue = "145329")]
3022unsafe impl<T: ?Sized> CloneFromCell for Weak<T> {}
3023
3024impl<T> Weak<T> {
3025 /// Constructs a new `Weak<T>`, without allocating any memory.
3026 /// Calling [`upgrade`] on the return value always gives [`None`].
3027 ///
3028 /// [`upgrade`]: Weak::upgrade
3029 ///
3030 /// # Examples
3031 ///
3032 /// ```
3033 /// use std::rc::Weak;
3034 ///
3035 /// let empty: Weak<i64> = Weak::new();
3036 /// assert!(empty.upgrade().is_none());
3037 /// ```
3038 #[inline]
3039 #[stable(feature = "downgraded_weak", since = "1.10.0")]
3040 #[rustc_const_stable(feature = "const_weak_new", since = "1.73.0")]
3041 #[must_use]
3042 pub const fn new() -> Weak<T> {
3043 Weak { ptr: NonNull::without_provenance(NonZeroUsize::MAX), alloc: Global }
3044 }
3045}
3046
3047impl<T, A: Allocator> Weak<T, A> {
3048 /// Constructs a new `Weak<T>`, without allocating any memory, technically in the provided
3049 /// allocator.
3050 /// Calling [`upgrade`] on the return value always gives [`None`].
3051 ///
3052 /// [`upgrade`]: Weak::upgrade
3053 ///
3054 /// # Examples
3055 ///
3056 /// ```
3057 /// use std::rc::Weak;
3058 ///
3059 /// let empty: Weak<i64> = Weak::new();
3060 /// assert!(empty.upgrade().is_none());
3061 /// ```
3062 #[inline]
3063 #[unstable(feature = "allocator_api", issue = "32838")]
3064 pub fn new_in(alloc: A) -> Weak<T, A> {
3065 Weak { ptr: NonNull::without_provenance(NonZeroUsize::MAX), alloc }
3066 }
3067}
3068
3069pub(crate) fn is_dangling<T: ?Sized>(ptr: *const T) -> bool {
3070 (ptr.cast::<()>()).addr() == usize::MAX
3071}
3072
3073/// Helper type to allow accessing the reference counts without
3074/// making any assertions about the data field.
3075struct WeakInner<'a> {
3076 weak: &'a Cell<usize>,
3077 strong: &'a Cell<usize>,
3078}
3079
3080impl<T: ?Sized> Weak<T> {
3081 /// Converts a raw pointer previously created by [`into_raw`] back into `Weak<T>`.
3082 ///
3083 /// This can be used to safely get a strong reference (by calling [`upgrade`]
3084 /// later) or to deallocate the weak count by dropping the `Weak<T>`.
3085 ///
3086 /// It takes ownership of one weak reference (with the exception of pointers created by [`new`],
3087 /// as these don't own anything; the method still works on them).
3088 ///
3089 /// # Safety
3090 ///
3091 /// The pointer must have originated from the [`into_raw`] and must still own its potential
3092 /// weak reference, and `ptr` must point to a block of memory allocated by the global allocator.
3093 ///
3094 /// It is allowed for the strong count to be 0 at the time of calling this. Nevertheless, this
3095 /// takes ownership of one weak reference currently represented as a raw pointer (the weak
3096 /// count is not modified by this operation) and therefore it must be paired with a previous
3097 /// call to [`into_raw`].
3098 ///
3099 /// # Examples
3100 ///
3101 /// ```
3102 /// use std::rc::{Rc, Weak};
3103 ///
3104 /// let strong = Rc::new("hello".to_owned());
3105 ///
3106 /// let raw_1 = Rc::downgrade(&strong).into_raw();
3107 /// let raw_2 = Rc::downgrade(&strong).into_raw();
3108 ///
3109 /// assert_eq!(2, Rc::weak_count(&strong));
3110 ///
3111 /// assert_eq!("hello", &*unsafe { Weak::from_raw(raw_1) }.upgrade().unwrap());
3112 /// assert_eq!(1, Rc::weak_count(&strong));
3113 ///
3114 /// drop(strong);
3115 ///
3116 /// // Decrement the last weak count.
3117 /// assert!(unsafe { Weak::from_raw(raw_2) }.upgrade().is_none());
3118 /// ```
3119 ///
3120 /// [`into_raw`]: Weak::into_raw
3121 /// [`upgrade`]: Weak::upgrade
3122 /// [`new`]: Weak::new
3123 #[inline]
3124 #[stable(feature = "weak_into_raw", since = "1.45.0")]
3125 pub unsafe fn from_raw(ptr: *const T) -> Self {
3126 unsafe { Self::from_raw_in(ptr, Global) }
3127 }
3128
3129 /// Consumes the `Weak<T>` and turns it into a raw pointer.
3130 ///
3131 /// This converts the weak pointer into a raw pointer, while still preserving the ownership of
3132 /// one weak reference (the weak count is not modified by this operation). It can be turned
3133 /// back into the `Weak<T>` with [`from_raw`].
3134 ///
3135 /// The same restrictions of accessing the target of the pointer as with
3136 /// [`as_ptr`] apply.
3137 ///
3138 /// # Examples
3139 ///
3140 /// ```
3141 /// use std::rc::{Rc, Weak};
3142 ///
3143 /// let strong = Rc::new("hello".to_owned());
3144 /// let weak = Rc::downgrade(&strong);
3145 /// let raw = weak.into_raw();
3146 ///
3147 /// assert_eq!(1, Rc::weak_count(&strong));
3148 /// assert_eq!("hello", unsafe { &*raw });
3149 ///
3150 /// drop(unsafe { Weak::from_raw(raw) });
3151 /// assert_eq!(0, Rc::weak_count(&strong));
3152 /// ```
3153 ///
3154 /// [`from_raw`]: Weak::from_raw
3155 /// [`as_ptr`]: Weak::as_ptr
3156 #[must_use = "losing the pointer will leak memory"]
3157 #[stable(feature = "weak_into_raw", since = "1.45.0")]
3158 pub fn into_raw(self) -> *const T {
3159 mem::ManuallyDrop::new(self).as_ptr()
3160 }
3161}
3162
3163impl<T: ?Sized, A: Allocator> Weak<T, A> {
3164 /// Returns a reference to the underlying allocator.
3165 #[inline]
3166 #[unstable(feature = "allocator_api", issue = "32838")]
3167 pub fn allocator(&self) -> &A {
3168 &self.alloc
3169 }
3170
3171 /// Returns a raw pointer to the object `T` pointed to by this `Weak<T>`.
3172 ///
3173 /// The pointer is valid only if there are some strong references. The pointer may be dangling,
3174 /// unaligned or even [`null`] otherwise.
3175 ///
3176 /// # Examples
3177 ///
3178 /// ```
3179 /// use std::rc::Rc;
3180 /// use std::ptr;
3181 ///
3182 /// let strong = Rc::new("hello".to_owned());
3183 /// let weak = Rc::downgrade(&strong);
3184 /// // Both point to the same object
3185 /// assert!(ptr::eq(&*strong, weak.as_ptr()));
3186 /// // The strong here keeps it alive, so we can still access the object.
3187 /// assert_eq!("hello", unsafe { &*weak.as_ptr() });
3188 ///
3189 /// drop(strong);
3190 /// // But not any more. We can do weak.as_ptr(), but accessing the pointer would lead to
3191 /// // undefined behavior.
3192 /// // assert_eq!("hello", unsafe { &*weak.as_ptr() });
3193 /// ```
3194 ///
3195 /// [`null`]: ptr::null
3196 #[must_use]
3197 #[stable(feature = "rc_as_ptr", since = "1.45.0")]
3198 pub fn as_ptr(&self) -> *const T {
3199 let ptr: *mut RcInner<T> = NonNull::as_ptr(self.ptr);
3200
3201 if is_dangling(ptr) {
3202 // If the pointer is dangling, we return the sentinel directly. This cannot be
3203 // a valid payload address, as the payload is at least as aligned as RcInner (usize).
3204 ptr as *const T
3205 } else {
3206 // SAFETY: if is_dangling returns false, then the pointer is dereferenceable.
3207 // The payload may be dropped at this point, and we have to maintain provenance,
3208 // so use raw pointer manipulation.
3209 unsafe { &raw mut (*ptr).value }
3210 }
3211 }
3212
3213 /// Consumes the `Weak<T>`, returning the wrapped pointer and allocator.
3214 ///
3215 /// This converts the weak pointer into a raw pointer, while still preserving the ownership of
3216 /// one weak reference (the weak count is not modified by this operation). It can be turned
3217 /// back into the `Weak<T>` with [`from_raw_in`].
3218 ///
3219 /// The same restrictions of accessing the target of the pointer as with
3220 /// [`as_ptr`] apply.
3221 ///
3222 /// # Examples
3223 ///
3224 /// ```
3225 /// #![feature(allocator_api)]
3226 /// use std::rc::{Rc, Weak};
3227 /// use std::alloc::System;
3228 ///
3229 /// let strong = Rc::new_in("hello".to_owned(), System);
3230 /// let weak = Rc::downgrade(&strong);
3231 /// let (raw, alloc) = weak.into_raw_with_allocator();
3232 ///
3233 /// assert_eq!(1, Rc::weak_count(&strong));
3234 /// assert_eq!("hello", unsafe { &*raw });
3235 ///
3236 /// drop(unsafe { Weak::from_raw_in(raw, alloc) });
3237 /// assert_eq!(0, Rc::weak_count(&strong));
3238 /// ```
3239 ///
3240 /// [`from_raw_in`]: Weak::from_raw_in
3241 /// [`as_ptr`]: Weak::as_ptr
3242 #[must_use = "losing the pointer will leak memory"]
3243 #[inline]
3244 #[unstable(feature = "allocator_api", issue = "32838")]
3245 pub fn into_raw_with_allocator(self) -> (*const T, A) {
3246 let this = mem::ManuallyDrop::new(self);
3247 let result = this.as_ptr();
3248 // Safety: `this` is ManuallyDrop so the allocator will not be double-dropped
3249 let alloc = unsafe { ptr::read(&this.alloc) };
3250 (result, alloc)
3251 }
3252
3253 /// Converts a raw pointer previously created by [`into_raw`] back into `Weak<T>`.
3254 ///
3255 /// This can be used to safely get a strong reference (by calling [`upgrade`]
3256 /// later) or to deallocate the weak count by dropping the `Weak<T>`.
3257 ///
3258 /// It takes ownership of one weak reference (with the exception of pointers created by [`new`],
3259 /// as these don't own anything; the method still works on them).
3260 ///
3261 /// # Safety
3262 ///
3263 /// The pointer must have originated from the [`into_raw`] and must still own its potential
3264 /// weak reference, and `ptr` must point to a block of memory allocated by `alloc`.
3265 ///
3266 /// It is allowed for the strong count to be 0 at the time of calling this. Nevertheless, this
3267 /// takes ownership of one weak reference currently represented as a raw pointer (the weak
3268 /// count is not modified by this operation) and therefore it must be paired with a previous
3269 /// call to [`into_raw`].
3270 ///
3271 /// # Examples
3272 ///
3273 /// ```
3274 /// use std::rc::{Rc, Weak};
3275 ///
3276 /// let strong = Rc::new("hello".to_owned());
3277 ///
3278 /// let raw_1 = Rc::downgrade(&strong).into_raw();
3279 /// let raw_2 = Rc::downgrade(&strong).into_raw();
3280 ///
3281 /// assert_eq!(2, Rc::weak_count(&strong));
3282 ///
3283 /// assert_eq!("hello", &*unsafe { Weak::from_raw(raw_1) }.upgrade().unwrap());
3284 /// assert_eq!(1, Rc::weak_count(&strong));
3285 ///
3286 /// drop(strong);
3287 ///
3288 /// // Decrement the last weak count.
3289 /// assert!(unsafe { Weak::from_raw(raw_2) }.upgrade().is_none());
3290 /// ```
3291 ///
3292 /// [`into_raw`]: Weak::into_raw
3293 /// [`upgrade`]: Weak::upgrade
3294 /// [`new`]: Weak::new
3295 #[inline]
3296 #[unstable(feature = "allocator_api", issue = "32838")]
3297 pub unsafe fn from_raw_in(ptr: *const T, alloc: A) -> Self {
3298 // See Weak::as_ptr for context on how the input pointer is derived.
3299
3300 let ptr = if is_dangling(ptr) {
3301 // This is a dangling Weak.
3302 ptr as *mut RcInner<T>
3303 } else {
3304 // Otherwise, we're guaranteed the pointer came from a nondangling Weak.
3305 // SAFETY: data_offset is safe to call, as ptr references a real (potentially dropped) T.
3306 let offset = unsafe { data_offset(ptr) };
3307 // Thus, we reverse the offset to get the whole RcInner.
3308 // SAFETY: the pointer originated from a Weak, so this offset is safe.
3309 unsafe { ptr.byte_sub(offset) as *mut RcInner<T> }
3310 };
3311
3312 // SAFETY: we now have recovered the original Weak pointer, so can create the Weak.
3313 Weak { ptr: unsafe { NonNull::new_unchecked(ptr) }, alloc }
3314 }
3315
3316 /// Attempts to upgrade the `Weak` pointer to an [`Rc`], delaying
3317 /// dropping of the inner value if successful.
3318 ///
3319 /// Returns [`None`] if the inner value has since been dropped.
3320 ///
3321 /// # Examples
3322 ///
3323 /// ```
3324 /// use std::rc::Rc;
3325 ///
3326 /// let five = Rc::new(5);
3327 ///
3328 /// let weak_five = Rc::downgrade(&five);
3329 ///
3330 /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
3331 /// assert!(strong_five.is_some());
3332 ///
3333 /// // Destroy all strong pointers.
3334 /// drop(strong_five);
3335 /// drop(five);
3336 ///
3337 /// assert!(weak_five.upgrade().is_none());
3338 /// ```
3339 #[must_use = "this returns a new `Rc`, \
3340 without modifying the original weak pointer"]
3341 #[stable(feature = "rc_weak", since = "1.4.0")]
3342 pub fn upgrade(&self) -> Option<Rc<T, A>>
3343 where
3344 A: Clone,
3345 {
3346 let inner = self.inner()?;
3347
3348 if inner.strong() == 0 {
3349 None
3350 } else {
3351 unsafe {
3352 inner.inc_strong();
3353 Some(Rc::from_inner_in(self.ptr, self.alloc.clone()))
3354 }
3355 }
3356 }
3357
3358 /// Gets the number of strong (`Rc`) pointers pointing to this allocation.
3359 ///
3360 /// If `self` was created using [`Weak::new`], this will return 0.
3361 #[must_use]
3362 #[stable(feature = "weak_counts", since = "1.41.0")]
3363 pub fn strong_count(&self) -> usize {
3364 if let Some(inner) = self.inner() { inner.strong() } else { 0 }
3365 }
3366
3367 /// Gets the number of `Weak` pointers pointing to this allocation.
3368 ///
3369 /// If no strong pointers remain, this will return zero.
3370 #[must_use]
3371 #[stable(feature = "weak_counts", since = "1.41.0")]
3372 pub fn weak_count(&self) -> usize {
3373 if let Some(inner) = self.inner() {
3374 if inner.strong() > 0 {
3375 inner.weak() - 1 // subtract the implicit weak ptr
3376 } else {
3377 0
3378 }
3379 } else {
3380 0
3381 }
3382 }
3383
3384 /// Returns `None` when the pointer is dangling and there is no allocated `RcInner`,
3385 /// (i.e., when this `Weak` was created by `Weak::new`).
3386 #[inline]
3387 fn inner(&self) -> Option<WeakInner<'_>> {
3388 if is_dangling(self.ptr.as_ptr()) {
3389 None
3390 } else {
3391 // We are careful to *not* create a reference covering the "data" field, as
3392 // the field may be mutated concurrently (for example, if the last `Rc`
3393 // is dropped, the data field will be dropped in-place).
3394 Some(unsafe {
3395 let ptr = self.ptr.as_ptr();
3396 WeakInner { strong: &(*ptr).strong, weak: &(*ptr).weak }
3397 })
3398 }
3399 }
3400
3401 /// Returns `true` if the two `Weak`s point to the same allocation similar to [`ptr::eq`], or if
3402 /// both don't point to any allocation (because they were created with `Weak::new()`). However,
3403 /// this function ignores the metadata of `dyn Trait` pointers.
3404 ///
3405 /// # Notes
3406 ///
3407 /// Since this compares pointers it means that `Weak::new()` will equal each
3408 /// other, even though they don't point to any allocation.
3409 ///
3410 /// # Examples
3411 ///
3412 /// ```
3413 /// use std::rc::Rc;
3414 ///
3415 /// let first_rc = Rc::new(5);
3416 /// let first = Rc::downgrade(&first_rc);
3417 /// let second = Rc::downgrade(&first_rc);
3418 ///
3419 /// assert!(first.ptr_eq(&second));
3420 ///
3421 /// let third_rc = Rc::new(5);
3422 /// let third = Rc::downgrade(&third_rc);
3423 ///
3424 /// assert!(!first.ptr_eq(&third));
3425 /// ```
3426 ///
3427 /// Comparing `Weak::new`.
3428 ///
3429 /// ```
3430 /// use std::rc::{Rc, Weak};
3431 ///
3432 /// let first = Weak::new();
3433 /// let second = Weak::new();
3434 /// assert!(first.ptr_eq(&second));
3435 ///
3436 /// let third_rc = Rc::new(());
3437 /// let third = Rc::downgrade(&third_rc);
3438 /// assert!(!first.ptr_eq(&third));
3439 /// ```
3440 #[inline]
3441 #[must_use]
3442 #[stable(feature = "weak_ptr_eq", since = "1.39.0")]
3443 pub fn ptr_eq(&self, other: &Self) -> bool {
3444 ptr::addr_eq(self.ptr.as_ptr(), other.ptr.as_ptr())
3445 }
3446}
3447
3448#[stable(feature = "rc_weak", since = "1.4.0")]
3449unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Weak<T, A> {
3450 /// Drops the `Weak` pointer.
3451 ///
3452 /// # Examples
3453 ///
3454 /// ```
3455 /// use std::rc::{Rc, Weak};
3456 ///
3457 /// struct Foo;
3458 ///
3459 /// impl Drop for Foo {
3460 /// fn drop(&mut self) {
3461 /// println!("dropped!");
3462 /// }
3463 /// }
3464 ///
3465 /// let foo = Rc::new(Foo);
3466 /// let weak_foo = Rc::downgrade(&foo);
3467 /// let other_weak_foo = Weak::clone(&weak_foo);
3468 ///
3469 /// drop(weak_foo); // Doesn't print anything
3470 /// drop(foo); // Prints "dropped!"
3471 ///
3472 /// assert!(other_weak_foo.upgrade().is_none());
3473 /// ```
3474 fn drop(&mut self) {
3475 let inner = if let Some(inner) = self.inner() { inner } else { return };
3476
3477 inner.dec_weak();
3478 // the weak count starts at 1, and will only go to zero if all
3479 // the strong pointers have disappeared.
3480 if inner.weak() == 0 {
3481 unsafe {
3482 self.alloc.deallocate(self.ptr.cast(), Layout::for_value_raw(self.ptr.as_ptr()));
3483 }
3484 }
3485 }
3486}
3487
3488#[stable(feature = "rc_weak", since = "1.4.0")]
3489impl<T: ?Sized, A: Allocator + Clone> Clone for Weak<T, A> {
3490 /// Makes a clone of the `Weak` pointer that points to the same allocation.
3491 ///
3492 /// # Examples
3493 ///
3494 /// ```
3495 /// use std::rc::{Rc, Weak};
3496 ///
3497 /// let weak_five = Rc::downgrade(&Rc::new(5));
3498 ///
3499 /// let _ = Weak::clone(&weak_five);
3500 /// ```
3501 #[inline]
3502 fn clone(&self) -> Weak<T, A> {
3503 if let Some(inner) = self.inner() {
3504 inner.inc_weak()
3505 }
3506 Weak { ptr: self.ptr, alloc: self.alloc.clone() }
3507 }
3508}
3509
3510#[unstable(feature = "ergonomic_clones", issue = "132290")]
3511impl<T: ?Sized, A: Allocator + Clone> UseCloned for Weak<T, A> {}
3512
3513#[stable(feature = "rc_weak", since = "1.4.0")]
3514impl<T: ?Sized, A: Allocator> fmt::Debug for Weak<T, A> {
3515 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3516 write!(f, "(Weak)")
3517 }
3518}
3519
3520#[stable(feature = "downgraded_weak", since = "1.10.0")]
3521impl<T> Default for Weak<T> {
3522 /// Constructs a new `Weak<T>`, without allocating any memory.
3523 /// Calling [`upgrade`] on the return value always gives [`None`].
3524 ///
3525 /// [`upgrade`]: Weak::upgrade
3526 ///
3527 /// # Examples
3528 ///
3529 /// ```
3530 /// use std::rc::Weak;
3531 ///
3532 /// let empty: Weak<i64> = Default::default();
3533 /// assert!(empty.upgrade().is_none());
3534 /// ```
3535 fn default() -> Weak<T> {
3536 Weak::new()
3537 }
3538}
3539
3540// NOTE: If you mem::forget Rcs (or Weaks), drop is skipped and the ref-count
3541// is not decremented, meaning the ref-count can overflow, and then you can
3542// free the allocation while outstanding Rcs (or Weaks) exist, which would be
3543// unsound. We abort because this is such a degenerate scenario that we don't
3544// care about what happens -- no real program should ever experience this.
3545//
3546// This should have negligible overhead since you don't actually need to
3547// clone these much in Rust thanks to ownership and move-semantics.
3548
3549#[doc(hidden)]
3550trait RcInnerPtr {
3551 fn weak_ref(&self) -> &Cell<usize>;
3552 fn strong_ref(&self) -> &Cell<usize>;
3553
3554 #[inline]
3555 fn strong(&self) -> usize {
3556 self.strong_ref().get()
3557 }
3558
3559 #[inline]
3560 fn inc_strong(&self) {
3561 let strong = self.strong();
3562
3563 // We insert an `assume` here to hint LLVM at an otherwise
3564 // missed optimization.
3565 // SAFETY: The reference count will never be zero when this is
3566 // called.
3567 unsafe {
3568 hint::assert_unchecked(strong != 0);
3569 }
3570
3571 let strong = strong.wrapping_add(1);
3572 self.strong_ref().set(strong);
3573
3574 // We want to abort on overflow instead of dropping the value.
3575 // Checking for overflow after the store instead of before
3576 // allows for slightly better code generation.
3577 if core::intrinsics::unlikely(strong == 0) {
3578 abort();
3579 }
3580 }
3581
3582 #[inline]
3583 fn dec_strong(&self) {
3584 self.strong_ref().set(self.strong() - 1);
3585 }
3586
3587 #[inline]
3588 fn weak(&self) -> usize {
3589 self.weak_ref().get()
3590 }
3591
3592 #[inline]
3593 fn inc_weak(&self) {
3594 let weak = self.weak();
3595
3596 // We insert an `assume` here to hint LLVM at an otherwise
3597 // missed optimization.
3598 // SAFETY: The reference count will never be zero when this is
3599 // called.
3600 unsafe {
3601 hint::assert_unchecked(weak != 0);
3602 }
3603
3604 let weak = weak.wrapping_add(1);
3605 self.weak_ref().set(weak);
3606
3607 // We want to abort on overflow instead of dropping the value.
3608 // Checking for overflow after the store instead of before
3609 // allows for slightly better code generation.
3610 if core::intrinsics::unlikely(weak == 0) {
3611 abort();
3612 }
3613 }
3614
3615 #[inline]
3616 fn dec_weak(&self) {
3617 self.weak_ref().set(self.weak() - 1);
3618 }
3619}
3620
3621impl<T: ?Sized> RcInnerPtr for RcInner<T> {
3622 #[inline(always)]
3623 fn weak_ref(&self) -> &Cell<usize> {
3624 &self.weak
3625 }
3626
3627 #[inline(always)]
3628 fn strong_ref(&self) -> &Cell<usize> {
3629 &self.strong
3630 }
3631}
3632
3633impl<'a> RcInnerPtr for WeakInner<'a> {
3634 #[inline(always)]
3635 fn weak_ref(&self) -> &Cell<usize> {
3636 self.weak
3637 }
3638
3639 #[inline(always)]
3640 fn strong_ref(&self) -> &Cell<usize> {
3641 self.strong
3642 }
3643}
3644
3645#[stable(feature = "rust1", since = "1.0.0")]
3646impl<T: ?Sized, A: Allocator> borrow::Borrow<T> for Rc<T, A> {
3647 fn borrow(&self) -> &T {
3648 &**self
3649 }
3650}
3651
3652#[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
3653impl<T: ?Sized, A: Allocator> AsRef<T> for Rc<T, A> {
3654 fn as_ref(&self) -> &T {
3655 &**self
3656 }
3657}
3658
3659#[stable(feature = "pin", since = "1.33.0")]
3660impl<T: ?Sized, A: Allocator> Unpin for Rc<T, A> {}
3661
3662/// Gets the offset within an `RcInner` for the payload behind a pointer.
3663///
3664/// # Safety
3665///
3666/// The pointer must point to (and have valid metadata for) a previously
3667/// valid instance of T, but the T is allowed to be dropped.
3668unsafe fn data_offset<T: ?Sized>(ptr: *const T) -> usize {
3669 // Align the unsized value to the end of the RcInner.
3670 // Because RcInner is repr(C), it will always be the last field in memory.
3671 // SAFETY: since the only unsized types possible are slices, trait objects,
3672 // and extern types, the input safety requirement is currently enough to
3673 // satisfy the requirements of align_of_val_raw; this is an implementation
3674 // detail of the language that must not be relied upon outside of std.
3675 unsafe { data_offset_align(align_of_val_raw(ptr)) }
3676}
3677
3678#[inline]
3679fn data_offset_align(align: usize) -> usize {
3680 let layout = Layout::new::<RcInner<()>>();
3681 layout.size() + layout.padding_needed_for(align)
3682}
3683
3684/// A uniquely owned [`Rc`].
3685///
3686/// This represents an `Rc` that is known to be uniquely owned -- that is, have exactly one strong
3687/// reference. Multiple weak pointers can be created, but attempts to upgrade those to strong
3688/// references will fail unless the `UniqueRc` they point to has been converted into a regular `Rc`.
3689///
3690/// Because they are uniquely owned, the contents of a `UniqueRc` can be freely mutated. A common
3691/// use case is to have an object be mutable during its initialization phase but then have it become
3692/// immutable and converted to a normal `Rc`.
3693///
3694/// This can be used as a flexible way to create cyclic data structures, as in the example below.
3695///
3696/// ```
3697/// #![feature(unique_rc_arc)]
3698/// use std::rc::{Rc, Weak, UniqueRc};
3699///
3700/// struct Gadget {
3701/// #[allow(dead_code)]
3702/// me: Weak<Gadget>,
3703/// }
3704///
3705/// fn create_gadget() -> Option<Rc<Gadget>> {
3706/// let mut rc = UniqueRc::new(Gadget {
3707/// me: Weak::new(),
3708/// });
3709/// rc.me = UniqueRc::downgrade(&rc);
3710/// Some(UniqueRc::into_rc(rc))
3711/// }
3712///
3713/// create_gadget().unwrap();
3714/// ```
3715///
3716/// An advantage of using `UniqueRc` over [`Rc::new_cyclic`] to build cyclic data structures is that
3717/// [`Rc::new_cyclic`]'s `data_fn` parameter cannot be async or return a [`Result`]. As shown in the
3718/// previous example, `UniqueRc` allows for more flexibility in the construction of cyclic data,
3719/// including fallible or async constructors.
3720#[unstable(feature = "unique_rc_arc", issue = "112566")]
3721pub struct UniqueRc<
3722 T: ?Sized,
3723 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
3724> {
3725 ptr: NonNull<RcInner<T>>,
3726 // Define the ownership of `RcInner<T>` for drop-check
3727 _marker: PhantomData<RcInner<T>>,
3728 // Invariance is necessary for soundness: once other `Weak`
3729 // references exist, we already have a form of shared mutability!
3730 _marker2: PhantomData<*mut T>,
3731 alloc: A,
3732}
3733
3734// Not necessary for correctness since `UniqueRc` contains `NonNull`,
3735// but having an explicit negative impl is nice for documentation purposes
3736// and results in nicer error messages.
3737#[unstable(feature = "unique_rc_arc", issue = "112566")]
3738impl<T: ?Sized, A: Allocator> !Send for UniqueRc<T, A> {}
3739
3740// Not necessary for correctness since `UniqueRc` contains `NonNull`,
3741// but having an explicit negative impl is nice for documentation purposes
3742// and results in nicer error messages.
3743#[unstable(feature = "unique_rc_arc", issue = "112566")]
3744impl<T: ?Sized, A: Allocator> !Sync for UniqueRc<T, A> {}
3745
3746#[unstable(feature = "unique_rc_arc", issue = "112566")]
3747impl<T: ?Sized + Unsize<U>, U: ?Sized, A: Allocator> CoerceUnsized<UniqueRc<U, A>>
3748 for UniqueRc<T, A>
3749{
3750}
3751
3752//#[unstable(feature = "unique_rc_arc", issue = "112566")]
3753#[unstable(feature = "dispatch_from_dyn", issue = "none")]
3754impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<UniqueRc<U>> for UniqueRc<T> {}
3755
3756#[unstable(feature = "unique_rc_arc", issue = "112566")]
3757impl<T: ?Sized + fmt::Display, A: Allocator> fmt::Display for UniqueRc<T, A> {
3758 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3759 fmt::Display::fmt(&**self, f)
3760 }
3761}
3762
3763#[unstable(feature = "unique_rc_arc", issue = "112566")]
3764impl<T: ?Sized + fmt::Debug, A: Allocator> fmt::Debug for UniqueRc<T, A> {
3765 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3766 fmt::Debug::fmt(&**self, f)
3767 }
3768}
3769
3770#[unstable(feature = "unique_rc_arc", issue = "112566")]
3771impl<T: ?Sized, A: Allocator> fmt::Pointer for UniqueRc<T, A> {
3772 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3773 fmt::Pointer::fmt(&(&raw const **self), f)
3774 }
3775}
3776
3777#[unstable(feature = "unique_rc_arc", issue = "112566")]
3778impl<T: ?Sized, A: Allocator> borrow::Borrow<T> for UniqueRc<T, A> {
3779 fn borrow(&self) -> &T {
3780 &**self
3781 }
3782}
3783
3784#[unstable(feature = "unique_rc_arc", issue = "112566")]
3785impl<T: ?Sized, A: Allocator> borrow::BorrowMut<T> for UniqueRc<T, A> {
3786 fn borrow_mut(&mut self) -> &mut T {
3787 &mut **self
3788 }
3789}
3790
3791#[unstable(feature = "unique_rc_arc", issue = "112566")]
3792impl<T: ?Sized, A: Allocator> AsRef<T> for UniqueRc<T, A> {
3793 fn as_ref(&self) -> &T {
3794 &**self
3795 }
3796}
3797
3798#[unstable(feature = "unique_rc_arc", issue = "112566")]
3799impl<T: ?Sized, A: Allocator> AsMut<T> for UniqueRc<T, A> {
3800 fn as_mut(&mut self) -> &mut T {
3801 &mut **self
3802 }
3803}
3804
3805#[unstable(feature = "unique_rc_arc", issue = "112566")]
3806impl<T: ?Sized, A: Allocator> Unpin for UniqueRc<T, A> {}
3807
3808#[unstable(feature = "unique_rc_arc", issue = "112566")]
3809impl<T: ?Sized + PartialEq, A: Allocator> PartialEq for UniqueRc<T, A> {
3810 /// Equality for two `UniqueRc`s.
3811 ///
3812 /// Two `UniqueRc`s are equal if their inner values are equal.
3813 ///
3814 /// # Examples
3815 ///
3816 /// ```
3817 /// #![feature(unique_rc_arc)]
3818 /// use std::rc::UniqueRc;
3819 ///
3820 /// let five = UniqueRc::new(5);
3821 ///
3822 /// assert!(five == UniqueRc::new(5));
3823 /// ```
3824 #[inline]
3825 fn eq(&self, other: &Self) -> bool {
3826 PartialEq::eq(&**self, &**other)
3827 }
3828
3829 /// Inequality for two `UniqueRc`s.
3830 ///
3831 /// Two `UniqueRc`s are not equal if their inner values are not equal.
3832 ///
3833 /// # Examples
3834 ///
3835 /// ```
3836 /// #![feature(unique_rc_arc)]
3837 /// use std::rc::UniqueRc;
3838 ///
3839 /// let five = UniqueRc::new(5);
3840 ///
3841 /// assert!(five != UniqueRc::new(6));
3842 /// ```
3843 #[inline]
3844 fn ne(&self, other: &Self) -> bool {
3845 PartialEq::ne(&**self, &**other)
3846 }
3847}
3848
3849#[unstable(feature = "unique_rc_arc", issue = "112566")]
3850impl<T: ?Sized + PartialOrd, A: Allocator> PartialOrd for UniqueRc<T, A> {
3851 /// Partial comparison for two `UniqueRc`s.
3852 ///
3853 /// The two are compared by calling `partial_cmp()` on their inner values.
3854 ///
3855 /// # Examples
3856 ///
3857 /// ```
3858 /// #![feature(unique_rc_arc)]
3859 /// use std::rc::UniqueRc;
3860 /// use std::cmp::Ordering;
3861 ///
3862 /// let five = UniqueRc::new(5);
3863 ///
3864 /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&UniqueRc::new(6)));
3865 /// ```
3866 #[inline(always)]
3867 fn partial_cmp(&self, other: &UniqueRc<T, A>) -> Option<Ordering> {
3868 (**self).partial_cmp(&**other)
3869 }
3870
3871 /// Less-than comparison for two `UniqueRc`s.
3872 ///
3873 /// The two are compared by calling `<` on their inner values.
3874 ///
3875 /// # Examples
3876 ///
3877 /// ```
3878 /// #![feature(unique_rc_arc)]
3879 /// use std::rc::UniqueRc;
3880 ///
3881 /// let five = UniqueRc::new(5);
3882 ///
3883 /// assert!(five < UniqueRc::new(6));
3884 /// ```
3885 #[inline(always)]
3886 fn lt(&self, other: &UniqueRc<T, A>) -> bool {
3887 **self < **other
3888 }
3889
3890 /// 'Less than or equal to' comparison for two `UniqueRc`s.
3891 ///
3892 /// The two are compared by calling `<=` on their inner values.
3893 ///
3894 /// # Examples
3895 ///
3896 /// ```
3897 /// #![feature(unique_rc_arc)]
3898 /// use std::rc::UniqueRc;
3899 ///
3900 /// let five = UniqueRc::new(5);
3901 ///
3902 /// assert!(five <= UniqueRc::new(5));
3903 /// ```
3904 #[inline(always)]
3905 fn le(&self, other: &UniqueRc<T, A>) -> bool {
3906 **self <= **other
3907 }
3908
3909 /// Greater-than comparison for two `UniqueRc`s.
3910 ///
3911 /// The two are compared by calling `>` on their inner values.
3912 ///
3913 /// # Examples
3914 ///
3915 /// ```
3916 /// #![feature(unique_rc_arc)]
3917 /// use std::rc::UniqueRc;
3918 ///
3919 /// let five = UniqueRc::new(5);
3920 ///
3921 /// assert!(five > UniqueRc::new(4));
3922 /// ```
3923 #[inline(always)]
3924 fn gt(&self, other: &UniqueRc<T, A>) -> bool {
3925 **self > **other
3926 }
3927
3928 /// 'Greater than or equal to' comparison for two `UniqueRc`s.
3929 ///
3930 /// The two are compared by calling `>=` on their inner values.
3931 ///
3932 /// # Examples
3933 ///
3934 /// ```
3935 /// #![feature(unique_rc_arc)]
3936 /// use std::rc::UniqueRc;
3937 ///
3938 /// let five = UniqueRc::new(5);
3939 ///
3940 /// assert!(five >= UniqueRc::new(5));
3941 /// ```
3942 #[inline(always)]
3943 fn ge(&self, other: &UniqueRc<T, A>) -> bool {
3944 **self >= **other
3945 }
3946}
3947
3948#[unstable(feature = "unique_rc_arc", issue = "112566")]
3949impl<T: ?Sized + Ord, A: Allocator> Ord for UniqueRc<T, A> {
3950 /// Comparison for two `UniqueRc`s.
3951 ///
3952 /// The two are compared by calling `cmp()` on their inner values.
3953 ///
3954 /// # Examples
3955 ///
3956 /// ```
3957 /// #![feature(unique_rc_arc)]
3958 /// use std::rc::UniqueRc;
3959 /// use std::cmp::Ordering;
3960 ///
3961 /// let five = UniqueRc::new(5);
3962 ///
3963 /// assert_eq!(Ordering::Less, five.cmp(&UniqueRc::new(6)));
3964 /// ```
3965 #[inline]
3966 fn cmp(&self, other: &UniqueRc<T, A>) -> Ordering {
3967 (**self).cmp(&**other)
3968 }
3969}
3970
3971#[unstable(feature = "unique_rc_arc", issue = "112566")]
3972impl<T: ?Sized + Eq, A: Allocator> Eq for UniqueRc<T, A> {}
3973
3974#[unstable(feature = "unique_rc_arc", issue = "112566")]
3975impl<T: ?Sized + Hash, A: Allocator> Hash for UniqueRc<T, A> {
3976 fn hash<H: Hasher>(&self, state: &mut H) {
3977 (**self).hash(state);
3978 }
3979}
3980
3981// Depends on A = Global
3982impl<T> UniqueRc<T> {
3983 /// Creates a new `UniqueRc`.
3984 ///
3985 /// Weak references to this `UniqueRc` can be created with [`UniqueRc::downgrade`]. Upgrading
3986 /// these weak references will fail before the `UniqueRc` has been converted into an [`Rc`].
3987 /// After converting the `UniqueRc` into an [`Rc`], any weak references created beforehand will
3988 /// point to the new [`Rc`].
3989 #[cfg(not(no_global_oom_handling))]
3990 #[unstable(feature = "unique_rc_arc", issue = "112566")]
3991 pub fn new(value: T) -> Self {
3992 Self::new_in(value, Global)
3993 }
3994}
3995
3996impl<T, A: Allocator> UniqueRc<T, A> {
3997 /// Creates a new `UniqueRc` in the provided allocator.
3998 ///
3999 /// Weak references to this `UniqueRc` can be created with [`UniqueRc::downgrade`]. Upgrading
4000 /// these weak references will fail before the `UniqueRc` has been converted into an [`Rc`].
4001 /// After converting the `UniqueRc` into an [`Rc`], any weak references created beforehand will
4002 /// point to the new [`Rc`].
4003 #[cfg(not(no_global_oom_handling))]
4004 #[unstable(feature = "unique_rc_arc", issue = "112566")]
4005 pub fn new_in(value: T, alloc: A) -> Self {
4006 let (ptr, alloc) = Box::into_unique(Box::new_in(
4007 RcInner {
4008 strong: Cell::new(0),
4009 // keep one weak reference so if all the weak pointers that are created are dropped
4010 // the UniqueRc still stays valid.
4011 weak: Cell::new(1),
4012 value,
4013 },
4014 alloc,
4015 ));
4016 Self { ptr: ptr.into(), _marker: PhantomData, _marker2: PhantomData, alloc }
4017 }
4018}
4019
4020impl<T: ?Sized, A: Allocator> UniqueRc<T, A> {
4021 /// Converts the `UniqueRc` into a regular [`Rc`].
4022 ///
4023 /// This consumes the `UniqueRc` and returns a regular [`Rc`] that contains the `value` that
4024 /// is passed to `into_rc`.
4025 ///
4026 /// Any weak references created before this method is called can now be upgraded to strong
4027 /// references.
4028 #[unstable(feature = "unique_rc_arc", issue = "112566")]
4029 pub fn into_rc(this: Self) -> Rc<T, A> {
4030 let mut this = ManuallyDrop::new(this);
4031
4032 // Move the allocator out.
4033 // SAFETY: `this.alloc` will not be accessed again, nor dropped because it is in
4034 // a `ManuallyDrop`.
4035 let alloc: A = unsafe { ptr::read(&this.alloc) };
4036
4037 // SAFETY: This pointer was allocated at creation time so we know it is valid.
4038 unsafe {
4039 // Convert our weak reference into a strong reference
4040 this.ptr.as_mut().strong.set(1);
4041 Rc::from_inner_in(this.ptr, alloc)
4042 }
4043 }
4044}
4045
4046impl<T: ?Sized, A: Allocator + Clone> UniqueRc<T, A> {
4047 /// Creates a new weak reference to the `UniqueRc`.
4048 ///
4049 /// Attempting to upgrade this weak reference will fail before the `UniqueRc` has been converted
4050 /// to a [`Rc`] using [`UniqueRc::into_rc`].
4051 #[unstable(feature = "unique_rc_arc", issue = "112566")]
4052 pub fn downgrade(this: &Self) -> Weak<T, A> {
4053 // SAFETY: This pointer was allocated at creation time and we guarantee that we only have
4054 // one strong reference before converting to a regular Rc.
4055 unsafe {
4056 this.ptr.as_ref().inc_weak();
4057 }
4058 Weak { ptr: this.ptr, alloc: this.alloc.clone() }
4059 }
4060}
4061
4062#[unstable(feature = "unique_rc_arc", issue = "112566")]
4063impl<T: ?Sized, A: Allocator> Deref for UniqueRc<T, A> {
4064 type Target = T;
4065
4066 fn deref(&self) -> &T {
4067 // SAFETY: This pointer was allocated at creation time so we know it is valid.
4068 unsafe { &self.ptr.as_ref().value }
4069 }
4070}
4071
4072#[unstable(feature = "unique_rc_arc", issue = "112566")]
4073impl<T: ?Sized, A: Allocator> DerefMut for UniqueRc<T, A> {
4074 fn deref_mut(&mut self) -> &mut T {
4075 // SAFETY: This pointer was allocated at creation time so we know it is valid. We know we
4076 // have unique ownership and therefore it's safe to make a mutable reference because
4077 // `UniqueRc` owns the only strong reference to itself.
4078 unsafe { &mut (*self.ptr.as_ptr()).value }
4079 }
4080}
4081
4082#[unstable(feature = "unique_rc_arc", issue = "112566")]
4083unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for UniqueRc<T, A> {
4084 fn drop(&mut self) {
4085 unsafe {
4086 // destroy the contained object
4087 drop_in_place(DerefMut::deref_mut(self));
4088
4089 // remove the implicit "strong weak" pointer now that we've destroyed the contents.
4090 self.ptr.as_ref().dec_weak();
4091
4092 if self.ptr.as_ref().weak() == 0 {
4093 self.alloc.deallocate(self.ptr.cast(), Layout::for_value_raw(self.ptr.as_ptr()));
4094 }
4095 }
4096 }
4097}
4098
4099/// A unique owning pointer to a [`RcInner`] **that does not imply the contents are initialized,**
4100/// but will deallocate it (without dropping the value) when dropped.
4101///
4102/// This is a helper for [`Rc::make_mut()`] to ensure correct cleanup on panic.
4103/// It is nearly a duplicate of `UniqueRc<MaybeUninit<T>, A>` except that it allows `T: !Sized`,
4104/// which `MaybeUninit` does not.
4105#[cfg(not(no_global_oom_handling))]
4106struct UniqueRcUninit<T: ?Sized, A: Allocator> {
4107 ptr: NonNull<RcInner<T>>,
4108 layout_for_value: Layout,
4109 alloc: Option<A>,
4110}
4111
4112#[cfg(not(no_global_oom_handling))]
4113impl<T: ?Sized, A: Allocator> UniqueRcUninit<T, A> {
4114 /// Allocates a RcInner with layout suitable to contain `for_value` or a clone of it.
4115 fn new(for_value: &T, alloc: A) -> UniqueRcUninit<T, A> {
4116 let layout = Layout::for_value(for_value);
4117 let ptr = unsafe {
4118 Rc::allocate_for_layout(
4119 layout,
4120 |layout_for_rc_inner| alloc.allocate(layout_for_rc_inner),
4121 |mem| mem.with_metadata_of(ptr::from_ref(for_value) as *const RcInner<T>),
4122 )
4123 };
4124 Self { ptr: NonNull::new(ptr).unwrap(), layout_for_value: layout, alloc: Some(alloc) }
4125 }
4126
4127 /// Returns the pointer to be written into to initialize the [`Rc`].
4128 fn data_ptr(&mut self) -> *mut T {
4129 let offset = data_offset_align(self.layout_for_value.align());
4130 unsafe { self.ptr.as_ptr().byte_add(offset) as *mut T }
4131 }
4132
4133 /// Upgrade this into a normal [`Rc`].
4134 ///
4135 /// # Safety
4136 ///
4137 /// The data must have been initialized (by writing to [`Self::data_ptr()`]).
4138 unsafe fn into_rc(self) -> Rc<T, A> {
4139 let mut this = ManuallyDrop::new(self);
4140 let ptr = this.ptr;
4141 let alloc = this.alloc.take().unwrap();
4142
4143 // SAFETY: The pointer is valid as per `UniqueRcUninit::new`, and the caller is responsible
4144 // for having initialized the data.
4145 unsafe { Rc::from_ptr_in(ptr.as_ptr(), alloc) }
4146 }
4147}
4148
4149#[cfg(not(no_global_oom_handling))]
4150impl<T: ?Sized, A: Allocator> Drop for UniqueRcUninit<T, A> {
4151 fn drop(&mut self) {
4152 // SAFETY:
4153 // * new() produced a pointer safe to deallocate.
4154 // * We own the pointer unless into_rc() was called, which forgets us.
4155 unsafe {
4156 self.alloc.take().unwrap().deallocate(
4157 self.ptr.cast(),
4158 rc_inner_layout_for_value_layout(self.layout_for_value),
4159 );
4160 }
4161 }
4162}