]> git.proxmox.com Git - rustc.git/blob - library/alloc/src/rc.rs
New upstream version 1.55.0+dfsg1
[rustc.git] / library / alloc / src / 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`][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 //! 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 //! [send]: core::marker::Send
236 //! [arc]: crate::sync::Arc
237 //! [`Deref`]: core::ops::Deref
238 //! [downgrade]: Rc::downgrade
239 //! [upgrade]: Weak::upgrade
240 //! [mutability]: core::cell#introducing-mutability-inside-of-something-immutable
241 //! [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
242
243 #![stable(feature = "rust1", since = "1.0.0")]
244
245 #[cfg(not(test))]
246 use crate::boxed::Box;
247 #[cfg(test)]
248 use std::boxed::Box;
249
250 use core::any::Any;
251 use core::borrow;
252 use core::cell::Cell;
253 use core::cmp::Ordering;
254 use core::convert::{From, TryFrom};
255 use core::fmt;
256 use core::hash::{Hash, Hasher};
257 use core::intrinsics::abort;
258 #[cfg(not(no_global_oom_handling))]
259 use core::iter;
260 use core::marker::{self, PhantomData, Unpin, Unsize};
261 #[cfg(not(no_global_oom_handling))]
262 use core::mem::size_of_val;
263 use core::mem::{self, align_of_val_raw, forget};
264 use core::ops::{CoerceUnsized, Deref, DispatchFromDyn, Receiver};
265 #[cfg(not(no_global_oom_handling))]
266 use core::pin::Pin;
267 use core::ptr::{self, NonNull};
268 #[cfg(not(no_global_oom_handling))]
269 use core::slice::from_raw_parts_mut;
270
271 #[cfg(not(no_global_oom_handling))]
272 use crate::alloc::handle_alloc_error;
273 #[cfg(not(no_global_oom_handling))]
274 use crate::alloc::{box_free, WriteCloneIntoRaw};
275 use crate::alloc::{AllocError, Allocator, Global, Layout};
276 use crate::borrow::{Cow, ToOwned};
277 #[cfg(not(no_global_oom_handling))]
278 use crate::string::String;
279 #[cfg(not(no_global_oom_handling))]
280 use crate::vec::Vec;
281
282 #[cfg(test)]
283 mod tests;
284
285 // This is repr(C) to future-proof against possible field-reordering, which
286 // would interfere with otherwise safe [into|from]_raw() of transmutable
287 // inner types.
288 #[repr(C)]
289 struct RcBox<T: ?Sized> {
290 strong: Cell<usize>,
291 weak: Cell<usize>,
292 value: T,
293 }
294
295 /// A single-threaded reference-counting pointer. 'Rc' stands for 'Reference
296 /// Counted'.
297 ///
298 /// See the [module-level documentation](./index.html) for more details.
299 ///
300 /// The inherent methods of `Rc` are all associated functions, which means
301 /// that you have to call them as e.g., [`Rc::get_mut(&mut value)`][get_mut] instead of
302 /// `value.get_mut()`. This avoids conflicts with methods of the inner type `T`.
303 ///
304 /// [get_mut]: Rc::get_mut
305 #[cfg_attr(not(test), rustc_diagnostic_item = "Rc")]
306 #[stable(feature = "rust1", since = "1.0.0")]
307 pub struct Rc<T: ?Sized> {
308 ptr: NonNull<RcBox<T>>,
309 phantom: PhantomData<RcBox<T>>,
310 }
311
312 #[stable(feature = "rust1", since = "1.0.0")]
313 impl<T: ?Sized> !marker::Send for Rc<T> {}
314 #[stable(feature = "rust1", since = "1.0.0")]
315 impl<T: ?Sized> !marker::Sync for Rc<T> {}
316
317 #[unstable(feature = "coerce_unsized", issue = "27732")]
318 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Rc<U>> for Rc<T> {}
319
320 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
321 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Rc<U>> for Rc<T> {}
322
323 impl<T: ?Sized> Rc<T> {
324 #[inline(always)]
325 fn inner(&self) -> &RcBox<T> {
326 // This unsafety is ok because while this Rc is alive we're guaranteed
327 // that the inner pointer is valid.
328 unsafe { self.ptr.as_ref() }
329 }
330
331 fn from_inner(ptr: NonNull<RcBox<T>>) -> Self {
332 Self { ptr, phantom: PhantomData }
333 }
334
335 unsafe fn from_ptr(ptr: *mut RcBox<T>) -> Self {
336 Self::from_inner(unsafe { NonNull::new_unchecked(ptr) })
337 }
338 }
339
340 impl<T> Rc<T> {
341 /// Constructs a new `Rc<T>`.
342 ///
343 /// # Examples
344 ///
345 /// ```
346 /// use std::rc::Rc;
347 ///
348 /// let five = Rc::new(5);
349 /// ```
350 #[cfg(not(no_global_oom_handling))]
351 #[stable(feature = "rust1", since = "1.0.0")]
352 pub fn new(value: T) -> Rc<T> {
353 // There is an implicit weak pointer owned by all the strong
354 // pointers, which ensures that the weak destructor never frees
355 // the allocation while the strong destructor is running, even
356 // if the weak pointer is stored inside the strong one.
357 Self::from_inner(
358 Box::leak(box RcBox { strong: Cell::new(1), weak: Cell::new(1), value }).into(),
359 )
360 }
361
362 /// Constructs a new `Rc<T>` using a weak reference to itself. Attempting
363 /// to upgrade the weak reference before this function returns will result
364 /// in a `None` value. However, the weak reference may be cloned freely and
365 /// stored for use at a later time.
366 ///
367 /// # Examples
368 ///
369 /// ```
370 /// #![feature(arc_new_cyclic)]
371 /// #![allow(dead_code)]
372 /// use std::rc::{Rc, Weak};
373 ///
374 /// struct Gadget {
375 /// self_weak: Weak<Self>,
376 /// // ... more fields
377 /// }
378 /// impl Gadget {
379 /// pub fn new() -> Rc<Self> {
380 /// Rc::new_cyclic(|self_weak| {
381 /// Gadget { self_weak: self_weak.clone(), /* ... */ }
382 /// })
383 /// }
384 /// }
385 /// ```
386 #[cfg(not(no_global_oom_handling))]
387 #[unstable(feature = "arc_new_cyclic", issue = "75861")]
388 pub fn new_cyclic(data_fn: impl FnOnce(&Weak<T>) -> T) -> Rc<T> {
389 // Construct the inner in the "uninitialized" state with a single
390 // weak reference.
391 let uninit_ptr: NonNull<_> = Box::leak(box RcBox {
392 strong: Cell::new(0),
393 weak: Cell::new(1),
394 value: mem::MaybeUninit::<T>::uninit(),
395 })
396 .into();
397
398 let init_ptr: NonNull<RcBox<T>> = uninit_ptr.cast();
399
400 let weak = Weak { ptr: init_ptr };
401
402 // It's important we don't give up ownership of the weak pointer, or
403 // else the memory might be freed by the time `data_fn` returns. If
404 // we really wanted to pass ownership, we could create an additional
405 // weak pointer for ourselves, but this would result in additional
406 // updates to the weak reference count which might not be necessary
407 // otherwise.
408 let data = data_fn(&weak);
409
410 unsafe {
411 let inner = init_ptr.as_ptr();
412 ptr::write(ptr::addr_of_mut!((*inner).value), data);
413
414 let prev_value = (*inner).strong.get();
415 debug_assert_eq!(prev_value, 0, "No prior strong references should exist");
416 (*inner).strong.set(1);
417 }
418
419 let strong = Rc::from_inner(init_ptr);
420
421 // Strong references should collectively own a shared weak reference,
422 // so don't run the destructor for our old weak reference.
423 mem::forget(weak);
424 strong
425 }
426
427 /// Constructs a new `Rc` with uninitialized contents.
428 ///
429 /// # Examples
430 ///
431 /// ```
432 /// #![feature(new_uninit)]
433 /// #![feature(get_mut_unchecked)]
434 ///
435 /// use std::rc::Rc;
436 ///
437 /// let mut five = Rc::<u32>::new_uninit();
438 ///
439 /// let five = unsafe {
440 /// // Deferred initialization:
441 /// Rc::get_mut_unchecked(&mut five).as_mut_ptr().write(5);
442 ///
443 /// five.assume_init()
444 /// };
445 ///
446 /// assert_eq!(*five, 5)
447 /// ```
448 #[cfg(not(no_global_oom_handling))]
449 #[unstable(feature = "new_uninit", issue = "63291")]
450 pub fn new_uninit() -> Rc<mem::MaybeUninit<T>> {
451 unsafe {
452 Rc::from_ptr(Rc::allocate_for_layout(
453 Layout::new::<T>(),
454 |layout| Global.allocate(layout),
455 |mem| mem as *mut RcBox<mem::MaybeUninit<T>>,
456 ))
457 }
458 }
459
460 /// Constructs a new `Rc` with uninitialized contents, with the memory
461 /// being filled with `0` bytes.
462 ///
463 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and
464 /// incorrect usage of this method.
465 ///
466 /// # Examples
467 ///
468 /// ```
469 /// #![feature(new_uninit)]
470 ///
471 /// use std::rc::Rc;
472 ///
473 /// let zero = Rc::<u32>::new_zeroed();
474 /// let zero = unsafe { zero.assume_init() };
475 ///
476 /// assert_eq!(*zero, 0)
477 /// ```
478 ///
479 /// [zeroed]: mem::MaybeUninit::zeroed
480 #[cfg(not(no_global_oom_handling))]
481 #[unstable(feature = "new_uninit", issue = "63291")]
482 pub fn new_zeroed() -> Rc<mem::MaybeUninit<T>> {
483 unsafe {
484 Rc::from_ptr(Rc::allocate_for_layout(
485 Layout::new::<T>(),
486 |layout| Global.allocate_zeroed(layout),
487 |mem| mem as *mut RcBox<mem::MaybeUninit<T>>,
488 ))
489 }
490 }
491
492 /// Constructs a new `Rc<T>`, returning an error if the allocation fails
493 ///
494 /// # Examples
495 ///
496 /// ```
497 /// #![feature(allocator_api)]
498 /// use std::rc::Rc;
499 ///
500 /// let five = Rc::try_new(5);
501 /// # Ok::<(), std::alloc::AllocError>(())
502 /// ```
503 #[unstable(feature = "allocator_api", issue = "32838")]
504 pub fn try_new(value: T) -> Result<Rc<T>, AllocError> {
505 // There is an implicit weak pointer owned by all the strong
506 // pointers, which ensures that the weak destructor never frees
507 // the allocation while the strong destructor is running, even
508 // if the weak pointer is stored inside the strong one.
509 Ok(Self::from_inner(
510 Box::leak(Box::try_new(RcBox { strong: Cell::new(1), weak: Cell::new(1), value })?)
511 .into(),
512 ))
513 }
514
515 /// Constructs a new `Rc` with uninitialized contents, returning an error if the allocation fails
516 ///
517 /// # Examples
518 ///
519 /// ```
520 /// #![feature(allocator_api, new_uninit)]
521 /// #![feature(get_mut_unchecked)]
522 ///
523 /// use std::rc::Rc;
524 ///
525 /// let mut five = Rc::<u32>::try_new_uninit()?;
526 ///
527 /// let five = unsafe {
528 /// // Deferred initialization:
529 /// Rc::get_mut_unchecked(&mut five).as_mut_ptr().write(5);
530 ///
531 /// five.assume_init()
532 /// };
533 ///
534 /// assert_eq!(*five, 5);
535 /// # Ok::<(), std::alloc::AllocError>(())
536 /// ```
537 #[unstable(feature = "allocator_api", issue = "32838")]
538 // #[unstable(feature = "new_uninit", issue = "63291")]
539 pub fn try_new_uninit() -> Result<Rc<mem::MaybeUninit<T>>, AllocError> {
540 unsafe {
541 Ok(Rc::from_ptr(Rc::try_allocate_for_layout(
542 Layout::new::<T>(),
543 |layout| Global.allocate(layout),
544 |mem| mem as *mut RcBox<mem::MaybeUninit<T>>,
545 )?))
546 }
547 }
548
549 /// Constructs a new `Rc` with uninitialized contents, with the memory
550 /// being filled with `0` bytes, returning an error if the allocation fails
551 ///
552 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and
553 /// incorrect usage of this method.
554 ///
555 /// # Examples
556 ///
557 /// ```
558 /// #![feature(allocator_api, new_uninit)]
559 ///
560 /// use std::rc::Rc;
561 ///
562 /// let zero = Rc::<u32>::try_new_zeroed()?;
563 /// let zero = unsafe { zero.assume_init() };
564 ///
565 /// assert_eq!(*zero, 0);
566 /// # Ok::<(), std::alloc::AllocError>(())
567 /// ```
568 ///
569 /// [zeroed]: mem::MaybeUninit::zeroed
570 #[unstable(feature = "allocator_api", issue = "32838")]
571 //#[unstable(feature = "new_uninit", issue = "63291")]
572 pub fn try_new_zeroed() -> Result<Rc<mem::MaybeUninit<T>>, AllocError> {
573 unsafe {
574 Ok(Rc::from_ptr(Rc::try_allocate_for_layout(
575 Layout::new::<T>(),
576 |layout| Global.allocate_zeroed(layout),
577 |mem| mem as *mut RcBox<mem::MaybeUninit<T>>,
578 )?))
579 }
580 }
581 /// Constructs a new `Pin<Rc<T>>`. If `T` does not implement `Unpin`, then
582 /// `value` will be pinned in memory and unable to be moved.
583 #[cfg(not(no_global_oom_handling))]
584 #[stable(feature = "pin", since = "1.33.0")]
585 pub fn pin(value: T) -> Pin<Rc<T>> {
586 unsafe { Pin::new_unchecked(Rc::new(value)) }
587 }
588
589 /// Returns the inner value, if the `Rc` has exactly one strong reference.
590 ///
591 /// Otherwise, an [`Err`] is returned with the same `Rc` that was
592 /// passed in.
593 ///
594 /// This will succeed even if there are outstanding weak references.
595 ///
596 /// # Examples
597 ///
598 /// ```
599 /// use std::rc::Rc;
600 ///
601 /// let x = Rc::new(3);
602 /// assert_eq!(Rc::try_unwrap(x), Ok(3));
603 ///
604 /// let x = Rc::new(4);
605 /// let _y = Rc::clone(&x);
606 /// assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4);
607 /// ```
608 #[inline]
609 #[stable(feature = "rc_unique", since = "1.4.0")]
610 pub fn try_unwrap(this: Self) -> Result<T, Self> {
611 if Rc::strong_count(&this) == 1 {
612 unsafe {
613 let val = ptr::read(&*this); // copy the contained object
614
615 // Indicate to Weaks that they can't be promoted by decrementing
616 // the strong count, and then remove the implicit "strong weak"
617 // pointer while also handling drop logic by just crafting a
618 // fake Weak.
619 this.inner().dec_strong();
620 let _weak = Weak { ptr: this.ptr };
621 forget(this);
622 Ok(val)
623 }
624 } else {
625 Err(this)
626 }
627 }
628 }
629
630 impl<T> Rc<[T]> {
631 /// Constructs a new reference-counted slice with uninitialized contents.
632 ///
633 /// # Examples
634 ///
635 /// ```
636 /// #![feature(new_uninit)]
637 /// #![feature(get_mut_unchecked)]
638 ///
639 /// use std::rc::Rc;
640 ///
641 /// let mut values = Rc::<[u32]>::new_uninit_slice(3);
642 ///
643 /// let values = unsafe {
644 /// // Deferred initialization:
645 /// Rc::get_mut_unchecked(&mut values)[0].as_mut_ptr().write(1);
646 /// Rc::get_mut_unchecked(&mut values)[1].as_mut_ptr().write(2);
647 /// Rc::get_mut_unchecked(&mut values)[2].as_mut_ptr().write(3);
648 ///
649 /// values.assume_init()
650 /// };
651 ///
652 /// assert_eq!(*values, [1, 2, 3])
653 /// ```
654 #[cfg(not(no_global_oom_handling))]
655 #[unstable(feature = "new_uninit", issue = "63291")]
656 pub fn new_uninit_slice(len: usize) -> Rc<[mem::MaybeUninit<T>]> {
657 unsafe { Rc::from_ptr(Rc::allocate_for_slice(len)) }
658 }
659
660 /// Constructs a new reference-counted slice with uninitialized contents, with the memory being
661 /// filled with `0` bytes.
662 ///
663 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and
664 /// incorrect usage of this method.
665 ///
666 /// # Examples
667 ///
668 /// ```
669 /// #![feature(new_uninit)]
670 ///
671 /// use std::rc::Rc;
672 ///
673 /// let values = Rc::<[u32]>::new_zeroed_slice(3);
674 /// let values = unsafe { values.assume_init() };
675 ///
676 /// assert_eq!(*values, [0, 0, 0])
677 /// ```
678 ///
679 /// [zeroed]: mem::MaybeUninit::zeroed
680 #[cfg(not(no_global_oom_handling))]
681 #[unstable(feature = "new_uninit", issue = "63291")]
682 pub fn new_zeroed_slice(len: usize) -> Rc<[mem::MaybeUninit<T>]> {
683 unsafe {
684 Rc::from_ptr(Rc::allocate_for_layout(
685 Layout::array::<T>(len).unwrap(),
686 |layout| Global.allocate_zeroed(layout),
687 |mem| {
688 ptr::slice_from_raw_parts_mut(mem as *mut T, len)
689 as *mut RcBox<[mem::MaybeUninit<T>]>
690 },
691 ))
692 }
693 }
694 }
695
696 impl<T> Rc<mem::MaybeUninit<T>> {
697 /// Converts to `Rc<T>`.
698 ///
699 /// # Safety
700 ///
701 /// As with [`MaybeUninit::assume_init`],
702 /// it is up to the caller to guarantee that the inner value
703 /// really is in an initialized state.
704 /// Calling this when the content is not yet fully initialized
705 /// causes immediate undefined behavior.
706 ///
707 /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
708 ///
709 /// # Examples
710 ///
711 /// ```
712 /// #![feature(new_uninit)]
713 /// #![feature(get_mut_unchecked)]
714 ///
715 /// use std::rc::Rc;
716 ///
717 /// let mut five = Rc::<u32>::new_uninit();
718 ///
719 /// let five = unsafe {
720 /// // Deferred initialization:
721 /// Rc::get_mut_unchecked(&mut five).as_mut_ptr().write(5);
722 ///
723 /// five.assume_init()
724 /// };
725 ///
726 /// assert_eq!(*five, 5)
727 /// ```
728 #[unstable(feature = "new_uninit", issue = "63291")]
729 #[inline]
730 pub unsafe fn assume_init(self) -> Rc<T> {
731 Rc::from_inner(mem::ManuallyDrop::new(self).ptr.cast())
732 }
733 }
734
735 impl<T> Rc<[mem::MaybeUninit<T>]> {
736 /// Converts to `Rc<[T]>`.
737 ///
738 /// # Safety
739 ///
740 /// As with [`MaybeUninit::assume_init`],
741 /// it is up to the caller to guarantee that the inner value
742 /// really is in an initialized state.
743 /// Calling this when the content is not yet fully initialized
744 /// causes immediate undefined behavior.
745 ///
746 /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
747 ///
748 /// # Examples
749 ///
750 /// ```
751 /// #![feature(new_uninit)]
752 /// #![feature(get_mut_unchecked)]
753 ///
754 /// use std::rc::Rc;
755 ///
756 /// let mut values = Rc::<[u32]>::new_uninit_slice(3);
757 ///
758 /// let values = unsafe {
759 /// // Deferred initialization:
760 /// Rc::get_mut_unchecked(&mut values)[0].as_mut_ptr().write(1);
761 /// Rc::get_mut_unchecked(&mut values)[1].as_mut_ptr().write(2);
762 /// Rc::get_mut_unchecked(&mut values)[2].as_mut_ptr().write(3);
763 ///
764 /// values.assume_init()
765 /// };
766 ///
767 /// assert_eq!(*values, [1, 2, 3])
768 /// ```
769 #[unstable(feature = "new_uninit", issue = "63291")]
770 #[inline]
771 pub unsafe fn assume_init(self) -> Rc<[T]> {
772 unsafe { Rc::from_ptr(mem::ManuallyDrop::new(self).ptr.as_ptr() as _) }
773 }
774 }
775
776 impl<T: ?Sized> Rc<T> {
777 /// Consumes the `Rc`, returning the wrapped pointer.
778 ///
779 /// To avoid a memory leak the pointer must be converted back to an `Rc` using
780 /// [`Rc::from_raw`][from_raw].
781 ///
782 /// [from_raw]: Rc::from_raw
783 ///
784 /// # Examples
785 ///
786 /// ```
787 /// use std::rc::Rc;
788 ///
789 /// let x = Rc::new("hello".to_owned());
790 /// let x_ptr = Rc::into_raw(x);
791 /// assert_eq!(unsafe { &*x_ptr }, "hello");
792 /// ```
793 #[stable(feature = "rc_raw", since = "1.17.0")]
794 pub fn into_raw(this: Self) -> *const T {
795 let ptr = Self::as_ptr(&this);
796 mem::forget(this);
797 ptr
798 }
799
800 /// Provides a raw pointer to the data.
801 ///
802 /// The counts are not affected in any way and the `Rc` is not consumed. The pointer is valid
803 /// for as long there are strong counts in the `Rc`.
804 ///
805 /// # Examples
806 ///
807 /// ```
808 /// use std::rc::Rc;
809 ///
810 /// let x = Rc::new("hello".to_owned());
811 /// let y = Rc::clone(&x);
812 /// let x_ptr = Rc::as_ptr(&x);
813 /// assert_eq!(x_ptr, Rc::as_ptr(&y));
814 /// assert_eq!(unsafe { &*x_ptr }, "hello");
815 /// ```
816 #[stable(feature = "weak_into_raw", since = "1.45.0")]
817 pub fn as_ptr(this: &Self) -> *const T {
818 let ptr: *mut RcBox<T> = NonNull::as_ptr(this.ptr);
819
820 // SAFETY: This cannot go through Deref::deref or Rc::inner because
821 // this is required to retain raw/mut provenance such that e.g. `get_mut` can
822 // write through the pointer after the Rc is recovered through `from_raw`.
823 unsafe { ptr::addr_of_mut!((*ptr).value) }
824 }
825
826 /// Constructs an `Rc<T>` from a raw pointer.
827 ///
828 /// The raw pointer must have been previously returned by a call to
829 /// [`Rc<U>::into_raw`][into_raw] where `U` must have the same size
830 /// and alignment as `T`. This is trivially true if `U` is `T`.
831 /// Note that if `U` is not `T` but has the same size and alignment, this is
832 /// basically like transmuting references of different types. See
833 /// [`mem::transmute`][transmute] for more information on what
834 /// restrictions apply in this case.
835 ///
836 /// The user of `from_raw` has to make sure a specific value of `T` is only
837 /// dropped once.
838 ///
839 /// This function is unsafe because improper use may lead to memory unsafety,
840 /// even if the returned `Rc<T>` is never accessed.
841 ///
842 /// [into_raw]: Rc::into_raw
843 /// [transmute]: core::mem::transmute
844 ///
845 /// # Examples
846 ///
847 /// ```
848 /// use std::rc::Rc;
849 ///
850 /// let x = Rc::new("hello".to_owned());
851 /// let x_ptr = Rc::into_raw(x);
852 ///
853 /// unsafe {
854 /// // Convert back to an `Rc` to prevent leak.
855 /// let x = Rc::from_raw(x_ptr);
856 /// assert_eq!(&*x, "hello");
857 ///
858 /// // Further calls to `Rc::from_raw(x_ptr)` would be memory-unsafe.
859 /// }
860 ///
861 /// // The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling!
862 /// ```
863 #[stable(feature = "rc_raw", since = "1.17.0")]
864 pub unsafe fn from_raw(ptr: *const T) -> Self {
865 let offset = unsafe { data_offset(ptr) };
866
867 // Reverse the offset to find the original RcBox.
868 let rc_ptr =
869 unsafe { (ptr as *mut RcBox<T>).set_ptr_value((ptr as *mut u8).offset(-offset)) };
870
871 unsafe { Self::from_ptr(rc_ptr) }
872 }
873
874 /// Creates a new [`Weak`] pointer to this allocation.
875 ///
876 /// # Examples
877 ///
878 /// ```
879 /// use std::rc::Rc;
880 ///
881 /// let five = Rc::new(5);
882 ///
883 /// let weak_five = Rc::downgrade(&five);
884 /// ```
885 #[stable(feature = "rc_weak", since = "1.4.0")]
886 pub fn downgrade(this: &Self) -> Weak<T> {
887 this.inner().inc_weak();
888 // Make sure we do not create a dangling Weak
889 debug_assert!(!is_dangling(this.ptr.as_ptr()));
890 Weak { ptr: this.ptr }
891 }
892
893 /// Gets the number of [`Weak`] pointers to this allocation.
894 ///
895 /// # Examples
896 ///
897 /// ```
898 /// use std::rc::Rc;
899 ///
900 /// let five = Rc::new(5);
901 /// let _weak_five = Rc::downgrade(&five);
902 ///
903 /// assert_eq!(1, Rc::weak_count(&five));
904 /// ```
905 #[inline]
906 #[stable(feature = "rc_counts", since = "1.15.0")]
907 pub fn weak_count(this: &Self) -> usize {
908 this.inner().weak() - 1
909 }
910
911 /// Gets the number of strong (`Rc`) pointers to this allocation.
912 ///
913 /// # Examples
914 ///
915 /// ```
916 /// use std::rc::Rc;
917 ///
918 /// let five = Rc::new(5);
919 /// let _also_five = Rc::clone(&five);
920 ///
921 /// assert_eq!(2, Rc::strong_count(&five));
922 /// ```
923 #[inline]
924 #[stable(feature = "rc_counts", since = "1.15.0")]
925 pub fn strong_count(this: &Self) -> usize {
926 this.inner().strong()
927 }
928
929 /// Increments the strong reference count on the `Rc<T>` associated with the
930 /// provided pointer by one.
931 ///
932 /// # Safety
933 ///
934 /// The pointer must have been obtained through `Rc::into_raw`, and the
935 /// associated `Rc` instance must be valid (i.e. the strong count must be at
936 /// least 1) for the duration of this method.
937 ///
938 /// # Examples
939 ///
940 /// ```
941 /// use std::rc::Rc;
942 ///
943 /// let five = Rc::new(5);
944 ///
945 /// unsafe {
946 /// let ptr = Rc::into_raw(five);
947 /// Rc::increment_strong_count(ptr);
948 ///
949 /// let five = Rc::from_raw(ptr);
950 /// assert_eq!(2, Rc::strong_count(&five));
951 /// }
952 /// ```
953 #[inline]
954 #[stable(feature = "rc_mutate_strong_count", since = "1.53.0")]
955 pub unsafe fn increment_strong_count(ptr: *const T) {
956 // Retain Rc, but don't touch refcount by wrapping in ManuallyDrop
957 let rc = unsafe { mem::ManuallyDrop::new(Rc::<T>::from_raw(ptr)) };
958 // Now increase refcount, but don't drop new refcount either
959 let _rc_clone: mem::ManuallyDrop<_> = rc.clone();
960 }
961
962 /// Decrements the strong reference count on the `Rc<T>` associated with the
963 /// provided pointer by one.
964 ///
965 /// # Safety
966 ///
967 /// The pointer must have been obtained through `Rc::into_raw`, and the
968 /// associated `Rc` instance must be valid (i.e. the strong count must be at
969 /// least 1) when invoking this method. This method can be used to release
970 /// the final `Rc` and backing storage, but **should not** be called after
971 /// the final `Rc` has been released.
972 ///
973 /// # Examples
974 ///
975 /// ```
976 /// use std::rc::Rc;
977 ///
978 /// let five = Rc::new(5);
979 ///
980 /// unsafe {
981 /// let ptr = Rc::into_raw(five);
982 /// Rc::increment_strong_count(ptr);
983 ///
984 /// let five = Rc::from_raw(ptr);
985 /// assert_eq!(2, Rc::strong_count(&five));
986 /// Rc::decrement_strong_count(ptr);
987 /// assert_eq!(1, Rc::strong_count(&five));
988 /// }
989 /// ```
990 #[inline]
991 #[stable(feature = "rc_mutate_strong_count", since = "1.53.0")]
992 pub unsafe fn decrement_strong_count(ptr: *const T) {
993 unsafe { mem::drop(Rc::from_raw(ptr)) };
994 }
995
996 /// Returns `true` if there are no other `Rc` or [`Weak`] pointers to
997 /// this allocation.
998 #[inline]
999 fn is_unique(this: &Self) -> bool {
1000 Rc::weak_count(this) == 0 && Rc::strong_count(this) == 1
1001 }
1002
1003 /// Returns a mutable reference into the given `Rc`, if there are
1004 /// no other `Rc` or [`Weak`] pointers to the same allocation.
1005 ///
1006 /// Returns [`None`] otherwise, because it is not safe to
1007 /// mutate a shared value.
1008 ///
1009 /// See also [`make_mut`][make_mut], which will [`clone`][clone]
1010 /// the inner value when there are other pointers.
1011 ///
1012 /// [make_mut]: Rc::make_mut
1013 /// [clone]: Clone::clone
1014 ///
1015 /// # Examples
1016 ///
1017 /// ```
1018 /// use std::rc::Rc;
1019 ///
1020 /// let mut x = Rc::new(3);
1021 /// *Rc::get_mut(&mut x).unwrap() = 4;
1022 /// assert_eq!(*x, 4);
1023 ///
1024 /// let _y = Rc::clone(&x);
1025 /// assert!(Rc::get_mut(&mut x).is_none());
1026 /// ```
1027 #[inline]
1028 #[stable(feature = "rc_unique", since = "1.4.0")]
1029 pub fn get_mut(this: &mut Self) -> Option<&mut T> {
1030 if Rc::is_unique(this) { unsafe { Some(Rc::get_mut_unchecked(this)) } } else { None }
1031 }
1032
1033 /// Returns a mutable reference into the given `Rc`,
1034 /// without any check.
1035 ///
1036 /// See also [`get_mut`], which is safe and does appropriate checks.
1037 ///
1038 /// [`get_mut`]: Rc::get_mut
1039 ///
1040 /// # Safety
1041 ///
1042 /// Any other `Rc` or [`Weak`] pointers to the same allocation must not be dereferenced
1043 /// for the duration of the returned borrow.
1044 /// This is trivially the case if no such pointers exist,
1045 /// for example immediately after `Rc::new`.
1046 ///
1047 /// # Examples
1048 ///
1049 /// ```
1050 /// #![feature(get_mut_unchecked)]
1051 ///
1052 /// use std::rc::Rc;
1053 ///
1054 /// let mut x = Rc::new(String::new());
1055 /// unsafe {
1056 /// Rc::get_mut_unchecked(&mut x).push_str("foo")
1057 /// }
1058 /// assert_eq!(*x, "foo");
1059 /// ```
1060 #[inline]
1061 #[unstable(feature = "get_mut_unchecked", issue = "63292")]
1062 pub unsafe fn get_mut_unchecked(this: &mut Self) -> &mut T {
1063 // We are careful to *not* create a reference covering the "count" fields, as
1064 // this would conflict with accesses to the reference counts (e.g. by `Weak`).
1065 unsafe { &mut (*this.ptr.as_ptr()).value }
1066 }
1067
1068 #[inline]
1069 #[stable(feature = "ptr_eq", since = "1.17.0")]
1070 /// Returns `true` if the two `Rc`s point to the same allocation
1071 /// (in a vein similar to [`ptr::eq`]).
1072 ///
1073 /// # Examples
1074 ///
1075 /// ```
1076 /// use std::rc::Rc;
1077 ///
1078 /// let five = Rc::new(5);
1079 /// let same_five = Rc::clone(&five);
1080 /// let other_five = Rc::new(5);
1081 ///
1082 /// assert!(Rc::ptr_eq(&five, &same_five));
1083 /// assert!(!Rc::ptr_eq(&five, &other_five));
1084 /// ```
1085 ///
1086 /// [`ptr::eq`]: core::ptr::eq
1087 pub fn ptr_eq(this: &Self, other: &Self) -> bool {
1088 this.ptr.as_ptr() == other.ptr.as_ptr()
1089 }
1090 }
1091
1092 impl<T: Clone> Rc<T> {
1093 /// Makes a mutable reference into the given `Rc`.
1094 ///
1095 /// If there are other `Rc` pointers to the same allocation, then `make_mut` will
1096 /// [`clone`] the inner value to a new allocation to ensure unique ownership. This is also
1097 /// referred to as clone-on-write.
1098 ///
1099 /// If there are no other `Rc` pointers to this allocation, then [`Weak`]
1100 /// pointers to this allocation will be disassociated.
1101 ///
1102 /// See also [`get_mut`], which will fail rather than cloning.
1103 ///
1104 /// [`clone`]: Clone::clone
1105 /// [`get_mut`]: Rc::get_mut
1106 ///
1107 /// # Examples
1108 ///
1109 /// ```
1110 /// use std::rc::Rc;
1111 ///
1112 /// let mut data = Rc::new(5);
1113 ///
1114 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
1115 /// let mut other_data = Rc::clone(&data); // Won't clone inner data
1116 /// *Rc::make_mut(&mut data) += 1; // Clones inner data
1117 /// *Rc::make_mut(&mut data) += 1; // Won't clone anything
1118 /// *Rc::make_mut(&mut other_data) *= 2; // Won't clone anything
1119 ///
1120 /// // Now `data` and `other_data` point to different allocations.
1121 /// assert_eq!(*data, 8);
1122 /// assert_eq!(*other_data, 12);
1123 /// ```
1124 ///
1125 /// [`Weak`] pointers will be disassociated:
1126 ///
1127 /// ```
1128 /// use std::rc::Rc;
1129 ///
1130 /// let mut data = Rc::new(75);
1131 /// let weak = Rc::downgrade(&data);
1132 ///
1133 /// assert!(75 == *data);
1134 /// assert!(75 == *weak.upgrade().unwrap());
1135 ///
1136 /// *Rc::make_mut(&mut data) += 1;
1137 ///
1138 /// assert!(76 == *data);
1139 /// assert!(weak.upgrade().is_none());
1140 /// ```
1141 #[cfg(not(no_global_oom_handling))]
1142 #[inline]
1143 #[stable(feature = "rc_unique", since = "1.4.0")]
1144 pub fn make_mut(this: &mut Self) -> &mut T {
1145 if Rc::strong_count(this) != 1 {
1146 // Gotta clone the data, there are other Rcs.
1147 // Pre-allocate memory to allow writing the cloned value directly.
1148 let mut rc = Self::new_uninit();
1149 unsafe {
1150 let data = Rc::get_mut_unchecked(&mut rc);
1151 (**this).write_clone_into_raw(data.as_mut_ptr());
1152 *this = rc.assume_init();
1153 }
1154 } else if Rc::weak_count(this) != 0 {
1155 // Can just steal the data, all that's left is Weaks
1156 let mut rc = Self::new_uninit();
1157 unsafe {
1158 let data = Rc::get_mut_unchecked(&mut rc);
1159 data.as_mut_ptr().copy_from_nonoverlapping(&**this, 1);
1160
1161 this.inner().dec_strong();
1162 // Remove implicit strong-weak ref (no need to craft a fake
1163 // Weak here -- we know other Weaks can clean up for us)
1164 this.inner().dec_weak();
1165 ptr::write(this, rc.assume_init());
1166 }
1167 }
1168 // This unsafety is ok because we're guaranteed that the pointer
1169 // returned is the *only* pointer that will ever be returned to T. Our
1170 // reference count is guaranteed to be 1 at this point, and we required
1171 // the `Rc<T>` itself to be `mut`, so we're returning the only possible
1172 // reference to the allocation.
1173 unsafe { &mut this.ptr.as_mut().value }
1174 }
1175 }
1176
1177 impl Rc<dyn Any> {
1178 #[inline]
1179 #[stable(feature = "rc_downcast", since = "1.29.0")]
1180 /// Attempt to downcast the `Rc<dyn Any>` to a concrete type.
1181 ///
1182 /// # Examples
1183 ///
1184 /// ```
1185 /// use std::any::Any;
1186 /// use std::rc::Rc;
1187 ///
1188 /// fn print_if_string(value: Rc<dyn Any>) {
1189 /// if let Ok(string) = value.downcast::<String>() {
1190 /// println!("String ({}): {}", string.len(), string);
1191 /// }
1192 /// }
1193 ///
1194 /// let my_string = "Hello World".to_string();
1195 /// print_if_string(Rc::new(my_string));
1196 /// print_if_string(Rc::new(0i8));
1197 /// ```
1198 pub fn downcast<T: Any>(self) -> Result<Rc<T>, Rc<dyn Any>> {
1199 if (*self).is::<T>() {
1200 let ptr = self.ptr.cast::<RcBox<T>>();
1201 forget(self);
1202 Ok(Rc::from_inner(ptr))
1203 } else {
1204 Err(self)
1205 }
1206 }
1207 }
1208
1209 impl<T: ?Sized> Rc<T> {
1210 /// Allocates an `RcBox<T>` with sufficient space for
1211 /// a possibly-unsized inner value where the value has the layout provided.
1212 ///
1213 /// The function `mem_to_rcbox` is called with the data pointer
1214 /// and must return back a (potentially fat)-pointer for the `RcBox<T>`.
1215 #[cfg(not(no_global_oom_handling))]
1216 unsafe fn allocate_for_layout(
1217 value_layout: Layout,
1218 allocate: impl FnOnce(Layout) -> Result<NonNull<[u8]>, AllocError>,
1219 mem_to_rcbox: impl FnOnce(*mut u8) -> *mut RcBox<T>,
1220 ) -> *mut RcBox<T> {
1221 // Calculate layout using the given value layout.
1222 // Previously, layout was calculated on the expression
1223 // `&*(ptr as *const RcBox<T>)`, but this created a misaligned
1224 // reference (see #54908).
1225 let layout = Layout::new::<RcBox<()>>().extend(value_layout).unwrap().0.pad_to_align();
1226 unsafe {
1227 Rc::try_allocate_for_layout(value_layout, allocate, mem_to_rcbox)
1228 .unwrap_or_else(|_| handle_alloc_error(layout))
1229 }
1230 }
1231
1232 /// Allocates an `RcBox<T>` with sufficient space for
1233 /// a possibly-unsized inner value where the value has the layout provided,
1234 /// returning an error if allocation fails.
1235 ///
1236 /// The function `mem_to_rcbox` is called with the data pointer
1237 /// and must return back a (potentially fat)-pointer for the `RcBox<T>`.
1238 #[inline]
1239 unsafe fn try_allocate_for_layout(
1240 value_layout: Layout,
1241 allocate: impl FnOnce(Layout) -> Result<NonNull<[u8]>, AllocError>,
1242 mem_to_rcbox: impl FnOnce(*mut u8) -> *mut RcBox<T>,
1243 ) -> Result<*mut RcBox<T>, AllocError> {
1244 // Calculate layout using the given value layout.
1245 // Previously, layout was calculated on the expression
1246 // `&*(ptr as *const RcBox<T>)`, but this created a misaligned
1247 // reference (see #54908).
1248 let layout = Layout::new::<RcBox<()>>().extend(value_layout).unwrap().0.pad_to_align();
1249
1250 // Allocate for the layout.
1251 let ptr = allocate(layout)?;
1252
1253 // Initialize the RcBox
1254 let inner = mem_to_rcbox(ptr.as_non_null_ptr().as_ptr());
1255 unsafe {
1256 debug_assert_eq!(Layout::for_value(&*inner), layout);
1257
1258 ptr::write(&mut (*inner).strong, Cell::new(1));
1259 ptr::write(&mut (*inner).weak, Cell::new(1));
1260 }
1261
1262 Ok(inner)
1263 }
1264
1265 /// Allocates an `RcBox<T>` with sufficient space for an unsized inner value
1266 #[cfg(not(no_global_oom_handling))]
1267 unsafe fn allocate_for_ptr(ptr: *const T) -> *mut RcBox<T> {
1268 // Allocate for the `RcBox<T>` using the given value.
1269 unsafe {
1270 Self::allocate_for_layout(
1271 Layout::for_value(&*ptr),
1272 |layout| Global.allocate(layout),
1273 |mem| (ptr as *mut RcBox<T>).set_ptr_value(mem),
1274 )
1275 }
1276 }
1277
1278 #[cfg(not(no_global_oom_handling))]
1279 fn from_box(v: Box<T>) -> Rc<T> {
1280 unsafe {
1281 let (box_unique, alloc) = Box::into_unique(v);
1282 let bptr = box_unique.as_ptr();
1283
1284 let value_size = size_of_val(&*bptr);
1285 let ptr = Self::allocate_for_ptr(bptr);
1286
1287 // Copy value as bytes
1288 ptr::copy_nonoverlapping(
1289 bptr as *const T as *const u8,
1290 &mut (*ptr).value as *mut _ as *mut u8,
1291 value_size,
1292 );
1293
1294 // Free the allocation without dropping its contents
1295 box_free(box_unique, alloc);
1296
1297 Self::from_ptr(ptr)
1298 }
1299 }
1300 }
1301
1302 impl<T> Rc<[T]> {
1303 /// Allocates an `RcBox<[T]>` with the given length.
1304 #[cfg(not(no_global_oom_handling))]
1305 unsafe fn allocate_for_slice(len: usize) -> *mut RcBox<[T]> {
1306 unsafe {
1307 Self::allocate_for_layout(
1308 Layout::array::<T>(len).unwrap(),
1309 |layout| Global.allocate(layout),
1310 |mem| ptr::slice_from_raw_parts_mut(mem as *mut T, len) as *mut RcBox<[T]>,
1311 )
1312 }
1313 }
1314
1315 /// Copy elements from slice into newly allocated Rc<\[T\]>
1316 ///
1317 /// Unsafe because the caller must either take ownership or bind `T: Copy`
1318 #[cfg(not(no_global_oom_handling))]
1319 unsafe fn copy_from_slice(v: &[T]) -> Rc<[T]> {
1320 unsafe {
1321 let ptr = Self::allocate_for_slice(v.len());
1322 ptr::copy_nonoverlapping(v.as_ptr(), &mut (*ptr).value as *mut [T] as *mut T, v.len());
1323 Self::from_ptr(ptr)
1324 }
1325 }
1326
1327 /// Constructs an `Rc<[T]>` from an iterator known to be of a certain size.
1328 ///
1329 /// Behavior is undefined should the size be wrong.
1330 #[cfg(not(no_global_oom_handling))]
1331 unsafe fn from_iter_exact(iter: impl iter::Iterator<Item = T>, len: usize) -> Rc<[T]> {
1332 // Panic guard while cloning T elements.
1333 // In the event of a panic, elements that have been written
1334 // into the new RcBox will be dropped, then the memory freed.
1335 struct Guard<T> {
1336 mem: NonNull<u8>,
1337 elems: *mut T,
1338 layout: Layout,
1339 n_elems: usize,
1340 }
1341
1342 impl<T> Drop for Guard<T> {
1343 fn drop(&mut self) {
1344 unsafe {
1345 let slice = from_raw_parts_mut(self.elems, self.n_elems);
1346 ptr::drop_in_place(slice);
1347
1348 Global.deallocate(self.mem, self.layout);
1349 }
1350 }
1351 }
1352
1353 unsafe {
1354 let ptr = Self::allocate_for_slice(len);
1355
1356 let mem = ptr as *mut _ as *mut u8;
1357 let layout = Layout::for_value(&*ptr);
1358
1359 // Pointer to first element
1360 let elems = &mut (*ptr).value as *mut [T] as *mut T;
1361
1362 let mut guard = Guard { mem: NonNull::new_unchecked(mem), elems, layout, n_elems: 0 };
1363
1364 for (i, item) in iter.enumerate() {
1365 ptr::write(elems.add(i), item);
1366 guard.n_elems += 1;
1367 }
1368
1369 // All clear. Forget the guard so it doesn't free the new RcBox.
1370 forget(guard);
1371
1372 Self::from_ptr(ptr)
1373 }
1374 }
1375 }
1376
1377 /// Specialization trait used for `From<&[T]>`.
1378 trait RcFromSlice<T> {
1379 fn from_slice(slice: &[T]) -> Self;
1380 }
1381
1382 #[cfg(not(no_global_oom_handling))]
1383 impl<T: Clone> RcFromSlice<T> for Rc<[T]> {
1384 #[inline]
1385 default fn from_slice(v: &[T]) -> Self {
1386 unsafe { Self::from_iter_exact(v.iter().cloned(), v.len()) }
1387 }
1388 }
1389
1390 #[cfg(not(no_global_oom_handling))]
1391 impl<T: Copy> RcFromSlice<T> for Rc<[T]> {
1392 #[inline]
1393 fn from_slice(v: &[T]) -> Self {
1394 unsafe { Rc::copy_from_slice(v) }
1395 }
1396 }
1397
1398 #[stable(feature = "rust1", since = "1.0.0")]
1399 impl<T: ?Sized> Deref for Rc<T> {
1400 type Target = T;
1401
1402 #[inline(always)]
1403 fn deref(&self) -> &T {
1404 &self.inner().value
1405 }
1406 }
1407
1408 #[unstable(feature = "receiver_trait", issue = "none")]
1409 impl<T: ?Sized> Receiver for Rc<T> {}
1410
1411 #[stable(feature = "rust1", since = "1.0.0")]
1412 unsafe impl<#[may_dangle] T: ?Sized> Drop for Rc<T> {
1413 /// Drops the `Rc`.
1414 ///
1415 /// This will decrement the strong reference count. If the strong reference
1416 /// count reaches zero then the only other references (if any) are
1417 /// [`Weak`], so we `drop` the inner value.
1418 ///
1419 /// # Examples
1420 ///
1421 /// ```
1422 /// use std::rc::Rc;
1423 ///
1424 /// struct Foo;
1425 ///
1426 /// impl Drop for Foo {
1427 /// fn drop(&mut self) {
1428 /// println!("dropped!");
1429 /// }
1430 /// }
1431 ///
1432 /// let foo = Rc::new(Foo);
1433 /// let foo2 = Rc::clone(&foo);
1434 ///
1435 /// drop(foo); // Doesn't print anything
1436 /// drop(foo2); // Prints "dropped!"
1437 /// ```
1438 fn drop(&mut self) {
1439 unsafe {
1440 self.inner().dec_strong();
1441 if self.inner().strong() == 0 {
1442 // destroy the contained object
1443 ptr::drop_in_place(Self::get_mut_unchecked(self));
1444
1445 // remove the implicit "strong weak" pointer now that we've
1446 // destroyed the contents.
1447 self.inner().dec_weak();
1448
1449 if self.inner().weak() == 0 {
1450 Global.deallocate(self.ptr.cast(), Layout::for_value(self.ptr.as_ref()));
1451 }
1452 }
1453 }
1454 }
1455 }
1456
1457 #[stable(feature = "rust1", since = "1.0.0")]
1458 impl<T: ?Sized> Clone for Rc<T> {
1459 /// Makes a clone of the `Rc` pointer.
1460 ///
1461 /// This creates another pointer to the same allocation, increasing the
1462 /// strong reference count.
1463 ///
1464 /// # Examples
1465 ///
1466 /// ```
1467 /// use std::rc::Rc;
1468 ///
1469 /// let five = Rc::new(5);
1470 ///
1471 /// let _ = Rc::clone(&five);
1472 /// ```
1473 #[inline]
1474 fn clone(&self) -> Rc<T> {
1475 self.inner().inc_strong();
1476 Self::from_inner(self.ptr)
1477 }
1478 }
1479
1480 #[cfg(not(no_global_oom_handling))]
1481 #[stable(feature = "rust1", since = "1.0.0")]
1482 impl<T: Default> Default for Rc<T> {
1483 /// Creates a new `Rc<T>`, with the `Default` value for `T`.
1484 ///
1485 /// # Examples
1486 ///
1487 /// ```
1488 /// use std::rc::Rc;
1489 ///
1490 /// let x: Rc<i32> = Default::default();
1491 /// assert_eq!(*x, 0);
1492 /// ```
1493 #[inline]
1494 fn default() -> Rc<T> {
1495 Rc::new(Default::default())
1496 }
1497 }
1498
1499 #[stable(feature = "rust1", since = "1.0.0")]
1500 trait RcEqIdent<T: ?Sized + PartialEq> {
1501 fn eq(&self, other: &Rc<T>) -> bool;
1502 fn ne(&self, other: &Rc<T>) -> bool;
1503 }
1504
1505 #[stable(feature = "rust1", since = "1.0.0")]
1506 impl<T: ?Sized + PartialEq> RcEqIdent<T> for Rc<T> {
1507 #[inline]
1508 default fn eq(&self, other: &Rc<T>) -> bool {
1509 **self == **other
1510 }
1511
1512 #[inline]
1513 default fn ne(&self, other: &Rc<T>) -> bool {
1514 **self != **other
1515 }
1516 }
1517
1518 // Hack to allow specializing on `Eq` even though `Eq` has a method.
1519 #[rustc_unsafe_specialization_marker]
1520 pub(crate) trait MarkerEq: PartialEq<Self> {}
1521
1522 impl<T: Eq> MarkerEq for T {}
1523
1524 /// We're doing this specialization here, and not as a more general optimization on `&T`, because it
1525 /// would otherwise add a cost to all equality checks on refs. We assume that `Rc`s are used to
1526 /// store large values, that are slow to clone, but also heavy to check for equality, causing this
1527 /// cost to pay off more easily. It's also more likely to have two `Rc` clones, that point to
1528 /// the same value, than two `&T`s.
1529 ///
1530 /// We can only do this when `T: Eq` as a `PartialEq` might be deliberately irreflexive.
1531 #[stable(feature = "rust1", since = "1.0.0")]
1532 impl<T: ?Sized + MarkerEq> RcEqIdent<T> for Rc<T> {
1533 #[inline]
1534 fn eq(&self, other: &Rc<T>) -> bool {
1535 Rc::ptr_eq(self, other) || **self == **other
1536 }
1537
1538 #[inline]
1539 fn ne(&self, other: &Rc<T>) -> bool {
1540 !Rc::ptr_eq(self, other) && **self != **other
1541 }
1542 }
1543
1544 #[stable(feature = "rust1", since = "1.0.0")]
1545 impl<T: ?Sized + PartialEq> PartialEq for Rc<T> {
1546 /// Equality for two `Rc`s.
1547 ///
1548 /// Two `Rc`s are equal if their inner values are equal, even if they are
1549 /// stored in different allocation.
1550 ///
1551 /// If `T` also implements `Eq` (implying reflexivity of equality),
1552 /// two `Rc`s that point to the same allocation are
1553 /// always equal.
1554 ///
1555 /// # Examples
1556 ///
1557 /// ```
1558 /// use std::rc::Rc;
1559 ///
1560 /// let five = Rc::new(5);
1561 ///
1562 /// assert!(five == Rc::new(5));
1563 /// ```
1564 #[inline]
1565 fn eq(&self, other: &Rc<T>) -> bool {
1566 RcEqIdent::eq(self, other)
1567 }
1568
1569 /// Inequality for two `Rc`s.
1570 ///
1571 /// Two `Rc`s are unequal if their inner values are unequal.
1572 ///
1573 /// If `T` also implements `Eq` (implying reflexivity of equality),
1574 /// two `Rc`s that point to the same allocation are
1575 /// never unequal.
1576 ///
1577 /// # Examples
1578 ///
1579 /// ```
1580 /// use std::rc::Rc;
1581 ///
1582 /// let five = Rc::new(5);
1583 ///
1584 /// assert!(five != Rc::new(6));
1585 /// ```
1586 #[inline]
1587 fn ne(&self, other: &Rc<T>) -> bool {
1588 RcEqIdent::ne(self, other)
1589 }
1590 }
1591
1592 #[stable(feature = "rust1", since = "1.0.0")]
1593 impl<T: ?Sized + Eq> Eq for Rc<T> {}
1594
1595 #[stable(feature = "rust1", since = "1.0.0")]
1596 impl<T: ?Sized + PartialOrd> PartialOrd for Rc<T> {
1597 /// Partial comparison for two `Rc`s.
1598 ///
1599 /// The two are compared by calling `partial_cmp()` on their inner values.
1600 ///
1601 /// # Examples
1602 ///
1603 /// ```
1604 /// use std::rc::Rc;
1605 /// use std::cmp::Ordering;
1606 ///
1607 /// let five = Rc::new(5);
1608 ///
1609 /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&Rc::new(6)));
1610 /// ```
1611 #[inline(always)]
1612 fn partial_cmp(&self, other: &Rc<T>) -> Option<Ordering> {
1613 (**self).partial_cmp(&**other)
1614 }
1615
1616 /// Less-than comparison for two `Rc`s.
1617 ///
1618 /// The two are compared by calling `<` on their inner values.
1619 ///
1620 /// # Examples
1621 ///
1622 /// ```
1623 /// use std::rc::Rc;
1624 ///
1625 /// let five = Rc::new(5);
1626 ///
1627 /// assert!(five < Rc::new(6));
1628 /// ```
1629 #[inline(always)]
1630 fn lt(&self, other: &Rc<T>) -> bool {
1631 **self < **other
1632 }
1633
1634 /// 'Less than or equal to' comparison for two `Rc`s.
1635 ///
1636 /// The two are compared by calling `<=` on their inner values.
1637 ///
1638 /// # Examples
1639 ///
1640 /// ```
1641 /// use std::rc::Rc;
1642 ///
1643 /// let five = Rc::new(5);
1644 ///
1645 /// assert!(five <= Rc::new(5));
1646 /// ```
1647 #[inline(always)]
1648 fn le(&self, other: &Rc<T>) -> bool {
1649 **self <= **other
1650 }
1651
1652 /// Greater-than comparison for two `Rc`s.
1653 ///
1654 /// The two are compared by calling `>` on their inner values.
1655 ///
1656 /// # Examples
1657 ///
1658 /// ```
1659 /// use std::rc::Rc;
1660 ///
1661 /// let five = Rc::new(5);
1662 ///
1663 /// assert!(five > Rc::new(4));
1664 /// ```
1665 #[inline(always)]
1666 fn gt(&self, other: &Rc<T>) -> bool {
1667 **self > **other
1668 }
1669
1670 /// 'Greater than or equal to' comparison for two `Rc`s.
1671 ///
1672 /// The two are compared by calling `>=` on their inner values.
1673 ///
1674 /// # Examples
1675 ///
1676 /// ```
1677 /// use std::rc::Rc;
1678 ///
1679 /// let five = Rc::new(5);
1680 ///
1681 /// assert!(five >= Rc::new(5));
1682 /// ```
1683 #[inline(always)]
1684 fn ge(&self, other: &Rc<T>) -> bool {
1685 **self >= **other
1686 }
1687 }
1688
1689 #[stable(feature = "rust1", since = "1.0.0")]
1690 impl<T: ?Sized + Ord> Ord for Rc<T> {
1691 /// Comparison for two `Rc`s.
1692 ///
1693 /// The two are compared by calling `cmp()` on their inner values.
1694 ///
1695 /// # Examples
1696 ///
1697 /// ```
1698 /// use std::rc::Rc;
1699 /// use std::cmp::Ordering;
1700 ///
1701 /// let five = Rc::new(5);
1702 ///
1703 /// assert_eq!(Ordering::Less, five.cmp(&Rc::new(6)));
1704 /// ```
1705 #[inline]
1706 fn cmp(&self, other: &Rc<T>) -> Ordering {
1707 (**self).cmp(&**other)
1708 }
1709 }
1710
1711 #[stable(feature = "rust1", since = "1.0.0")]
1712 impl<T: ?Sized + Hash> Hash for Rc<T> {
1713 fn hash<H: Hasher>(&self, state: &mut H) {
1714 (**self).hash(state);
1715 }
1716 }
1717
1718 #[stable(feature = "rust1", since = "1.0.0")]
1719 impl<T: ?Sized + fmt::Display> fmt::Display for Rc<T> {
1720 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1721 fmt::Display::fmt(&**self, f)
1722 }
1723 }
1724
1725 #[stable(feature = "rust1", since = "1.0.0")]
1726 impl<T: ?Sized + fmt::Debug> fmt::Debug for Rc<T> {
1727 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1728 fmt::Debug::fmt(&**self, f)
1729 }
1730 }
1731
1732 #[stable(feature = "rust1", since = "1.0.0")]
1733 impl<T: ?Sized> fmt::Pointer for Rc<T> {
1734 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1735 fmt::Pointer::fmt(&(&**self as *const T), f)
1736 }
1737 }
1738
1739 #[cfg(not(no_global_oom_handling))]
1740 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
1741 impl<T> From<T> for Rc<T> {
1742 /// Converts a generic type `T` into a `Rc<T>`
1743 ///
1744 /// The conversion allocates on the heap and moves `t`
1745 /// from the stack into it.
1746 ///
1747 /// # Example
1748 /// ```rust
1749 /// # use std::rc::Rc;
1750 /// let x = 5;
1751 /// let rc = Rc::new(5);
1752 ///
1753 /// assert_eq!(Rc::from(x), rc);
1754 /// ```
1755 fn from(t: T) -> Self {
1756 Rc::new(t)
1757 }
1758 }
1759
1760 #[cfg(not(no_global_oom_handling))]
1761 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1762 impl<T: Clone> From<&[T]> for Rc<[T]> {
1763 /// Allocate a reference-counted slice and fill it by cloning `v`'s items.
1764 ///
1765 /// # Example
1766 ///
1767 /// ```
1768 /// # use std::rc::Rc;
1769 /// let original: &[i32] = &[1, 2, 3];
1770 /// let shared: Rc<[i32]> = Rc::from(original);
1771 /// assert_eq!(&[1, 2, 3], &shared[..]);
1772 /// ```
1773 #[inline]
1774 fn from(v: &[T]) -> Rc<[T]> {
1775 <Self as RcFromSlice<T>>::from_slice(v)
1776 }
1777 }
1778
1779 #[cfg(not(no_global_oom_handling))]
1780 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1781 impl From<&str> for Rc<str> {
1782 /// Allocate a reference-counted string slice and copy `v` into it.
1783 ///
1784 /// # Example
1785 ///
1786 /// ```
1787 /// # use std::rc::Rc;
1788 /// let shared: Rc<str> = Rc::from("statue");
1789 /// assert_eq!("statue", &shared[..]);
1790 /// ```
1791 #[inline]
1792 fn from(v: &str) -> Rc<str> {
1793 let rc = Rc::<[u8]>::from(v.as_bytes());
1794 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const str) }
1795 }
1796 }
1797
1798 #[cfg(not(no_global_oom_handling))]
1799 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1800 impl From<String> for Rc<str> {
1801 /// Allocate a reference-counted string slice and copy `v` into it.
1802 ///
1803 /// # Example
1804 ///
1805 /// ```
1806 /// # use std::rc::Rc;
1807 /// let original: String = "statue".to_owned();
1808 /// let shared: Rc<str> = Rc::from(original);
1809 /// assert_eq!("statue", &shared[..]);
1810 /// ```
1811 #[inline]
1812 fn from(v: String) -> Rc<str> {
1813 Rc::from(&v[..])
1814 }
1815 }
1816
1817 #[cfg(not(no_global_oom_handling))]
1818 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1819 impl<T: ?Sized> From<Box<T>> for Rc<T> {
1820 /// Move a boxed object to a new, reference counted, allocation.
1821 ///
1822 /// # Example
1823 ///
1824 /// ```
1825 /// # use std::rc::Rc;
1826 /// let original: Box<i32> = Box::new(1);
1827 /// let shared: Rc<i32> = Rc::from(original);
1828 /// assert_eq!(1, *shared);
1829 /// ```
1830 #[inline]
1831 fn from(v: Box<T>) -> Rc<T> {
1832 Rc::from_box(v)
1833 }
1834 }
1835
1836 #[cfg(not(no_global_oom_handling))]
1837 #[stable(feature = "shared_from_slice", since = "1.21.0")]
1838 impl<T> From<Vec<T>> for Rc<[T]> {
1839 /// Allocate a reference-counted slice and move `v`'s items into it.
1840 ///
1841 /// # Example
1842 ///
1843 /// ```
1844 /// # use std::rc::Rc;
1845 /// let original: Box<Vec<i32>> = Box::new(vec![1, 2, 3]);
1846 /// let shared: Rc<Vec<i32>> = Rc::from(original);
1847 /// assert_eq!(vec![1, 2, 3], *shared);
1848 /// ```
1849 #[inline]
1850 fn from(mut v: Vec<T>) -> Rc<[T]> {
1851 unsafe {
1852 let rc = Rc::copy_from_slice(&v);
1853
1854 // Allow the Vec to free its memory, but not destroy its contents
1855 v.set_len(0);
1856
1857 rc
1858 }
1859 }
1860 }
1861
1862 #[stable(feature = "shared_from_cow", since = "1.45.0")]
1863 impl<'a, B> From<Cow<'a, B>> for Rc<B>
1864 where
1865 B: ToOwned + ?Sized,
1866 Rc<B>: From<&'a B> + From<B::Owned>,
1867 {
1868 /// Create a reference-counted pointer from
1869 /// a clone-on-write pointer by copying its content.
1870 ///
1871 /// # Example
1872 ///
1873 /// ```rust
1874 /// # use std::rc::Rc;
1875 /// # use std::borrow::Cow;
1876 /// let cow: Cow<str> = Cow::Borrowed("eggplant");
1877 /// let shared: Rc<str> = Rc::from(cow);
1878 /// assert_eq!("eggplant", &shared[..]);
1879 /// ```
1880 #[inline]
1881 fn from(cow: Cow<'a, B>) -> Rc<B> {
1882 match cow {
1883 Cow::Borrowed(s) => Rc::from(s),
1884 Cow::Owned(s) => Rc::from(s),
1885 }
1886 }
1887 }
1888
1889 #[stable(feature = "boxed_slice_try_from", since = "1.43.0")]
1890 impl<T, const N: usize> TryFrom<Rc<[T]>> for Rc<[T; N]> {
1891 type Error = Rc<[T]>;
1892
1893 fn try_from(boxed_slice: Rc<[T]>) -> Result<Self, Self::Error> {
1894 if boxed_slice.len() == N {
1895 Ok(unsafe { Rc::from_raw(Rc::into_raw(boxed_slice) as *mut [T; N]) })
1896 } else {
1897 Err(boxed_slice)
1898 }
1899 }
1900 }
1901
1902 #[cfg(not(no_global_oom_handling))]
1903 #[stable(feature = "shared_from_iter", since = "1.37.0")]
1904 impl<T> iter::FromIterator<T> for Rc<[T]> {
1905 /// Takes each element in the `Iterator` and collects it into an `Rc<[T]>`.
1906 ///
1907 /// # Performance characteristics
1908 ///
1909 /// ## The general case
1910 ///
1911 /// In the general case, collecting into `Rc<[T]>` is done by first
1912 /// collecting into a `Vec<T>`. That is, when writing the following:
1913 ///
1914 /// ```rust
1915 /// # use std::rc::Rc;
1916 /// let evens: Rc<[u8]> = (0..10).filter(|&x| x % 2 == 0).collect();
1917 /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]);
1918 /// ```
1919 ///
1920 /// this behaves as if we wrote:
1921 ///
1922 /// ```rust
1923 /// # use std::rc::Rc;
1924 /// let evens: Rc<[u8]> = (0..10).filter(|&x| x % 2 == 0)
1925 /// .collect::<Vec<_>>() // The first set of allocations happens here.
1926 /// .into(); // A second allocation for `Rc<[T]>` happens here.
1927 /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]);
1928 /// ```
1929 ///
1930 /// This will allocate as many times as needed for constructing the `Vec<T>`
1931 /// and then it will allocate once for turning the `Vec<T>` into the `Rc<[T]>`.
1932 ///
1933 /// ## Iterators of known length
1934 ///
1935 /// When your `Iterator` implements `TrustedLen` and is of an exact size,
1936 /// a single allocation will be made for the `Rc<[T]>`. For example:
1937 ///
1938 /// ```rust
1939 /// # use std::rc::Rc;
1940 /// let evens: Rc<[u8]> = (0..10).collect(); // Just a single allocation happens here.
1941 /// # assert_eq!(&*evens, &*(0..10).collect::<Vec<_>>());
1942 /// ```
1943 fn from_iter<I: iter::IntoIterator<Item = T>>(iter: I) -> Self {
1944 ToRcSlice::to_rc_slice(iter.into_iter())
1945 }
1946 }
1947
1948 /// Specialization trait used for collecting into `Rc<[T]>`.
1949 #[cfg(not(no_global_oom_handling))]
1950 trait ToRcSlice<T>: Iterator<Item = T> + Sized {
1951 fn to_rc_slice(self) -> Rc<[T]>;
1952 }
1953
1954 #[cfg(not(no_global_oom_handling))]
1955 impl<T, I: Iterator<Item = T>> ToRcSlice<T> for I {
1956 default fn to_rc_slice(self) -> Rc<[T]> {
1957 self.collect::<Vec<T>>().into()
1958 }
1959 }
1960
1961 #[cfg(not(no_global_oom_handling))]
1962 impl<T, I: iter::TrustedLen<Item = T>> ToRcSlice<T> for I {
1963 fn to_rc_slice(self) -> Rc<[T]> {
1964 // This is the case for a `TrustedLen` iterator.
1965 let (low, high) = self.size_hint();
1966 if let Some(high) = high {
1967 debug_assert_eq!(
1968 low,
1969 high,
1970 "TrustedLen iterator's size hint is not exact: {:?}",
1971 (low, high)
1972 );
1973
1974 unsafe {
1975 // SAFETY: We need to ensure that the iterator has an exact length and we have.
1976 Rc::from_iter_exact(self, low)
1977 }
1978 } else {
1979 // TrustedLen contract guarantees that `upper_bound == `None` implies an iterator
1980 // length exceeding `usize::MAX`.
1981 // The default implementation would collect into a vec which would panic.
1982 // Thus we panic here immediately without invoking `Vec` code.
1983 panic!("capacity overflow");
1984 }
1985 }
1986 }
1987
1988 /// `Weak` is a version of [`Rc`] that holds a non-owning reference to the
1989 /// managed allocation. The allocation is accessed by calling [`upgrade`] on the `Weak`
1990 /// pointer, which returns an [`Option`]`<`[`Rc`]`<T>>`.
1991 ///
1992 /// Since a `Weak` reference does not count towards ownership, it will not
1993 /// prevent the value stored in the allocation from being dropped, and `Weak` itself makes no
1994 /// guarantees about the value still being present. Thus it may return [`None`]
1995 /// when [`upgrade`]d. Note however that a `Weak` reference *does* prevent the allocation
1996 /// itself (the backing store) from being deallocated.
1997 ///
1998 /// A `Weak` pointer is useful for keeping a temporary reference to the allocation
1999 /// managed by [`Rc`] without preventing its inner value from being dropped. It is also used to
2000 /// prevent circular references between [`Rc`] pointers, since mutual owning references
2001 /// would never allow either [`Rc`] to be dropped. For example, a tree could
2002 /// have strong [`Rc`] pointers from parent nodes to children, and `Weak`
2003 /// pointers from children back to their parents.
2004 ///
2005 /// The typical way to obtain a `Weak` pointer is to call [`Rc::downgrade`].
2006 ///
2007 /// [`upgrade`]: Weak::upgrade
2008 #[stable(feature = "rc_weak", since = "1.4.0")]
2009 pub struct Weak<T: ?Sized> {
2010 // This is a `NonNull` to allow optimizing the size of this type in enums,
2011 // but it is not necessarily a valid pointer.
2012 // `Weak::new` sets this to `usize::MAX` so that it doesn’t need
2013 // to allocate space on the heap. That's not a value a real pointer
2014 // will ever have because RcBox has alignment at least 2.
2015 // This is only possible when `T: Sized`; unsized `T` never dangle.
2016 ptr: NonNull<RcBox<T>>,
2017 }
2018
2019 #[stable(feature = "rc_weak", since = "1.4.0")]
2020 impl<T: ?Sized> !marker::Send for Weak<T> {}
2021 #[stable(feature = "rc_weak", since = "1.4.0")]
2022 impl<T: ?Sized> !marker::Sync for Weak<T> {}
2023
2024 #[unstable(feature = "coerce_unsized", issue = "27732")]
2025 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {}
2026
2027 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
2028 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Weak<U>> for Weak<T> {}
2029
2030 impl<T> Weak<T> {
2031 /// Constructs a new `Weak<T>`, without allocating any memory.
2032 /// Calling [`upgrade`] on the return value always gives [`None`].
2033 ///
2034 /// [`upgrade`]: Weak::upgrade
2035 ///
2036 /// # Examples
2037 ///
2038 /// ```
2039 /// use std::rc::Weak;
2040 ///
2041 /// let empty: Weak<i64> = Weak::new();
2042 /// assert!(empty.upgrade().is_none());
2043 /// ```
2044 #[stable(feature = "downgraded_weak", since = "1.10.0")]
2045 pub fn new() -> Weak<T> {
2046 Weak { ptr: NonNull::new(usize::MAX as *mut RcBox<T>).expect("MAX is not 0") }
2047 }
2048 }
2049
2050 pub(crate) fn is_dangling<T: ?Sized>(ptr: *mut T) -> bool {
2051 let address = ptr as *mut () as usize;
2052 address == usize::MAX
2053 }
2054
2055 /// Helper type to allow accessing the reference counts without
2056 /// making any assertions about the data field.
2057 struct WeakInner<'a> {
2058 weak: &'a Cell<usize>,
2059 strong: &'a Cell<usize>,
2060 }
2061
2062 impl<T: ?Sized> Weak<T> {
2063 /// Returns a raw pointer to the object `T` pointed to by this `Weak<T>`.
2064 ///
2065 /// The pointer is valid only if there are some strong references. The pointer may be dangling,
2066 /// unaligned or even [`null`] otherwise.
2067 ///
2068 /// # Examples
2069 ///
2070 /// ```
2071 /// use std::rc::Rc;
2072 /// use std::ptr;
2073 ///
2074 /// let strong = Rc::new("hello".to_owned());
2075 /// let weak = Rc::downgrade(&strong);
2076 /// // Both point to the same object
2077 /// assert!(ptr::eq(&*strong, weak.as_ptr()));
2078 /// // The strong here keeps it alive, so we can still access the object.
2079 /// assert_eq!("hello", unsafe { &*weak.as_ptr() });
2080 ///
2081 /// drop(strong);
2082 /// // But not any more. We can do weak.as_ptr(), but accessing the pointer would lead to
2083 /// // undefined behaviour.
2084 /// // assert_eq!("hello", unsafe { &*weak.as_ptr() });
2085 /// ```
2086 ///
2087 /// [`null`]: core::ptr::null
2088 #[stable(feature = "rc_as_ptr", since = "1.45.0")]
2089 pub fn as_ptr(&self) -> *const T {
2090 let ptr: *mut RcBox<T> = NonNull::as_ptr(self.ptr);
2091
2092 if is_dangling(ptr) {
2093 // If the pointer is dangling, we return the sentinel directly. This cannot be
2094 // a valid payload address, as the payload is at least as aligned as RcBox (usize).
2095 ptr as *const T
2096 } else {
2097 // SAFETY: if is_dangling returns false, then the pointer is dereferencable.
2098 // The payload may be dropped at this point, and we have to maintain provenance,
2099 // so use raw pointer manipulation.
2100 unsafe { ptr::addr_of_mut!((*ptr).value) }
2101 }
2102 }
2103
2104 /// Consumes the `Weak<T>` and turns it into a raw pointer.
2105 ///
2106 /// This converts the weak pointer into a raw pointer, while still preserving the ownership of
2107 /// one weak reference (the weak count is not modified by this operation). It can be turned
2108 /// back into the `Weak<T>` with [`from_raw`].
2109 ///
2110 /// The same restrictions of accessing the target of the pointer as with
2111 /// [`as_ptr`] apply.
2112 ///
2113 /// # Examples
2114 ///
2115 /// ```
2116 /// use std::rc::{Rc, Weak};
2117 ///
2118 /// let strong = Rc::new("hello".to_owned());
2119 /// let weak = Rc::downgrade(&strong);
2120 /// let raw = weak.into_raw();
2121 ///
2122 /// assert_eq!(1, Rc::weak_count(&strong));
2123 /// assert_eq!("hello", unsafe { &*raw });
2124 ///
2125 /// drop(unsafe { Weak::from_raw(raw) });
2126 /// assert_eq!(0, Rc::weak_count(&strong));
2127 /// ```
2128 ///
2129 /// [`from_raw`]: Weak::from_raw
2130 /// [`as_ptr`]: Weak::as_ptr
2131 #[stable(feature = "weak_into_raw", since = "1.45.0")]
2132 pub fn into_raw(self) -> *const T {
2133 let result = self.as_ptr();
2134 mem::forget(self);
2135 result
2136 }
2137
2138 /// Converts a raw pointer previously created by [`into_raw`] back into `Weak<T>`.
2139 ///
2140 /// This can be used to safely get a strong reference (by calling [`upgrade`]
2141 /// later) or to deallocate the weak count by dropping the `Weak<T>`.
2142 ///
2143 /// It takes ownership of one weak reference (with the exception of pointers created by [`new`],
2144 /// as these don't own anything; the method still works on them).
2145 ///
2146 /// # Safety
2147 ///
2148 /// The pointer must have originated from the [`into_raw`] and must still own its potential
2149 /// weak reference.
2150 ///
2151 /// It is allowed for the strong count to be 0 at the time of calling this. Nevertheless, this
2152 /// takes ownership of one weak reference currently represented as a raw pointer (the weak
2153 /// count is not modified by this operation) and therefore it must be paired with a previous
2154 /// call to [`into_raw`].
2155 ///
2156 /// # Examples
2157 ///
2158 /// ```
2159 /// use std::rc::{Rc, Weak};
2160 ///
2161 /// let strong = Rc::new("hello".to_owned());
2162 ///
2163 /// let raw_1 = Rc::downgrade(&strong).into_raw();
2164 /// let raw_2 = Rc::downgrade(&strong).into_raw();
2165 ///
2166 /// assert_eq!(2, Rc::weak_count(&strong));
2167 ///
2168 /// assert_eq!("hello", &*unsafe { Weak::from_raw(raw_1) }.upgrade().unwrap());
2169 /// assert_eq!(1, Rc::weak_count(&strong));
2170 ///
2171 /// drop(strong);
2172 ///
2173 /// // Decrement the last weak count.
2174 /// assert!(unsafe { Weak::from_raw(raw_2) }.upgrade().is_none());
2175 /// ```
2176 ///
2177 /// [`into_raw`]: Weak::into_raw
2178 /// [`upgrade`]: Weak::upgrade
2179 /// [`new`]: Weak::new
2180 #[stable(feature = "weak_into_raw", since = "1.45.0")]
2181 pub unsafe fn from_raw(ptr: *const T) -> Self {
2182 // See Weak::as_ptr for context on how the input pointer is derived.
2183
2184 let ptr = if is_dangling(ptr as *mut T) {
2185 // This is a dangling Weak.
2186 ptr as *mut RcBox<T>
2187 } else {
2188 // Otherwise, we're guaranteed the pointer came from a nondangling Weak.
2189 // SAFETY: data_offset is safe to call, as ptr references a real (potentially dropped) T.
2190 let offset = unsafe { data_offset(ptr) };
2191 // Thus, we reverse the offset to get the whole RcBox.
2192 // SAFETY: the pointer originated from a Weak, so this offset is safe.
2193 unsafe { (ptr as *mut RcBox<T>).set_ptr_value((ptr as *mut u8).offset(-offset)) }
2194 };
2195
2196 // SAFETY: we now have recovered the original Weak pointer, so can create the Weak.
2197 Weak { ptr: unsafe { NonNull::new_unchecked(ptr) } }
2198 }
2199
2200 /// Attempts to upgrade the `Weak` pointer to an [`Rc`], delaying
2201 /// dropping of the inner value if successful.
2202 ///
2203 /// Returns [`None`] if the inner value has since been dropped.
2204 ///
2205 /// # Examples
2206 ///
2207 /// ```
2208 /// use std::rc::Rc;
2209 ///
2210 /// let five = Rc::new(5);
2211 ///
2212 /// let weak_five = Rc::downgrade(&five);
2213 ///
2214 /// let strong_five: Option<Rc<_>> = weak_five.upgrade();
2215 /// assert!(strong_five.is_some());
2216 ///
2217 /// // Destroy all strong pointers.
2218 /// drop(strong_five);
2219 /// drop(five);
2220 ///
2221 /// assert!(weak_five.upgrade().is_none());
2222 /// ```
2223 #[stable(feature = "rc_weak", since = "1.4.0")]
2224 pub fn upgrade(&self) -> Option<Rc<T>> {
2225 let inner = self.inner()?;
2226 if inner.strong() == 0 {
2227 None
2228 } else {
2229 inner.inc_strong();
2230 Some(Rc::from_inner(self.ptr))
2231 }
2232 }
2233
2234 /// Gets the number of strong (`Rc`) pointers pointing to this allocation.
2235 ///
2236 /// If `self` was created using [`Weak::new`], this will return 0.
2237 #[stable(feature = "weak_counts", since = "1.41.0")]
2238 pub fn strong_count(&self) -> usize {
2239 if let Some(inner) = self.inner() { inner.strong() } else { 0 }
2240 }
2241
2242 /// Gets the number of `Weak` pointers pointing to this allocation.
2243 ///
2244 /// If no strong pointers remain, this will return zero.
2245 #[stable(feature = "weak_counts", since = "1.41.0")]
2246 pub fn weak_count(&self) -> usize {
2247 self.inner()
2248 .map(|inner| {
2249 if inner.strong() > 0 {
2250 inner.weak() - 1 // subtract the implicit weak ptr
2251 } else {
2252 0
2253 }
2254 })
2255 .unwrap_or(0)
2256 }
2257
2258 /// Returns `None` when the pointer is dangling and there is no allocated `RcBox`,
2259 /// (i.e., when this `Weak` was created by `Weak::new`).
2260 #[inline]
2261 fn inner(&self) -> Option<WeakInner<'_>> {
2262 if is_dangling(self.ptr.as_ptr()) {
2263 None
2264 } else {
2265 // We are careful to *not* create a reference covering the "data" field, as
2266 // the field may be mutated concurrently (for example, if the last `Rc`
2267 // is dropped, the data field will be dropped in-place).
2268 Some(unsafe {
2269 let ptr = self.ptr.as_ptr();
2270 WeakInner { strong: &(*ptr).strong, weak: &(*ptr).weak }
2271 })
2272 }
2273 }
2274
2275 /// Returns `true` if the two `Weak`s point to the same allocation (similar to
2276 /// [`ptr::eq`]), or if both don't point to any allocation
2277 /// (because they were created with `Weak::new()`).
2278 ///
2279 /// # Notes
2280 ///
2281 /// Since this compares pointers it means that `Weak::new()` will equal each
2282 /// other, even though they don't point to any allocation.
2283 ///
2284 /// # Examples
2285 ///
2286 /// ```
2287 /// use std::rc::Rc;
2288 ///
2289 /// let first_rc = Rc::new(5);
2290 /// let first = Rc::downgrade(&first_rc);
2291 /// let second = Rc::downgrade(&first_rc);
2292 ///
2293 /// assert!(first.ptr_eq(&second));
2294 ///
2295 /// let third_rc = Rc::new(5);
2296 /// let third = Rc::downgrade(&third_rc);
2297 ///
2298 /// assert!(!first.ptr_eq(&third));
2299 /// ```
2300 ///
2301 /// Comparing `Weak::new`.
2302 ///
2303 /// ```
2304 /// use std::rc::{Rc, Weak};
2305 ///
2306 /// let first = Weak::new();
2307 /// let second = Weak::new();
2308 /// assert!(first.ptr_eq(&second));
2309 ///
2310 /// let third_rc = Rc::new(());
2311 /// let third = Rc::downgrade(&third_rc);
2312 /// assert!(!first.ptr_eq(&third));
2313 /// ```
2314 ///
2315 /// [`ptr::eq`]: core::ptr::eq
2316 #[inline]
2317 #[stable(feature = "weak_ptr_eq", since = "1.39.0")]
2318 pub fn ptr_eq(&self, other: &Self) -> bool {
2319 self.ptr.as_ptr() == other.ptr.as_ptr()
2320 }
2321 }
2322
2323 #[stable(feature = "rc_weak", since = "1.4.0")]
2324 unsafe impl<#[may_dangle] T: ?Sized> Drop for Weak<T> {
2325 /// Drops the `Weak` pointer.
2326 ///
2327 /// # Examples
2328 ///
2329 /// ```
2330 /// use std::rc::{Rc, Weak};
2331 ///
2332 /// struct Foo;
2333 ///
2334 /// impl Drop for Foo {
2335 /// fn drop(&mut self) {
2336 /// println!("dropped!");
2337 /// }
2338 /// }
2339 ///
2340 /// let foo = Rc::new(Foo);
2341 /// let weak_foo = Rc::downgrade(&foo);
2342 /// let other_weak_foo = Weak::clone(&weak_foo);
2343 ///
2344 /// drop(weak_foo); // Doesn't print anything
2345 /// drop(foo); // Prints "dropped!"
2346 ///
2347 /// assert!(other_weak_foo.upgrade().is_none());
2348 /// ```
2349 fn drop(&mut self) {
2350 let inner = if let Some(inner) = self.inner() { inner } else { return };
2351
2352 inner.dec_weak();
2353 // the weak count starts at 1, and will only go to zero if all
2354 // the strong pointers have disappeared.
2355 if inner.weak() == 0 {
2356 unsafe {
2357 Global.deallocate(self.ptr.cast(), Layout::for_value_raw(self.ptr.as_ptr()));
2358 }
2359 }
2360 }
2361 }
2362
2363 #[stable(feature = "rc_weak", since = "1.4.0")]
2364 impl<T: ?Sized> Clone for Weak<T> {
2365 /// Makes a clone of the `Weak` pointer that points to the same allocation.
2366 ///
2367 /// # Examples
2368 ///
2369 /// ```
2370 /// use std::rc::{Rc, Weak};
2371 ///
2372 /// let weak_five = Rc::downgrade(&Rc::new(5));
2373 ///
2374 /// let _ = Weak::clone(&weak_five);
2375 /// ```
2376 #[inline]
2377 fn clone(&self) -> Weak<T> {
2378 if let Some(inner) = self.inner() {
2379 inner.inc_weak()
2380 }
2381 Weak { ptr: self.ptr }
2382 }
2383 }
2384
2385 #[stable(feature = "rc_weak", since = "1.4.0")]
2386 impl<T: ?Sized + fmt::Debug> fmt::Debug for Weak<T> {
2387 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2388 write!(f, "(Weak)")
2389 }
2390 }
2391
2392 #[stable(feature = "downgraded_weak", since = "1.10.0")]
2393 impl<T> Default for Weak<T> {
2394 /// Constructs a new `Weak<T>`, without allocating any memory.
2395 /// Calling [`upgrade`] on the return value always gives [`None`].
2396 ///
2397 /// [`None`]: Option
2398 /// [`upgrade`]: Weak::upgrade
2399 ///
2400 /// # Examples
2401 ///
2402 /// ```
2403 /// use std::rc::Weak;
2404 ///
2405 /// let empty: Weak<i64> = Default::default();
2406 /// assert!(empty.upgrade().is_none());
2407 /// ```
2408 fn default() -> Weak<T> {
2409 Weak::new()
2410 }
2411 }
2412
2413 // NOTE: We checked_add here to deal with mem::forget safely. In particular
2414 // if you mem::forget Rcs (or Weaks), the ref-count can overflow, and then
2415 // you can free the allocation while outstanding Rcs (or Weaks) exist.
2416 // We abort because this is such a degenerate scenario that we don't care about
2417 // what happens -- no real program should ever experience this.
2418 //
2419 // This should have negligible overhead since you don't actually need to
2420 // clone these much in Rust thanks to ownership and move-semantics.
2421
2422 #[doc(hidden)]
2423 trait RcInnerPtr {
2424 fn weak_ref(&self) -> &Cell<usize>;
2425 fn strong_ref(&self) -> &Cell<usize>;
2426
2427 #[inline]
2428 fn strong(&self) -> usize {
2429 self.strong_ref().get()
2430 }
2431
2432 #[inline]
2433 fn inc_strong(&self) {
2434 let strong = self.strong();
2435
2436 // We want to abort on overflow instead of dropping the value.
2437 // The reference count will never be zero when this is called;
2438 // nevertheless, we insert an abort here to hint LLVM at
2439 // an otherwise missed optimization.
2440 if strong == 0 || strong == usize::MAX {
2441 abort();
2442 }
2443 self.strong_ref().set(strong + 1);
2444 }
2445
2446 #[inline]
2447 fn dec_strong(&self) {
2448 self.strong_ref().set(self.strong() - 1);
2449 }
2450
2451 #[inline]
2452 fn weak(&self) -> usize {
2453 self.weak_ref().get()
2454 }
2455
2456 #[inline]
2457 fn inc_weak(&self) {
2458 let weak = self.weak();
2459
2460 // We want to abort on overflow instead of dropping the value.
2461 // The reference count will never be zero when this is called;
2462 // nevertheless, we insert an abort here to hint LLVM at
2463 // an otherwise missed optimization.
2464 if weak == 0 || weak == usize::MAX {
2465 abort();
2466 }
2467 self.weak_ref().set(weak + 1);
2468 }
2469
2470 #[inline]
2471 fn dec_weak(&self) {
2472 self.weak_ref().set(self.weak() - 1);
2473 }
2474 }
2475
2476 impl<T: ?Sized> RcInnerPtr for RcBox<T> {
2477 #[inline(always)]
2478 fn weak_ref(&self) -> &Cell<usize> {
2479 &self.weak
2480 }
2481
2482 #[inline(always)]
2483 fn strong_ref(&self) -> &Cell<usize> {
2484 &self.strong
2485 }
2486 }
2487
2488 impl<'a> RcInnerPtr for WeakInner<'a> {
2489 #[inline(always)]
2490 fn weak_ref(&self) -> &Cell<usize> {
2491 self.weak
2492 }
2493
2494 #[inline(always)]
2495 fn strong_ref(&self) -> &Cell<usize> {
2496 self.strong
2497 }
2498 }
2499
2500 #[stable(feature = "rust1", since = "1.0.0")]
2501 impl<T: ?Sized> borrow::Borrow<T> for Rc<T> {
2502 fn borrow(&self) -> &T {
2503 &**self
2504 }
2505 }
2506
2507 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
2508 impl<T: ?Sized> AsRef<T> for Rc<T> {
2509 fn as_ref(&self) -> &T {
2510 &**self
2511 }
2512 }
2513
2514 #[stable(feature = "pin", since = "1.33.0")]
2515 impl<T: ?Sized> Unpin for Rc<T> {}
2516
2517 /// Get the offset within an `RcBox` for the payload behind a pointer.
2518 ///
2519 /// # Safety
2520 ///
2521 /// The pointer must point to (and have valid metadata for) a previously
2522 /// valid instance of T, but the T is allowed to be dropped.
2523 unsafe fn data_offset<T: ?Sized>(ptr: *const T) -> isize {
2524 // Align the unsized value to the end of the RcBox.
2525 // Because RcBox is repr(C), it will always be the last field in memory.
2526 // SAFETY: since the only unsized types possible are slices, trait objects,
2527 // and extern types, the input safety requirement is currently enough to
2528 // satisfy the requirements of align_of_val_raw; this is an implementation
2529 // detail of the language that may not be relied upon outside of std.
2530 unsafe { data_offset_align(align_of_val_raw(ptr)) }
2531 }
2532
2533 #[inline]
2534 fn data_offset_align(align: usize) -> isize {
2535 let layout = Layout::new::<RcBox<()>>();
2536 (layout.size() + layout.padding_needed_for(align)) as isize
2537 }