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