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