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