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