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