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