Skip to main content

core/
cell.rs

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