core/
cell.rs

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