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