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