core/
cell.rs

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