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