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