Skip to main content

core/
cell.rs

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