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