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