core/
cell.rs

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