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