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