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