Skip to main content

core/
cell.rs

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