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