core/
cell.rs

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