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