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