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 #[rustc_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 #[rustc_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`, it is safe to call [`get_mut_unchecked`]
2001 /// immediately afterward.
2002 ///
2003 /// # Examples
2004 ///
2005 /// ```
2006 /// #![feature(arc_is_unique)]
2007 ///
2008 /// use std::rc::Rc;
2009 ///
2010 /// let x = Rc::new(3);
2011 /// assert!(Rc::is_unique(&x));
2012 ///
2013 /// let y = Rc::clone(&x);
2014 /// assert!(!Rc::is_unique(&x));
2015 /// drop(y);
2016 ///
2017 /// // Weak references also count, because they could be upgraded at any time.
2018 /// let z = Rc::downgrade(&x);
2019 /// assert!(!Rc::is_unique(&x));
2020 /// ```
2021 ///
2022 /// # Pointer invalidation
2023 ///
2024 /// This function will always return the same value as `Rc::get_mut(rc).is_some()`. However,
2025 /// unlike that operation it does not produce any mutable references to the underlying data,
2026 /// meaning no pointers to the data inside the `Rc` are invalidated by the call. Thus, the
2027 /// following code is valid, even though it would be UB if it used `Rc::get_mut`:
2028 ///
2029 /// ```
2030 /// #![feature(arc_is_unique)]
2031 ///
2032 /// use std::rc::Rc;
2033 ///
2034 /// let rc = Rc::new(5);
2035 /// let pointer: *const i32 = &*rc;
2036 /// assert!(Rc::is_unique(&rc));
2037 /// assert_eq!(unsafe { *pointer }, 5);
2038 /// ```
2039 ///
2040 /// [`get_mut_unchecked`]: Self::get_mut_unchecked
2041 #[inline]
2042 #[unstable(feature = "arc_is_unique", issue = "138938")]
2043 pub fn is_unique(this: &Self) -> bool {
2044 Rc::weak_count(this) == 0 && Rc::strong_count(this) == 1
2045 }
2046
2047 /// Returns a mutable reference into the given `Rc`, if there are
2048 /// no other `Rc` or [`Weak`] pointers to the same allocation.
2049 ///
2050 /// Returns [`None`] otherwise, because it is not safe to
2051 /// mutate a shared value.
2052 ///
2053 /// See also [`make_mut`][make_mut], which will [`clone`][clone]
2054 /// the inner value when there are other `Rc` pointers.
2055 ///
2056 /// [make_mut]: Rc::make_mut
2057 /// [clone]: Clone::clone
2058 ///
2059 /// # Examples
2060 ///
2061 /// ```
2062 /// use std::rc::Rc;
2063 ///
2064 /// let mut x = Rc::new(3);
2065 /// *Rc::get_mut(&mut x).unwrap() = 4;
2066 /// assert_eq!(*x, 4);
2067 ///
2068 /// let _y = Rc::clone(&x);
2069 /// assert!(Rc::get_mut(&mut x).is_none());
2070 /// ```
2071 #[inline]
2072 #[stable(feature = "rc_unique", since = "1.4.0")]
2073 pub fn get_mut(this: &mut Self) -> Option<&mut T> {
2074 // SAFETY: Ensured by uniqueness check.
2075 if Rc::is_unique(this) { unsafe { Some(Rc::get_mut_unchecked(this)) } } else { None }
2076 }
2077
2078 /// Returns a mutable reference into the given `Rc`,
2079 /// without any check.
2080 ///
2081 /// See also [`get_mut`], which is safe and does appropriate checks.
2082 ///
2083 /// [`get_mut`]: Rc::get_mut
2084 ///
2085 /// # Safety
2086 ///
2087 /// If any other `Rc` or [`Weak`] pointers to the same allocation exist, then
2088 /// they must not be dereferenced or have active borrows for the duration
2089 /// of the returned borrow, and their inner type must be exactly the same as the
2090 /// inner type of this Rc (including lifetimes). This is trivially the case if no
2091 /// such pointers exist, for example immediately after `Rc::new`.
2092 ///
2093 /// # Examples
2094 ///
2095 /// ```
2096 /// #![feature(get_mut_unchecked)]
2097 ///
2098 /// use std::rc::Rc;
2099 ///
2100 /// let mut x = Rc::new(String::new());
2101 /// unsafe {
2102 /// Rc::get_mut_unchecked(&mut x).push_str("foo")
2103 /// }
2104 /// assert_eq!(*x, "foo");
2105 /// ```
2106 /// Other `Rc` pointers to the same allocation must be to the same type.
2107 /// ```no_run
2108 /// #![feature(get_mut_unchecked)]
2109 ///
2110 /// use std::rc::Rc;
2111 ///
2112 /// let x: Rc<str> = Rc::from("Hello, world!");
2113 /// let mut y: Rc<[u8]> = x.clone().into();
2114 /// unsafe {
2115 /// // this is Undefined Behavior, because x's inner type is str, not [u8]
2116 /// Rc::get_mut_unchecked(&mut y).fill(0xff); // 0xff is invalid in UTF-8
2117 /// }
2118 /// println!("{}", &*x); // Invalid UTF-8 in a str
2119 /// ```
2120 /// Other `Rc` pointers to the same allocation must be to the exact same type, including lifetimes.
2121 /// ```no_run
2122 /// #![feature(get_mut_unchecked)]
2123 ///
2124 /// use std::rc::Rc;
2125 ///
2126 /// let x: Rc<&str> = Rc::new("Hello, world!");
2127 /// {
2128 /// let s = String::from("Oh, no!");
2129 /// let mut y: Rc<&str> = x.clone();
2130 /// unsafe {
2131 /// // this is Undefined Behavior, because x's inner type
2132 /// // is &'long str, not &'short str
2133 /// *Rc::get_mut_unchecked(&mut y) = &s;
2134 /// }
2135 /// }
2136 /// println!("{}", &*x); // Use-after-free
2137 /// ```
2138 #[inline]
2139 #[unstable(feature = "get_mut_unchecked", issue = "63292")]
2140 pub unsafe fn get_mut_unchecked(this: &mut Self) -> &mut T {
2141 // We are careful to *not* create a reference covering the "count" fields, as
2142 // this would conflict with accesses to the reference counts (e.g. by `Weak`).
2143 // ignore-tidy-undocumented-unsafe
2144 unsafe { &mut (*this.ptr.as_ptr()).value }
2145 }
2146
2147 #[inline]
2148 #[stable(feature = "ptr_eq", since = "1.17.0")]
2149 /// Returns `true` if the two `Rc`s point to the same allocation in a vein similar to
2150 /// [`ptr::eq`]. This function ignores the metadata of `dyn Trait` pointers.
2151 ///
2152 /// # Examples
2153 ///
2154 /// ```
2155 /// use std::rc::Rc;
2156 ///
2157 /// let five = Rc::new(5);
2158 /// let same_five = Rc::clone(&five);
2159 /// let other_five = Rc::new(5);
2160 ///
2161 /// assert!(Rc::ptr_eq(&five, &same_five));
2162 /// assert!(!Rc::ptr_eq(&five, &other_five));
2163 /// ```
2164 pub fn ptr_eq(this: &Self, other: &Self) -> bool {
2165 ptr::addr_eq(this.ptr.as_ptr(), other.ptr.as_ptr())
2166 }
2167}
2168
2169#[cfg(not(no_global_oom_handling))]
2170impl<T: ?Sized + CloneToUninit, A: AllocatorClone> Rc<T, A> {
2171 /// Makes a mutable reference into the given `Rc`.
2172 ///
2173 /// If there are other `Rc` pointers to the same allocation, then `make_mut` will
2174 /// [`clone`] the inner value to a new allocation to ensure unique ownership. This is also
2175 /// referred to as clone-on-write.
2176 ///
2177 /// However, if there are no other `Rc` pointers to this allocation, but some [`Weak`]
2178 /// pointers, then the [`Weak`] pointers will be disassociated and the inner value will not
2179 /// be cloned.
2180 ///
2181 /// See also [`get_mut`], which will fail rather than cloning the inner value
2182 /// or disassociating [`Weak`] pointers.
2183 ///
2184 /// [`clone`]: Clone::clone
2185 /// [`get_mut`]: Rc::get_mut
2186 ///
2187 /// # Examples
2188 ///
2189 /// ```
2190 /// use std::rc::Rc;
2191 ///
2192 /// let mut data = Rc::new(5);
2193 ///
2194 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
2195 /// let mut other_data = Rc::clone(&data); // Won't clone inner data
2196 /// *Rc::make_mut(&mut data) += 1; // Clones inner data
2197 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
2198 /// *Rc::make_mut(&mut other_data) *= 2; // Won't clone anything
2199 ///
2200 /// // Now `data` and `other_data` point to different allocations.
2201 /// assert_eq!(*data, 8);
2202 /// assert_eq!(*other_data, 12);
2203 /// ```
2204 ///
2205 /// [`Weak`] pointers will be disassociated:
2206 ///
2207 /// ```
2208 /// use std::rc::Rc;
2209 ///
2210 /// let mut data = Rc::new(75);
2211 /// let weak = Rc::downgrade(&data);
2212 ///
2213 /// assert!(75 == *data);
2214 /// assert!(75 == *weak.upgrade().unwrap());
2215 ///
2216 /// *Rc::make_mut(&mut data) += 1;
2217 ///
2218 /// assert!(76 == *data);
2219 /// assert!(weak.upgrade().is_none());
2220 /// ```
2221 #[inline]
2222 #[stable(feature = "rc_unique", since = "1.4.0")]
2223 pub fn make_mut(this: &mut Self) -> &mut T {
2224 let size_of_val = size_of_val::<T>(&**this);
2225
2226 if Rc::strong_count(this) != 1 {
2227 // Gotta clone the data, there are other Rcs.
2228 *this = Rc::clone_from_ref_in(&**this, this.alloc.clone());
2229 } else if Rc::weak_count(this) != 0 {
2230 // Can just steal the data, all that's left is Weaks
2231
2232 let mut in_progress: UniqueRcUninit<T, A> =
2233 UniqueRcUninit::new(&**this, this.alloc.clone());
2234 // ignore-tidy-undocumented-unsafe
2235 unsafe {
2236 // Initialize `in_progress` with move of **this.
2237 // We have to express this in terms of bytes because `T: ?Sized`; there is no
2238 // operation that just copies a value based on its `size_of_val()`.
2239 ptr::copy_nonoverlapping(
2240 ptr::from_ref(&**this).cast::<u8>(),
2241 in_progress.data_ptr().cast::<u8>(),
2242 size_of_val,
2243 );
2244
2245 // This leaves us with 0 strong refs, so the data has
2246 // effectively been moved to the new rc.
2247 this.inner().dec_strong();
2248
2249 // Remove implicit strong-weak ref (no need to craft a fake
2250 // Weak here -- we know other Weaks can clean up for us)
2251 this.inner().dec_weak();
2252
2253 // Last chance to not accidentally forget the allocator.
2254 // Only drop at the end of the scope to avoid panics.
2255 let _alloc = ptr::read(&this.alloc);
2256
2257 // Replace `this` with newly constructed Rc that has the moved data.
2258 ptr::write(this, in_progress.into_rc());
2259 }
2260 }
2261 // SAFETY: We're guaranteed that the pointer
2262 // returned is the *only* pointer that will ever be returned to T. Our
2263 // reference count is guaranteed to be 1 at this point, and we required
2264 // the `Rc<T>` itself to be `mut`, so we're returning the only possible
2265 // reference to the allocation.
2266 unsafe { &mut this.ptr.as_mut().value }
2267 }
2268}
2269
2270impl<T: Clone, A: Allocator> Rc<T, A> {
2271 /// If we have the only reference to `T` then unwrap it. Otherwise, clone `T` and return the
2272 /// clone.
2273 ///
2274 /// Assuming `rc_t` is of type `Rc<T>`, this function is functionally equivalent to
2275 /// `(*rc_t).clone()`, but will avoid cloning the inner value where possible.
2276 ///
2277 /// # Examples
2278 ///
2279 /// ```
2280 /// # use std::{ptr, rc::Rc};
2281 /// let inner = String::from("test");
2282 /// let ptr = inner.as_ptr();
2283 ///
2284 /// let rc = Rc::new(inner);
2285 /// let inner = Rc::unwrap_or_clone(rc);
2286 /// // The inner value was not cloned
2287 /// assert!(ptr::eq(ptr, inner.as_ptr()));
2288 ///
2289 /// let rc = Rc::new(inner);
2290 /// let rc2 = rc.clone();
2291 /// let inner = Rc::unwrap_or_clone(rc);
2292 /// // Because there were 2 references, we had to clone the inner value.
2293 /// assert!(!ptr::eq(ptr, inner.as_ptr()));
2294 /// // `rc2` is the last reference, so when we unwrap it we get back
2295 /// // the original `String`.
2296 /// let inner = Rc::unwrap_or_clone(rc2);
2297 /// assert!(ptr::eq(ptr, inner.as_ptr()));
2298 /// ```
2299 #[inline]
2300 #[stable(feature = "arc_unwrap_or_clone", since = "1.76.0")]
2301 pub fn unwrap_or_clone(this: Self) -> T {
2302 Rc::try_unwrap(this).unwrap_or_else(|rc| (*rc).clone())
2303 }
2304}
2305
2306impl<A: Allocator> Rc<dyn Any, A> {
2307 /// Attempts to downcast the `Rc<dyn Any>` to a concrete type.
2308 ///
2309 /// # Examples
2310 ///
2311 /// ```
2312 /// use std::any::Any;
2313 /// use std::rc::Rc;
2314 ///
2315 /// fn print_if_string(value: Rc<dyn Any>) {
2316 /// if let Ok(string) = value.downcast::<String>() {
2317 /// println!("String ({}): {}", string.len(), string);
2318 /// }
2319 /// }
2320 ///
2321 /// let my_string = "Hello World".to_string();
2322 /// print_if_string(Rc::new(my_string));
2323 /// print_if_string(Rc::new(0i8));
2324 /// ```
2325 #[inline]
2326 #[stable(feature = "rc_downcast", since = "1.29.0")]
2327 pub fn downcast<T: Any>(self) -> Result<Rc<T, A>, Self> {
2328 if (*self).is::<T>() {
2329 // SAFETY: Check ensures typecast is corrext.
2330 unsafe {
2331 let (ptr, alloc) = Rc::into_inner_with_allocator(self);
2332 Ok(Rc::from_inner_in(ptr.cast(), alloc))
2333 }
2334 } else {
2335 Err(self)
2336 }
2337 }
2338
2339 /// Downcasts the `Rc<dyn Any>` to a concrete type.
2340 ///
2341 /// For a safe alternative see [`downcast`].
2342 ///
2343 /// # Examples
2344 ///
2345 /// ```
2346 /// #![feature(downcast_unchecked)]
2347 ///
2348 /// use std::any::Any;
2349 /// use std::rc::Rc;
2350 ///
2351 /// let x: Rc<dyn Any> = Rc::new(1_usize);
2352 ///
2353 /// unsafe {
2354 /// assert_eq!(*x.downcast_unchecked::<usize>(), 1);
2355 /// }
2356 /// ```
2357 ///
2358 /// # Safety
2359 ///
2360 /// The contained value must be of type `T`. Calling this method
2361 /// with the incorrect type is *undefined behavior*.
2362 ///
2363 /// [`downcast`]: Self::downcast
2364 #[inline]
2365 #[unstable(feature = "downcast_unchecked", issue = "90850")]
2366 pub unsafe fn downcast_unchecked<T: Any>(self) -> Rc<T, A> {
2367 // SAFETY: Caller ensures typecast is correct.
2368 unsafe {
2369 let (ptr, alloc) = Rc::into_inner_with_allocator(self);
2370 Rc::from_inner_in(ptr.cast(), alloc)
2371 }
2372 }
2373}
2374
2375impl<T: ?Sized> Rc<T> {
2376 /// Allocates an `RcInner<T>` with sufficient space for
2377 /// a possibly-unsized inner value where the value has the layout provided.
2378 ///
2379 /// The function `mem_to_rc_inner` is called with the data pointer
2380 /// and must return back a (potentially fat)-pointer for the `RcInner<T>`.
2381 #[cfg(not(no_global_oom_handling))]
2382 unsafe fn allocate_for_layout(
2383 value_layout: Layout,
2384 allocate: impl FnOnce(Layout) -> Result<NonNull<[u8]>, AllocError>,
2385 mem_to_rc_inner: impl FnOnce(*mut u8) -> *mut RcInner<T>,
2386 ) -> *mut RcInner<T> {
2387 let layout = rc_inner_layout_for_value_layout(value_layout);
2388 // ignore-tidy-undocumented-unsafe
2389 unsafe {
2390 Rc::try_allocate_for_layout(value_layout, allocate, mem_to_rc_inner)
2391 .unwrap_or_else(|_| handle_alloc_error(layout))
2392 }
2393 }
2394
2395 /// Allocates an `RcInner<T>` with sufficient space for
2396 /// a possibly-unsized inner value where the value has the layout provided,
2397 /// returning an error if allocation fails.
2398 ///
2399 /// The function `mem_to_rc_inner` is called with the data pointer
2400 /// and must return back a (potentially fat)-pointer for the `RcInner<T>`.
2401 #[inline]
2402 unsafe fn try_allocate_for_layout(
2403 value_layout: Layout,
2404 allocate: impl FnOnce(Layout) -> Result<NonNull<[u8]>, AllocError>,
2405 mem_to_rc_inner: impl FnOnce(*mut u8) -> *mut RcInner<T>,
2406 ) -> Result<*mut RcInner<T>, AllocError> {
2407 let layout = rc_inner_layout_for_value_layout(value_layout);
2408
2409 // Allocate for the layout.
2410 let ptr = allocate(layout)?;
2411
2412 // Initialize the RcInner
2413 let inner = mem_to_rc_inner(ptr.as_non_null_ptr().as_ptr());
2414 // ignore-tidy-undocumented-unsafe
2415 unsafe {
2416 debug_assert_eq!(Layout::for_value_raw(inner), layout);
2417
2418 (&raw mut (*inner).strong).write(Cell::new(1));
2419 (&raw mut (*inner).weak).write(Cell::new(1));
2420 }
2421
2422 Ok(inner)
2423 }
2424}
2425
2426impl<T: ?Sized, A: Allocator> Rc<T, A> {
2427 /// Allocates an `RcInner<T>` with sufficient space for an unsized inner value
2428 #[cfg(not(no_global_oom_handling))]
2429 unsafe fn allocate_for_ptr_in(ptr: *const T, alloc: &A) -> *mut RcInner<T> {
2430 // Allocate for the `RcInner<T>` using the given value.
2431 // ignore-tidy-undocumented-unsafe
2432 unsafe {
2433 Rc::<T>::allocate_for_layout(
2434 Layout::for_value_raw(ptr),
2435 |layout| alloc.allocate(layout),
2436 |mem| mem.with_metadata_of(ptr as *const RcInner<T>),
2437 )
2438 }
2439 }
2440
2441 #[cfg(not(no_global_oom_handling))]
2442 fn from_box_in(src: Box<T, A>) -> Rc<T, A> {
2443 let value_size = size_of_val(&*src);
2444 // ignore-tidy-undocumented-unsafe
2445 unsafe {
2446 let ptr = Self::allocate_for_ptr_in(&*src, Box::allocator(&src));
2447
2448 // Copy value as bytes
2449 ptr::copy_nonoverlapping(
2450 (&raw const *src) as *const u8,
2451 (&raw mut (*ptr).value) as *mut u8,
2452 value_size,
2453 );
2454
2455 // Free the allocation without dropping its contents
2456 let (bptr, alloc) = Box::into_raw_with_allocator(src);
2457 let src = Box::from_raw_in(bptr as *mut mem::ManuallyDrop<T>, &alloc);
2458 drop(src);
2459
2460 Self::from_ptr_in(ptr, alloc)
2461 }
2462 }
2463}
2464
2465impl<T> Rc<[T]> {
2466 /// Allocates an `RcInner<[T]>` with the given length.
2467 #[cfg(not(no_global_oom_handling))]
2468 unsafe fn allocate_for_slice(len: usize) -> *mut RcInner<[T]> {
2469 // ignore-tidy-undocumented-unsafe
2470 unsafe {
2471 Self::allocate_for_layout(
2472 Layout::array::<T>(len).unwrap(),
2473 |layout| Global.allocate(layout),
2474 |mem| mem.cast::<T>().cast_slice(len) as *mut RcInner<[T]>,
2475 )
2476 }
2477 }
2478
2479 /// Copy elements from slice into newly allocated `Rc<[T]>`
2480 ///
2481 /// Unsafe because the caller must either take ownership, bind `T: Copy` or
2482 /// bind `T: TrivialClone`.
2483 #[cfg(not(no_global_oom_handling))]
2484 unsafe fn copy_from_slice(v: &[T]) -> Rc<[T]> {
2485 // ignore-tidy-undocumented-unsafe
2486 unsafe {
2487 let ptr = Self::allocate_for_slice(v.len());
2488 ptr::copy_nonoverlapping(v.as_ptr(), (&raw mut (*ptr).value) as *mut T, v.len());
2489 Self::from_ptr(ptr)
2490 }
2491 }
2492
2493 /// Constructs an `Rc<[T]>` from an iterator known to be of a certain size.
2494 ///
2495 /// Behavior is undefined should the size be wrong.
2496 #[cfg(not(no_global_oom_handling))]
2497 unsafe fn from_iter_exact(iter: impl Iterator<Item = T>, len: usize) -> Rc<[T]> {
2498 // Panic guard while cloning T elements.
2499 // In the event of a panic, elements that have been written
2500 // into the new RcInner will be dropped, then the memory freed.
2501 struct Guard<T> {
2502 mem: NonNull<u8>,
2503 elems: *mut T,
2504 layout: Layout,
2505 n_elems: usize,
2506 }
2507
2508 impl<T> Drop for Guard<T> {
2509 fn drop(&mut self) {
2510 // ignore-tidy-undocumented-unsafe
2511 unsafe {
2512 let slice = from_raw_parts_mut(self.elems, self.n_elems);
2513 ptr::drop_in_place(slice);
2514
2515 Global.deallocate(self.mem, self.layout);
2516 }
2517 }
2518 }
2519
2520 // ignore-tidy-undocumented-unsafe
2521 unsafe {
2522 let ptr = Self::allocate_for_slice(len);
2523
2524 let mem = ptr as *mut _ as *mut u8;
2525 let layout = Layout::for_value_raw(ptr);
2526
2527 // Pointer to first element
2528 let elems = (&raw mut (*ptr).value) as *mut T;
2529
2530 let mut guard = Guard { mem: NonNull::new_unchecked(mem), elems, layout, n_elems: 0 };
2531
2532 for (i, item) in iter.enumerate() {
2533 ptr::write(elems.add(i), item);
2534 guard.n_elems += 1;
2535 }
2536
2537 // All clear. Forget the guard so it doesn't free the new RcInner.
2538 mem::forget(guard);
2539
2540 Self::from_ptr(ptr)
2541 }
2542 }
2543}
2544
2545impl<T, A: Allocator> Rc<[T], A> {
2546 /// Allocates an `RcInner<[T]>` with the given length.
2547 #[inline]
2548 #[cfg(not(no_global_oom_handling))]
2549 unsafe fn allocate_for_slice_in(len: usize, alloc: &A) -> *mut RcInner<[T]> {
2550 // ignore-tidy-undocumented-unsafe
2551 unsafe {
2552 Rc::<[T]>::allocate_for_layout(
2553 Layout::array::<T>(len).unwrap(),
2554 |layout| alloc.allocate(layout),
2555 |mem| mem.cast::<T>().cast_slice(len) as *mut RcInner<[T]>,
2556 )
2557 }
2558 }
2559}
2560
2561#[cfg(not(no_global_oom_handling))]
2562/// Specialization trait used for `From<&[T]>`.
2563trait RcFromSlice<T> {
2564 fn from_slice(slice: &[T]) -> Self;
2565}
2566
2567#[cfg(not(no_global_oom_handling))]
2568impl<T: Clone> RcFromSlice<T> for Rc<[T]> {
2569 #[inline]
2570 default fn from_slice(v: &[T]) -> Self {
2571 // ignore-tidy-undocumented-unsafe
2572 unsafe { Self::from_iter_exact(v.iter().cloned(), v.len()) }
2573 }
2574}
2575
2576#[cfg(not(no_global_oom_handling))]
2577impl<T: TrivialClone> RcFromSlice<T> for Rc<[T]> {
2578 #[inline]
2579 fn from_slice(v: &[T]) -> Self {
2580 // SAFETY: `T` implements `TrivialClone`, so this is sound and equivalent
2581 // to the above.
2582 unsafe { Rc::copy_from_slice(v) }
2583 }
2584}
2585
2586#[stable(feature = "rust1", since = "1.0.0")]
2587impl<T: ?Sized, A: Allocator> Deref for Rc<T, A> {
2588 type Target = T;
2589
2590 #[inline(always)]
2591 fn deref(&self) -> &T {
2592 &self.inner().value
2593 }
2594}
2595
2596// The API of this pointer type enforces that if the `T` is pinned, then *all*
2597// clones of this `Rc<T>` are wrapped as `Pin<Rc<T>>`. Since an `&Rc<T>` could
2598// be used to obtain an `Rc<T>` that is not wrapped in `Pin` (and later used
2599// with `Rc::get_mut`), this means that this type treats `&Rc<T>` as evidence
2600// that the `T` is not pinned. The implementations of various traits are written
2601// accordingly. Since this type is not fundamental, downstream crates cannot
2602// provide malicious implementations of any of the traits relevant for `Pin`.
2603#[unstable(feature = "pin_coerce_unsized_trait", issue = "150112")]
2604unsafe impl<T: ?Sized, A: StaticAllocator> PinSafePointer for Rc<T, A> {}
2605
2606//#[unstable(feature = "unique_rc_arc", issue = "112566")]
2607#[unstable(feature = "pin_coerce_unsized_trait", issue = "150112")]
2608unsafe impl<T: ?Sized, A: StaticAllocator> PinSafePointer for UniqueRc<T, A> {}
2609
2610#[unstable(feature = "deref_pure_trait", issue = "87121")]
2611unsafe impl<T: ?Sized, A: Allocator> DerefPure for Rc<T, A> {}
2612
2613//#[unstable(feature = "unique_rc_arc", issue = "112566")]
2614#[unstable(feature = "deref_pure_trait", issue = "87121")]
2615unsafe impl<T: ?Sized, A: Allocator> DerefPure for UniqueRc<T, A> {}
2616
2617#[unstable(feature = "legacy_receiver_trait", issue = "none")]
2618impl<T: ?Sized> LegacyReceiver for Rc<T> {}
2619
2620#[stable(feature = "rust1", since = "1.0.0")]
2621unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Rc<T, A> {
2622 /// Drops the `Rc`.
2623 ///
2624 /// This will decrement the strong reference count. If the strong reference
2625 /// count reaches zero then the only other references (if any) are
2626 /// [`Weak`], so we `drop` the inner value.
2627 ///
2628 /// # Examples
2629 ///
2630 /// ```
2631 /// use std::rc::Rc;
2632 ///
2633 /// struct Foo;
2634 ///
2635 /// impl Drop for Foo {
2636 /// fn drop(&mut self) {
2637 /// println!("dropped!");
2638 /// }
2639 /// }
2640 ///
2641 /// let foo = Rc::new(Foo);
2642 /// let foo2 = Rc::clone(&foo);
2643 ///
2644 /// drop(foo); // Doesn't print anything
2645 /// drop(foo2); // Prints "dropped!"
2646 /// ```
2647 #[inline]
2648 fn drop(&mut self) {
2649 // ignore-tidy-undocumented-unsafe
2650 unsafe {
2651 self.inner().dec_strong();
2652 if self.inner().strong() == 0 {
2653 self.drop_slow();
2654 }
2655 }
2656 }
2657}
2658
2659#[stable(feature = "rust1", since = "1.0.0")]
2660impl<T: ?Sized, A: AllocatorClone> Clone for Rc<T, A> {
2661 /// Makes a clone of the `Rc` pointer.
2662 ///
2663 /// This creates another pointer to the same allocation, increasing the
2664 /// strong reference count.
2665 ///
2666 /// # Examples
2667 ///
2668 /// ```
2669 /// use std::rc::Rc;
2670 ///
2671 /// let five = Rc::new(5);
2672 ///
2673 /// let _ = Rc::clone(&five);
2674 /// ```
2675 #[inline]
2676 fn clone(&self) -> Self {
2677 // ignore-tidy-undocumented-unsafe
2678 unsafe {
2679 self.inner().inc_strong();
2680 Self::from_inner_in(self.ptr, self.alloc.clone())
2681 }
2682 }
2683}
2684
2685#[unstable(feature = "ergonomic_clones", issue = "132290")]
2686impl<T: ?Sized, A: AllocatorClone> UseCloned for Rc<T, A> {}
2687
2688#[unstable(feature = "share_trait", issue = "156756")]
2689impl<T: ?Sized, A: AllocatorClone> Share for Rc<T, A> {}
2690
2691#[cfg(not(no_global_oom_handling))]
2692#[stable(feature = "rust1", since = "1.0.0")]
2693impl<T: Default> Default for Rc<T> {
2694 /// Creates a new `Rc<T>`, with the `Default` value for `T`.
2695 ///
2696 /// # Examples
2697 ///
2698 /// ```
2699 /// use std::rc::Rc;
2700 ///
2701 /// let x: Rc<i32> = Default::default();
2702 /// assert_eq!(*x, 0);
2703 /// ```
2704 #[inline]
2705 fn default() -> Self {
2706 // ignore-tidy-undocumented-unsafe
2707 unsafe {
2708 Self::from_inner(Box::into_non_null(Box::write(
2709 Box::new_uninit(),
2710 RcInner { strong: Cell::new(1), weak: Cell::new(1), value: T::default() },
2711 )))
2712 }
2713 }
2714}
2715
2716#[cfg(not(no_global_oom_handling))]
2717#[stable(feature = "more_rc_default_impls", since = "1.80.0")]
2718impl Default for Rc<str> {
2719 /// Creates an empty `str` inside an `Rc`.
2720 ///
2721 /// This may or may not share an allocation with other Rcs on the same thread.
2722 #[inline]
2723 fn default() -> Self {
2724 let rc = Rc::<[u8]>::default();
2725 // SAFETY: `[u8]` has the same layout as `str`.
2726 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const str) }
2727 }
2728}
2729
2730#[cfg(not(no_global_oom_handling))]
2731#[stable(feature = "more_rc_default_impls", since = "1.80.0")]
2732impl<T> Default for Rc<[T]> {
2733 /// Creates an empty `[T]` inside an `Rc`.
2734 ///
2735 /// This may or may not share an allocation with other Rcs on the same thread.
2736 #[inline]
2737 fn default() -> Self {
2738 let arr: [T; 0] = [];
2739 Rc::from(arr)
2740 }
2741}
2742
2743#[cfg(not(no_global_oom_handling))]
2744#[stable(feature = "pin_default_impls", since = "1.91.0")]
2745impl<T> Default for Pin<Rc<T>>
2746where
2747 T: ?Sized,
2748 Rc<T>: Default,
2749{
2750 #[inline]
2751 fn default() -> Self {
2752 // SAFETY: We own and create the pinned pointer.
2753 unsafe { Pin::new_unchecked(Rc::<T>::default()) }
2754 }
2755}
2756
2757#[stable(feature = "rust1", since = "1.0.0")]
2758trait RcEqIdent<T: ?Sized + PartialEq, A: Allocator> {
2759 fn eq(&self, other: &Rc<T, A>) -> bool;
2760 fn ne(&self, other: &Rc<T, A>) -> bool;
2761}
2762
2763#[stable(feature = "rust1", since = "1.0.0")]
2764impl<T: ?Sized + PartialEq, A: Allocator> RcEqIdent<T, A> for Rc<T, A> {
2765 #[inline]
2766 default fn eq(&self, other: &Rc<T, A>) -> bool {
2767 **self == **other
2768 }
2769
2770 #[inline]
2771 default fn ne(&self, other: &Rc<T, A>) -> bool {
2772 **self != **other
2773 }
2774}
2775
2776// Hack to allow specializing on `Eq` even though `Eq` has a method.
2777#[unsafe(rustc_allow_lifetime_dependent_specialization)]
2778pub(crate) trait MarkerEq: PartialEq<Self> {}
2779
2780impl<T: ?Sized + Eq> MarkerEq for T {}
2781
2782/// We're doing this specialization here, and not as a more general optimization on `&T`, because it
2783/// would otherwise add a cost to all equality checks on refs. We assume that `Rc`s are used to
2784/// store large values, that are slow to clone, but also heavy to check for equality, causing this
2785/// cost to pay off more easily. It's also more likely to have two `Rc` clones, that point to
2786/// the same value, than two `&T`s.
2787///
2788/// We can only do this when `T: Eq` as a `PartialEq` might be deliberately irreflexive.
2789#[stable(feature = "rust1", since = "1.0.0")]
2790impl<T: ?Sized + MarkerEq, A: Allocator> RcEqIdent<T, A> for Rc<T, A> {
2791 #[inline]
2792 fn eq(&self, other: &Rc<T, A>) -> bool {
2793 ptr::eq(self.ptr.as_ptr(), other.ptr.as_ptr()) || **self == **other
2794 }
2795
2796 #[inline]
2797 fn ne(&self, other: &Rc<T, A>) -> bool {
2798 !ptr::eq(self.ptr.as_ptr(), other.ptr.as_ptr()) && **self != **other
2799 }
2800}
2801
2802#[stable(feature = "rust1", since = "1.0.0")]
2803impl<T: ?Sized + PartialEq, A: Allocator> PartialEq for Rc<T, A> {
2804 /// Equality for two `Rc`s.
2805 ///
2806 /// Two `Rc`s are equal if their inner values are equal, even if they are
2807 /// stored in different allocation.
2808 ///
2809 /// If `T` also implements `Eq` (implying reflexivity of equality),
2810 /// two `Rc`s that point to the same allocation are
2811 /// always equal.
2812 ///
2813 /// # Examples
2814 ///
2815 /// ```
2816 /// use std::rc::Rc;
2817 ///
2818 /// let five = Rc::new(5);
2819 ///
2820 /// assert!(five == Rc::new(5));
2821 /// ```
2822 #[inline]
2823 fn eq(&self, other: &Rc<T, A>) -> bool {
2824 RcEqIdent::eq(self, other)
2825 }
2826
2827 /// Inequality for two `Rc`s.
2828 ///
2829 /// Two `Rc`s are not equal if their inner values are not equal.
2830 ///
2831 /// If `T` also implements `Eq` (implying reflexivity of equality),
2832 /// two `Rc`s that point to the same allocation are
2833 /// always equal.
2834 ///
2835 /// # Examples
2836 ///
2837 /// ```
2838 /// use std::rc::Rc;
2839 ///
2840 /// let five = Rc::new(5);
2841 ///
2842 /// assert!(five != Rc::new(6));
2843 /// ```
2844 #[inline]
2845 fn ne(&self, other: &Rc<T, A>) -> bool {
2846 RcEqIdent::ne(self, other)
2847 }
2848}
2849
2850#[stable(feature = "rust1", since = "1.0.0")]
2851impl<T: ?Sized + Eq, A: Allocator> Eq for Rc<T, A> {}
2852
2853#[stable(feature = "rust1", since = "1.0.0")]
2854impl<T: ?Sized + PartialOrd, A: Allocator> PartialOrd for Rc<T, A> {
2855 /// Partial comparison for two `Rc`s.
2856 ///
2857 /// The two are compared by calling `partial_cmp()` on their inner values.
2858 ///
2859 /// # Examples
2860 ///
2861 /// ```
2862 /// use std::rc::Rc;
2863 /// use std::cmp::Ordering;
2864 ///
2865 /// let five = Rc::new(5);
2866 ///
2867 /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&Rc::new(6)));
2868 /// ```
2869 #[inline(always)]
2870 fn partial_cmp(&self, other: &Rc<T, A>) -> Option<Ordering> {
2871 (**self).partial_cmp(&**other)
2872 }
2873
2874 /// Less-than comparison for two `Rc`s.
2875 ///
2876 /// The two are compared by calling `<` on their inner values.
2877 ///
2878 /// # Examples
2879 ///
2880 /// ```
2881 /// use std::rc::Rc;
2882 ///
2883 /// let five = Rc::new(5);
2884 ///
2885 /// assert!(five < Rc::new(6));
2886 /// ```
2887 #[inline(always)]
2888 fn lt(&self, other: &Rc<T, A>) -> bool {
2889 **self < **other
2890 }
2891
2892 /// 'Less than or equal to' comparison for two `Rc`s.
2893 ///
2894 /// The two are compared by calling `<=` on their inner values.
2895 ///
2896 /// # Examples
2897 ///
2898 /// ```
2899 /// use std::rc::Rc;
2900 ///
2901 /// let five = Rc::new(5);
2902 ///
2903 /// assert!(five <= Rc::new(5));
2904 /// ```
2905 #[inline(always)]
2906 fn le(&self, other: &Rc<T, A>) -> bool {
2907 **self <= **other
2908 }
2909
2910 /// Greater-than comparison for two `Rc`s.
2911 ///
2912 /// The two are compared by calling `>` on their inner values.
2913 ///
2914 /// # Examples
2915 ///
2916 /// ```
2917 /// use std::rc::Rc;
2918 ///
2919 /// let five = Rc::new(5);
2920 ///
2921 /// assert!(five > Rc::new(4));
2922 /// ```
2923 #[inline(always)]
2924 fn gt(&self, other: &Rc<T, A>) -> bool {
2925 **self > **other
2926 }
2927
2928 /// 'Greater than or equal to' comparison for two `Rc`s.
2929 ///
2930 /// The two are compared by calling `>=` on their inner values.
2931 ///
2932 /// # Examples
2933 ///
2934 /// ```
2935 /// use std::rc::Rc;
2936 ///
2937 /// let five = Rc::new(5);
2938 ///
2939 /// assert!(five >= Rc::new(5));
2940 /// ```
2941 #[inline(always)]
2942 fn ge(&self, other: &Rc<T, A>) -> bool {
2943 **self >= **other
2944 }
2945}
2946
2947#[stable(feature = "rust1", since = "1.0.0")]
2948impl<T: ?Sized + Ord, A: Allocator> Ord for Rc<T, A> {
2949 /// Comparison for two `Rc`s.
2950 ///
2951 /// The two are compared by calling `cmp()` on their inner values.
2952 ///
2953 /// # Examples
2954 ///
2955 /// ```
2956 /// use std::rc::Rc;
2957 /// use std::cmp::Ordering;
2958 ///
2959 /// let five = Rc::new(5);
2960 ///
2961 /// assert_eq!(Ordering::Less, five.cmp(&Rc::new(6)));
2962 /// ```
2963 #[inline]
2964 fn cmp(&self, other: &Rc<T, A>) -> Ordering {
2965 (**self).cmp(&**other)
2966 }
2967}
2968
2969#[stable(feature = "rust1", since = "1.0.0")]
2970impl<T: ?Sized + Hash, A: Allocator> Hash for Rc<T, A> {
2971 fn hash<H: Hasher>(&self, state: &mut H) {
2972 (**self).hash(state);
2973 }
2974}
2975
2976#[stable(feature = "rust1", since = "1.0.0")]
2977impl<T: ?Sized + fmt::Display, A: Allocator> fmt::Display for Rc<T, A> {
2978 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2979 fmt::Display::fmt(&**self, f)
2980 }
2981}
2982
2983#[stable(feature = "rust1", since = "1.0.0")]
2984impl<T: ?Sized + fmt::Debug, A: Allocator> fmt::Debug for Rc<T, A> {
2985 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2986 fmt::Debug::fmt(&**self, f)
2987 }
2988}
2989
2990#[stable(feature = "rust1", since = "1.0.0")]
2991impl<T: ?Sized, A: Allocator> fmt::Pointer for Rc<T, A> {
2992 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2993 fmt::Pointer::fmt(&(&raw const **self), f)
2994 }
2995}
2996
2997#[cfg(not(no_global_oom_handling))]
2998#[stable(feature = "from_for_ptrs", since = "1.6.0")]
2999impl<T> From<T> for Rc<T> {
3000 /// Converts a generic type `T` into an `Rc<T>`
3001 ///
3002 /// The conversion allocates on the heap and moves `t`
3003 /// from the stack into it.
3004 ///
3005 /// # Example
3006 /// ```rust
3007 /// # use std::rc::Rc;
3008 /// let x = 5;
3009 /// let rc = Rc::new(5);
3010 ///
3011 /// assert_eq!(Rc::from(x), rc);
3012 /// ```
3013 fn from(t: T) -> Self {
3014 Rc::new(t)
3015 }
3016}
3017
3018#[cfg(not(no_global_oom_handling))]
3019#[stable(feature = "shared_from_array", since = "1.74.0")]
3020impl<T, const N: usize> From<[T; N]> for Rc<[T]> {
3021 /// Converts a [`[T; N]`](prim@array) into an `Rc<[T]>`.
3022 ///
3023 /// The conversion moves the array into a newly allocated `Rc`.
3024 ///
3025 /// # Example
3026 ///
3027 /// ```
3028 /// # use std::rc::Rc;
3029 /// let original: [i32; 3] = [1, 2, 3];
3030 /// let shared: Rc<[i32]> = Rc::from(original);
3031 /// assert_eq!(&[1, 2, 3], &shared[..]);
3032 /// ```
3033 #[inline]
3034 fn from(v: [T; N]) -> Rc<[T]> {
3035 Rc::<[T; N]>::from(v)
3036 }
3037}
3038
3039#[cfg(not(no_global_oom_handling))]
3040#[stable(feature = "shared_from_slice", since = "1.21.0")]
3041impl<T: Clone> From<&[T]> for Rc<[T]> {
3042 /// Allocates a reference-counted slice and fills it by cloning `v`'s items.
3043 ///
3044 /// # Example
3045 ///
3046 /// ```
3047 /// # use std::rc::Rc;
3048 /// let original: &[i32] = &[1, 2, 3];
3049 /// let shared: Rc<[i32]> = Rc::from(original);
3050 /// assert_eq!(&[1, 2, 3], &shared[..]);
3051 /// ```
3052 #[inline]
3053 fn from(v: &[T]) -> Rc<[T]> {
3054 <Self as RcFromSlice<T>>::from_slice(v)
3055 }
3056}
3057
3058#[cfg(not(no_global_oom_handling))]
3059#[stable(feature = "shared_from_mut_slice", since = "1.84.0")]
3060impl<T: Clone> From<&mut [T]> for Rc<[T]> {
3061 /// Allocates a reference-counted slice and fills it by cloning `v`'s items.
3062 ///
3063 /// # Example
3064 ///
3065 /// ```
3066 /// # use std::rc::Rc;
3067 /// let mut original = [1, 2, 3];
3068 /// let original: &mut [i32] = &mut original;
3069 /// let shared: Rc<[i32]> = Rc::from(original);
3070 /// assert_eq!(&[1, 2, 3], &shared[..]);
3071 /// ```
3072 #[inline]
3073 fn from(v: &mut [T]) -> Rc<[T]> {
3074 Rc::from(&*v)
3075 }
3076}
3077
3078#[cfg(not(no_global_oom_handling))]
3079#[stable(feature = "shared_from_slice", since = "1.21.0")]
3080impl From<&str> for Rc<str> {
3081 /// Allocates a reference-counted string slice and copies `v` into it.
3082 ///
3083 /// # Example
3084 ///
3085 /// ```
3086 /// # use std::rc::Rc;
3087 /// let shared: Rc<str> = Rc::from("statue");
3088 /// assert_eq!("statue", &shared[..]);
3089 /// ```
3090 #[inline]
3091 fn from(v: &str) -> Rc<str> {
3092 let rc = Rc::<[u8]>::from(v.as_bytes());
3093 // ignore-tidy-undocumented-unsafe
3094 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const str) }
3095 }
3096}
3097
3098#[cfg(not(no_global_oom_handling))]
3099#[stable(feature = "shared_from_mut_slice", since = "1.84.0")]
3100impl From<&mut str> for Rc<str> {
3101 /// Allocates a reference-counted string slice and copies `v` into it.
3102 ///
3103 /// # Example
3104 ///
3105 /// ```
3106 /// # use std::rc::Rc;
3107 /// let mut original = String::from("statue");
3108 /// let original: &mut str = &mut original;
3109 /// let shared: Rc<str> = Rc::from(original);
3110 /// assert_eq!("statue", &shared[..]);
3111 /// ```
3112 #[inline]
3113 fn from(v: &mut str) -> Rc<str> {
3114 Rc::from(&*v)
3115 }
3116}
3117
3118#[cfg(not(no_global_oom_handling))]
3119#[stable(feature = "shared_from_slice", since = "1.21.0")]
3120impl From<String> for Rc<str> {
3121 /// Allocates a reference-counted string slice and copies `v` into it.
3122 ///
3123 /// # Example
3124 ///
3125 /// ```
3126 /// # use std::rc::Rc;
3127 /// let original: String = "statue".to_owned();
3128 /// let shared: Rc<str> = Rc::from(original);
3129 /// assert_eq!("statue", &shared[..]);
3130 /// ```
3131 #[inline]
3132 fn from(v: String) -> Rc<str> {
3133 Rc::from(&v[..])
3134 }
3135}
3136
3137#[cfg(not(no_global_oom_handling))]
3138#[stable(feature = "shared_from_slice", since = "1.21.0")]
3139impl<T: ?Sized, A: AllocatorNightly> From<Box<T, A>> for Rc<T, A> {
3140 /// Move a boxed object to a new, reference counted, allocation.
3141 ///
3142 /// # Example
3143 ///
3144 /// ```
3145 /// # use std::rc::Rc;
3146 /// let original: Box<i32> = Box::new(1);
3147 /// let shared: Rc<i32> = Rc::from(original);
3148 /// assert_eq!(1, *shared);
3149 /// ```
3150 #[inline]
3151 fn from(v: Box<T, A>) -> Rc<T, A> {
3152 Rc::from_box_in(v)
3153 }
3154}
3155
3156#[cfg(not(no_global_oom_handling))]
3157#[stable(feature = "shared_from_slice", since = "1.21.0")]
3158impl<T, A: AllocatorNightly> From<Vec<T, A>> for Rc<[T], A> {
3159 /// Allocates a reference-counted slice and moves `v`'s items into it.
3160 ///
3161 /// # Example
3162 ///
3163 /// ```
3164 /// # use std::rc::Rc;
3165 /// let unique: Vec<i32> = vec![1, 2, 3];
3166 /// let shared: Rc<[i32]> = Rc::from(unique);
3167 /// assert_eq!(&[1, 2, 3], &shared[..]);
3168 /// ```
3169 #[inline]
3170 fn from(v: Vec<T, A>) -> Rc<[T], A> {
3171 // ignore-tidy-undocumented-unsafe
3172 unsafe {
3173 let (vec_ptr, len, cap, alloc) = v.into_raw_parts_with_allocator();
3174
3175 let rc_ptr = Self::allocate_for_slice_in(len, &alloc);
3176 ptr::copy_nonoverlapping(vec_ptr, (&raw mut (*rc_ptr).value) as *mut T, len);
3177
3178 // Create a `Vec<T, &A>` with length 0, to deallocate the buffer
3179 // without dropping its contents or the allocator
3180 let _ = Vec::from_raw_parts_in(vec_ptr, 0, cap, &alloc);
3181
3182 Self::from_ptr_in(rc_ptr, alloc)
3183 }
3184 }
3185}
3186
3187#[stable(feature = "shared_from_cow", since = "1.45.0")]
3188impl<'a, B> From<Cow<'a, B>> for Rc<B>
3189where
3190 B: ToOwned + ?Sized,
3191 Rc<B>: From<&'a B> + From<B::Owned>,
3192{
3193 /// Creates a reference-counted pointer from a clone-on-write pointer by
3194 /// copying its content.
3195 ///
3196 /// # Example
3197 ///
3198 /// ```rust
3199 /// # use std::rc::Rc;
3200 /// # use std::borrow::Cow;
3201 /// let cow: Cow<'_, str> = Cow::Borrowed("eggplant");
3202 /// let shared: Rc<str> = Rc::from(cow);
3203 /// assert_eq!("eggplant", &shared[..]);
3204 /// ```
3205 #[inline]
3206 fn from(cow: Cow<'a, B>) -> Rc<B> {
3207 match cow {
3208 Cow::Borrowed(s) => Rc::from(s),
3209 Cow::Owned(s) => Rc::from(s),
3210 }
3211 }
3212}
3213
3214#[stable(feature = "shared_from_str", since = "1.62.0")]
3215impl From<Rc<str>> for Rc<[u8]> {
3216 /// Converts a reference-counted string slice into a byte slice.
3217 ///
3218 /// # Example
3219 ///
3220 /// ```
3221 /// # use std::rc::Rc;
3222 /// let string: Rc<str> = Rc::from("eggplant");
3223 /// let bytes: Rc<[u8]> = Rc::from(string);
3224 /// assert_eq!("eggplant".as_bytes(), bytes.as_ref());
3225 /// ```
3226 #[inline]
3227 fn from(rc: Rc<str>) -> Self {
3228 // SAFETY: `str` has the same layout as `[u8]`.
3229 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const [u8]) }
3230 }
3231}
3232
3233#[stable(feature = "boxed_slice_try_from", since = "1.43.0")]
3234impl<T, A: Allocator, const N: usize> TryFrom<Rc<[T], A>> for Rc<[T; N], A> {
3235 type Error = Rc<[T], A>;
3236
3237 fn try_from(boxed_slice: Rc<[T], A>) -> Result<Self, Self::Error> {
3238 if boxed_slice.len() == N {
3239 let (ptr, alloc) = Rc::into_inner_with_allocator(boxed_slice);
3240 // ignore-tidy-undocumented-unsafe
3241 Ok(unsafe { Rc::from_inner_in(ptr.cast(), alloc) })
3242 } else {
3243 Err(boxed_slice)
3244 }
3245 }
3246}
3247
3248#[cfg(not(no_global_oom_handling))]
3249#[stable(feature = "shared_from_iter", since = "1.37.0")]
3250impl<T> FromIterator<T> for Rc<[T]> {
3251 /// Takes each element in the `Iterator` and collects it into an `Rc<[T]>`.
3252 ///
3253 /// # Performance characteristics
3254 ///
3255 /// ## The general case
3256 ///
3257 /// In the general case, collecting into `Rc<[T]>` is done by first
3258 /// collecting into a `Vec<T>`. That is, when writing the following:
3259 ///
3260 /// ```rust
3261 /// # use std::rc::Rc;
3262 /// let evens: Rc<[u8]> = (0..10).filter(|&x| x % 2 == 0).collect();
3263 /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]);
3264 /// ```
3265 ///
3266 /// this behaves as if we wrote:
3267 ///
3268 /// ```rust
3269 /// # use std::rc::Rc;
3270 /// let evens: Rc<[u8]> = (0..10).filter(|&x| x % 2 == 0)
3271 /// .collect::<Vec<_>>() // The first set of allocations happens here.
3272 /// .into(); // A second allocation for `Rc<[T]>` happens here.
3273 /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]);
3274 /// ```
3275 ///
3276 /// This will allocate as many times as needed for constructing the `Vec<T>`
3277 /// and then it will allocate once for turning the `Vec<T>` into the `Rc<[T]>`.
3278 ///
3279 /// ## Iterators of known length
3280 ///
3281 /// When your `Iterator` implements `TrustedLen` and is of an exact size,
3282 /// a single allocation will be made for the `Rc<[T]>`. For example:
3283 ///
3284 /// ```rust
3285 /// # use std::rc::Rc;
3286 /// let evens: Rc<[u8]> = (0..10).collect(); // Just a single allocation happens here.
3287 /// # assert_eq!(&*evens, &*(0..10).collect::<Vec<_>>());
3288 /// ```
3289 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
3290 ToRcSlice::to_rc_slice(iter.into_iter())
3291 }
3292}
3293
3294/// Specialization trait used for collecting into `Rc<[T]>`.
3295#[cfg(not(no_global_oom_handling))]
3296trait ToRcSlice<T>: Iterator<Item = T> + Sized {
3297 fn to_rc_slice(self) -> Rc<[T]>;
3298}
3299
3300#[cfg(not(no_global_oom_handling))]
3301impl<T, I: Iterator<Item = T>> ToRcSlice<T> for I {
3302 default fn to_rc_slice(self) -> Rc<[T]> {
3303 self.collect::<Vec<T>>().into()
3304 }
3305}
3306
3307#[cfg(not(no_global_oom_handling))]
3308impl<T, I: iter::TrustedLen<Item = T>> ToRcSlice<T> for I {
3309 fn to_rc_slice(self) -> Rc<[T]> {
3310 // This is the case for a `TrustedLen` iterator.
3311 let (low, high) = self.size_hint();
3312 if let Some(high) = high {
3313 debug_assert_eq!(
3314 low,
3315 high,
3316 "TrustedLen iterator's size hint is not exact: {:?}",
3317 (low, high)
3318 );
3319
3320 // SAFETY: We need to ensure that the iterator has an exact length and we have.
3321 unsafe { Rc::from_iter_exact(self, low) }
3322 } else {
3323 // TrustedLen contract guarantees that `upper_bound == None` implies an iterator
3324 // length exceeding `usize::MAX`.
3325 // The default implementation would collect into a vec which would panic.
3326 // Thus we panic here immediately without invoking `Vec` code.
3327 panic!("capacity overflow");
3328 }
3329 }
3330}
3331
3332/// `Weak` is a version of [`Rc`] that holds a non-owning reference to the
3333/// managed allocation.
3334///
3335/// The allocation is accessed by calling [`upgrade`] on the `Weak`
3336/// pointer, which returns an <code>[Option]<[Rc]\<T>></code>.
3337///
3338/// Since a `Weak` reference does not count towards ownership, it will not
3339/// prevent the value stored in the allocation from being dropped, and `Weak` itself makes no
3340/// guarantees about the value still being present. Thus it may return [`None`]
3341/// when [`upgrade`]d. Note however that a `Weak` reference *does* prevent the allocation
3342/// itself (the backing store) from being deallocated.
3343///
3344/// A `Weak` pointer is useful for keeping a temporary reference to the allocation
3345/// managed by [`Rc`] without preventing its inner value from being dropped. It is also used to
3346/// prevent circular references between [`Rc`] pointers, since mutual owning references
3347/// would never allow either [`Rc`] to be dropped. For example, a tree could
3348/// have strong [`Rc`] pointers from parent nodes to children, and `Weak`
3349/// pointers from children back to their parents.
3350///
3351/// The typical way to obtain a `Weak` pointer is to call [`Rc::downgrade`].
3352///
3353/// [`upgrade`]: Weak::upgrade
3354#[stable(feature = "rc_weak", since = "1.4.0")]
3355#[rustc_diagnostic_item = "RcWeak"]
3356pub struct Weak<
3357 T: ?Sized,
3358 #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] A: Allocator = Global,
3359> {
3360 // This is a `NonNull` to allow optimizing the size of this type in enums,
3361 // but it is not necessarily a valid pointer.
3362 // `Weak::new` sets this to `usize::MAX` so that it doesn’t need
3363 // to allocate space on the heap. That's not a value a real pointer
3364 // will ever have because RcInner has alignment at least 2.
3365 ptr: NonNull<RcInner<T>>,
3366 alloc: A,
3367}
3368
3369#[stable(feature = "rc_weak", since = "1.4.0")]
3370impl<T: ?Sized, A: Allocator> !Send for Weak<T, A> {}
3371#[stable(feature = "rc_weak", since = "1.4.0")]
3372impl<T: ?Sized, A: Allocator> !Sync for Weak<T, A> {}
3373
3374#[unstable(feature = "coerce_unsized", issue = "18598")]
3375impl<T: ?Sized + Unsize<U>, U: ?Sized, A: Allocator> CoerceUnsized<Weak<U, A>> for Weak<T, A> {}
3376
3377#[unstable(feature = "dispatch_from_dyn", issue = "none")]
3378impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Weak<U>> for Weak<T> {}
3379
3380// SAFETY: `Weak::clone` doesn't access any `Cell`s which could contain the `Weak` being cloned.
3381#[unstable(feature = "cell_get_cloned", issue = "145329")]
3382unsafe impl<T: ?Sized> CloneFromCell for Weak<T> {}
3383
3384impl<T> Weak<T> {
3385 /// Constructs a new `Weak<T>`, without allocating any memory.
3386 /// Calling [`upgrade`] on the return value always gives [`None`].
3387 ///
3388 /// [`upgrade`]: Weak::upgrade
3389 ///
3390 /// # Examples
3391 ///
3392 /// ```
3393 /// use std::rc::Weak;
3394 ///
3395 /// let empty: Weak<i64> = Weak::new();
3396 /// assert!(empty.upgrade().is_none());
3397 /// ```
3398 #[inline]
3399 #[stable(feature = "downgraded_weak", since = "1.10.0")]
3400 #[rustc_const_stable(feature = "const_weak_new", since = "1.73.0")]
3401 #[must_use]
3402 pub const fn new() -> Weak<T> {
3403 Weak { ptr: NonNull::without_provenance(NonZeroUsize::MAX), alloc: Global }
3404 }
3405}
3406
3407impl<T, A: Allocator> Weak<T, A> {
3408 /// Constructs a new `Weak<T>`, without allocating any memory, technically in the provided
3409 /// allocator.
3410 /// Calling [`upgrade`] on the return value always gives [`None`].
3411 ///
3412 /// [`upgrade`]: Weak::upgrade
3413 ///
3414 /// # Examples
3415 ///
3416 /// ```
3417 /// use std::rc::Weak;
3418 ///
3419 /// let empty: Weak<i64> = Weak::new();
3420 /// assert!(empty.upgrade().is_none());
3421 /// ```
3422 #[inline]
3423 #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
3424 pub fn new_in(alloc: A) -> Weak<T, A> {
3425 Weak { ptr: NonNull::without_provenance(NonZeroUsize::MAX), alloc }
3426 }
3427}
3428
3429pub(crate) fn is_dangling<T: ?Sized>(ptr: *const T) -> bool {
3430 (ptr.cast::<()>()).addr() == usize::MAX
3431}
3432
3433/// Helper type to allow accessing the reference counts without
3434/// making any assertions about the data field.
3435struct WeakInner<'a> {
3436 weak: &'a Cell<usize>,
3437 strong: &'a Cell<usize>,
3438}
3439
3440impl<T: ?Sized> Weak<T> {
3441 /// Converts a raw pointer previously created by [`into_raw`] back into `Weak<T>`.
3442 ///
3443 /// This can be used to safely get a strong reference (by calling [`upgrade`]
3444 /// later) or to deallocate the weak count by dropping the `Weak<T>`.
3445 ///
3446 /// It takes ownership of one weak reference (with the exception of pointers created by [`new`],
3447 /// as these don't own anything; the method still works on them).
3448 ///
3449 /// # Safety
3450 ///
3451 /// The pointer must have originated from the [`into_raw`] and must still own its potential
3452 /// weak reference, and `ptr` must point to a block of memory allocated by the global allocator.
3453 ///
3454 /// It is allowed for the strong count to be 0 at the time of calling this. Nevertheless, this
3455 /// takes ownership of one weak reference currently represented as a raw pointer (the weak
3456 /// count is not modified by this operation) and therefore it must be paired with a previous
3457 /// call to [`into_raw`].
3458 ///
3459 /// # Examples
3460 ///
3461 /// ```
3462 /// use std::rc::{Rc, Weak};
3463 ///
3464 /// let strong = Rc::new("hello".to_owned());
3465 ///
3466 /// let raw_1 = Rc::downgrade(&strong).into_raw();
3467 /// let raw_2 = Rc::downgrade(&strong).into_raw();
3468 ///
3469 /// assert_eq!(2, Rc::weak_count(&strong));
3470 ///
3471 /// assert_eq!("hello", &*unsafe { Weak::from_raw(raw_1) }.upgrade().unwrap());
3472 /// assert_eq!(1, Rc::weak_count(&strong));
3473 ///
3474 /// drop(strong);
3475 ///
3476 /// // Decrement the last weak count.
3477 /// assert!(unsafe { Weak::from_raw(raw_2) }.upgrade().is_none());
3478 /// ```
3479 ///
3480 /// [`into_raw`]: Weak::into_raw
3481 /// [`upgrade`]: Weak::upgrade
3482 /// [`new`]: Weak::new
3483 #[inline]
3484 #[stable(feature = "weak_into_raw", since = "1.45.0")]
3485 pub unsafe fn from_raw(ptr: *const T) -> Self {
3486 // SAFETY: Upheld by caller.
3487 unsafe { Self::from_raw_in(ptr, Global) }
3488 }
3489
3490 /// Consumes the `Weak<T>` and turns it into a raw pointer.
3491 ///
3492 /// This converts the weak pointer into a raw pointer, while still preserving the ownership of
3493 /// one weak reference (the weak count is not modified by this operation). It can be turned
3494 /// back into the `Weak<T>` with [`from_raw`].
3495 ///
3496 /// The same restrictions of accessing the target of the pointer as with
3497 /// [`as_ptr`] apply.
3498 ///
3499 /// # Examples
3500 ///
3501 /// ```
3502 /// use std::rc::{Rc, Weak};
3503 ///
3504 /// let strong = Rc::new("hello".to_owned());
3505 /// let weak = Rc::downgrade(&strong);
3506 /// let raw = weak.into_raw();
3507 ///
3508 /// assert_eq!(1, Rc::weak_count(&strong));
3509 /// assert_eq!("hello", unsafe { &*raw });
3510 ///
3511 /// drop(unsafe { Weak::from_raw(raw) });
3512 /// assert_eq!(0, Rc::weak_count(&strong));
3513 /// ```
3514 ///
3515 /// [`from_raw`]: Weak::from_raw
3516 /// [`as_ptr`]: Weak::as_ptr
3517 #[must_use = "losing the pointer will leak memory"]
3518 #[stable(feature = "weak_into_raw", since = "1.45.0")]
3519 pub fn into_raw(self) -> *const T {
3520 mem::ManuallyDrop::new(self).as_ptr()
3521 }
3522}
3523
3524impl<T: ?Sized, A: Allocator> Weak<T, A> {
3525 /// Returns a reference to the underlying allocator.
3526 #[inline]
3527 #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
3528 pub fn allocator(&self) -> &A {
3529 &self.alloc
3530 }
3531
3532 /// Returns a raw pointer to the object `T` pointed to by this `Weak<T>`.
3533 ///
3534 /// The pointer is valid only if there are some strong references. The pointer may be dangling,
3535 /// unaligned or even [`null`] otherwise.
3536 ///
3537 /// # Examples
3538 ///
3539 /// ```
3540 /// use std::rc::Rc;
3541 /// use std::ptr;
3542 ///
3543 /// let strong = Rc::new("hello".to_owned());
3544 /// let weak = Rc::downgrade(&strong);
3545 /// // Both point to the same object
3546 /// assert!(ptr::eq(&*strong, weak.as_ptr()));
3547 /// // The strong here keeps it alive, so we can still access the object.
3548 /// assert_eq!("hello", unsafe { &*weak.as_ptr() });
3549 ///
3550 /// drop(strong);
3551 /// // But not any more. We can do weak.as_ptr(), but accessing the pointer would lead to
3552 /// // undefined behavior.
3553 /// // assert_eq!("hello", unsafe { &*weak.as_ptr() });
3554 /// ```
3555 ///
3556 /// [`null`]: ptr::null
3557 #[must_use]
3558 #[stable(feature = "rc_as_ptr", since = "1.45.0")]
3559 pub fn as_ptr(&self) -> *const T {
3560 let ptr: *mut RcInner<T> = NonNull::as_ptr(self.ptr);
3561
3562 if is_dangling(ptr) {
3563 // If the pointer is dangling, we return the sentinel directly. This cannot be
3564 // a valid payload address, as the payload is at least as aligned as RcInner (usize).
3565 ptr as *const T
3566 } else {
3567 // SAFETY: if is_dangling returns false, then the pointer is dereferenceable.
3568 // The payload may be dropped at this point, and we have to maintain provenance,
3569 // so use raw pointer manipulation.
3570 unsafe { &raw mut (*ptr).value }
3571 }
3572 }
3573
3574 /// Consumes the `Weak<T>`, returning the wrapped pointer and allocator.
3575 ///
3576 /// This converts the weak pointer into a raw pointer, while still preserving the ownership of
3577 /// one weak reference (the weak count is not modified by this operation). It can be turned
3578 /// back into the `Weak<T>` with [`from_raw_in`].
3579 ///
3580 /// The same restrictions of accessing the target of the pointer as with
3581 /// [`as_ptr`] apply.
3582 ///
3583 /// # Examples
3584 ///
3585 /// ```
3586 /// #![feature(allocator_ext)]
3587 /// use std::rc::{Rc, Weak};
3588 /// use std::alloc::System;
3589 ///
3590 /// let strong = Rc::new_in("hello".to_owned(), System);
3591 /// let weak = Rc::downgrade(&strong);
3592 /// let (raw, alloc) = weak.into_raw_with_allocator();
3593 ///
3594 /// assert_eq!(1, Rc::weak_count(&strong));
3595 /// assert_eq!("hello", unsafe { &*raw });
3596 ///
3597 /// drop(unsafe { Weak::from_raw_in(raw, alloc) });
3598 /// assert_eq!(0, Rc::weak_count(&strong));
3599 /// ```
3600 ///
3601 /// [`from_raw_in`]: Weak::from_raw_in
3602 /// [`as_ptr`]: Weak::as_ptr
3603 #[must_use = "losing the pointer will leak memory"]
3604 #[inline]
3605 #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
3606 pub fn into_raw_with_allocator(self) -> (*const T, A) {
3607 let this = mem::ManuallyDrop::new(self);
3608 let result = this.as_ptr();
3609 // SAFETY: `this` is ManuallyDrop so the allocator will not be double-dropped
3610 let alloc = unsafe { ptr::read(&this.alloc) };
3611 (result, alloc)
3612 }
3613
3614 /// Converts a raw pointer previously created by [`into_raw`] back into `Weak<T>`.
3615 ///
3616 /// This can be used to safely get a strong reference (by calling [`upgrade`]
3617 /// later) or to deallocate the weak count by dropping the `Weak<T>`.
3618 ///
3619 /// It takes ownership of one weak reference (with the exception of pointers created by [`new`],
3620 /// as these don't own anything; the method still works on them).
3621 ///
3622 /// # Safety
3623 ///
3624 /// The pointer must have originated from the [`into_raw`] and must still own its potential
3625 /// weak reference, and `ptr` must point to a block of memory allocated by `alloc`.
3626 ///
3627 /// It is allowed for the strong count to be 0 at the time of calling this. Nevertheless, this
3628 /// takes ownership of one weak reference currently represented as a raw pointer (the weak
3629 /// count is not modified by this operation) and therefore it must be paired with a previous
3630 /// call to [`into_raw`].
3631 ///
3632 /// # Examples
3633 ///
3634 /// ```
3635 /// use std::rc::{Rc, Weak};
3636 ///
3637 /// let strong = Rc::new("hello".to_owned());
3638 ///
3639 /// let raw_1 = Rc::downgrade(&strong).into_raw();
3640 /// let raw_2 = Rc::downgrade(&strong).into_raw();
3641 ///
3642 /// assert_eq!(2, Rc::weak_count(&strong));
3643 ///
3644 /// assert_eq!("hello", &*unsafe { Weak::from_raw(raw_1) }.upgrade().unwrap());
3645 /// assert_eq!(1, Rc::weak_count(&strong));
3646 ///
3647 /// drop(strong);
3648 ///
3649 /// // Decrement the last weak count.
3650 /// assert!(unsafe { Weak::from_raw(raw_2) }.upgrade().is_none());
3651 /// ```
3652 ///
3653 /// [`into_raw`]: Weak::into_raw
3654 /// [`upgrade`]: Weak::upgrade
3655 /// [`new`]: Weak::new
3656 #[inline]
3657 #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
3658 pub unsafe fn from_raw_in(ptr: *const T, alloc: A) -> Self {
3659 // See Weak::as_ptr for context on how the input pointer is derived.
3660
3661 let ptr = if is_dangling(ptr) {
3662 // This is a dangling Weak.
3663 ptr as *mut RcInner<T>
3664 } else {
3665 // Otherwise, we're guaranteed the pointer came from a nondangling Weak.
3666 // SAFETY: data_offset is safe to call, as ptr references a real (potentially dropped) T.
3667 let offset = unsafe { data_offset(ptr) };
3668 // Thus, we reverse the offset to get the whole RcInner.
3669 // SAFETY: the pointer originated from a Weak, so this offset is safe.
3670 unsafe { ptr.byte_sub(offset) as *mut RcInner<T> }
3671 };
3672
3673 // SAFETY: we now have recovered the original Weak pointer, so can create the Weak.
3674 Weak { ptr: unsafe { NonNull::new_unchecked(ptr) }, alloc }
3675 }
3676
3677 /// Attempts to upgrade the `Weak` pointer to an [`Rc`], delaying
3678 /// dropping of the inner value if successful.
3679 ///
3680 /// Returns [`None`] in the following cases:
3681 ///
3682 /// 1. The inner value has since been dropped or moved out.
3683 ///
3684 /// 2. This `Weak` does not point to an allocation.
3685 ///
3686 /// 3. The owning reference this `Weak` is associated with is either not fully-constructed or does not allow an upgrade.
3687 ///
3688 /// # Examples
3689 ///
3690 /// ```
3691 /// use std::rc::Rc;
3692 ///
3693 /// let five = Rc::new(5);
3694 ///
3695 /// let weak_five = Rc::downgrade(&five);
3696 ///
3697 /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
3698 /// assert!(strong_five.is_some());
3699 ///
3700 /// // Destroy all strong pointers.
3701 /// drop(strong_five);
3702 /// drop(five);
3703 ///
3704 /// assert!(weak_five.upgrade().is_none());
3705 /// ```
3706 #[must_use = "this returns a new `Rc`, \
3707 without modifying the original weak pointer"]
3708 #[stable(feature = "rc_weak", since = "1.4.0")]
3709 pub fn upgrade(&self) -> Option<Rc<T, A>>
3710 where
3711 A: AllocatorClone,
3712 {
3713 let inner = self.inner()?;
3714
3715 if inner.strong() == 0 {
3716 None
3717 } else {
3718 // ignore-tidy-undocumented-unsafe
3719 unsafe {
3720 inner.inc_strong();
3721 Some(Rc::from_inner_in(self.ptr, self.alloc.clone()))
3722 }
3723 }
3724 }
3725
3726 /// Gets the number of strong (`Rc`) pointers pointing to this allocation.
3727 ///
3728 /// If `self` was created using [`Weak::new`], this will return 0.
3729 #[must_use]
3730 #[stable(feature = "weak_counts", since = "1.41.0")]
3731 pub fn strong_count(&self) -> usize {
3732 if let Some(inner) = self.inner() { inner.strong() } else { 0 }
3733 }
3734
3735 /// Gets the number of `Weak` pointers pointing to this allocation.
3736 ///
3737 /// If no strong pointers remain, this will return zero.
3738 #[must_use]
3739 #[stable(feature = "weak_counts", since = "1.41.0")]
3740 pub fn weak_count(&self) -> usize {
3741 if let Some(inner) = self.inner() {
3742 if inner.strong() > 0 {
3743 inner.weak() - 1 // subtract the implicit weak ptr
3744 } else {
3745 0
3746 }
3747 } else {
3748 0
3749 }
3750 }
3751
3752 /// Returns `None` when the pointer is dangling and there is no allocated `RcInner`,
3753 /// (i.e., when this `Weak` was created by `Weak::new`).
3754 #[inline]
3755 fn inner(&self) -> Option<WeakInner<'_>> {
3756 if is_dangling(self.ptr.as_ptr()) {
3757 None
3758 } else {
3759 // We are careful to *not* create a reference covering the "data" field, as
3760 // the field may be mutated concurrently (for example, if the last `Rc`
3761 // is dropped, the data field will be dropped in-place).
3762 // ignore-tidy-undocumented-unsafe
3763 Some(unsafe {
3764 let ptr = self.ptr.as_ptr();
3765 WeakInner { strong: &(*ptr).strong, weak: &(*ptr).weak }
3766 })
3767 }
3768 }
3769
3770 /// Returns `true` if the two `Weak`s point to the same allocation similar to [`ptr::eq`], or if
3771 /// both don't point to any allocation (because they were created with `Weak::new()`). However,
3772 /// this function ignores the metadata of `dyn Trait` pointers.
3773 ///
3774 /// # Notes
3775 ///
3776 /// Since this compares pointers it means that `Weak::new()` will equal each
3777 /// other, even though they don't point to any allocation.
3778 ///
3779 /// # Examples
3780 ///
3781 /// ```
3782 /// use std::rc::Rc;
3783 ///
3784 /// let first_rc = Rc::new(5);
3785 /// let first = Rc::downgrade(&first_rc);
3786 /// let second = Rc::downgrade(&first_rc);
3787 ///
3788 /// assert!(first.ptr_eq(&second));
3789 ///
3790 /// let third_rc = Rc::new(5);
3791 /// let third = Rc::downgrade(&third_rc);
3792 ///
3793 /// assert!(!first.ptr_eq(&third));
3794 /// ```
3795 ///
3796 /// Comparing `Weak::new`.
3797 ///
3798 /// ```
3799 /// use std::rc::{Rc, Weak};
3800 ///
3801 /// let first = Weak::new();
3802 /// let second = Weak::new();
3803 /// assert!(first.ptr_eq(&second));
3804 ///
3805 /// let third_rc = Rc::new(());
3806 /// let third = Rc::downgrade(&third_rc);
3807 /// assert!(!first.ptr_eq(&third));
3808 /// ```
3809 #[inline]
3810 #[must_use]
3811 #[stable(feature = "weak_ptr_eq", since = "1.39.0")]
3812 pub fn ptr_eq(&self, other: &Self) -> bool {
3813 ptr::addr_eq(self.ptr.as_ptr(), other.ptr.as_ptr())
3814 }
3815}
3816
3817#[stable(feature = "rc_weak", since = "1.4.0")]
3818unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Weak<T, A> {
3819 /// Drops the `Weak` pointer.
3820 ///
3821 /// # Examples
3822 ///
3823 /// ```
3824 /// use std::rc::{Rc, Weak};
3825 ///
3826 /// struct Foo;
3827 ///
3828 /// impl Drop for Foo {
3829 /// fn drop(&mut self) {
3830 /// println!("dropped!");
3831 /// }
3832 /// }
3833 ///
3834 /// let foo = Rc::new(Foo);
3835 /// let weak_foo = Rc::downgrade(&foo);
3836 /// let other_weak_foo = Weak::clone(&weak_foo);
3837 ///
3838 /// drop(weak_foo); // Doesn't print anything
3839 /// drop(foo); // Prints "dropped!"
3840 ///
3841 /// assert!(other_weak_foo.upgrade().is_none());
3842 /// ```
3843 fn drop(&mut self) {
3844 let inner = if let Some(inner) = self.inner() { inner } else { return };
3845
3846 inner.dec_weak();
3847 // the weak count starts at 1, and will only go to zero if all
3848 // the strong pointers have disappeared.
3849 if inner.weak() == 0 {
3850 // ignore-tidy-undocumented-unsafe
3851 unsafe {
3852 self.alloc.deallocate(self.ptr.cast(), Layout::for_value_raw(self.ptr.as_ptr()));
3853 }
3854 }
3855 }
3856}
3857
3858#[stable(feature = "rc_weak", since = "1.4.0")]
3859impl<T: ?Sized, A: AllocatorClone> Clone for Weak<T, A> {
3860 /// Makes a clone of the `Weak` pointer that points to the same allocation.
3861 ///
3862 /// # Examples
3863 ///
3864 /// ```
3865 /// use std::rc::{Rc, Weak};
3866 ///
3867 /// let weak_five = Rc::downgrade(&Rc::new(5));
3868 ///
3869 /// let _ = Weak::clone(&weak_five);
3870 /// ```
3871 #[inline]
3872 fn clone(&self) -> Weak<T, A> {
3873 if let Some(inner) = self.inner() {
3874 inner.inc_weak()
3875 }
3876 Weak { ptr: self.ptr, alloc: self.alloc.clone() }
3877 }
3878}
3879
3880#[unstable(feature = "ergonomic_clones", issue = "132290")]
3881impl<T: ?Sized, A: AllocatorClone> UseCloned for Weak<T, A> {}
3882
3883#[stable(feature = "rc_weak", since = "1.4.0")]
3884impl<T: ?Sized, A: Allocator> fmt::Debug for Weak<T, A> {
3885 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3886 write!(f, "(Weak)")
3887 }
3888}
3889
3890#[stable(feature = "downgraded_weak", since = "1.10.0")]
3891impl<T> Default for Weak<T> {
3892 /// Constructs a new `Weak<T>`, without allocating any memory.
3893 /// Calling [`upgrade`] on the return value always gives [`None`].
3894 ///
3895 /// [`upgrade`]: Weak::upgrade
3896 ///
3897 /// # Examples
3898 ///
3899 /// ```
3900 /// use std::rc::Weak;
3901 ///
3902 /// let empty: Weak<i64> = Default::default();
3903 /// assert!(empty.upgrade().is_none());
3904 /// ```
3905 fn default() -> Weak<T> {
3906 Weak::new()
3907 }
3908}
3909
3910// NOTE: If you mem::forget Rcs (or Weaks), drop is skipped and the ref-count
3911// is not decremented, meaning the ref-count can overflow, and then you can
3912// free the allocation while outstanding Rcs (or Weaks) exist, which would be
3913// unsound. We abort because this is such a degenerate scenario that we don't
3914// care about what happens -- no real program should ever experience this.
3915//
3916// This should have negligible overhead since you don't actually need to
3917// clone these much in Rust thanks to ownership and move-semantics.
3918
3919#[doc(hidden)]
3920trait RcInnerPtr {
3921 fn weak_ref(&self) -> &Cell<usize>;
3922 fn strong_ref(&self) -> &Cell<usize>;
3923
3924 #[inline]
3925 fn strong(&self) -> usize {
3926 self.strong_ref().get()
3927 }
3928
3929 #[inline]
3930 fn inc_strong(&self) {
3931 let strong = self.strong();
3932
3933 // We insert an `assume` here to hint LLVM at an otherwise
3934 // missed optimization.
3935 // SAFETY: The reference count will never be zero when this is
3936 // called.
3937 unsafe {
3938 hint::assert_unchecked(strong != 0);
3939 }
3940
3941 let strong = strong.wrapping_add(1);
3942 self.strong_ref().set(strong);
3943
3944 // We want to abort on overflow instead of dropping the value.
3945 // Checking for overflow after the store instead of before
3946 // allows for slightly better code generation.
3947 if intrinsics::unlikely(strong == 0) {
3948 intrinsics::abort_immediate();
3949 }
3950 }
3951
3952 #[inline]
3953 fn dec_strong(&self) {
3954 self.strong_ref().set(self.strong() - 1);
3955 }
3956
3957 #[inline]
3958 fn weak(&self) -> usize {
3959 self.weak_ref().get()
3960 }
3961
3962 #[inline]
3963 fn inc_weak(&self) {
3964 let weak = self.weak();
3965
3966 // We insert an `assume` here to hint LLVM at an otherwise
3967 // missed optimization.
3968 // SAFETY: The reference count will never be zero when this is
3969 // called.
3970 unsafe {
3971 hint::assert_unchecked(weak != 0);
3972 }
3973
3974 let weak = weak.wrapping_add(1);
3975 self.weak_ref().set(weak);
3976
3977 // We want to abort on overflow instead of dropping the value.
3978 // Checking for overflow after the store instead of before
3979 // allows for slightly better code generation.
3980 if intrinsics::unlikely(weak == 0) {
3981 intrinsics::abort_immediate();
3982 }
3983 }
3984
3985 #[inline]
3986 fn dec_weak(&self) {
3987 self.weak_ref().set(self.weak() - 1);
3988 }
3989}
3990
3991impl<T: ?Sized> RcInnerPtr for RcInner<T> {
3992 #[inline(always)]
3993 fn weak_ref(&self) -> &Cell<usize> {
3994 &self.weak
3995 }
3996
3997 #[inline(always)]
3998 fn strong_ref(&self) -> &Cell<usize> {
3999 &self.strong
4000 }
4001}
4002
4003impl<'a> RcInnerPtr for WeakInner<'a> {
4004 #[inline(always)]
4005 fn weak_ref(&self) -> &Cell<usize> {
4006 self.weak
4007 }
4008
4009 #[inline(always)]
4010 fn strong_ref(&self) -> &Cell<usize> {
4011 self.strong
4012 }
4013}
4014
4015#[stable(feature = "rust1", since = "1.0.0")]
4016impl<T: ?Sized, A: Allocator> borrow::Borrow<T> for Rc<T, A> {
4017 fn borrow(&self) -> &T {
4018 self
4019 }
4020}
4021
4022#[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
4023impl<T: ?Sized, A: Allocator> AsRef<T> for Rc<T, A> {
4024 fn as_ref(&self) -> &T {
4025 self
4026 }
4027}
4028
4029#[stable(feature = "pin", since = "1.33.0")]
4030impl<T: ?Sized, A: Allocator> Unpin for Rc<T, A> {}
4031
4032/// Gets the offset within an `RcInner` for the payload behind a pointer.
4033///
4034/// # Safety
4035///
4036/// The pointer must point to (and have valid metadata for) a previously
4037/// valid instance of T, but the T is allowed to be dropped.
4038unsafe fn data_offset<T: ?Sized>(ptr: *const T) -> usize {
4039 // Align the unsized value to the end of the RcInner.
4040 // Because RcInner is repr(C), it will always be the last field in memory.
4041 // SAFETY: since the only unsized types possible are slices, trait objects,
4042 // and extern types, the input safety requirement is currently enough to
4043 // satisfy the requirements of Alignment::of_val_raw; this is an implementation
4044 // detail of the language that must not be relied upon outside of std.
4045 unsafe { data_offset_alignment(Alignment::of_val_raw(ptr)) }
4046}
4047
4048#[inline]
4049fn data_offset_alignment(alignment: Alignment) -> usize {
4050 let layout = Layout::new::<RcInner<()>>();
4051 layout.size() + layout.padding_needed_for(alignment)
4052}
4053
4054/// A uniquely owned [`Rc`].
4055///
4056/// This represents an `Rc` that is known to be uniquely owned -- that is, have exactly one strong
4057/// reference. Multiple weak pointers can be created, but attempts to upgrade those to strong
4058/// references will fail unless the `UniqueRc` they point to has been converted into a regular `Rc`.
4059///
4060/// Because they are uniquely owned, the contents of a `UniqueRc` can be freely mutated. A common
4061/// use case is to have an object be mutable during its initialization phase but then have it become
4062/// immutable and converted to a normal `Rc`.
4063///
4064/// This can be used as a flexible way to create cyclic data structures, as in the example below.
4065///
4066/// ```
4067/// #![feature(unique_rc_arc)]
4068/// use std::rc::{Rc, Weak, UniqueRc};
4069///
4070/// struct Gadget {
4071/// #[allow(dead_code)]
4072/// me: Weak<Gadget>,
4073/// }
4074///
4075/// fn create_gadget() -> Option<Rc<Gadget>> {
4076/// let mut rc = UniqueRc::new(Gadget {
4077/// me: Weak::new(),
4078/// });
4079/// rc.me = UniqueRc::downgrade(&rc);
4080/// Some(UniqueRc::into_rc(rc))
4081/// }
4082///
4083/// create_gadget().unwrap();
4084/// ```
4085///
4086/// An advantage of using `UniqueRc` over [`Rc::new_cyclic`] to build cyclic data structures is that
4087/// [`Rc::new_cyclic`]'s `data_fn` parameter cannot be async or return a [`Result`]. As shown in the
4088/// previous example, `UniqueRc` allows for more flexibility in the construction of cyclic data,
4089/// including fallible or async constructors.
4090#[unstable(feature = "unique_rc_arc", issue = "112566")]
4091pub struct UniqueRc<
4092 T: ?Sized,
4093 #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] A: Allocator = Global,
4094> {
4095 ptr: NonNull<RcInner<T>>,
4096 // Define the ownership of `RcInner<T>` for drop-check
4097 _marker: PhantomData<RcInner<T>>,
4098 // Invariance is necessary for soundness: once other `Weak`
4099 // references exist, we already have a form of shared mutability!
4100 _marker2: PhantomData<*mut T>,
4101 alloc: A,
4102}
4103
4104// Not necessary for correctness since `UniqueRc` contains `NonNull`,
4105// but having an explicit negative impl is nice for documentation purposes
4106// and results in nicer error messages.
4107#[unstable(feature = "unique_rc_arc", issue = "112566")]
4108impl<T: ?Sized, A: Allocator> !Send for UniqueRc<T, A> {}
4109
4110// Not necessary for correctness since `UniqueRc` contains `NonNull`,
4111// but having an explicit negative impl is nice for documentation purposes
4112// and results in nicer error messages.
4113#[unstable(feature = "unique_rc_arc", issue = "112566")]
4114impl<T: ?Sized, A: Allocator> !Sync for UniqueRc<T, A> {}
4115
4116#[unstable(feature = "unique_rc_arc", issue = "112566")]
4117impl<T: ?Sized + Unsize<U>, U: ?Sized, A: Allocator> CoerceUnsized<UniqueRc<U, A>>
4118 for UniqueRc<T, A>
4119{
4120}
4121
4122//#[unstable(feature = "unique_rc_arc", issue = "112566")]
4123#[unstable(feature = "dispatch_from_dyn", issue = "none")]
4124impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<UniqueRc<U>> for UniqueRc<T> {}
4125
4126#[unstable(feature = "unique_rc_arc", issue = "112566")]
4127impl<T: ?Sized + fmt::Display, A: Allocator> fmt::Display for UniqueRc<T, A> {
4128 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4129 fmt::Display::fmt(&**self, f)
4130 }
4131}
4132
4133#[unstable(feature = "unique_rc_arc", issue = "112566")]
4134impl<T: ?Sized + fmt::Debug, A: Allocator> fmt::Debug for UniqueRc<T, A> {
4135 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4136 fmt::Debug::fmt(&**self, f)
4137 }
4138}
4139
4140#[unstable(feature = "unique_rc_arc", issue = "112566")]
4141impl<T: ?Sized, A: Allocator> fmt::Pointer for UniqueRc<T, A> {
4142 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4143 fmt::Pointer::fmt(&(&raw const **self), f)
4144 }
4145}
4146
4147#[unstable(feature = "unique_rc_arc", issue = "112566")]
4148impl<T: ?Sized, A: Allocator> borrow::Borrow<T> for UniqueRc<T, A> {
4149 fn borrow(&self) -> &T {
4150 self
4151 }
4152}
4153
4154#[unstable(feature = "unique_rc_arc", issue = "112566")]
4155impl<T: ?Sized, A: Allocator> borrow::BorrowMut<T> for UniqueRc<T, A> {
4156 fn borrow_mut(&mut self) -> &mut T {
4157 self
4158 }
4159}
4160
4161#[unstable(feature = "unique_rc_arc", issue = "112566")]
4162impl<T: ?Sized, A: Allocator> AsRef<T> for UniqueRc<T, A> {
4163 fn as_ref(&self) -> &T {
4164 self
4165 }
4166}
4167
4168#[unstable(feature = "unique_rc_arc", issue = "112566")]
4169impl<T: ?Sized, A: Allocator> AsMut<T> for UniqueRc<T, A> {
4170 fn as_mut(&mut self) -> &mut T {
4171 self
4172 }
4173}
4174
4175#[unstable(feature = "unique_rc_arc", issue = "112566")]
4176impl<T: ?Sized, A: Allocator> Unpin for UniqueRc<T, A> {}
4177
4178#[cfg(not(no_global_oom_handling))]
4179#[unstable(feature = "unique_rc_arc", issue = "112566")]
4180impl<T> From<T> for UniqueRc<T> {
4181 #[inline(always)]
4182 fn from(value: T) -> Self {
4183 Self::new(value)
4184 }
4185}
4186
4187#[unstable(feature = "unique_rc_arc", issue = "112566")]
4188impl<T: ?Sized + PartialEq, A: Allocator> PartialEq for UniqueRc<T, A> {
4189 /// Equality for two `UniqueRc`s.
4190 ///
4191 /// Two `UniqueRc`s are equal if their inner values are equal.
4192 ///
4193 /// # Examples
4194 ///
4195 /// ```
4196 /// #![feature(unique_rc_arc)]
4197 /// use std::rc::UniqueRc;
4198 ///
4199 /// let five = UniqueRc::new(5);
4200 ///
4201 /// assert!(five == UniqueRc::new(5));
4202 /// ```
4203 #[inline]
4204 fn eq(&self, other: &Self) -> bool {
4205 PartialEq::eq(&**self, &**other)
4206 }
4207
4208 /// Inequality for two `UniqueRc`s.
4209 ///
4210 /// Two `UniqueRc`s are not equal if their inner values are not equal.
4211 ///
4212 /// # Examples
4213 ///
4214 /// ```
4215 /// #![feature(unique_rc_arc)]
4216 /// use std::rc::UniqueRc;
4217 ///
4218 /// let five = UniqueRc::new(5);
4219 ///
4220 /// assert!(five != UniqueRc::new(6));
4221 /// ```
4222 #[inline]
4223 fn ne(&self, other: &Self) -> bool {
4224 PartialEq::ne(&**self, &**other)
4225 }
4226}
4227
4228#[unstable(feature = "unique_rc_arc", issue = "112566")]
4229impl<T: ?Sized + PartialOrd, A: Allocator> PartialOrd for UniqueRc<T, A> {
4230 /// Partial comparison for two `UniqueRc`s.
4231 ///
4232 /// The two are compared by calling `partial_cmp()` on their inner values.
4233 ///
4234 /// # Examples
4235 ///
4236 /// ```
4237 /// #![feature(unique_rc_arc)]
4238 /// use std::rc::UniqueRc;
4239 /// use std::cmp::Ordering;
4240 ///
4241 /// let five = UniqueRc::new(5);
4242 ///
4243 /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&UniqueRc::new(6)));
4244 /// ```
4245 #[inline(always)]
4246 fn partial_cmp(&self, other: &UniqueRc<T, A>) -> Option<Ordering> {
4247 (**self).partial_cmp(&**other)
4248 }
4249
4250 /// Less-than comparison for two `UniqueRc`s.
4251 ///
4252 /// The two are compared by calling `<` on their inner values.
4253 ///
4254 /// # Examples
4255 ///
4256 /// ```
4257 /// #![feature(unique_rc_arc)]
4258 /// use std::rc::UniqueRc;
4259 ///
4260 /// let five = UniqueRc::new(5);
4261 ///
4262 /// assert!(five < UniqueRc::new(6));
4263 /// ```
4264 #[inline(always)]
4265 fn lt(&self, other: &UniqueRc<T, A>) -> bool {
4266 **self < **other
4267 }
4268
4269 /// 'Less than or equal to' comparison for two `UniqueRc`s.
4270 ///
4271 /// The two are compared by calling `<=` on their inner values.
4272 ///
4273 /// # Examples
4274 ///
4275 /// ```
4276 /// #![feature(unique_rc_arc)]
4277 /// use std::rc::UniqueRc;
4278 ///
4279 /// let five = UniqueRc::new(5);
4280 ///
4281 /// assert!(five <= UniqueRc::new(5));
4282 /// ```
4283 #[inline(always)]
4284 fn le(&self, other: &UniqueRc<T, A>) -> bool {
4285 **self <= **other
4286 }
4287
4288 /// Greater-than comparison for two `UniqueRc`s.
4289 ///
4290 /// The two are compared by calling `>` on their inner values.
4291 ///
4292 /// # Examples
4293 ///
4294 /// ```
4295 /// #![feature(unique_rc_arc)]
4296 /// use std::rc::UniqueRc;
4297 ///
4298 /// let five = UniqueRc::new(5);
4299 ///
4300 /// assert!(five > UniqueRc::new(4));
4301 /// ```
4302 #[inline(always)]
4303 fn gt(&self, other: &UniqueRc<T, A>) -> bool {
4304 **self > **other
4305 }
4306
4307 /// 'Greater than or equal to' comparison for two `UniqueRc`s.
4308 ///
4309 /// The two are compared by calling `>=` on their inner values.
4310 ///
4311 /// # Examples
4312 ///
4313 /// ```
4314 /// #![feature(unique_rc_arc)]
4315 /// use std::rc::UniqueRc;
4316 ///
4317 /// let five = UniqueRc::new(5);
4318 ///
4319 /// assert!(five >= UniqueRc::new(5));
4320 /// ```
4321 #[inline(always)]
4322 fn ge(&self, other: &UniqueRc<T, A>) -> bool {
4323 **self >= **other
4324 }
4325}
4326
4327#[unstable(feature = "unique_rc_arc", issue = "112566")]
4328impl<T: ?Sized + Ord, A: Allocator> Ord for UniqueRc<T, A> {
4329 /// Comparison for two `UniqueRc`s.
4330 ///
4331 /// The two are compared by calling `cmp()` on their inner values.
4332 ///
4333 /// # Examples
4334 ///
4335 /// ```
4336 /// #![feature(unique_rc_arc)]
4337 /// use std::rc::UniqueRc;
4338 /// use std::cmp::Ordering;
4339 ///
4340 /// let five = UniqueRc::new(5);
4341 ///
4342 /// assert_eq!(Ordering::Less, five.cmp(&UniqueRc::new(6)));
4343 /// ```
4344 #[inline]
4345 fn cmp(&self, other: &UniqueRc<T, A>) -> Ordering {
4346 (**self).cmp(&**other)
4347 }
4348}
4349
4350#[unstable(feature = "unique_rc_arc", issue = "112566")]
4351impl<T: ?Sized + Eq, A: Allocator> Eq for UniqueRc<T, A> {}
4352
4353#[unstable(feature = "unique_rc_arc", issue = "112566")]
4354impl<T: ?Sized + Hash, A: Allocator> Hash for UniqueRc<T, A> {
4355 fn hash<H: Hasher>(&self, state: &mut H) {
4356 (**self).hash(state);
4357 }
4358}
4359
4360// Depends on A = Global
4361impl<T> UniqueRc<T> {
4362 /// Creates a new `UniqueRc`.
4363 ///
4364 /// Weak references to this `UniqueRc` can be created with [`UniqueRc::downgrade`]. Upgrading
4365 /// these weak references will fail before the `UniqueRc` has been converted into an [`Rc`].
4366 /// After converting the `UniqueRc` into an [`Rc`], any weak references created beforehand will
4367 /// point to the new [`Rc`].
4368 #[cfg(not(no_global_oom_handling))]
4369 #[unstable(feature = "unique_rc_arc", issue = "112566")]
4370 pub fn new(value: T) -> Self {
4371 Self::new_in(value, Global)
4372 }
4373
4374 /// Like [`new`](Self::new), but returns an error if the allocation
4375 /// fails, instead of calling [`handle_alloc_error`].
4376 #[unstable(feature = "unique_rc_arc", issue = "112566")]
4377 pub fn try_new(value: T) -> Result<Self, AllocError> {
4378 Self::try_new_in(value, Global)
4379 }
4380}
4381
4382impl<T, A: Allocator> UniqueRc<T, A> {
4383 /// Creates a new `UniqueRc` in the provided allocator.
4384 ///
4385 /// Weak references to this `UniqueRc` can be created with [`UniqueRc::downgrade`]. Upgrading
4386 /// these weak references will fail before the `UniqueRc` has been converted into an [`Rc`].
4387 /// After converting the `UniqueRc` into an [`Rc`], any weak references created beforehand will
4388 /// point to the new [`Rc`].
4389 #[cfg(not(no_global_oom_handling))]
4390 #[unstable(feature = "unique_rc_arc", issue = "112566")]
4391 // #[unstable(feature = "allocator_api", issue = "163177")]
4392 #[must_use]
4393 pub fn new_in(value: T, alloc: A) -> Self {
4394 let (ptr, alloc) = Box::into_non_null_with_allocator(Box::new_in(
4395 RcInner {
4396 strong: Cell::new(0),
4397 // keep one weak reference so if all the weak pointers that are created are dropped
4398 // the UniqueRc still stays valid.
4399 weak: Cell::new(1),
4400 value,
4401 },
4402 alloc,
4403 ));
4404 Self { ptr, _marker: PhantomData, _marker2: PhantomData, alloc }
4405 }
4406
4407 /// Like [`new_in`](Self::new_in), but returns an error if the allocation
4408 /// fails, instead of calling [`handle_alloc_error`].
4409 #[unstable(feature = "unique_rc_arc", issue = "112566")]
4410 // #[unstable(feature = "allocator_api", issue = "163177")]
4411 pub fn try_new_in(value: T, alloc: A) -> Result<Self, AllocError> {
4412 let (ptr, alloc) = Box::into_non_null_with_allocator(Box::try_new_in(
4413 RcInner {
4414 strong: Cell::new(0),
4415 // keep one weak reference so if all the weak pointers that are created are dropped
4416 // the UniqueRc still stays valid.
4417 weak: Cell::new(1),
4418 value,
4419 },
4420 alloc,
4421 )?);
4422 Ok(Self { ptr, _marker: PhantomData, _marker2: PhantomData, alloc })
4423 }
4424
4425 /// Consumes the `UniqueRc`, returning its wrapped value and allocator.
4426 #[unstable(feature = "unique_rc_arc", issue = "112566")]
4427 // #[unstable(feature = "allocator_api", issue = "163177")]
4428 #[must_use]
4429 pub fn unwrap_with_allocator(this: Self) -> (T, A) {
4430 let inner_ptr = this.ptr;
4431 let (data_ptr, alloc) = Self::into_raw_with_allocator(this);
4432
4433 // SAFETY: Conceptually moves out of the `UniqueRc`.
4434 // We do not use the data inside ever again.
4435 let val = unsafe { data_ptr.read() };
4436
4437 // Drop the strong-weak ref
4438 drop(Weak { ptr: inner_ptr, alloc: &alloc });
4439
4440 (val, alloc)
4441 }
4442
4443 /// Consumes the `UniqueRc`, returning its wrapped value.
4444 #[unstable(feature = "unique_rc_arc", issue = "112566")]
4445 #[must_use]
4446 pub fn unwrap(this: Self) -> T {
4447 Self::unwrap_with_allocator(this).0
4448 }
4449
4450 /// Maps the value in a `UniqueRc`, reusing the allocation if possible.
4451 ///
4452 /// `f` is called on a reference to the value in the `UniqueRc`, and the result is returned,
4453 /// also in a `UniqueRc`.
4454 ///
4455 /// Note: this is an associated function, which means that you have
4456 /// to call it as `UniqueRc::map(u, f)` instead of `u.map(f)`. This
4457 /// is so that there is no conflict with a method on the inner type.
4458 ///
4459 /// # Examples
4460 ///
4461 /// ```
4462 /// #![feature(unique_rc_arc)]
4463 ///
4464 /// use std::rc::UniqueRc;
4465 ///
4466 /// let r = UniqueRc::new(7);
4467 /// let new = UniqueRc::map(r, |i| i + 7);
4468 /// assert_eq!(*new, 14);
4469 /// ```
4470 #[cfg(not(no_global_oom_handling))]
4471 #[unstable(feature = "unique_rc_arc", issue = "112566")]
4472 pub fn map<U>(this: Self, f: impl FnOnce(T) -> U) -> UniqueRc<U, A> {
4473 if size_of::<T>() == size_of::<U>()
4474 && align_of::<T>() == align_of::<U>()
4475 && UniqueRc::weak_count(&this) == 0
4476 {
4477 // ignore-tidy-undocumented-unsafe
4478 unsafe {
4479 let (ptr, alloc) = UniqueRc::into_raw_with_allocator(this);
4480 let value = ptr.read();
4481 let allocation =
4482 UniqueRc::from_raw_with_allocator(ptr.cast::<mem::MaybeUninit<U>>(), alloc);
4483
4484 UniqueRc::write(allocation, f(value))
4485 }
4486 } else {
4487 let (val, alloc) = UniqueRc::unwrap_with_allocator(this);
4488 UniqueRc::new_in(f(val), alloc)
4489 }
4490 }
4491
4492 /// Attempts to map the value in a `UniqueRc`, reusing the allocation if possible.
4493 ///
4494 /// `f` is called on a reference to the value in the `UniqueRc`, and if the operation succeeds,
4495 /// the result is returned, also in a `UniqueRc`.
4496 ///
4497 /// Note: this is an associated function, which means that you have
4498 /// to call it as `UniqueRc::try_map(u, f)` instead of `u.try_map(f)`. This
4499 /// is so that there is no conflict with a method on the inner type.
4500 ///
4501 /// # Examples
4502 ///
4503 /// ```
4504 /// #![feature(smart_pointer_try_map)]
4505 /// #![feature(unique_rc_arc)]
4506 ///
4507 /// use std::rc::UniqueRc;
4508 ///
4509 /// let b = UniqueRc::new(7);
4510 /// let new = UniqueRc::try_map(b, u32::try_from).unwrap();
4511 /// assert_eq!(*new, 7);
4512 /// ```
4513 #[cfg(not(no_global_oom_handling))]
4514 #[unstable(feature = "smart_pointer_try_map", issue = "144419")]
4515 pub fn try_map<R>(
4516 this: Self,
4517 f: impl FnOnce(T) -> R,
4518 ) -> <R::Residual as Residual<UniqueRc<R::Output, A>>>::TryType
4519 where
4520 R: Try,
4521 R::Residual: Residual<UniqueRc<R::Output, A>>,
4522 {
4523 if size_of::<T>() == size_of::<R::Output>()
4524 && align_of::<T>() == align_of::<R::Output>()
4525 && UniqueRc::weak_count(&this) == 0
4526 {
4527 // ignore-tidy-undocumented-unsafe
4528 unsafe {
4529 let (ptr, alloc) = UniqueRc::into_raw_with_allocator(this);
4530 let value = ptr.read();
4531 let allocation = UniqueRc::from_raw_with_allocator(
4532 ptr.cast::<mem::MaybeUninit<R::Output>>(),
4533 alloc,
4534 );
4535
4536 try { UniqueRc::write(allocation, f(value)?) }
4537 }
4538 } else {
4539 let (val, alloc) = UniqueRc::unwrap_with_allocator(this);
4540 try { UniqueRc::new_in(f(val)?, alloc) }
4541 }
4542 }
4543}
4544
4545impl<T: ?Sized, A: Allocator> UniqueRc<T, A> {
4546 #[cfg(not(no_global_oom_handling))]
4547 unsafe fn from_raw_with_allocator(ptr: *const T, alloc: A) -> Self {
4548 // SAFETY: Upheld by caller
4549 let offset = unsafe { data_offset(ptr) };
4550
4551 // Reverse the offset to find the original RcInner.
4552 // SAFETY: As above.
4553 let rc_ptr = unsafe { ptr.byte_sub(offset) as *mut RcInner<T> };
4554
4555 Self {
4556 // SAFETY: Upheld by caller.
4557 ptr: unsafe { NonNull::new_unchecked(rc_ptr) },
4558 _marker: PhantomData,
4559 _marker2: PhantomData,
4560 alloc,
4561 }
4562 }
4563
4564 fn into_raw_with_allocator(this: Self) -> (*const T, A) {
4565 let this = ManuallyDrop::new(this);
4566 // SAFETY: The copy of the allocator stored in `this` is forgotten
4567 (Self::as_ptr(&this), unsafe { ptr::read(&this.alloc) })
4568 }
4569
4570 /// Converts the `UniqueRc` into a regular [`Rc`].
4571 ///
4572 /// This consumes the `UniqueRc` and returns a regular [`Rc`] that contains the `value` that
4573 /// is passed to `into_rc`.
4574 ///
4575 /// Any weak references created before this method is called can now be upgraded to strong
4576 /// references.
4577 #[unstable(feature = "unique_rc_arc", issue = "112566")]
4578 pub fn into_rc(this: Self) -> Rc<T, A> {
4579 let mut this = ManuallyDrop::new(this);
4580
4581 // Move the allocator out.
4582 // SAFETY: `this.alloc` will not be accessed again, nor dropped because it is in
4583 // a `ManuallyDrop`.
4584 let alloc: A = unsafe { ptr::read(&this.alloc) };
4585
4586 // SAFETY: This pointer was allocated at creation time so we know it is valid.
4587 unsafe {
4588 // Convert our weak reference into a strong reference
4589 this.ptr.as_mut().strong.set(1);
4590 Rc::from_inner_in(this.ptr, alloc)
4591 }
4592 }
4593
4594 #[cfg(not(no_global_oom_handling))]
4595 fn weak_count(this: &Self) -> usize {
4596 this.inner().weak() - 1
4597 }
4598
4599 #[cfg(not(no_global_oom_handling))]
4600 fn inner(&self) -> &RcInner<T> {
4601 // SAFETY: while this UniqueRc is alive we're guaranteed that the inner pointer is valid.
4602 unsafe { self.ptr.as_ref() }
4603 }
4604
4605 fn as_ptr(this: &Self) -> *const T {
4606 let ptr: *mut RcInner<T> = NonNull::as_ptr(this.ptr);
4607
4608 // SAFETY: This cannot go through Deref::deref or UniqueRc::inner because
4609 // this is required to retain raw/mut provenance such that e.g. `get_mut` can
4610 // write through the pointer after the Rc is recovered through `from_raw`.
4611 unsafe { &raw mut (*ptr).value }
4612 }
4613
4614 #[inline]
4615 fn into_inner_with_allocator(this: Self) -> (NonNull<RcInner<T>>, A) {
4616 let this = mem::ManuallyDrop::new(this);
4617 // SAFETY: Pointer is valid for reads.
4618 (this.ptr, unsafe { ptr::read(&this.alloc) })
4619 }
4620
4621 #[inline]
4622 unsafe fn from_inner_in(ptr: NonNull<RcInner<T>>, alloc: A) -> Self {
4623 Self { ptr, _marker: PhantomData, _marker2: PhantomData, alloc }
4624 }
4625}
4626
4627impl<T: ?Sized, A: AllocatorClone> UniqueRc<T, A> {
4628 /// Creates a new weak reference to the `UniqueRc`.
4629 ///
4630 /// Attempting to upgrade this weak reference will fail before the `UniqueRc` has been converted
4631 /// to a [`Rc`] using [`UniqueRc::into_rc`].
4632 #[unstable(feature = "unique_rc_arc", issue = "112566")]
4633 pub fn downgrade(this: &Self) -> Weak<T, A> {
4634 // SAFETY: This pointer was allocated at creation time and we guarantee that we only have
4635 // one strong reference before converting to a regular Rc.
4636 unsafe {
4637 this.ptr.as_ref().inc_weak();
4638 }
4639 Weak { ptr: this.ptr, alloc: this.alloc.clone() }
4640 }
4641}
4642
4643impl<T, A: Allocator> UniqueRc<mem::MaybeUninit<T>, A> {
4644 /// Writes the value and converts to `UniqueRc<T, A>`.
4645 ///
4646 /// This method converts similarly to [`assume_init`](Self::assume_init) but
4647 /// writes `value` into it before conversion, thus guaranteeing safety.
4648 #[unstable(feature = "unique_rc_arc", issue = "112566")]
4649 #[must_use]
4650 pub fn write(mut this: Self, value: T) -> UniqueRc<T, A> {
4651 // SAFETY: Writing initialises the wrapped value.
4652 unsafe {
4653 this.write(value);
4654 this.assume_init()
4655 }
4656 }
4657
4658 /// Converts to `UniqueRc<T, A>`.
4659 ///
4660 /// # Safety
4661 ///
4662 /// As with [`MaybeUninit::assume_init`],
4663 /// it is up to the caller to guarantee that the value
4664 /// really is in an initialized state.
4665 /// Calling this when the content is not yet fully initialized
4666 /// causes immediate undefined behavior.
4667 ///
4668 /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
4669 #[unstable(feature = "unique_rc_arc", issue = "112566")]
4670 #[must_use]
4671 pub unsafe fn assume_init(self) -> UniqueRc<T, A> {
4672 let (ptr, alloc) = UniqueRc::into_inner_with_allocator(self);
4673 // SAFETY: Upheld by caller.
4674 unsafe { UniqueRc::from_inner_in(ptr.cast(), alloc) }
4675 }
4676}
4677
4678#[unstable(feature = "unique_rc_arc", issue = "112566")]
4679impl<T: ?Sized, A: Allocator> Deref for UniqueRc<T, A> {
4680 type Target = T;
4681
4682 fn deref(&self) -> &T {
4683 // SAFETY: This pointer was allocated at creation time so we know it is valid.
4684 unsafe { &self.ptr.as_ref().value }
4685 }
4686}
4687
4688#[unstable(feature = "unique_rc_arc", issue = "112566")]
4689impl<T: ?Sized, A: Allocator> DerefMut for UniqueRc<T, A> {
4690 fn deref_mut(&mut self) -> &mut T {
4691 // SAFETY: This pointer was allocated at creation time so we know it is valid. We know we
4692 // have unique ownership and therefore it's safe to make a mutable reference because
4693 // `UniqueRc` owns the only strong reference to itself.
4694 unsafe { &mut (*self.ptr.as_ptr()).value }
4695 }
4696}
4697
4698#[unstable(feature = "unique_rc_arc", issue = "112566")]
4699unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for UniqueRc<T, A> {
4700 fn drop(&mut self) {
4701 // ignore-tidy-undocumented-unsafe
4702 unsafe {
4703 // destroy the contained object
4704 drop_in_place(DerefMut::deref_mut(self));
4705
4706 // remove the implicit "strong weak" pointer now that we've destroyed the contents.
4707 self.ptr.as_ref().dec_weak();
4708
4709 if self.ptr.as_ref().weak() == 0 {
4710 self.alloc.deallocate(self.ptr.cast(), Layout::for_value_raw(self.ptr.as_ptr()));
4711 }
4712 }
4713 }
4714}
4715
4716/// A unique owning pointer to a [`RcInner`] **that does not imply the contents are initialized,**
4717/// but will deallocate it (without dropping the value) when dropped.
4718///
4719/// This is a helper for [`Rc::make_mut()`] to ensure correct cleanup on panic.
4720/// It is nearly a duplicate of `UniqueRc<MaybeUninit<T>, A>` except that it allows `T: !Sized`,
4721/// which `MaybeUninit` does not.
4722struct UniqueRcUninit<T: ?Sized, A: Allocator> {
4723 ptr: NonNull<RcInner<T>>,
4724 layout_for_value: Layout,
4725 alloc: Option<A>,
4726}
4727
4728impl<T: ?Sized, A: Allocator> UniqueRcUninit<T, A> {
4729 /// Allocates a RcInner with layout suitable to contain `for_value` or a clone of it.
4730 #[cfg(not(no_global_oom_handling))]
4731 fn new(for_value: &T, alloc: A) -> UniqueRcUninit<T, A> {
4732 let layout = Layout::for_value(for_value);
4733 // ignore-tidy-undocumented-unsafe
4734 let ptr = unsafe {
4735 Rc::allocate_for_layout(
4736 layout,
4737 |layout_for_rc_inner| alloc.allocate(layout_for_rc_inner),
4738 |mem| mem.with_metadata_of(ptr::from_ref(for_value) as *const RcInner<T>),
4739 )
4740 };
4741 Self { ptr: NonNull::new(ptr).unwrap(), layout_for_value: layout, alloc: Some(alloc) }
4742 }
4743
4744 /// Allocates a RcInner with layout suitable to contain `for_value` or a clone of it,
4745 /// returning an error if allocation fails.
4746 fn try_new(for_value: &T, alloc: A) -> Result<UniqueRcUninit<T, A>, AllocError> {
4747 let layout = Layout::for_value(for_value);
4748 // ignore-tidy-undocumented-unsafe
4749 let ptr = unsafe {
4750 Rc::try_allocate_for_layout(
4751 layout,
4752 |layout_for_rc_inner| alloc.allocate(layout_for_rc_inner),
4753 |mem| mem.with_metadata_of(ptr::from_ref(for_value) as *const RcInner<T>),
4754 )?
4755 };
4756 Ok(Self { ptr: NonNull::new(ptr).unwrap(), layout_for_value: layout, alloc: Some(alloc) })
4757 }
4758
4759 /// Returns the pointer to be written into to initialize the [`Rc`].
4760 fn data_ptr(&mut self) -> *mut T {
4761 let offset = data_offset_alignment(self.layout_for_value.alignment());
4762 // ignore-tidy-undocumented-unsafe
4763 unsafe { self.ptr.as_ptr().byte_add(offset) as *mut T }
4764 }
4765
4766 /// Upgrade this into a normal [`Rc`].
4767 ///
4768 /// # Safety
4769 ///
4770 /// The data must have been initialized (by writing to [`Self::data_ptr()`]).
4771 unsafe fn into_rc(self) -> Rc<T, A> {
4772 let mut this = ManuallyDrop::new(self);
4773 let ptr = this.ptr;
4774 let alloc = this.alloc.take().unwrap();
4775
4776 // SAFETY: The pointer is valid as per `UniqueRcUninit::new`, and the caller is responsible
4777 // for having initialized the data.
4778 unsafe { Rc::from_ptr_in(ptr.as_ptr(), alloc) }
4779 }
4780}
4781
4782impl<T: ?Sized, A: Allocator> Drop for UniqueRcUninit<T, A> {
4783 fn drop(&mut self) {
4784 // SAFETY:
4785 // * new() produced a pointer safe to deallocate.
4786 // * We own the pointer unless into_rc() was called, which forgets us.
4787 unsafe {
4788 self.alloc.take().unwrap().deallocate(
4789 self.ptr.cast(),
4790 rc_inner_layout_for_value_layout(self.layout_for_value),
4791 );
4792 }
4793 }
4794}
4795
4796#[stable(feature = "allocator_api", since = "1.100.0")]
4797unsafe impl<T: ?Sized + Allocator, A: Allocator> Allocator for Rc<T, A> {
4798 #[inline]
4799 fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
4800 (**self).allocate(layout)
4801 }
4802
4803 #[inline]
4804 fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
4805 (**self).allocate_zeroed(layout)
4806 }
4807
4808 #[inline]
4809 unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
4810 // SAFETY: the safety contract must be upheld by the caller
4811 unsafe { (**self).deallocate(ptr, layout) }
4812 }
4813
4814 #[inline]
4815 unsafe fn grow(
4816 &self,
4817 ptr: NonNull<u8>,
4818 old_layout: Layout,
4819 new_layout: Layout,
4820 ) -> Result<NonNull<[u8]>, AllocError> {
4821 // SAFETY: the safety contract must be upheld by the caller
4822 unsafe { (**self).grow(ptr, old_layout, new_layout) }
4823 }
4824
4825 #[inline]
4826 unsafe fn grow_zeroed(
4827 &self,
4828 ptr: NonNull<u8>,
4829 old_layout: Layout,
4830 new_layout: Layout,
4831 ) -> Result<NonNull<[u8]>, AllocError> {
4832 // SAFETY: the safety contract must be upheld by the caller
4833 unsafe { (**self).grow_zeroed(ptr, old_layout, new_layout) }
4834 }
4835
4836 #[inline]
4837 unsafe fn shrink(
4838 &self,
4839 ptr: NonNull<u8>,
4840 old_layout: Layout,
4841 new_layout: Layout,
4842 ) -> Result<NonNull<[u8]>, AllocError> {
4843 // SAFETY: the safety contract must be upheld by the caller
4844 unsafe { (**self).shrink(ptr, old_layout, new_layout) }
4845 }
4846}
4847#[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
4848#[unstable_feature_bound(allocator_ext)]
4849impl<T: ?Sized + Allocator, A: Allocator> AllocatorNightly for Rc<T, A> {}
4850
4851#[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
4852unsafe impl<T: Allocator + ?Sized, A: AllocatorClone> AllocatorClone for Rc<T, A> {}