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