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