core/
cell.rs

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