Skip to main content

core/
cell.rs

1//! Shareable mutable containers.
2//!
3//! Rust memory safety is based on this rule: Given an object `T`, it is only possible to
4//! have one of the following:
5//!
6//! - Several immutable references (`&T`) to the object (also known as **aliasing**).
7//! - One mutable reference (`&mut T`) to the object (also known as **mutability**).
8//!
9//! This is enforced by the Rust compiler. However, there are situations where this rule is not
10//! flexible enough. Sometimes it is required to have multiple references to an object and yet
11//! mutate it.
12//!
13//! Shareable mutable containers exist to permit mutability in a controlled manner, even in the
14//! presence of aliasing. [`Cell<T>`], [`RefCell<T>`], and [`OnceCell<T>`] allow doing this in
15//! a single-threaded way—they do not implement [`Sync`]. (If you need to do aliasing and
16//! mutation among multiple threads, [`Mutex<T>`], [`RwLock<T>`], [`OnceLock<T>`] or [`atomic`]
17//! types are the correct data structures to do so).
18//!
19//! Values of the `Cell<T>`, `RefCell<T>`, and `OnceCell<T>` types may be mutated through shared
20//! references (i.e. the common `&T` type), whereas most Rust types can only be mutated through
21//! unique (`&mut T`) references. We say these cell types provide 'interior mutability'
22//! (mutable via `&T`), in contrast with typical Rust types that exhibit 'inherited mutability'
23//! (mutable only via `&mut T`).
24//!
25//! Cell types come in four flavors: `Cell<T>`, `RefCell<T>`, `OnceCell<T>`, and `LazyCell<T>`.
26//! Each provides a different way of providing safe interior mutability.
27//!
28//! ## `Cell<T>`
29//!
30//! [`Cell<T>`] implements interior mutability by moving values in and out of the cell. That is, a
31//! `&T` to the inner value can never be obtained, and the value itself cannot be directly
32//! obtained without replacing it with something else. This type provides the following
33//! methods:
34//!
35//!  - For types that implement [`Copy`], the [`get`](Cell::get) method retrieves the current
36//!    interior value by duplicating it.
37//!  - For types that implement [`Default`], the [`take`](Cell::take) method replaces the current
38//!    interior value with [`Default::default()`] and returns the replaced value.
39//!  - All types have:
40//!    - [`replace`](Cell::replace): replaces the current interior value and returns the replaced
41//!      value.
42//!    - [`into_inner`](Cell::into_inner): this method consumes the `Cell<T>` and returns the
43//!      interior value.
44//!    - [`set`](Cell::set): this method replaces the interior value, dropping the replaced value.
45//!
46//! `Cell<T>` is typically used for more simple types where copying or moving values isn't too
47//! resource intensive (e.g. numbers), and should usually be preferred over other cell types when
48//! possible. For larger and non-copy types, `RefCell` provides some advantages.
49//!
50//! ## `RefCell<T>`
51//!
52//! [`RefCell<T>`] uses Rust's lifetimes to implement "dynamic borrowing", a process whereby one can
53//! claim temporary, exclusive, mutable access to the inner value. Borrows for `RefCell<T>`s are
54//! tracked at _runtime_, unlike Rust's native reference types which are entirely tracked
55//! statically, at compile time.
56//!
57//! An immutable reference to a `RefCell`'s inner value (`&T`) can be obtained with
58//! [`borrow`](`RefCell::borrow`), and a mutable borrow (`&mut T`) can be obtained with
59//! [`borrow_mut`](`RefCell::borrow_mut`). When these functions are called, they first verify that
60//! Rust's borrow rules will be satisfied: any number of immutable borrows are allowed or a
61//! single mutable borrow is allowed, but never both. If a borrow is attempted that would violate
62//! these rules, the thread will panic.
63//!
64//! The corresponding [`Sync`] version of `RefCell<T>` is [`RwLock<T>`].
65//!
66//! ## `OnceCell<T>`
67//!
68//! [`OnceCell<T>`] is somewhat of a hybrid of `Cell` and `RefCell` that works for values that
69//! typically only need to be set once. This means that a reference `&T` can be obtained without
70//! moving or copying the inner value (unlike `Cell`) but also without runtime checks (unlike
71//! `RefCell`). However, once set, its value cannot be updated unless you have a mutable
72//! reference to the `OnceCell`.
73//!
74//! `OnceCell` provides the following methods:
75//!
76//! - [`get`](OnceCell::get): obtain a reference to the inner value
77//! - [`set`](OnceCell::set): set the inner value if it is unset (returns a `Result`)
78//! - [`get_or_init`](OnceCell::get_or_init): return the inner value, initializing it if needed
79//! - [`get_mut`](OnceCell::get_mut): provide a mutable reference to the inner value, only available
80//!   if you have a mutable reference to the cell itself.
81//!
82//! The corresponding [`Sync`] version of `OnceCell<T>` is [`OnceLock<T>`].
83//!
84//! ## `LazyCell<T, F>`
85//!
86//! A common pattern with OnceCell is, for a given OnceCell, to use the same function on every
87//! call to [`OnceCell::get_or_init`] with that cell. This is what is offered by [`LazyCell`],
88//! which pairs cells of `T` with functions of `F`, and always calls `F` before it yields `&T`.
89//! This happens implicitly by simply attempting to dereference the LazyCell to get its contents,
90//! so its use is much more transparent with a place which has been initialized by a constant.
91//!
92//! More complicated patterns that don't fit this description can be built on `OnceCell<T>` instead.
93//!
94//! `LazyCell` works by providing an implementation of `impl Deref` that calls the function,
95//! so you can just use it by dereference (e.g. `*lazy_cell` or `lazy_cell.deref()`).
96//!
97//! The corresponding [`Sync`] version of `LazyCell<T, F>` is [`LazyLock<T, F>`].
98//!
99//! # When to choose interior mutability
100//!
101//! The more common inherited mutability, where one must have unique access to mutate a value, is
102//! one of the key language elements that enables Rust to reason strongly about pointer aliasing,
103//! statically preventing crash bugs. Because of that, inherited mutability is preferred, and
104//! interior mutability is something of a last resort. Since cell types enable mutation where it
105//! would otherwise be disallowed though, there are occasions when interior mutability might be
106//! appropriate, or even *must* be used, e.g.
107//!
108//! * Introducing mutability 'inside' of something immutable
109//! * Implementation details of logically-immutable methods.
110//! * Mutating implementations of [`Clone`].
111//!
112//! ## Introducing mutability 'inside' of something immutable
113//!
114//! Many shared smart pointer types, including [`Rc<T>`] and [`Arc<T>`], provide containers that can
115//! be cloned and shared between multiple parties. Because the contained values may be
116//! multiply-aliased, they can only be borrowed with `&`, not `&mut`. Without cells it would be
117//! impossible to mutate data inside of these smart pointers at all.
118//!
119//! It's very common then to put a `RefCell<T>` inside shared pointer types to reintroduce
120//! mutability:
121//!
122//! ```
123//! use std::cell::{RefCell, RefMut};
124//! use std::collections::HashMap;
125//! use std::rc::Rc;
126//!
127//! fn main() {
128//!     let shared_map: Rc<RefCell<_>> = Rc::new(RefCell::new(HashMap::new()));
129//!     // Create a new block to limit the scope of the dynamic borrow
130//!     {
131//!         let mut map: RefMut<'_, _> = shared_map.borrow_mut();
132//!         map.insert("africa", 92388);
133//!         map.insert("kyoto", 11837);
134//!         map.insert("piccadilly", 11826);
135//!         map.insert("marbles", 38);
136//!     }
137//!
138//!     // Note that if we had not let the previous borrow of the cache fall out
139//!     // of scope then the subsequent borrow would cause a dynamic thread panic.
140//!     // This is the major hazard of using `RefCell`.
141//!     let total: i32 = shared_map.borrow().values().sum();
142//!     println!("{total}");
143//! }
144//! ```
145//!
146//! Note that this example uses `Rc<T>` and not `Arc<T>`. `RefCell<T>`s are for single-threaded
147//! scenarios. Consider using [`RwLock<T>`] or [`Mutex<T>`] if you need shared mutability in a
148//! multi-threaded situation.
149//!
150//! ## Implementation details of logically-immutable methods
151//!
152//! Occasionally it may be desirable not to expose in an API that there is mutation happening
153//! "under the hood". This may be because logically the operation is immutable, but e.g., caching
154//! forces the implementation to perform mutation; or because you must employ mutation to implement
155//! a trait method that was originally defined to take `&self`.
156//!
157//! ```
158//! # #![allow(dead_code)]
159//! use std::cell::OnceCell;
160//!
161//! struct Graph {
162//!     edges: Vec<(i32, i32)>,
163//!     span_tree_cache: OnceCell<Vec<(i32, i32)>>
164//! }
165//!
166//! impl Graph {
167//!     fn minimum_spanning_tree(&self) -> Vec<(i32, i32)> {
168//!         self.span_tree_cache
169//!             .get_or_init(|| self.calc_span_tree())
170//!             .clone()
171//!     }
172//!
173//!     fn calc_span_tree(&self) -> Vec<(i32, i32)> {
174//!         // Expensive computation goes here
175//!         vec![]
176//!     }
177//! }
178//! ```
179//!
180//! ## Mutating implementations of `Clone`
181//!
182//! This is simply a special - but common - case of the previous: hiding mutability for operations
183//! that appear to be immutable. The [`clone`](Clone::clone) method is expected to not change the
184//! source value, and is declared to take `&self`, not `&mut self`. Therefore, any mutation that
185//! happens in the `clone` method must use cell types. For example, [`Rc<T>`] maintains its
186//! reference counts within a `Cell<T>`.
187//!
188//! ```
189//! use std::cell::Cell;
190//! use std::ptr::NonNull;
191//! use std::process::abort;
192//! use std::marker::PhantomData;
193//!
194//! struct Rc<T: ?Sized> {
195//!     ptr: NonNull<RcInner<T>>,
196//!     phantom: PhantomData<RcInner<T>>,
197//! }
198//!
199//! struct RcInner<T: ?Sized> {
200//!     strong: Cell<usize>,
201//!     refcount: Cell<usize>,
202//!     value: T,
203//! }
204//!
205//! impl<T: ?Sized> Clone for Rc<T> {
206//!     fn clone(&self) -> Rc<T> {
207//!         self.inc_strong();
208//!         Rc {
209//!             ptr: self.ptr,
210//!             phantom: PhantomData,
211//!         }
212//!     }
213//! }
214//!
215//! trait RcInnerPtr<T: ?Sized> {
216//!
217//!     fn inner(&self) -> &RcInner<T>;
218//!
219//!     fn strong(&self) -> usize {
220//!         self.inner().strong.get()
221//!     }
222//!
223//!     fn inc_strong(&self) {
224//!         self.inner()
225//!             .strong
226//!             .set(self.strong()
227//!                      .checked_add(1)
228//!                      .unwrap_or_else(|| abort() ));
229//!     }
230//! }
231//!
232//! impl<T: ?Sized> RcInnerPtr<T> for Rc<T> {
233//!    fn inner(&self) -> &RcInner<T> {
234//!        unsafe {
235//!            self.ptr.as_ref()
236//!        }
237//!    }
238//! }
239//! ```
240//!
241//! [`Arc<T>`]: ../../std/sync/struct.Arc.html
242//! [`Rc<T>`]: ../../std/rc/struct.Rc.html
243//! [`RwLock<T>`]: ../../std/sync/struct.RwLock.html
244//! [`Mutex<T>`]: ../../std/sync/struct.Mutex.html
245//! [`OnceLock<T>`]: ../../std/sync/struct.OnceLock.html
246//! [`LazyLock<T, F>`]: ../../std/sync/struct.LazyLock.html
247//! [`Sync`]: ../../std/marker/trait.Sync.html
248//! [`atomic`]: crate::sync::atomic
249
250#![stable(feature = "rust1", since = "1.0.0")]
251
252use crate::cmp::Ordering;
253use crate::fmt::{self, Debug, Display};
254use crate::marker::{Destruct, PhantomData, Unsize};
255use crate::mem::{self, ManuallyDrop};
256use crate::ops::{self, CoerceUnsized, Deref, DerefMut, DerefPure, DispatchFromDyn};
257use crate::panic::const_panic;
258use crate::pin::PinCoerceUnsized;
259use crate::ptr::{self, NonNull};
260use crate::range;
261
262mod covariant_unsafe_cell;
263mod lazy;
264mod once;
265
266#[unstable(feature = "covariant_unsafe_cell", issue = "159735")]
267pub use covariant_unsafe_cell::CovariantUnsafeCell;
268#[stable(feature = "lazy_cell", since = "1.80.0")]
269pub use lazy::LazyCell;
270#[stable(feature = "once_cell", since = "1.70.0")]
271pub use once::OnceCell;
272
273/// A mutable memory location.
274///
275/// # Memory layout
276///
277/// `Cell<T>` has the same [memory layout and caveats as
278/// `UnsafeCell<T>`](UnsafeCell#memory-layout). In particular, this means that
279/// `Cell<T>` has the same in-memory representation as its inner type `T`.
280///
281/// # Examples
282///
283/// In this example, you can see that `Cell<T>` enables mutation inside an
284/// immutable struct. In other words, it enables "interior mutability".
285///
286/// ```
287/// use std::cell::Cell;
288///
289/// struct SomeStruct {
290///     regular_field: u8,
291///     special_field: Cell<u8>,
292/// }
293///
294/// let my_struct = SomeStruct {
295///     regular_field: 0,
296///     special_field: Cell::new(1),
297/// };
298///
299/// let new_value = 100;
300///
301/// // ERROR: `my_struct` is immutable
302/// // my_struct.regular_field = new_value;
303///
304/// // WORKS: although `my_struct` is immutable, `special_field` is a `Cell`,
305/// // which can always be mutated
306/// my_struct.special_field.set(new_value);
307/// assert_eq!(my_struct.special_field.get(), new_value);
308/// ```
309///
310/// See the [module-level documentation](self) for more.
311#[rustc_diagnostic_item = "Cell"]
312#[stable(feature = "rust1", since = "1.0.0")]
313#[repr(transparent)]
314#[rustc_pub_transparent]
315pub struct Cell<T: ?Sized> {
316    value: UnsafeCell<T>,
317}
318
319#[stable(feature = "rust1", since = "1.0.0")]
320unsafe impl<T: ?Sized> Send for Cell<T> where T: Send {}
321
322// Note that this negative impl isn't strictly necessary for correctness,
323// as `Cell` wraps `UnsafeCell`, which is itself `!Sync`.
324// However, given how important `Cell`'s `!Sync`-ness is,
325// having an explicit negative impl is nice for documentation purposes
326// and results in nicer error messages.
327#[stable(feature = "rust1", since = "1.0.0")]
328impl<T: ?Sized> !Sync for Cell<T> {}
329
330#[stable(feature = "rust1", since = "1.0.0")]
331impl<T: Copy> Clone for Cell<T> {
332    #[inline]
333    fn clone(&self) -> Cell<T> {
334        Cell::new(self.get())
335    }
336}
337
338#[stable(feature = "rust1", since = "1.0.0")]
339#[rustc_const_unstable(feature = "const_default", issue = "143894")]
340const impl<T: [const] Default> Default for Cell<T> {
341    /// Creates a `Cell<T>`, with the `Default` value for T.
342    #[inline]
343    fn default() -> Cell<T> {
344        Cell::new(Default::default())
345    }
346}
347
348#[stable(feature = "rust1", since = "1.0.0")]
349impl<T: PartialEq + Copy> PartialEq for Cell<T> {
350    #[inline]
351    fn eq(&self, other: &Cell<T>) -> bool {
352        self.get() == other.get()
353    }
354}
355
356#[stable(feature = "cell_eq", since = "1.2.0")]
357impl<T: Eq + Copy> Eq for Cell<T> {}
358
359#[stable(feature = "cell_ord", since = "1.10.0")]
360impl<T: PartialOrd + Copy> PartialOrd for Cell<T> {
361    #[inline]
362    fn partial_cmp(&self, other: &Cell<T>) -> Option<Ordering> {
363        self.get().partial_cmp(&other.get())
364    }
365
366    #[inline]
367    fn lt(&self, other: &Cell<T>) -> bool {
368        self.get() < other.get()
369    }
370
371    #[inline]
372    fn le(&self, other: &Cell<T>) -> bool {
373        self.get() <= other.get()
374    }
375
376    #[inline]
377    fn gt(&self, other: &Cell<T>) -> bool {
378        self.get() > other.get()
379    }
380
381    #[inline]
382    fn ge(&self, other: &Cell<T>) -> bool {
383        self.get() >= other.get()
384    }
385}
386
387#[stable(feature = "cell_ord", since = "1.10.0")]
388impl<T: Ord + Copy> Ord for Cell<T> {
389    #[inline]
390    fn cmp(&self, other: &Cell<T>) -> Ordering {
391        self.get().cmp(&other.get())
392    }
393}
394
395#[stable(feature = "cell_from", since = "1.12.0")]
396#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
397const impl<T> From<T> for Cell<T> {
398    /// Creates a new `Cell<T>` containing the given value.
399    fn from(t: T) -> Cell<T> {
400        Cell::new(t)
401    }
402}
403
404impl<T> Cell<T> {
405    /// Creates a new `Cell` containing the given value.
406    ///
407    /// # Examples
408    ///
409    /// ```
410    /// use std::cell::Cell;
411    ///
412    /// let c = Cell::new(5);
413    /// ```
414    #[stable(feature = "rust1", since = "1.0.0")]
415    #[rustc_const_stable(feature = "const_cell_new", since = "1.24.0")]
416    #[inline]
417    pub const fn new(value: T) -> Cell<T> {
418        Cell { value: UnsafeCell::new(value) }
419    }
420
421    /// Sets the contained value.
422    ///
423    /// # Examples
424    ///
425    /// ```
426    /// use std::cell::Cell;
427    ///
428    /// let c = Cell::new(5);
429    ///
430    /// c.set(10);
431    /// ```
432    #[inline]
433    #[stable(feature = "rust1", since = "1.0.0")]
434    #[rustc_const_unstable(feature = "const_cell_traits", issue = "147787")]
435    #[rustc_should_not_be_called_on_const_items]
436    pub const fn set(&self, val: T)
437    where
438        T: [const] Destruct,
439    {
440        self.replace(val);
441    }
442
443    /// Swaps the values of two `Cell`s.
444    ///
445    /// The difference with `std::mem::swap` is that this function doesn't
446    /// require a `&mut` reference.
447    ///
448    /// # Panics
449    ///
450    /// This function will panic if `self` and `other` are different `Cell`s that partially overlap.
451    /// (Using just standard library methods, it is impossible to create such partially overlapping `Cell`s.
452    /// However, unsafe code is allowed to e.g. create two `&Cell<[i32; 2]>` that partially overlap.)
453    ///
454    /// # Examples
455    ///
456    /// ```
457    /// use std::cell::Cell;
458    ///
459    /// let c1 = Cell::new(5i32);
460    /// let c2 = Cell::new(10i32);
461    /// c1.swap(&c2);
462    /// assert_eq!(10, c1.get());
463    /// assert_eq!(5, c2.get());
464    /// ```
465    #[inline]
466    #[stable(feature = "move_cell", since = "1.17.0")]
467    #[rustc_should_not_be_called_on_const_items]
468    pub fn swap(&self, other: &Self) {
469        // This function documents that it *will* panic, and intrinsics::is_nonoverlapping doesn't
470        // do the check in const, so trying to use it here would be inviting unnecessary fragility.
471        fn is_nonoverlapping<T>(src: *const T, dst: *const T) -> bool {
472            let src_usize = src.addr();
473            let dst_usize = dst.addr();
474            let diff = src_usize.abs_diff(dst_usize);
475            diff >= size_of::<T>()
476        }
477
478        if ptr::eq(self, other) {
479            // Swapping wouldn't change anything.
480            return;
481        }
482        if !is_nonoverlapping(self, other) {
483            // See <https://github.com/rust-lang/rust/issues/80778> for why we need to stop here.
484            panic!("`Cell::swap` on overlapping non-identical `Cell`s");
485        }
486        // SAFETY: This can be risky if called from separate threads, but `Cell`
487        // is `!Sync` so this won't happen. This also won't invalidate any
488        // pointers since `Cell` makes sure nothing else will be pointing into
489        // either of these `Cell`s. We also excluded shenanigans like partially overlapping `Cell`s,
490        // so `swap` will just properly copy two full values of type `T` back and forth.
491        unsafe {
492            mem::swap(&mut *self.value.get(), &mut *other.value.get());
493        }
494    }
495
496    /// Replaces the contained value with `val`, and returns the old contained value.
497    ///
498    /// # Examples
499    ///
500    /// ```
501    /// use std::cell::Cell;
502    ///
503    /// let cell = Cell::new(5);
504    /// assert_eq!(cell.get(), 5);
505    /// assert_eq!(cell.replace(10), 5);
506    /// assert_eq!(cell.get(), 10);
507    /// ```
508    #[inline]
509    #[stable(feature = "move_cell", since = "1.17.0")]
510    #[rustc_const_stable(feature = "const_cell", since = "1.88.0")]
511    #[rustc_confusables("swap")]
512    #[rustc_should_not_be_called_on_const_items]
513    pub const fn replace(&self, val: T) -> T {
514        // SAFETY: This can cause data races if called from a separate thread,
515        // but `Cell` is `!Sync` so this won't happen.
516        mem::replace(unsafe { &mut *self.value.get() }, val)
517    }
518
519    /// Unwraps the value, consuming the cell.
520    ///
521    /// # Examples
522    ///
523    /// ```
524    /// use std::cell::Cell;
525    ///
526    /// let c = Cell::new(5);
527    /// let five = c.into_inner();
528    ///
529    /// assert_eq!(five, 5);
530    /// ```
531    #[stable(feature = "move_cell", since = "1.17.0")]
532    #[rustc_const_stable(feature = "const_cell_into_inner", since = "1.83.0")]
533    #[rustc_allow_const_fn_unstable(const_precise_live_drops)]
534    pub const fn into_inner(self) -> T {
535        self.value.into_inner()
536    }
537}
538
539impl<T: Copy> Cell<T> {
540    /// Returns a copy of the contained value.
541    ///
542    /// # Examples
543    ///
544    /// ```
545    /// use std::cell::Cell;
546    ///
547    /// let c = Cell::new(5);
548    ///
549    /// let five = c.get();
550    /// ```
551    #[inline]
552    #[stable(feature = "rust1", since = "1.0.0")]
553    #[rustc_const_stable(feature = "const_cell", since = "1.88.0")]
554    #[rustc_should_not_be_called_on_const_items]
555    pub const fn get(&self) -> T {
556        // SAFETY: This can cause data races if called from a separate thread,
557        // but `Cell` is `!Sync` so this won't happen.
558        unsafe { *self.value.get() }
559    }
560
561    /// Updates the contained value using a function.
562    ///
563    /// # Examples
564    ///
565    /// ```
566    /// use std::cell::Cell;
567    ///
568    /// let c = Cell::new(5);
569    /// c.update(|x| x + 1);
570    /// assert_eq!(c.get(), 6);
571    /// ```
572    #[inline]
573    #[stable(feature = "cell_update", since = "1.88.0")]
574    #[rustc_const_unstable(feature = "const_cell_traits", issue = "147787")]
575    #[rustc_should_not_be_called_on_const_items]
576    pub const fn update(&self, f: impl [const] FnOnce(T) -> T)
577    where
578        // FIXME(const-hack): `Copy` should imply `const Destruct`
579        T: [const] Destruct,
580    {
581        let old = self.get();
582        self.set(f(old));
583    }
584}
585
586impl<T: ?Sized> Cell<T> {
587    /// Returns a raw pointer to the underlying data in this cell.
588    ///
589    /// # Examples
590    ///
591    /// ```
592    /// use std::cell::Cell;
593    ///
594    /// let c = Cell::new(5);
595    ///
596    /// let ptr = c.as_ptr();
597    /// ```
598    #[inline]
599    #[stable(feature = "cell_as_ptr", since = "1.12.0")]
600    #[rustc_const_stable(feature = "const_cell_as_ptr", since = "1.32.0")]
601    #[rustc_as_ptr]
602    #[rustc_never_returns_null_ptr]
603    pub const fn as_ptr(&self) -> *mut T {
604        self.value.get()
605    }
606
607    /// Returns a mutable reference to the underlying data.
608    ///
609    /// This call borrows `Cell` mutably (at compile-time) which guarantees
610    /// that we possess the only reference.
611    ///
612    /// However be cautious: this method expects `self` to be mutable, which is
613    /// generally not the case when using a `Cell`. If you require interior
614    /// mutability by reference, consider using `RefCell` which provides
615    /// run-time checked mutable borrows through its [`borrow_mut`] method.
616    ///
617    /// [`borrow_mut`]: RefCell::borrow_mut()
618    ///
619    /// # Examples
620    ///
621    /// ```
622    /// use std::cell::Cell;
623    ///
624    /// let mut c = Cell::new(5);
625    /// *c.get_mut() += 1;
626    ///
627    /// assert_eq!(c.get(), 6);
628    /// ```
629    #[inline]
630    #[stable(feature = "cell_get_mut", since = "1.11.0")]
631    #[rustc_const_stable(feature = "const_cell", since = "1.88.0")]
632    pub const fn get_mut(&mut self) -> &mut T {
633        self.value.get_mut()
634    }
635
636    /// Returns a `&Cell<T>` from a `&mut T`
637    ///
638    /// # Examples
639    ///
640    /// ```
641    /// use std::cell::Cell;
642    ///
643    /// let slice: &mut [i32] = &mut [1, 2, 3];
644    /// let cell_slice: &Cell<[i32]> = Cell::from_mut(slice);
645    /// let slice_cell: &[Cell<i32>] = cell_slice.as_slice_of_cells();
646    ///
647    /// assert_eq!(slice_cell.len(), 3);
648    /// ```
649    #[inline]
650    #[stable(feature = "as_cell", since = "1.37.0")]
651    #[rustc_const_stable(feature = "const_cell", since = "1.88.0")]
652    pub const fn from_mut(t: &mut T) -> &Cell<T> {
653        // SAFETY: `&mut` ensures unique access.
654        unsafe { &*(t as *mut T as *const Cell<T>) }
655    }
656}
657
658impl<T: Default> Cell<T> {
659    /// Takes the value of the cell, leaving `Default::default()` in its place.
660    ///
661    /// # Examples
662    ///
663    /// ```
664    /// use std::cell::Cell;
665    ///
666    /// let c = Cell::new(5);
667    /// let five = c.take();
668    ///
669    /// assert_eq!(five, 5);
670    /// assert_eq!(c.into_inner(), 0);
671    /// ```
672    #[stable(feature = "move_cell", since = "1.17.0")]
673    #[rustc_const_unstable(feature = "const_cell_traits", issue = "147787")]
674    pub const fn take(&self) -> T
675    where
676        T: [const] Default,
677    {
678        self.replace(Default::default())
679    }
680}
681
682#[unstable(feature = "coerce_unsized", issue = "18598")]
683impl<T: CoerceUnsized<U>, U> CoerceUnsized<Cell<U>> for Cell<T> {}
684
685// Allow types that wrap `Cell` to also implement `DispatchFromDyn`
686// and become dyn-compatible method receivers.
687// Note that currently `Cell` itself cannot be a method receiver
688// because it does not implement Deref.
689// In other words:
690// `self: Cell<&Self>` won't work
691// `self: CellWrapper<Self>` becomes possible
692#[unstable(feature = "dispatch_from_dyn", issue = "none")]
693impl<T: DispatchFromDyn<U>, U> DispatchFromDyn<Cell<U>> for Cell<T> {}
694
695#[stable(feature = "more_conversion_trait_impls", since = "1.95.0")]
696impl<T, const N: usize> AsRef<[Cell<T>; N]> for Cell<[T; N]> {
697    #[inline]
698    fn as_ref(&self) -> &[Cell<T>; N] {
699        self.as_array_of_cells()
700    }
701}
702
703#[stable(feature = "more_conversion_trait_impls", since = "1.95.0")]
704impl<T, const N: usize> AsRef<[Cell<T>]> for Cell<[T; N]> {
705    #[inline]
706    fn as_ref(&self) -> &[Cell<T>] {
707        &*self.as_array_of_cells()
708    }
709}
710
711#[stable(feature = "more_conversion_trait_impls", since = "1.95.0")]
712impl<T> AsRef<[Cell<T>]> for Cell<[T]> {
713    #[inline]
714    fn as_ref(&self) -> &[Cell<T>] {
715        self.as_slice_of_cells()
716    }
717}
718
719impl<T> Cell<[T]> {
720    /// Returns a `&[Cell<T>]` from a `&Cell<[T]>`
721    ///
722    /// # Examples
723    ///
724    /// ```
725    /// use std::cell::Cell;
726    ///
727    /// let slice: &mut [i32] = &mut [1, 2, 3];
728    /// let cell_slice: &Cell<[i32]> = Cell::from_mut(slice);
729    /// let slice_cell: &[Cell<i32>] = cell_slice.as_slice_of_cells();
730    ///
731    /// assert_eq!(slice_cell.len(), 3);
732    /// ```
733    #[stable(feature = "as_cell", since = "1.37.0")]
734    #[rustc_const_stable(feature = "const_cell", since = "1.88.0")]
735    pub const fn as_slice_of_cells(&self) -> &[Cell<T>] {
736        // SAFETY: `Cell<T>` has the same memory layout as `T`.
737        unsafe { &*(self as *const Cell<[T]> as *const [Cell<T>]) }
738    }
739}
740
741impl<T, const N: usize> Cell<[T; N]> {
742    /// Returns a `&[Cell<T>; N]` from a `&Cell<[T; N]>`
743    ///
744    /// # Examples
745    ///
746    /// ```
747    /// use std::cell::Cell;
748    ///
749    /// let mut array: [i32; 3] = [1, 2, 3];
750    /// let cell_array: &Cell<[i32; 3]> = Cell::from_mut(&mut array);
751    /// let array_cell: &[Cell<i32>; 3] = cell_array.as_array_of_cells();
752    /// ```
753    #[stable(feature = "as_array_of_cells", since = "1.91.0")]
754    #[rustc_const_stable(feature = "as_array_of_cells", since = "1.91.0")]
755    pub const fn as_array_of_cells(&self) -> &[Cell<T>; N] {
756        // SAFETY: `Cell<T>` has the same memory layout as `T`.
757        unsafe { &*(self as *const Cell<[T; N]> as *const [Cell<T>; N]) }
758    }
759}
760
761/// Types for which cloning `Cell<Self>` is sound.
762///
763/// # Safety
764///
765/// Implementing this trait for a type is sound if and only if the following code is sound for T =
766/// that type.
767///
768/// ```
769/// #![feature(cell_get_cloned)]
770/// # use std::cell::{CloneFromCell, Cell};
771/// fn clone_from_cell<T: CloneFromCell>(cell: &Cell<T>) -> T {
772///     unsafe { T::clone(&*cell.as_ptr()) }
773/// }
774/// ```
775///
776/// Importantly, you can't just implement `CloneFromCell` for any arbitrary `Copy` type, e.g. the
777/// following is unsound:
778///
779/// ```rust
780/// # use std::cell::Cell;
781///
782/// #[derive(Copy, Debug)]
783/// pub struct Bad<'a>(Option<&'a Cell<Bad<'a>>>, u8);
784///
785/// impl Clone for Bad<'_> {
786///     fn clone(&self) -> Self {
787///         let a: &u8 = &self.1;
788///         // when self.0 points to self, we write to self.1 while we have a live `&u8` pointing to
789///         // it -- this is UB
790///         self.0.unwrap().set(Self(None, 1));
791///         dbg!((a, self));
792///         Self(None, 0)
793///     }
794/// }
795///
796/// // this is not sound
797/// // unsafe impl CloneFromCell for Bad<'_> {}
798/// ```
799#[unstable(feature = "cell_get_cloned", issue = "145329")]
800// Allow potential overlapping implementations in user code
801#[marker]
802pub unsafe trait CloneFromCell: Clone {}
803
804// `CloneFromCell` can be implemented for types that don't have indirection and which don't access
805// `Cell`s in their `Clone` implementation. A commonly-used subset is covered here.
806#[unstable(feature = "cell_get_cloned", issue = "145329")]
807unsafe impl<T: CloneFromCell, const N: usize> CloneFromCell for [T; N] {}
808#[unstable(feature = "cell_get_cloned", issue = "145329")]
809unsafe impl<T: CloneFromCell> CloneFromCell for Option<T> {}
810#[unstable(feature = "cell_get_cloned", issue = "145329")]
811unsafe impl<T: CloneFromCell, E: CloneFromCell> CloneFromCell for Result<T, E> {}
812#[unstable(feature = "cell_get_cloned", issue = "145329")]
813unsafe impl<T: ?Sized> CloneFromCell for PhantomData<T> {}
814#[unstable(feature = "cell_get_cloned", issue = "145329")]
815unsafe impl<T: CloneFromCell> CloneFromCell for ManuallyDrop<T> {}
816#[unstable(feature = "cell_get_cloned", issue = "145329")]
817unsafe impl<T: CloneFromCell> CloneFromCell for ops::Range<T> {}
818#[unstable(feature = "cell_get_cloned", issue = "145329")]
819unsafe impl<T: CloneFromCell> CloneFromCell for range::Range<T> {}
820
821#[unstable(feature = "cell_get_cloned", issue = "145329")]
822impl<T: CloneFromCell> Cell<T> {
823    /// Get a clone of the `Cell` that contains a copy of the original value.
824    ///
825    /// This allows a cheaply `Clone`-able type like an `Rc` to be stored in a `Cell`, exposing the
826    /// cheaper `clone()` method.
827    ///
828    /// # Examples
829    ///
830    /// ```
831    /// #![feature(cell_get_cloned)]
832    ///
833    /// use core::cell::Cell;
834    /// use std::rc::Rc;
835    ///
836    /// let rc = Rc::new(1usize);
837    /// let c1 = Cell::new(rc);
838    /// let c2 = c1.get_cloned();
839    /// assert_eq!(*c2.into_inner(), 1);
840    /// ```
841    pub fn get_cloned(&self) -> Self {
842        // SAFETY: T is CloneFromCell, which guarantees that this is sound.
843        Cell::new(T::clone(unsafe { &*self.as_ptr() }))
844    }
845}
846
847/// A mutable memory location with dynamically checked borrow rules
848///
849/// See the [module-level documentation](self) for more.
850#[rustc_diagnostic_item = "RefCell"]
851#[stable(feature = "rust1", since = "1.0.0")]
852pub struct RefCell<T: ?Sized> {
853    borrow: Cell<BorrowCounter>,
854    // Stores the location of the earliest currently active borrow.
855    // This gets updated whenever we go from having zero borrows
856    // to having a single borrow. When a borrow occurs, this gets included
857    // in the generated `BorrowError`/`BorrowMutError`
858    #[cfg(feature = "debug_refcell")]
859    borrowed_at: Cell<Option<&'static crate::panic::Location<'static>>>,
860    value: UnsafeCell<T>,
861}
862
863/// An error returned by [`RefCell::try_borrow`].
864#[stable(feature = "try_borrow", since = "1.13.0")]
865#[non_exhaustive]
866#[derive(Debug)]
867pub struct BorrowError {
868    #[cfg(feature = "debug_refcell")]
869    location: &'static crate::panic::Location<'static>,
870}
871
872#[stable(feature = "try_borrow", since = "1.13.0")]
873impl Display for BorrowError {
874    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
875        #[cfg(feature = "debug_refcell")]
876        let res = write!(
877            f,
878            "RefCell already mutably borrowed; a previous borrow was at {}",
879            self.location
880        );
881
882        #[cfg(not(feature = "debug_refcell"))]
883        let res = Display::fmt("RefCell already mutably borrowed", f);
884
885        res
886    }
887}
888
889/// An error returned by [`RefCell::try_borrow_mut`].
890#[stable(feature = "try_borrow", since = "1.13.0")]
891#[non_exhaustive]
892#[derive(Debug)]
893pub struct BorrowMutError {
894    #[cfg(feature = "debug_refcell")]
895    location: &'static crate::panic::Location<'static>,
896}
897
898#[stable(feature = "try_borrow", since = "1.13.0")]
899impl Display for BorrowMutError {
900    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
901        #[cfg(feature = "debug_refcell")]
902        let res = write!(f, "RefCell already borrowed; a previous borrow was at {}", self.location);
903
904        #[cfg(not(feature = "debug_refcell"))]
905        let res = Display::fmt("RefCell already borrowed", f);
906
907        res
908    }
909}
910
911// This ensures the panicking code is outlined from `borrow_mut` for `RefCell`.
912#[cfg_attr(not(panic = "immediate-abort"), inline(never))]
913#[track_caller]
914#[cold]
915const fn panic_already_borrowed(err: BorrowMutError) -> ! {
916    const_panic!(
917        "RefCell already borrowed",
918        "{err}",
919        err: BorrowMutError = err,
920    )
921}
922
923// This ensures the panicking code is outlined from `borrow` for `RefCell`.
924#[cfg_attr(not(panic = "immediate-abort"), inline(never))]
925#[track_caller]
926#[cold]
927const fn panic_already_mutably_borrowed(err: BorrowError) -> ! {
928    const_panic!(
929        "RefCell already mutably borrowed",
930        "{err}",
931        err: BorrowError = err,
932    )
933}
934
935// Positive values represent the number of `Ref` active. Negative values
936// represent the number of `RefMut` active. Multiple `RefMut`s can only be
937// active at a time if they refer to distinct, nonoverlapping components of a
938// `RefCell` (e.g., different ranges of a slice).
939//
940// `Ref` and `RefMut` are both two words in size, and so there will likely never
941// be enough `Ref`s or `RefMut`s in existence to overflow half of the `usize`
942// range. Thus, a `BorrowCounter` will probably never overflow or underflow.
943// However, this is not a guarantee, as a pathological program could repeatedly
944// create and then mem::forget `Ref`s or `RefMut`s. Thus, all code must
945// explicitly check for overflow and underflow in order to avoid unsafety, or at
946// least behave correctly in the event that overflow or underflow happens (e.g.,
947// see BorrowRef::new).
948type BorrowCounter = isize;
949const UNUSED: BorrowCounter = 0;
950
951#[inline(always)]
952const fn is_writing(x: BorrowCounter) -> bool {
953    x < UNUSED
954}
955
956#[inline(always)]
957const fn is_reading(x: BorrowCounter) -> bool {
958    x > UNUSED
959}
960
961impl<T> RefCell<T> {
962    /// Creates a new `RefCell` containing `value`.
963    ///
964    /// # Examples
965    ///
966    /// ```
967    /// use std::cell::RefCell;
968    ///
969    /// let c = RefCell::new(5);
970    /// ```
971    #[stable(feature = "rust1", since = "1.0.0")]
972    #[rustc_const_stable(feature = "const_refcell_new", since = "1.24.0")]
973    #[inline]
974    pub const fn new(value: T) -> RefCell<T> {
975        RefCell {
976            value: UnsafeCell::new(value),
977            borrow: Cell::new(UNUSED),
978            #[cfg(feature = "debug_refcell")]
979            borrowed_at: Cell::new(None),
980        }
981    }
982
983    /// Consumes the `RefCell`, returning the wrapped value.
984    ///
985    /// # Examples
986    ///
987    /// ```
988    /// use std::cell::RefCell;
989    ///
990    /// let c = RefCell::new(5);
991    ///
992    /// let five = c.into_inner();
993    /// ```
994    #[stable(feature = "rust1", since = "1.0.0")]
995    #[rustc_const_stable(feature = "const_cell_into_inner", since = "1.83.0")]
996    #[rustc_allow_const_fn_unstable(const_precise_live_drops)]
997    #[inline]
998    pub const fn into_inner(self) -> T {
999        // Since this function takes `self` (the `RefCell`) by value, the
1000        // compiler statically verifies that it is not currently borrowed.
1001        self.value.into_inner()
1002    }
1003
1004    /// Replaces the wrapped value with a new one, returning the old value,
1005    /// without deinitializing either one.
1006    ///
1007    /// This function corresponds to [`std::mem::replace`](../mem/fn.replace.html).
1008    ///
1009    /// # Panics
1010    ///
1011    /// Panics if the value is currently borrowed.
1012    ///
1013    /// # Examples
1014    ///
1015    /// ```
1016    /// use std::cell::RefCell;
1017    /// let cell = RefCell::new(5);
1018    /// let old_value = cell.replace(6);
1019    /// assert_eq!(old_value, 5);
1020    /// assert_eq!(cell, RefCell::new(6));
1021    /// ```
1022    #[inline]
1023    #[stable(feature = "refcell_replace", since = "1.24.0")]
1024    #[track_caller]
1025    #[rustc_confusables("swap")]
1026    #[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
1027    #[rustc_should_not_be_called_on_const_items]
1028    pub const fn replace(&self, t: T) -> T {
1029        mem::replace(&mut self.borrow_mut(), t)
1030    }
1031
1032    /// Replaces the wrapped value with a new one computed from `f`, returning
1033    /// the old value, without deinitializing either one.
1034    ///
1035    /// # Panics
1036    ///
1037    /// Panics if the value is currently borrowed.
1038    ///
1039    /// # Examples
1040    ///
1041    /// ```
1042    /// use std::cell::RefCell;
1043    /// let cell = RefCell::new(5);
1044    /// let old_value = cell.replace_with(|&mut old| old + 1);
1045    /// assert_eq!(old_value, 5);
1046    /// assert_eq!(cell, RefCell::new(6));
1047    /// ```
1048    #[inline]
1049    #[stable(feature = "refcell_replace_swap", since = "1.35.0")]
1050    #[track_caller]
1051    #[rustc_should_not_be_called_on_const_items]
1052    pub fn replace_with<F: FnOnce(&mut T) -> T>(&self, f: F) -> T {
1053        let mut_borrow = &mut *self.borrow_mut();
1054        let replacement = f(mut_borrow);
1055        mem::replace(mut_borrow, replacement)
1056    }
1057
1058    /// Swaps the wrapped value of `self` with the wrapped value of `other`,
1059    /// without deinitializing either one.
1060    ///
1061    /// This function corresponds to [`std::mem::swap`](../mem/fn.swap.html).
1062    ///
1063    /// # Panics
1064    ///
1065    /// Panics if the value in either `RefCell` is currently borrowed, or
1066    /// if `self` and `other` point to the same `RefCell`.
1067    ///
1068    /// # Examples
1069    ///
1070    /// ```
1071    /// use std::cell::RefCell;
1072    /// let c = RefCell::new(5);
1073    /// let d = RefCell::new(6);
1074    /// c.swap(&d);
1075    /// assert_eq!(c, RefCell::new(6));
1076    /// assert_eq!(d, RefCell::new(5));
1077    /// ```
1078    #[inline]
1079    #[stable(feature = "refcell_swap", since = "1.24.0")]
1080    #[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
1081    #[rustc_should_not_be_called_on_const_items]
1082    pub const fn swap(&self, other: &Self) {
1083        mem::swap(&mut *self.borrow_mut(), &mut *other.borrow_mut())
1084    }
1085}
1086
1087impl<T: ?Sized> RefCell<T> {
1088    /// Immutably borrows the wrapped value.
1089    ///
1090    /// The borrow lasts until the returned `Ref` exits scope. Multiple
1091    /// immutable borrows can be taken out at the same time.
1092    ///
1093    /// # Panics
1094    ///
1095    /// Panics if the value is currently mutably borrowed. For a non-panicking variant, use
1096    /// [`try_borrow`](#method.try_borrow).
1097    ///
1098    /// # Examples
1099    ///
1100    /// ```
1101    /// use std::cell::RefCell;
1102    ///
1103    /// let c = RefCell::new(5);
1104    ///
1105    /// let borrowed_five = c.borrow();
1106    /// let borrowed_five2 = c.borrow();
1107    /// ```
1108    ///
1109    /// An example of panic:
1110    ///
1111    /// ```should_panic
1112    /// use std::cell::RefCell;
1113    ///
1114    /// let c = RefCell::new(5);
1115    ///
1116    /// let m = c.borrow_mut();
1117    /// let b = c.borrow(); // this causes a panic
1118    /// ```
1119    #[stable(feature = "rust1", since = "1.0.0")]
1120    #[inline]
1121    #[track_caller]
1122    #[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
1123    #[rustc_should_not_be_called_on_const_items]
1124    pub const fn borrow(&self) -> Ref<'_, T> {
1125        match self.try_borrow() {
1126            Ok(b) => b,
1127            Err(err) => panic_already_mutably_borrowed(err),
1128        }
1129    }
1130
1131    /// Immutably borrows the wrapped value, returning an error if the value is currently mutably
1132    /// borrowed.
1133    ///
1134    /// The borrow lasts until the returned `Ref` exits scope. Multiple immutable borrows can be
1135    /// taken out at the same time.
1136    ///
1137    /// This is the non-panicking variant of [`borrow`](#method.borrow).
1138    ///
1139    /// # Examples
1140    ///
1141    /// ```
1142    /// use std::cell::RefCell;
1143    ///
1144    /// let c = RefCell::new(5);
1145    ///
1146    /// {
1147    ///     let m = c.borrow_mut();
1148    ///     assert!(c.try_borrow().is_err());
1149    /// }
1150    ///
1151    /// {
1152    ///     let m = c.borrow();
1153    ///     assert!(c.try_borrow().is_ok());
1154    /// }
1155    /// ```
1156    #[stable(feature = "try_borrow", since = "1.13.0")]
1157    #[inline]
1158    #[cfg_attr(feature = "debug_refcell", track_caller)]
1159    #[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
1160    #[rustc_should_not_be_called_on_const_items]
1161    pub const fn try_borrow(&self) -> Result<Ref<'_, T>, BorrowError> {
1162        match BorrowRef::new(&self.borrow) {
1163            Some(b) => {
1164                #[cfg(feature = "debug_refcell")]
1165                {
1166                    // `borrowed_at` is always the *first* active borrow
1167                    if b.borrow.get() == 1 {
1168                        self.borrowed_at.replace(Some(crate::panic::Location::caller()));
1169                    }
1170                }
1171
1172                // SAFETY: `BorrowRef` ensures that there is only immutable access
1173                // to the value while borrowed.
1174                let value = unsafe { NonNull::new_unchecked(self.value.get()) };
1175                Ok(Ref { value, borrow: b })
1176            }
1177            None => Err(BorrowError {
1178                // If a borrow occurred, then we must already have an outstanding borrow,
1179                // so `borrowed_at` will be `Some`
1180                #[cfg(feature = "debug_refcell")]
1181                location: self.borrowed_at.get().unwrap(),
1182            }),
1183        }
1184    }
1185
1186    /// Mutably borrows the wrapped value.
1187    ///
1188    /// The borrow lasts until the returned `RefMut` or all `RefMut`s derived
1189    /// from it exit scope. The value cannot be borrowed while this borrow is
1190    /// active.
1191    ///
1192    /// # Panics
1193    ///
1194    /// Panics if the value is currently borrowed. For a non-panicking variant, use
1195    /// [`try_borrow_mut`](#method.try_borrow_mut).
1196    ///
1197    /// # Examples
1198    ///
1199    /// ```
1200    /// use std::cell::RefCell;
1201    ///
1202    /// let c = RefCell::new("hello".to_owned());
1203    ///
1204    /// *c.borrow_mut() = "bonjour".to_owned();
1205    ///
1206    /// assert_eq!(&*c.borrow(), "bonjour");
1207    /// ```
1208    ///
1209    /// An example of panic:
1210    ///
1211    /// ```should_panic
1212    /// use std::cell::RefCell;
1213    ///
1214    /// let c = RefCell::new(5);
1215    /// let m = c.borrow();
1216    ///
1217    /// let b = c.borrow_mut(); // this causes a panic
1218    /// ```
1219    #[stable(feature = "rust1", since = "1.0.0")]
1220    #[inline]
1221    #[track_caller]
1222    #[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
1223    #[rustc_should_not_be_called_on_const_items]
1224    pub const fn borrow_mut(&self) -> RefMut<'_, T> {
1225        match self.try_borrow_mut() {
1226            Ok(b) => b,
1227            Err(err) => panic_already_borrowed(err),
1228        }
1229    }
1230
1231    /// Mutably borrows the wrapped value, returning an error if the value is currently borrowed.
1232    ///
1233    /// The borrow lasts until the returned `RefMut` or all `RefMut`s derived
1234    /// from it exit scope. The value cannot be borrowed while this borrow is
1235    /// active.
1236    ///
1237    /// This is the non-panicking variant of [`borrow_mut`](#method.borrow_mut).
1238    ///
1239    /// # Examples
1240    ///
1241    /// ```
1242    /// use std::cell::RefCell;
1243    ///
1244    /// let c = RefCell::new(5);
1245    ///
1246    /// {
1247    ///     let m = c.borrow();
1248    ///     assert!(c.try_borrow_mut().is_err());
1249    /// }
1250    ///
1251    /// assert!(c.try_borrow_mut().is_ok());
1252    /// ```
1253    #[stable(feature = "try_borrow", since = "1.13.0")]
1254    #[inline]
1255    #[cfg_attr(feature = "debug_refcell", track_caller)]
1256    #[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
1257    #[rustc_should_not_be_called_on_const_items]
1258    pub const fn try_borrow_mut(&self) -> Result<RefMut<'_, T>, BorrowMutError> {
1259        match BorrowRefMut::new(&self.borrow) {
1260            Some(b) => {
1261                #[cfg(feature = "debug_refcell")]
1262                {
1263                    self.borrowed_at.replace(Some(crate::panic::Location::caller()));
1264                }
1265
1266                // SAFETY: `BorrowRefMut` guarantees unique access.
1267                let value = unsafe { NonNull::new_unchecked(self.value.get()) };
1268                Ok(RefMut { value, borrow: b, marker: PhantomData })
1269            }
1270            None => Err(BorrowMutError {
1271                // If a borrow occurred, then we must already have an outstanding borrow,
1272                // so `borrowed_at` will be `Some`
1273                #[cfg(feature = "debug_refcell")]
1274                location: self.borrowed_at.get().unwrap(),
1275            }),
1276        }
1277    }
1278
1279    /// Returns a raw pointer to the underlying data in this cell.
1280    ///
1281    /// # Examples
1282    ///
1283    /// ```
1284    /// use std::cell::RefCell;
1285    ///
1286    /// let c = RefCell::new(5);
1287    ///
1288    /// let ptr = c.as_ptr();
1289    /// ```
1290    #[inline]
1291    #[stable(feature = "cell_as_ptr", since = "1.12.0")]
1292    #[rustc_as_ptr]
1293    #[rustc_never_returns_null_ptr]
1294    #[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
1295    pub const fn as_ptr(&self) -> *mut T {
1296        self.value.get()
1297    }
1298
1299    /// Returns a mutable reference to the underlying data.
1300    ///
1301    /// Since this method borrows `RefCell` mutably, it is statically guaranteed
1302    /// that no borrows to the underlying data exist. The dynamic checks inherent
1303    /// in [`borrow_mut`] and most other methods of `RefCell` are therefore
1304    /// unnecessary. Note that this method does not reset the borrowing state if borrows were previously leaked
1305    /// (e.g., via [`forget()`] on a [`Ref`] or [`RefMut`]). For that purpose,
1306    /// consider using the unstable [`undo_leak`] method.
1307    ///
1308    /// This method can only be called if `RefCell` can be mutably borrowed,
1309    /// which in general is only the case directly after the `RefCell` has
1310    /// been created. In these situations, skipping the aforementioned dynamic
1311    /// borrowing checks may yield better ergonomics and runtime-performance.
1312    ///
1313    /// In most situations where `RefCell` is used, it can't be borrowed mutably.
1314    /// Use [`borrow_mut`] to get mutable access to the underlying data then.
1315    ///
1316    /// [`borrow_mut`]: RefCell::borrow_mut()
1317    /// [`forget()`]: mem::forget
1318    /// [`undo_leak`]: RefCell::undo_leak()
1319    ///
1320    /// # Examples
1321    ///
1322    /// ```
1323    /// use std::cell::RefCell;
1324    ///
1325    /// let mut c = RefCell::new(5);
1326    /// *c.get_mut() += 1;
1327    ///
1328    /// assert_eq!(c, RefCell::new(6));
1329    /// ```
1330    #[inline]
1331    #[stable(feature = "cell_get_mut", since = "1.11.0")]
1332    #[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
1333    pub const fn get_mut(&mut self) -> &mut T {
1334        self.value.get_mut()
1335    }
1336
1337    /// Undo the effect of leaked guards on the borrow state of the `RefCell`.
1338    ///
1339    /// This call is similar to [`get_mut`] but more specialized. It borrows `RefCell` mutably to
1340    /// ensure no borrows exist and then resets the state tracking shared borrows. This is relevant
1341    /// if some `Ref` or `RefMut` borrows have been leaked.
1342    ///
1343    /// [`get_mut`]: RefCell::get_mut()
1344    ///
1345    /// # Examples
1346    ///
1347    /// ```
1348    /// #![feature(cell_leak)]
1349    /// use std::cell::RefCell;
1350    ///
1351    /// let mut c = RefCell::new(0);
1352    /// std::mem::forget(c.borrow_mut());
1353    ///
1354    /// assert!(c.try_borrow().is_err());
1355    /// c.undo_leak();
1356    /// assert!(c.try_borrow().is_ok());
1357    /// ```
1358    #[unstable(feature = "cell_leak", issue = "69099")]
1359    #[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
1360    pub const fn undo_leak(&mut self) -> &mut T {
1361        *self.borrow.get_mut() = UNUSED;
1362        self.get_mut()
1363    }
1364
1365    /// Immutably borrows the wrapped value, returning an error if the value is
1366    /// currently mutably borrowed.
1367    ///
1368    /// # Safety
1369    ///
1370    /// Unlike `RefCell::borrow`, this method is unsafe because it does not
1371    /// return a `Ref`, thus leaving the borrow flag untouched. Mutably
1372    /// borrowing the `RefCell` while the reference returned by this method
1373    /// is alive is undefined behavior.
1374    ///
1375    /// # Examples
1376    ///
1377    /// ```
1378    /// use std::cell::RefCell;
1379    ///
1380    /// let c = RefCell::new(5);
1381    ///
1382    /// {
1383    ///     let m = c.borrow_mut();
1384    ///     assert!(unsafe { c.try_borrow_unguarded() }.is_err());
1385    /// }
1386    ///
1387    /// {
1388    ///     let m = c.borrow();
1389    ///     assert!(unsafe { c.try_borrow_unguarded() }.is_ok());
1390    /// }
1391    /// ```
1392    #[stable(feature = "borrow_state", since = "1.37.0")]
1393    #[inline]
1394    #[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
1395    pub const unsafe fn try_borrow_unguarded(&self) -> Result<&T, BorrowError> {
1396        if !is_writing(self.borrow.get()) {
1397            // SAFETY: We check that nobody is actively writing now, but it is
1398            // the caller's responsibility to ensure that nobody writes until
1399            // the returned reference is no longer in use.
1400            // Also, `self.value.get()` refers to the value owned by `self`
1401            // and is thus guaranteed to be valid for the lifetime of `self`.
1402            Ok(unsafe { &*self.value.get() })
1403        } else {
1404            Err(BorrowError {
1405                // If a borrow occurred, then we must already have an outstanding borrow,
1406                // so `borrowed_at` will be `Some`
1407                #[cfg(feature = "debug_refcell")]
1408                location: self.borrowed_at.get().unwrap(),
1409            })
1410        }
1411    }
1412}
1413
1414impl<T: Default> RefCell<T> {
1415    /// Takes the wrapped value, leaving `Default::default()` in its place.
1416    ///
1417    /// # Panics
1418    ///
1419    /// Panics if the value is currently borrowed.
1420    ///
1421    /// # Examples
1422    ///
1423    /// ```
1424    /// use std::cell::RefCell;
1425    ///
1426    /// let c = RefCell::new(5);
1427    /// let five = c.take();
1428    ///
1429    /// assert_eq!(five, 5);
1430    /// assert_eq!(c.into_inner(), 0);
1431    /// ```
1432    #[stable(feature = "refcell_take", since = "1.50.0")]
1433    pub fn take(&self) -> T {
1434        self.replace(Default::default())
1435    }
1436}
1437
1438#[stable(feature = "rust1", since = "1.0.0")]
1439unsafe impl<T: ?Sized> Send for RefCell<T> where T: Send {}
1440
1441#[stable(feature = "rust1", since = "1.0.0")]
1442impl<T: ?Sized> !Sync for RefCell<T> {}
1443
1444#[stable(feature = "rust1", since = "1.0.0")]
1445impl<T: Clone> Clone for RefCell<T> {
1446    /// # Panics
1447    ///
1448    /// Panics if the value is currently mutably borrowed.
1449    #[inline]
1450    #[track_caller]
1451    fn clone(&self) -> RefCell<T> {
1452        RefCell::new(self.borrow().clone())
1453    }
1454
1455    /// # Panics
1456    ///
1457    /// Panics if `source` is currently mutably borrowed.
1458    #[inline]
1459    #[track_caller]
1460    fn clone_from(&mut self, source: &Self) {
1461        self.get_mut().clone_from(&source.borrow())
1462    }
1463}
1464
1465#[stable(feature = "rust1", since = "1.0.0")]
1466#[rustc_const_unstable(feature = "const_default", issue = "143894")]
1467const impl<T: [const] Default> Default for RefCell<T> {
1468    /// Creates a `RefCell<T>`, with the `Default` value for T.
1469    #[inline]
1470    fn default() -> RefCell<T> {
1471        RefCell::new(Default::default())
1472    }
1473}
1474
1475#[stable(feature = "rust1", since = "1.0.0")]
1476impl<T: ?Sized + PartialEq> PartialEq for RefCell<T> {
1477    /// # Panics
1478    ///
1479    /// Panics if the value in either `RefCell` is currently mutably borrowed.
1480    #[inline]
1481    fn eq(&self, other: &RefCell<T>) -> bool {
1482        *self.borrow() == *other.borrow()
1483    }
1484}
1485
1486#[stable(feature = "cell_eq", since = "1.2.0")]
1487impl<T: ?Sized + Eq> Eq for RefCell<T> {}
1488
1489#[stable(feature = "cell_ord", since = "1.10.0")]
1490impl<T: ?Sized + PartialOrd> PartialOrd for RefCell<T> {
1491    /// # Panics
1492    ///
1493    /// Panics if the value in either `RefCell` is currently mutably borrowed.
1494    #[inline]
1495    fn partial_cmp(&self, other: &RefCell<T>) -> Option<Ordering> {
1496        self.borrow().partial_cmp(&*other.borrow())
1497    }
1498
1499    /// # Panics
1500    ///
1501    /// Panics if the value in either `RefCell` is currently mutably borrowed.
1502    #[inline]
1503    fn lt(&self, other: &RefCell<T>) -> bool {
1504        *self.borrow() < *other.borrow()
1505    }
1506
1507    /// # Panics
1508    ///
1509    /// Panics if the value in either `RefCell` is currently mutably borrowed.
1510    #[inline]
1511    fn le(&self, other: &RefCell<T>) -> bool {
1512        *self.borrow() <= *other.borrow()
1513    }
1514
1515    /// # Panics
1516    ///
1517    /// Panics if the value in either `RefCell` is currently mutably borrowed.
1518    #[inline]
1519    fn gt(&self, other: &RefCell<T>) -> bool {
1520        *self.borrow() > *other.borrow()
1521    }
1522
1523    /// # Panics
1524    ///
1525    /// Panics if the value in either `RefCell` is currently mutably borrowed.
1526    #[inline]
1527    fn ge(&self, other: &RefCell<T>) -> bool {
1528        *self.borrow() >= *other.borrow()
1529    }
1530}
1531
1532#[stable(feature = "cell_ord", since = "1.10.0")]
1533impl<T: ?Sized + Ord> Ord for RefCell<T> {
1534    /// # Panics
1535    ///
1536    /// Panics if the value in either `RefCell` is currently mutably borrowed.
1537    #[inline]
1538    fn cmp(&self, other: &RefCell<T>) -> Ordering {
1539        self.borrow().cmp(&*other.borrow())
1540    }
1541}
1542
1543#[stable(feature = "cell_from", since = "1.12.0")]
1544#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
1545const impl<T> From<T> for RefCell<T> {
1546    /// Creates a new `RefCell<T>` containing the given value.
1547    fn from(t: T) -> RefCell<T> {
1548        RefCell::new(t)
1549    }
1550}
1551
1552#[unstable(feature = "coerce_unsized", issue = "18598")]
1553impl<T: CoerceUnsized<U>, U> CoerceUnsized<RefCell<U>> for RefCell<T> {}
1554
1555struct BorrowRef<'b> {
1556    borrow: &'b Cell<BorrowCounter>,
1557}
1558
1559impl<'b> BorrowRef<'b> {
1560    #[inline]
1561    const fn new(borrow: &'b Cell<BorrowCounter>) -> Option<BorrowRef<'b>> {
1562        let b = borrow.get().wrapping_add(1);
1563        if !is_reading(b) {
1564            // Incrementing borrow can result in a non-reading value (<= 0) in these cases:
1565            // 1. It was < 0, i.e. there are writing borrows, so we can't allow a read borrow
1566            //    due to Rust's reference aliasing rules
1567            // 2. It was isize::MAX (the max amount of reading borrows) and it overflowed
1568            //    into isize::MIN (the max amount of writing borrows) so we can't allow
1569            //    an additional read borrow because isize can't represent so many read borrows
1570            //    (this can only happen if you mem::forget more than a small constant amount of
1571            //    `Ref`s, which is not good practice)
1572            None
1573        } else {
1574            // Incrementing borrow can result in a reading value (> 0) in these cases:
1575            // 1. It was = 0, i.e. it wasn't borrowed, and we are taking the first read borrow
1576            // 2. It was > 0 and < isize::MAX, i.e. there were read borrows, and isize
1577            //    is large enough to represent having one more read borrow
1578            borrow.replace(b);
1579            Some(BorrowRef { borrow })
1580        }
1581    }
1582}
1583
1584#[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
1585const impl Drop for BorrowRef<'_> {
1586    #[inline]
1587    fn drop(&mut self) {
1588        let borrow = self.borrow.get();
1589        debug_assert!(is_reading(borrow));
1590        self.borrow.replace(borrow - 1);
1591    }
1592}
1593
1594#[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
1595const impl Clone for BorrowRef<'_> {
1596    #[inline]
1597    fn clone(&self) -> Self {
1598        // Since this Ref exists, we know the borrow flag
1599        // is a reading borrow.
1600        let borrow = self.borrow.get();
1601        debug_assert!(is_reading(borrow));
1602        // Prevent the borrow counter from overflowing into
1603        // a writing borrow.
1604        assert!(borrow != BorrowCounter::MAX);
1605        self.borrow.replace(borrow + 1);
1606        BorrowRef { borrow: self.borrow }
1607    }
1608}
1609
1610/// Wraps a borrowed reference to a value in a `RefCell` box.
1611/// A wrapper type for an immutably borrowed value from a `RefCell<T>`.
1612///
1613/// See the [module-level documentation](self) for more.
1614#[stable(feature = "rust1", since = "1.0.0")]
1615#[must_not_suspend = "holding a Ref across suspend points can cause BorrowErrors"]
1616#[rustc_diagnostic_item = "RefCellRef"]
1617pub struct Ref<'b, T: ?Sized + 'b> {
1618    // NB: we use a pointer instead of `&'b T` to avoid `noalias` violations, because a
1619    // `Ref` argument doesn't hold immutability for its whole scope, only until it drops.
1620    // `NonNull` is also covariant over `T`, just like we would have with `&T`.
1621    value: NonNull<T>,
1622    borrow: BorrowRef<'b>,
1623}
1624
1625#[stable(feature = "rust1", since = "1.0.0")]
1626#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
1627const impl<T: ?Sized> Deref for Ref<'_, T> {
1628    type Target = T;
1629
1630    #[inline]
1631    fn deref(&self) -> &T {
1632        // SAFETY: the value is accessible as long as we hold our borrow.
1633        unsafe { self.value.as_ref() }
1634    }
1635}
1636
1637#[unstable(feature = "deref_pure_trait", issue = "87121")]
1638unsafe impl<T: ?Sized> DerefPure for Ref<'_, T> {}
1639
1640impl<'b, T: ?Sized> Ref<'b, T> {
1641    /// Copies a `Ref`.
1642    ///
1643    /// The `RefCell` is already immutably borrowed, so this cannot fail.
1644    ///
1645    /// This is an associated function that needs to be used as
1646    /// `Ref::clone(...)`. A `Clone` implementation or a method would interfere
1647    /// with the widespread use of `r.borrow().clone()` to clone the contents of
1648    /// a `RefCell`.
1649    #[stable(feature = "cell_extras", since = "1.15.0")]
1650    #[must_use]
1651    #[inline]
1652    #[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
1653    pub const fn clone(orig: &Ref<'b, T>) -> Ref<'b, T> {
1654        Ref { value: orig.value, borrow: orig.borrow.clone() }
1655    }
1656
1657    /// Makes a new `Ref` for a component of the borrowed data.
1658    ///
1659    /// The `RefCell` is already immutably borrowed, so this cannot fail.
1660    ///
1661    /// This is an associated function that needs to be used as `Ref::map(...)`.
1662    /// A method would interfere with methods of the same name on the contents
1663    /// of a `RefCell` used through `Deref`.
1664    ///
1665    /// # Examples
1666    ///
1667    /// ```
1668    /// use std::cell::{RefCell, Ref};
1669    ///
1670    /// let c = RefCell::new((5, 'b'));
1671    /// let b1: Ref<'_, (u32, char)> = c.borrow();
1672    /// let b2: Ref<'_, u32> = Ref::map(b1, |t| &t.0);
1673    /// assert_eq!(*b2, 5)
1674    /// ```
1675    #[stable(feature = "cell_map", since = "1.8.0")]
1676    #[inline]
1677    pub fn map<U: ?Sized, F>(orig: Ref<'b, T>, f: F) -> Ref<'b, U>
1678    where
1679        F: FnOnce(&T) -> &U,
1680    {
1681        Ref { value: NonNull::from(f(&*orig)), borrow: orig.borrow }
1682    }
1683
1684    /// Makes a new `Ref` for an optional component of the borrowed data. The
1685    /// original guard is returned as an `Err(..)` if the closure returns
1686    /// `None`.
1687    ///
1688    /// The `RefCell` is already immutably borrowed, so this cannot fail.
1689    ///
1690    /// This is an associated function that needs to be used as
1691    /// `Ref::filter_map(...)`. A method would interfere with methods of the same
1692    /// name on the contents of a `RefCell` used through `Deref`.
1693    ///
1694    /// # Examples
1695    ///
1696    /// ```
1697    /// use std::cell::{RefCell, Ref};
1698    ///
1699    /// let c = RefCell::new(vec![1, 2, 3]);
1700    /// let b1: Ref<'_, Vec<u32>> = c.borrow();
1701    /// let b2: Result<Ref<'_, u32>, _> = Ref::filter_map(b1, |v| v.get(1));
1702    /// assert_eq!(*b2.unwrap(), 2);
1703    /// ```
1704    #[stable(feature = "cell_filter_map", since = "1.63.0")]
1705    #[inline]
1706    pub fn filter_map<U: ?Sized, F>(orig: Ref<'b, T>, f: F) -> Result<Ref<'b, U>, Self>
1707    where
1708        F: FnOnce(&T) -> Option<&U>,
1709    {
1710        match f(&*orig) {
1711            Some(value) => Ok(Ref { value: NonNull::from(value), borrow: orig.borrow }),
1712            None => Err(orig),
1713        }
1714    }
1715
1716    /// Tries to makes a new `Ref` for a component of the borrowed data.
1717    /// On failure, the original guard is returned alongside with the error
1718    /// returned by the closure.
1719    ///
1720    /// The `RefCell` is already immutably borrowed, so this cannot fail.
1721    ///
1722    /// This is an associated function that needs to be used as
1723    /// `Ref::try_map(...)`. A method would interfere with methods of the same
1724    /// name on the contents of a `RefCell` used through `Deref`.
1725    ///
1726    /// # Examples
1727    ///
1728    /// ```
1729    /// #![feature(refcell_try_map)]
1730    /// use std::cell::{RefCell, Ref};
1731    /// use std::str::{from_utf8, Utf8Error};
1732    ///
1733    /// let c = RefCell::new(vec![0xF0, 0x9F, 0xA6 ,0x80]);
1734    /// let b1: Ref<'_, Vec<u8>> = c.borrow();
1735    /// let b2: Result<Ref<'_, str>, _> = Ref::try_map(b1, |v| from_utf8(v));
1736    /// assert_eq!(&*b2.unwrap(), "🦀");
1737    ///
1738    /// let c = RefCell::new(vec![0xF0, 0x9F, 0xA6]);
1739    /// let b1: Ref<'_, Vec<u8>> = c.borrow();
1740    /// let b2: Result<_, (Ref<'_, Vec<u8>>, Utf8Error)> = Ref::try_map(b1, |v| from_utf8(v));
1741    /// let (b3, e) = b2.unwrap_err();
1742    /// assert_eq!(*b3, vec![0xF0, 0x9F, 0xA6]);
1743    /// assert_eq!(e.valid_up_to(), 0);
1744    /// ```
1745    #[unstable(feature = "refcell_try_map", issue = "143801")]
1746    #[inline]
1747    pub fn try_map<U: ?Sized, E>(
1748        orig: Ref<'b, T>,
1749        f: impl FnOnce(&T) -> Result<&U, E>,
1750    ) -> Result<Ref<'b, U>, (Self, E)> {
1751        match f(&*orig) {
1752            Ok(value) => Ok(Ref { value: NonNull::from(value), borrow: orig.borrow }),
1753            Err(e) => Err((orig, e)),
1754        }
1755    }
1756
1757    /// Splits a `Ref` into multiple `Ref`s for different components of the
1758    /// borrowed data.
1759    ///
1760    /// The `RefCell` is already immutably borrowed, so this cannot fail.
1761    ///
1762    /// This is an associated function that needs to be used as
1763    /// `Ref::map_split(...)`. A method would interfere with methods of the same
1764    /// name on the contents of a `RefCell` used through `Deref`.
1765    ///
1766    /// # Examples
1767    ///
1768    /// ```
1769    /// use std::cell::{Ref, RefCell};
1770    ///
1771    /// let cell = RefCell::new([1, 2, 3, 4]);
1772    /// let borrow = cell.borrow();
1773    /// let (begin, end) = Ref::map_split(borrow, |slice| slice.split_at(2));
1774    /// assert_eq!(*begin, [1, 2]);
1775    /// assert_eq!(*end, [3, 4]);
1776    /// ```
1777    #[stable(feature = "refcell_map_split", since = "1.35.0")]
1778    #[inline]
1779    pub fn map_split<U: ?Sized, V: ?Sized, F>(orig: Ref<'b, T>, f: F) -> (Ref<'b, U>, Ref<'b, V>)
1780    where
1781        F: FnOnce(&T) -> (&U, &V),
1782    {
1783        let (a, b) = f(&*orig);
1784        let borrow = orig.borrow.clone();
1785        (
1786            Ref { value: NonNull::from(a), borrow },
1787            Ref { value: NonNull::from(b), borrow: orig.borrow },
1788        )
1789    }
1790
1791    /// Converts into a reference to the underlying data.
1792    ///
1793    /// The underlying `RefCell` can never be mutably borrowed from again and will always appear
1794    /// already immutably borrowed. It is not a good idea to leak more than a constant number of
1795    /// references. The `RefCell` can be immutably borrowed again if only a smaller number of leaks
1796    /// have occurred in total.
1797    ///
1798    /// This is an associated function that needs to be used as
1799    /// `Ref::leak(...)`. A method would interfere with methods of the
1800    /// same name on the contents of a `RefCell` used through `Deref`.
1801    ///
1802    /// # Examples
1803    ///
1804    /// ```
1805    /// #![feature(cell_leak)]
1806    /// use std::cell::{RefCell, Ref};
1807    /// let cell = RefCell::new(0);
1808    ///
1809    /// let value = Ref::leak(cell.borrow());
1810    /// assert_eq!(*value, 0);
1811    ///
1812    /// assert!(cell.try_borrow().is_ok());
1813    /// assert!(cell.try_borrow_mut().is_err());
1814    /// ```
1815    #[unstable(feature = "cell_leak", issue = "69099")]
1816    #[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
1817    pub const fn leak(orig: Ref<'b, T>) -> &'b T {
1818        // By forgetting this Ref we ensure that the borrow counter in the RefCell can't go back to
1819        // UNUSED within the lifetime `'b`. Resetting the reference tracking state would require a
1820        // unique reference to the borrowed RefCell. No further mutable references can be created
1821        // from the original cell.
1822        mem::forget(orig.borrow);
1823        // SAFETY: after forgetting, we can form a reference for the rest of lifetime `'b`.
1824        unsafe { orig.value.as_ref() }
1825    }
1826}
1827
1828#[unstable(feature = "coerce_unsized", issue = "18598")]
1829impl<'b, T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Ref<'b, U>> for Ref<'b, T> {}
1830
1831#[stable(feature = "std_guard_impls", since = "1.20.0")]
1832impl<T: ?Sized + fmt::Display> fmt::Display for Ref<'_, T> {
1833    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1834        (**self).fmt(f)
1835    }
1836}
1837
1838impl<'b, T: ?Sized> RefMut<'b, T> {
1839    /// Makes a new `RefMut` for a component of the borrowed data, e.g., an enum
1840    /// variant.
1841    ///
1842    /// The `RefCell` is already mutably borrowed, so this cannot fail.
1843    ///
1844    /// This is an associated function that needs to be used as
1845    /// `RefMut::map(...)`. A method would interfere with methods of the same
1846    /// name on the contents of a `RefCell` used through `Deref`.
1847    ///
1848    /// # Examples
1849    ///
1850    /// ```
1851    /// use std::cell::{RefCell, RefMut};
1852    ///
1853    /// let c = RefCell::new((5, 'b'));
1854    /// {
1855    ///     let b1: RefMut<'_, (u32, char)> = c.borrow_mut();
1856    ///     let mut b2: RefMut<'_, u32> = RefMut::map(b1, |t| &mut t.0);
1857    ///     assert_eq!(*b2, 5);
1858    ///     *b2 = 42;
1859    /// }
1860    /// assert_eq!(*c.borrow(), (42, 'b'));
1861    /// ```
1862    #[stable(feature = "cell_map", since = "1.8.0")]
1863    #[inline]
1864    pub fn map<U: ?Sized, F>(mut orig: RefMut<'b, T>, f: F) -> RefMut<'b, U>
1865    where
1866        F: FnOnce(&mut T) -> &mut U,
1867    {
1868        let value = NonNull::from(f(&mut *orig));
1869        RefMut { value, borrow: orig.borrow, marker: PhantomData }
1870    }
1871
1872    /// Makes a new `RefMut` for an optional component of the borrowed data. The
1873    /// original guard is returned as an `Err(..)` if the closure returns
1874    /// `None`.
1875    ///
1876    /// The `RefCell` is already mutably borrowed, so this cannot fail.
1877    ///
1878    /// This is an associated function that needs to be used as
1879    /// `RefMut::filter_map(...)`. A method would interfere with methods of the
1880    /// same name on the contents of a `RefCell` used through `Deref`.
1881    ///
1882    /// # Examples
1883    ///
1884    /// ```
1885    /// use std::cell::{RefCell, RefMut};
1886    ///
1887    /// let c = RefCell::new(vec![1, 2, 3]);
1888    ///
1889    /// {
1890    ///     let b1: RefMut<'_, Vec<u32>> = c.borrow_mut();
1891    ///     let mut b2: Result<RefMut<'_, u32>, _> = RefMut::filter_map(b1, |v| v.get_mut(1));
1892    ///
1893    ///     if let Ok(mut b2) = b2 {
1894    ///         *b2 += 2;
1895    ///     }
1896    /// }
1897    ///
1898    /// assert_eq!(*c.borrow(), vec![1, 4, 3]);
1899    /// ```
1900    #[stable(feature = "cell_filter_map", since = "1.63.0")]
1901    #[inline]
1902    pub fn filter_map<U: ?Sized, F>(mut orig: RefMut<'b, T>, f: F) -> Result<RefMut<'b, U>, Self>
1903    where
1904        F: FnOnce(&mut T) -> Option<&mut U>,
1905    {
1906        // SAFETY: function holds onto an exclusive reference for the duration
1907        // of its call through `orig`, and the pointer is only de-referenced
1908        // inside of the function call never allowing the exclusive reference to
1909        // escape.
1910        match f(&mut *orig) {
1911            Some(value) => {
1912                Ok(RefMut { value: NonNull::from(value), borrow: orig.borrow, marker: PhantomData })
1913            }
1914            None => Err(orig),
1915        }
1916    }
1917
1918    /// Tries to makes a new `RefMut` for a component of the borrowed data.
1919    /// On failure, the original guard is returned alongside with the error
1920    /// returned by the closure.
1921    ///
1922    /// The `RefCell` is already mutably borrowed, so this cannot fail.
1923    ///
1924    /// This is an associated function that needs to be used as
1925    /// `RefMut::try_map(...)`. A method would interfere with methods of the same
1926    /// name on the contents of a `RefCell` used through `Deref`.
1927    ///
1928    /// # Examples
1929    ///
1930    /// ```
1931    /// #![feature(refcell_try_map)]
1932    /// use std::cell::{RefCell, RefMut};
1933    /// use std::str::{from_utf8_mut, Utf8Error};
1934    ///
1935    /// let c = RefCell::new(vec![0x68, 0x65, 0x6C, 0x6C, 0x6F]);
1936    /// {
1937    ///     let b1: RefMut<'_, Vec<u8>> = c.borrow_mut();
1938    ///     let b2: Result<RefMut<'_, str>, _> = RefMut::try_map(b1, |v| from_utf8_mut(v));
1939    ///     let mut b2 = b2.unwrap();
1940    ///     assert_eq!(&*b2, "hello");
1941    ///     b2.make_ascii_uppercase();
1942    /// }
1943    /// assert_eq!(*c.borrow(), "HELLO".as_bytes());
1944    ///
1945    /// let c = RefCell::new(vec![0xFF]);
1946    /// let b1: RefMut<'_, Vec<u8>> = c.borrow_mut();
1947    /// let b2: Result<_, (RefMut<'_, Vec<u8>>, Utf8Error)> = RefMut::try_map(b1, |v| from_utf8_mut(v));
1948    /// let (b3, e) = b2.unwrap_err();
1949    /// assert_eq!(*b3, vec![0xFF]);
1950    /// assert_eq!(e.valid_up_to(), 0);
1951    /// ```
1952    #[unstable(feature = "refcell_try_map", issue = "143801")]
1953    #[inline]
1954    pub fn try_map<U: ?Sized, E>(
1955        mut orig: RefMut<'b, T>,
1956        f: impl FnOnce(&mut T) -> Result<&mut U, E>,
1957    ) -> Result<RefMut<'b, U>, (Self, E)> {
1958        // SAFETY: function holds onto an exclusive reference for the duration
1959        // of its call through `orig`, and the pointer is only de-referenced
1960        // inside of the function call never allowing the exclusive reference to
1961        // escape.
1962        match f(&mut *orig) {
1963            Ok(value) => {
1964                Ok(RefMut { value: NonNull::from(value), borrow: orig.borrow, marker: PhantomData })
1965            }
1966            Err(e) => Err((orig, e)),
1967        }
1968    }
1969
1970    /// Splits a `RefMut` into multiple `RefMut`s for different components of the
1971    /// borrowed data.
1972    ///
1973    /// The underlying `RefCell` will remain mutably borrowed until both
1974    /// returned `RefMut`s go out of scope.
1975    ///
1976    /// The `RefCell` is already mutably borrowed, so this cannot fail.
1977    ///
1978    /// This is an associated function that needs to be used as
1979    /// `RefMut::map_split(...)`. A method would interfere with methods of the
1980    /// same name on the contents of a `RefCell` used through `Deref`.
1981    ///
1982    /// # Examples
1983    ///
1984    /// ```
1985    /// use std::cell::{RefCell, RefMut};
1986    ///
1987    /// let cell = RefCell::new([1, 2, 3, 4]);
1988    /// let borrow = cell.borrow_mut();
1989    /// let (mut begin, mut end) = RefMut::map_split(borrow, |slice| slice.split_at_mut(2));
1990    /// assert_eq!(*begin, [1, 2]);
1991    /// assert_eq!(*end, [3, 4]);
1992    /// begin.copy_from_slice(&[4, 3]);
1993    /// end.copy_from_slice(&[2, 1]);
1994    /// ```
1995    #[stable(feature = "refcell_map_split", since = "1.35.0")]
1996    #[inline]
1997    pub fn map_split<U: ?Sized, V: ?Sized, F>(
1998        mut orig: RefMut<'b, T>,
1999        f: F,
2000    ) -> (RefMut<'b, U>, RefMut<'b, V>)
2001    where
2002        F: FnOnce(&mut T) -> (&mut U, &mut V),
2003    {
2004        let borrow = orig.borrow.clone();
2005        let (a, b) = f(&mut *orig);
2006        (
2007            RefMut { value: NonNull::from(a), borrow, marker: PhantomData },
2008            RefMut { value: NonNull::from(b), borrow: orig.borrow, marker: PhantomData },
2009        )
2010    }
2011
2012    /// Converts into a mutable reference to the underlying data.
2013    ///
2014    /// The underlying `RefCell` can not be borrowed from again and will always appear already
2015    /// mutably borrowed, making the returned reference the only to the interior.
2016    ///
2017    /// This is an associated function that needs to be used as
2018    /// `RefMut::leak(...)`. A method would interfere with methods of the
2019    /// same name on the contents of a `RefCell` used through `Deref`.
2020    ///
2021    /// # Examples
2022    ///
2023    /// ```
2024    /// #![feature(cell_leak)]
2025    /// use std::cell::{RefCell, RefMut};
2026    /// let cell = RefCell::new(0);
2027    ///
2028    /// let value = RefMut::leak(cell.borrow_mut());
2029    /// assert_eq!(*value, 0);
2030    /// *value = 1;
2031    ///
2032    /// assert!(cell.try_borrow_mut().is_err());
2033    /// ```
2034    #[unstable(feature = "cell_leak", issue = "69099")]
2035    #[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
2036    pub const fn leak(mut orig: RefMut<'b, T>) -> &'b mut T {
2037        // By forgetting this BorrowRefMut we ensure that the borrow counter in the RefCell can't
2038        // go back to UNUSED within the lifetime `'b`. Resetting the reference tracking state would
2039        // require a unique reference to the borrowed RefCell. No further references can be created
2040        // from the original cell within that lifetime, making the current borrow the only
2041        // reference for the remaining lifetime.
2042        mem::forget(orig.borrow);
2043        // SAFETY: after forgetting, we can form a reference for the rest of lifetime `'b`.
2044        unsafe { orig.value.as_mut() }
2045    }
2046}
2047
2048struct BorrowRefMut<'b> {
2049    borrow: &'b Cell<BorrowCounter>,
2050}
2051
2052#[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
2053const impl Drop for BorrowRefMut<'_> {
2054    #[inline]
2055    fn drop(&mut self) {
2056        let borrow = self.borrow.get();
2057        debug_assert!(is_writing(borrow));
2058        self.borrow.replace(borrow + 1);
2059    }
2060}
2061
2062impl<'b> BorrowRefMut<'b> {
2063    #[inline]
2064    const fn new(borrow: &'b Cell<BorrowCounter>) -> Option<BorrowRefMut<'b>> {
2065        // NOTE: Unlike BorrowRefMut::clone, new is called to create the initial
2066        // mutable reference, and so there must currently be no existing
2067        // references. Thus, while clone increments the mutable refcount, here
2068        // we explicitly only allow going from UNUSED to UNUSED - 1.
2069        match borrow.get() {
2070            UNUSED => {
2071                borrow.replace(UNUSED - 1);
2072                Some(BorrowRefMut { borrow })
2073            }
2074            _ => None,
2075        }
2076    }
2077
2078    // Clones a `BorrowRefMut`.
2079    //
2080    // This is only valid if each `BorrowRefMut` is used to track a mutable
2081    // reference to a distinct, nonoverlapping range of the original object.
2082    // This isn't in a Clone impl so that code doesn't call this implicitly.
2083    #[inline]
2084    fn clone(&self) -> BorrowRefMut<'b> {
2085        let borrow = self.borrow.get();
2086        debug_assert!(is_writing(borrow));
2087        // Prevent the borrow counter from underflowing.
2088        assert!(borrow != BorrowCounter::MIN);
2089        self.borrow.set(borrow - 1);
2090        BorrowRefMut { borrow: self.borrow }
2091    }
2092}
2093
2094/// A wrapper type for a mutably borrowed value from a `RefCell<T>`.
2095///
2096/// See the [module-level documentation](self) for more.
2097#[stable(feature = "rust1", since = "1.0.0")]
2098#[must_not_suspend = "holding a RefMut across suspend points can cause BorrowErrors"]
2099#[rustc_diagnostic_item = "RefCellRefMut"]
2100pub struct RefMut<'b, T: ?Sized + 'b> {
2101    // NB: we use a pointer instead of `&'b mut T` to avoid `noalias` violations, because a
2102    // `RefMut` argument doesn't hold exclusivity for its whole scope, only until it drops.
2103    value: NonNull<T>,
2104    borrow: BorrowRefMut<'b>,
2105    // `NonNull` is covariant over `T`, so we need to reintroduce invariance.
2106    marker: PhantomData<&'b mut T>,
2107}
2108
2109#[stable(feature = "rust1", since = "1.0.0")]
2110#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
2111const impl<T: ?Sized> Deref for RefMut<'_, T> {
2112    type Target = T;
2113
2114    #[inline]
2115    fn deref(&self) -> &T {
2116        // SAFETY: the value is accessible as long as we hold our borrow.
2117        unsafe { self.value.as_ref() }
2118    }
2119}
2120
2121#[stable(feature = "rust1", since = "1.0.0")]
2122#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
2123const impl<T: ?Sized> DerefMut for RefMut<'_, T> {
2124    #[inline]
2125    fn deref_mut(&mut self) -> &mut T {
2126        // SAFETY: the value is accessible as long as we hold our borrow.
2127        unsafe { self.value.as_mut() }
2128    }
2129}
2130
2131#[unstable(feature = "deref_pure_trait", issue = "87121")]
2132unsafe impl<T: ?Sized> DerefPure for RefMut<'_, T> {}
2133
2134#[unstable(feature = "coerce_unsized", issue = "18598")]
2135impl<'b, T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<RefMut<'b, U>> for RefMut<'b, T> {}
2136
2137#[stable(feature = "std_guard_impls", since = "1.20.0")]
2138impl<T: ?Sized + fmt::Display> fmt::Display for RefMut<'_, T> {
2139    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2140        (**self).fmt(f)
2141    }
2142}
2143
2144/// The core primitive for interior mutability in Rust.
2145///
2146/// If you have a reference `&T`, then normally in Rust the compiler performs optimizations based on
2147/// the knowledge that `&T` points to immutable data. Mutating that data, for example through an
2148/// alias or by transmuting a `&T` into a `&mut T`, is considered undefined behavior.
2149/// `UnsafeCell<T>` opts-out of the immutability guarantee for `&T`: a shared reference
2150/// `&UnsafeCell<T>` may point to data that is being mutated. This is called "interior mutability".
2151///
2152/// All other types that allow internal mutability, such as [`Cell<T>`] and [`RefCell<T>`], internally
2153/// use `UnsafeCell` to wrap their data.
2154///
2155/// Note that only the immutability guarantee for shared references is affected by `UnsafeCell`. The
2156/// uniqueness guarantee for mutable references is unaffected. As explained below, for the duration
2157/// of the lifetime of an `&mut`, no other reference may exist and no pointer may be used to access
2158/// that memory; this applies even with `UnsafeCell<T>`.
2159///
2160/// `UnsafeCell` does nothing to avoid data races; they are still undefined behavior. If multiple
2161/// threads have access to the same `UnsafeCell`, they must follow the usual rules of the
2162/// [concurrent memory model]: conflicting non-synchronized accesses must be done via the APIs in
2163/// [`core::sync::atomic`].
2164///
2165/// The `UnsafeCell` API itself is technically very simple: [`.get()`] gives you a raw pointer
2166/// `*mut T` to its contents. It is up to _you_ as the abstraction designer to use that raw pointer
2167/// correctly.
2168///
2169/// [`.get()`]: `UnsafeCell::get`
2170/// [concurrent memory model]: ../sync/atomic/index.html#memory-model-for-atomic-accesses
2171///
2172/// # Aliasing rules
2173///
2174/// The precise Rust aliasing rules are somewhat in flux, but the main points are not contentious:
2175///
2176/// - If you create a safe reference with lifetime `'a` (either a `&T` or `&mut T` reference), then
2177///   you must not access the data in any way that contradicts that reference for the remainder of
2178///   `'a`, and you must not create any contradicting references. For example, this means that if
2179///   you take the `*mut T` from an `UnsafeCell<T>` and cast it to a `&T`, then the data in `T` must
2180///   remain immutable (modulo any `UnsafeCell` data found within `T`, of course) until that
2181///   reference's lifetime expires, and no `&mut` reference to this data may be created. Similarly,
2182///   if you create a `&mut T` reference, then you must not access the data within the `UnsafeCell`
2183///   with any other pointer/reference until that reference expires, and no reference of any kind
2184///   may be created.
2185///
2186/// - For both `&T` without `UnsafeCell<_>` and `&mut T`, you must also not deallocate the data
2187///   until the reference expires. As a special exception, given a `&T`, any part of it that is
2188///   inside an `UnsafeCell<_>` may be deallocated during the lifetime of the reference, after the
2189///   last time the reference is used (dereferenced or reborrowed). Since you cannot deallocate a part
2190///   of what a reference points to, this means the memory a `&T` points to can be deallocated only if
2191///   *every part of it* (including padding) is inside an `UnsafeCell`.
2192///
2193/// However, whenever a `&UnsafeCell<T>` is constructed or dereferenced, it must still point to
2194/// live memory and the compiler is allowed to insert spurious reads if it can prove that this
2195/// memory has not yet been deallocated.
2196///
2197/// To assist with proper design, the following scenarios are explicitly declared legal
2198/// for single-threaded code:
2199///
2200/// 1. A `&T` reference can be released to safe code and there it can co-exist with other `&T`
2201///    references, but not with a `&mut T`
2202///
2203/// 2. A `&mut T` reference may be released to safe code provided neither other `&mut T` nor `&T`
2204///    co-exist with it. A `&mut T` must always be unique.
2205///
2206/// Note that whilst mutating the contents of a `&UnsafeCell<T>` (even while other
2207/// `&UnsafeCell<T>` references alias the cell) is
2208/// ok (provided you enforce the above invariants some other way), it is still undefined behavior
2209/// to have aliasing `&mut UnsafeCell<T>` (or aliasing `&mut` of *any* type). That is, `UnsafeCell` is a wrapper
2210/// designed to have a special interaction with _shared_ accesses (_i.e._, through an
2211/// `&UnsafeCell<_>` reference); there is no magic whatsoever when dealing with _exclusive_
2212/// accesses (_e.g._, through a `&mut UnsafeCell<_>`): neither the cell nor the wrapped value
2213/// may be aliased for the duration of that `&mut` borrow.
2214/// This is showcased by the [`.get_mut()`] accessor, which is a _safe_ getter that yields
2215/// a `&mut T`.
2216///
2217/// [`.get_mut()`]: `UnsafeCell::get_mut`
2218///
2219/// # Memory layout
2220///
2221/// `UnsafeCell<T>` has the same in-memory representation as its inner type `T`. A consequence
2222/// of this guarantee is that it is possible to convert between `T` and `UnsafeCell<T>`.
2223/// Special care has to be taken when converting a nested `T` inside of an `Outer<T>` type
2224/// to an `Outer<UnsafeCell<T>>` type: this is not sound when the `Outer<T>` type enables [niche]
2225/// optimizations. For example, the type `Option<NonNull<u8>>` is typically 8 bytes large on
2226/// 64-bit platforms, but the type `Option<UnsafeCell<NonNull<u8>>>` takes up 16 bytes of space.
2227/// Therefore this is not a valid conversion, despite `NonNull<u8>` and `UnsafeCell<NonNull<u8>>>`
2228/// having the same memory layout. This is because `UnsafeCell` disables niche optimizations in
2229/// order to avoid its interior mutability property from spreading from `T` into the `Outer` type,
2230/// thus this can cause distortions in the type size in these cases.
2231///
2232/// The following examples make use of this guarantee:
2233///
2234/// ```rust
2235/// # use std::cell::UnsafeCell;
2236/// /// # Safety
2237/// /// The caller must not call `get_mut_unchecked` again (on any alias of `ptr`) for the duration
2238/// /// of the lifetime of the returned reference.
2239/// unsafe fn get_mut_unchecked<T>(ptr: &UnsafeCell<T>) -> &mut T {
2240///   let t = ptr as *const UnsafeCell<T> as *mut T;
2241///   unsafe { &mut *t }
2242/// }
2243/// ```
2244///
2245/// ```rust
2246/// # use std::cell::UnsafeCell;
2247/// fn get_shared<T>(ptr: &mut T) -> &UnsafeCell<T> {
2248///   let t = ptr as *mut T as *const UnsafeCell<T>;
2249///   // SAFETY: `T` and `UnsafeCell<T>` have the same memory layout
2250///   unsafe { &*t }
2251/// }
2252/// ```
2253///
2254/// [niche]: https://rust-lang.github.io/unsafe-code-guidelines/glossary.html#niche
2255///
2256/// # Examples
2257///
2258/// Here is an example showcasing how to soundly mutate the contents of an `UnsafeCell<_>` despite
2259/// there being multiple references aliasing the cell:
2260///
2261/// ```
2262/// use std::cell::UnsafeCell;
2263///
2264/// let x: UnsafeCell<i32> = 42.into();
2265/// // Get multiple / concurrent / shared references to the same `x`.
2266/// let (p1, p2): (&UnsafeCell<i32>, &UnsafeCell<i32>) = (&x, &x);
2267///
2268/// unsafe {
2269///     // SAFETY: within this scope there are no other references to `x`'s contents,
2270///     // so ours is effectively unique.
2271///     let p1_exclusive: &mut i32 = &mut *p1.get(); // -- borrow --+
2272///     *p1_exclusive += 27; //                                     |
2273/// } // <---------- cannot go beyond this point -------------------+
2274///
2275/// unsafe {
2276///     // SAFETY: within this scope nobody expects to have exclusive access to `x`'s contents,
2277///     // so we can have multiple shared accesses concurrently.
2278///     let p2_shared: &i32 = &*p2.get();
2279///     assert_eq!(*p2_shared, 42 + 27);
2280///     let p1_shared: &i32 = &*p1.get();
2281///     assert_eq!(*p1_shared, *p2_shared);
2282/// }
2283/// ```
2284///
2285/// The following example showcases the fact that exclusive access to an `UnsafeCell<T>`
2286/// implies exclusive access to its `T`:
2287///
2288/// ```rust
2289/// #![forbid(unsafe_code)]
2290/// // with exclusive accesses, `UnsafeCell` is a transparent no-op wrapper, so no need for
2291/// // `unsafe` here.
2292/// use std::cell::UnsafeCell;
2293///
2294/// let mut x: UnsafeCell<i32> = 42.into();
2295///
2296/// // Get a compile-time-checked unique reference to `x`.
2297/// let p_unique: &mut UnsafeCell<i32> = &mut x;
2298/// // With an exclusive reference, we can mutate the contents for free.
2299/// *p_unique.get_mut() = 0;
2300/// // Or, equivalently:
2301/// x = UnsafeCell::new(0);
2302///
2303/// // When we own the value, we can extract the contents for free.
2304/// let contents: i32 = x.into_inner();
2305/// assert_eq!(contents, 0);
2306/// ```
2307#[lang = "unsafe_cell"]
2308#[stable(feature = "rust1", since = "1.0.0")]
2309#[repr(transparent)]
2310#[rustc_pub_transparent]
2311pub struct UnsafeCell<T: ?Sized> {
2312    value: T,
2313}
2314
2315#[stable(feature = "rust1", since = "1.0.0")]
2316impl<T: ?Sized> !Sync for UnsafeCell<T> {}
2317
2318impl<T> UnsafeCell<T> {
2319    /// Constructs a new instance of `UnsafeCell` which will wrap the specified
2320    /// value.
2321    ///
2322    /// All access to the inner value through `&UnsafeCell<T>` requires `unsafe` code.
2323    ///
2324    /// # Examples
2325    ///
2326    /// ```
2327    /// use std::cell::UnsafeCell;
2328    ///
2329    /// let uc = UnsafeCell::new(5);
2330    /// ```
2331    #[stable(feature = "rust1", since = "1.0.0")]
2332    #[rustc_const_stable(feature = "const_unsafe_cell_new", since = "1.32.0")]
2333    #[inline(always)]
2334    pub const fn new(value: T) -> UnsafeCell<T> {
2335        UnsafeCell { value }
2336    }
2337
2338    /// Unwraps the value, consuming the cell.
2339    ///
2340    /// # Examples
2341    ///
2342    /// ```
2343    /// use std::cell::UnsafeCell;
2344    ///
2345    /// let uc = UnsafeCell::new(5);
2346    ///
2347    /// let five = uc.into_inner();
2348    /// ```
2349    #[inline(always)]
2350    #[stable(feature = "rust1", since = "1.0.0")]
2351    #[rustc_const_stable(feature = "const_cell_into_inner", since = "1.83.0")]
2352    #[rustc_allow_const_fn_unstable(const_precise_live_drops)]
2353    pub const fn into_inner(self) -> T {
2354        self.value
2355    }
2356
2357    /// Replace the value in this `UnsafeCell` and return the old value.
2358    ///
2359    /// # Safety
2360    ///
2361    /// The caller must take care to avoid aliasing and data races.
2362    ///
2363    /// - It is Undefined Behavior to allow calls to race with
2364    ///   any other access to the wrapped value.
2365    /// - It is Undefined Behavior to call this while any other
2366    ///   reference(s) to the wrapped value are alive.
2367    ///
2368    /// # Examples
2369    ///
2370    /// ```
2371    /// #![feature(unsafe_cell_access)]
2372    /// use std::cell::UnsafeCell;
2373    ///
2374    /// let uc = UnsafeCell::new(5);
2375    ///
2376    /// let old = unsafe { uc.replace(10) };
2377    /// assert_eq!(old, 5);
2378    /// ```
2379    #[inline]
2380    #[unstable(feature = "unsafe_cell_access", issue = "136327")]
2381    #[rustc_should_not_be_called_on_const_items]
2382    pub const unsafe fn replace(&self, value: T) -> T {
2383        // SAFETY: pointer comes from `&self` so naturally satisfies invariants.
2384        unsafe { ptr::replace(self.get(), value) }
2385    }
2386}
2387
2388impl<T: ?Sized> UnsafeCell<T> {
2389    /// Converts from `&mut T` to `&mut UnsafeCell<T>`.
2390    ///
2391    /// # Examples
2392    ///
2393    /// ```
2394    /// use std::cell::UnsafeCell;
2395    ///
2396    /// let mut val = 42;
2397    /// let uc = UnsafeCell::from_mut(&mut val);
2398    ///
2399    /// *uc.get_mut() -= 1;
2400    /// assert_eq!(*uc.get_mut(), 41);
2401    /// ```
2402    #[inline(always)]
2403    #[stable(feature = "unsafe_cell_from_mut", since = "1.84.0")]
2404    #[rustc_const_stable(feature = "unsafe_cell_from_mut", since = "1.84.0")]
2405    pub const fn from_mut(value: &mut T) -> &mut UnsafeCell<T> {
2406        // SAFETY: `UnsafeCell<T>` has the same memory layout as `T` due to #[repr(transparent)].
2407        unsafe { &mut *(value as *mut T as *mut UnsafeCell<T>) }
2408    }
2409
2410    /// Gets a mutable pointer to the wrapped value.
2411    ///
2412    /// This can be cast to a pointer of any kind. When creating (shared or mutable) references, you
2413    /// must uphold the aliasing rules; see [the type-level docs][UnsafeCell#aliasing-rules] for
2414    /// more discussion and caveats.
2415    ///
2416    /// This is equivalent to casting `self` to a raw pointer and then casting that raw
2417    /// pointer to `*mut T`.
2418    ///
2419    /// # Examples
2420    ///
2421    /// ```
2422    /// use std::cell::UnsafeCell;
2423    ///
2424    /// let uc = UnsafeCell::new(5);
2425    ///
2426    /// let five = uc.get();
2427    /// ```
2428    #[inline(always)]
2429    #[stable(feature = "rust1", since = "1.0.0")]
2430    #[rustc_const_stable(feature = "const_unsafecell_get", since = "1.32.0")]
2431    #[rustc_as_ptr]
2432    #[rustc_never_returns_null_ptr]
2433    #[rustc_should_not_be_called_on_const_items]
2434    pub const fn get(&self) -> *mut T {
2435        // We can just cast the pointer from `UnsafeCell<T>` to `T` because of
2436        // #[repr(transparent)].
2437        self as *const UnsafeCell<T> as *const T as *mut T
2438    }
2439
2440    /// Returns a mutable reference to the underlying data.
2441    ///
2442    /// This call borrows the `UnsafeCell` mutably (at compile-time) which
2443    /// guarantees that we possess the only reference.
2444    ///
2445    /// # Examples
2446    ///
2447    /// ```
2448    /// use std::cell::UnsafeCell;
2449    ///
2450    /// let mut c = UnsafeCell::new(5);
2451    /// *c.get_mut() += 1;
2452    ///
2453    /// assert_eq!(*c.get_mut(), 6);
2454    /// ```
2455    #[inline(always)]
2456    #[stable(feature = "unsafe_cell_get_mut", since = "1.50.0")]
2457    #[rustc_const_stable(feature = "const_unsafecell_get_mut", since = "1.83.0")]
2458    pub const fn get_mut(&mut self) -> &mut T {
2459        &mut self.value
2460    }
2461
2462    /// Gets a mutable pointer to the wrapped value.
2463    /// The difference from [`get`] is that this function accepts a raw pointer,
2464    /// which is useful to avoid the creation of temporary references.
2465    ///
2466    /// This can be cast to a pointer of any kind. When creating (shared or mutable) references, you
2467    /// must uphold the aliasing rules; see [the type-level docs][UnsafeCell#aliasing-rules] for
2468    /// more discussion and caveats.
2469    ///
2470    /// This is equivalent to casting `this` to `*mut T`.
2471    ///
2472    /// [`get`]: UnsafeCell::get()
2473    ///
2474    /// # Examples
2475    ///
2476    /// Gradual initialization of an `UnsafeCell` requires `raw_get`, as
2477    /// calling `get` would require creating a reference to uninitialized data:
2478    ///
2479    /// ```
2480    /// use std::cell::UnsafeCell;
2481    /// use std::mem::MaybeUninit;
2482    ///
2483    /// let m = MaybeUninit::<UnsafeCell<i32>>::uninit();
2484    /// unsafe { UnsafeCell::raw_get(m.as_ptr()).write(5); }
2485    /// // avoid below which references to uninitialized data
2486    /// // unsafe { UnsafeCell::get(&*m.as_ptr()).write(5); }
2487    /// let uc = unsafe { m.assume_init() };
2488    ///
2489    /// assert_eq!(uc.into_inner(), 5);
2490    /// ```
2491    #[inline(always)]
2492    #[stable(feature = "unsafe_cell_raw_get", since = "1.56.0")]
2493    #[rustc_const_stable(feature = "unsafe_cell_raw_get", since = "1.56.0")]
2494    #[rustc_diagnostic_item = "unsafe_cell_raw_get"]
2495    pub const fn raw_get(this: *const Self) -> *mut T {
2496        // We can just cast the pointer from `UnsafeCell<T>` to `T` because of
2497        // #[repr(transparent)]. This exploits std's special status, there is
2498        // no guarantee for user code that this will work in future versions of the compiler!
2499        this as *const T as *mut T
2500    }
2501
2502    /// Get a shared reference to the value within the `UnsafeCell`.
2503    ///
2504    /// # Safety
2505    ///
2506    /// - It is Undefined Behavior to call this while any mutable
2507    ///   reference to the wrapped value is alive.
2508    /// - Mutating the wrapped value while the returned
2509    ///   reference is alive is Undefined Behavior.
2510    ///
2511    /// # Examples
2512    ///
2513    /// ```
2514    /// #![feature(unsafe_cell_access)]
2515    /// use std::cell::UnsafeCell;
2516    ///
2517    /// let uc = UnsafeCell::new(5);
2518    ///
2519    /// let val = unsafe { uc.as_ref_unchecked() };
2520    /// assert_eq!(val, &5);
2521    /// ```
2522    #[inline]
2523    #[unstable(feature = "unsafe_cell_access", issue = "136327")]
2524    #[rustc_should_not_be_called_on_const_items]
2525    pub const unsafe fn as_ref_unchecked(&self) -> &T {
2526        // SAFETY: pointer comes from `&self` so naturally satisfies ptr-to-ref invariants.
2527        unsafe { self.get().as_ref_unchecked() }
2528    }
2529
2530    /// Get an exclusive reference to the value within the `UnsafeCell`.
2531    ///
2532    /// # Safety
2533    ///
2534    /// - It is Undefined Behavior to call this while any other
2535    ///   reference(s) to the wrapped value are alive.
2536    /// - Mutating the wrapped value through other means while the
2537    ///   returned reference is alive is Undefined Behavior.
2538    ///
2539    /// # Examples
2540    ///
2541    /// ```
2542    /// #![feature(unsafe_cell_access)]
2543    /// use std::cell::UnsafeCell;
2544    ///
2545    /// let uc = UnsafeCell::new(5);
2546    ///
2547    /// unsafe { *uc.as_mut_unchecked() += 1; }
2548    /// assert_eq!(uc.into_inner(), 6);
2549    /// ```
2550    #[inline]
2551    #[unstable(feature = "unsafe_cell_access", issue = "136327")]
2552    #[allow(clippy::mut_from_ref)]
2553    #[rustc_should_not_be_called_on_const_items]
2554    pub const unsafe fn as_mut_unchecked(&self) -> &mut T {
2555        // SAFETY: pointer comes from `&self` so naturally satisfies ptr-to-ref invariants.
2556        unsafe { self.get().as_mut_unchecked() }
2557    }
2558}
2559
2560#[stable(feature = "unsafe_cell_default", since = "1.10.0")]
2561#[rustc_const_unstable(feature = "const_default", issue = "143894")]
2562const impl<T: [const] Default> Default for UnsafeCell<T> {
2563    /// Creates an `UnsafeCell`, with the `Default` value for T.
2564    fn default() -> UnsafeCell<T> {
2565        UnsafeCell::new(Default::default())
2566    }
2567}
2568
2569#[stable(feature = "cell_from", since = "1.12.0")]
2570#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
2571const impl<T> From<T> for UnsafeCell<T> {
2572    /// Creates a new `UnsafeCell<T>` containing the given value.
2573    fn from(t: T) -> UnsafeCell<T> {
2574        UnsafeCell::new(t)
2575    }
2576}
2577
2578#[unstable(feature = "coerce_unsized", issue = "18598")]
2579impl<T: CoerceUnsized<U>, U> CoerceUnsized<UnsafeCell<U>> for UnsafeCell<T> {}
2580
2581// Allow types that wrap `UnsafeCell` to also implement `DispatchFromDyn`
2582// and become dyn-compatible method receivers.
2583// Note that currently `UnsafeCell` itself cannot be a method receiver
2584// because it does not implement Deref.
2585// In other words:
2586// `self: UnsafeCell<&Self>` won't work
2587// `self: UnsafeCellWrapper<Self>` becomes possible
2588#[unstable(feature = "dispatch_from_dyn", issue = "none")]
2589impl<T: DispatchFromDyn<U>, U> DispatchFromDyn<UnsafeCell<U>> for UnsafeCell<T> {}
2590
2591/// [`UnsafeCell`], but [`Sync`].
2592///
2593/// This is just an `UnsafeCell`, except it implements `Sync`
2594/// if `T` implements `Sync`.
2595///
2596/// `UnsafeCell` doesn't implement `Sync`, to prevent accidental mis-use.
2597/// You can use `SyncUnsafeCell` instead of `UnsafeCell` to allow it to be
2598/// shared between threads, if that's intentional.
2599/// Providing proper synchronization is still the task of the user,
2600/// making this type just as unsafe to use.
2601///
2602/// See [`UnsafeCell`] for details.
2603#[unstable(feature = "sync_unsafe_cell", issue = "95439")]
2604#[repr(transparent)]
2605#[rustc_diagnostic_item = "SyncUnsafeCell"]
2606#[rustc_pub_transparent]
2607pub struct SyncUnsafeCell<T: ?Sized> {
2608    value: UnsafeCell<T>,
2609}
2610
2611#[unstable(feature = "sync_unsafe_cell", issue = "95439")]
2612unsafe impl<T: ?Sized + Sync> Sync for SyncUnsafeCell<T> {}
2613
2614#[unstable(feature = "sync_unsafe_cell", issue = "95439")]
2615impl<T> SyncUnsafeCell<T> {
2616    /// Constructs a new instance of `SyncUnsafeCell` which will wrap the specified value.
2617    #[inline]
2618    pub const fn new(value: T) -> Self {
2619        Self { value: UnsafeCell { value } }
2620    }
2621
2622    /// Unwraps the value, consuming the cell.
2623    #[inline]
2624    #[rustc_const_unstable(feature = "sync_unsafe_cell", issue = "95439")]
2625    pub const fn into_inner(self) -> T {
2626        self.value.into_inner()
2627    }
2628}
2629
2630#[unstable(feature = "sync_unsafe_cell", issue = "95439")]
2631impl<T: ?Sized> SyncUnsafeCell<T> {
2632    /// Gets a mutable pointer to the wrapped value.
2633    ///
2634    /// This can be cast to a pointer of any kind.
2635    /// Ensure that the access is unique (no active references, mutable or not)
2636    /// when casting to `&mut T`, and ensure that there are no mutations
2637    /// or mutable aliases going on when casting to `&T`
2638    #[inline]
2639    #[rustc_as_ptr]
2640    #[rustc_never_returns_null_ptr]
2641    #[rustc_should_not_be_called_on_const_items]
2642    pub const fn get(&self) -> *mut T {
2643        self.value.get()
2644    }
2645
2646    /// Returns a mutable reference to the underlying data.
2647    ///
2648    /// This call borrows the `SyncUnsafeCell` mutably (at compile-time) which
2649    /// guarantees that we possess the only reference.
2650    #[inline]
2651    pub const fn get_mut(&mut self) -> &mut T {
2652        self.value.get_mut()
2653    }
2654
2655    /// Gets a mutable pointer to the wrapped value.
2656    ///
2657    /// See [`UnsafeCell::get`] for details.
2658    #[inline]
2659    pub const fn raw_get(this: *const Self) -> *mut T {
2660        // We can just cast the pointer from `SyncUnsafeCell<T>` to `T` because
2661        // of #[repr(transparent)] on both SyncUnsafeCell and UnsafeCell.
2662        // See UnsafeCell::raw_get.
2663        this as *const T as *mut T
2664    }
2665}
2666
2667#[unstable(feature = "sync_unsafe_cell", issue = "95439")]
2668#[rustc_const_unstable(feature = "const_default", issue = "143894")]
2669const impl<T: [const] Default> Default for SyncUnsafeCell<T> {
2670    /// Creates an `SyncUnsafeCell`, with the `Default` value for T.
2671    fn default() -> SyncUnsafeCell<T> {
2672        SyncUnsafeCell::new(Default::default())
2673    }
2674}
2675
2676#[unstable(feature = "sync_unsafe_cell", issue = "95439")]
2677#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
2678const impl<T> From<T> for SyncUnsafeCell<T> {
2679    /// Creates a new `SyncUnsafeCell<T>` containing the given value.
2680    fn from(t: T) -> SyncUnsafeCell<T> {
2681        SyncUnsafeCell::new(t)
2682    }
2683}
2684
2685#[unstable(feature = "coerce_unsized", issue = "18598")]
2686//#[unstable(feature = "sync_unsafe_cell", issue = "95439")]
2687impl<T: CoerceUnsized<U>, U> CoerceUnsized<SyncUnsafeCell<U>> for SyncUnsafeCell<T> {}
2688
2689// Allow types that wrap `SyncUnsafeCell` to also implement `DispatchFromDyn`
2690// and become dyn-compatible method receivers.
2691// Note that currently `SyncUnsafeCell` itself cannot be a method receiver
2692// because it does not implement Deref.
2693// In other words:
2694// `self: SyncUnsafeCell<&Self>` won't work
2695// `self: SyncUnsafeCellWrapper<Self>` becomes possible
2696#[unstable(feature = "dispatch_from_dyn", issue = "none")]
2697//#[unstable(feature = "sync_unsafe_cell", issue = "95439")]
2698impl<T: DispatchFromDyn<U>, U> DispatchFromDyn<SyncUnsafeCell<U>> for SyncUnsafeCell<T> {}
2699
2700#[allow(unused)]
2701fn assert_coerce_unsized(
2702    a: UnsafeCell<&i32>,
2703    b: SyncUnsafeCell<&i32>,
2704    c: Cell<&i32>,
2705    d: RefCell<&i32>,
2706) {
2707    let _: UnsafeCell<&dyn Send> = a;
2708    let _: SyncUnsafeCell<&dyn Send> = b;
2709    let _: Cell<&dyn Send> = c;
2710    let _: RefCell<&dyn Send> = d;
2711}
2712
2713#[unstable(feature = "pin_coerce_unsized_trait", issue = "150112")]
2714unsafe impl<'b, T: ?Sized> PinCoerceUnsized for Ref<'b, T> {}
2715
2716#[unstable(feature = "pin_coerce_unsized_trait", issue = "150112")]
2717unsafe impl<'b, T: ?Sized> PinCoerceUnsized for RefMut<'b, T> {}