1 //! Shareable mutable containers.
3 //! Rust memory safety is based on this rule: Given an object `T`, it is only possible to
4 //! have one of the following:
6 //! - Having several immutable references (`&T`) to the object (also known as **aliasing**).
7 //! - Having one mutable reference (`&mut T`) to the object (also known as **mutability**).
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
13 //! Shareable mutable containers exist to permit mutability in a controlled manner, even in the
14 //! presence of aliasing. Both [`Cell<T>`] and [`RefCell<T>`] allow doing this in a single-threaded
15 //! way. However, neither `Cell<T>` nor `RefCell<T>` are thread safe (they do not implement
16 //! [`Sync`]). If you need to do aliasing and mutation between multiple threads it is possible to
17 //! use [`Mutex<T>`], [`RwLock<T>`] or [`atomic`] types.
19 //! Values of the `Cell<T>` and `RefCell<T>` types may be mutated through shared references (i.e.
20 //! the common `&T` type), whereas most Rust types can only be mutated through unique (`&mut T`)
21 //! references. We say that `Cell<T>` and `RefCell<T>` provide 'interior mutability', in contrast
22 //! with typical Rust types that exhibit 'inherited mutability'.
24 //! Cell types come in two flavors: `Cell<T>` and `RefCell<T>`. `Cell<T>` implements interior
25 //! mutability by moving values in and out of the `Cell<T>`. To use references instead of values,
26 //! one must use the `RefCell<T>` type, acquiring a write lock before mutating. `Cell<T>` provides
27 //! methods to retrieve and change the current interior value:
29 //! - For types that implement [`Copy`], the [`get`](Cell::get) method retrieves the current
31 //! - For types that implement [`Default`], the [`take`](Cell::take) method replaces the current
32 //! interior value with [`Default::default()`] and returns the replaced value.
33 //! - For all types, the [`replace`](Cell::replace) method replaces the current interior value and
34 //! returns the replaced value and the [`into_inner`](Cell::into_inner) method consumes the
35 //! `Cell<T>` and returns the interior value. Additionally, the [`set`](Cell::set) method
36 //! replaces the interior value, dropping the replaced value.
38 //! `RefCell<T>` uses Rust's lifetimes to implement 'dynamic borrowing', a process whereby one can
39 //! claim temporary, exclusive, mutable access to the inner value. Borrows for `RefCell<T>`s are
40 //! tracked 'at runtime', unlike Rust's native reference types which are entirely tracked
41 //! statically, at compile time. Because `RefCell<T>` borrows are dynamic it is possible to attempt
42 //! to borrow a value that is already mutably borrowed; when this happens it results in thread
45 //! # When to choose interior mutability
47 //! The more common inherited mutability, where one must have unique access to mutate a value, is
48 //! one of the key language elements that enables Rust to reason strongly about pointer aliasing,
49 //! statically preventing crash bugs. Because of that, inherited mutability is preferred, and
50 //! interior mutability is something of a last resort. Since cell types enable mutation where it
51 //! would otherwise be disallowed though, there are occasions when interior mutability might be
52 //! appropriate, or even *must* be used, e.g.
54 //! * Introducing mutability 'inside' of something immutable
55 //! * Implementation details of logically-immutable methods.
56 //! * Mutating implementations of [`Clone`].
58 //! ## Introducing mutability 'inside' of something immutable
60 //! Many shared smart pointer types, including [`Rc<T>`] and [`Arc<T>`], provide containers that can
61 //! be cloned and shared between multiple parties. Because the contained values may be
62 //! multiply-aliased, they can only be borrowed with `&`, not `&mut`. Without cells it would be
63 //! impossible to mutate data inside of these smart pointers at all.
65 //! It's very common then to put a `RefCell<T>` inside shared pointer types to reintroduce
69 //! use std::cell::{RefCell, RefMut};
70 //! use std::collections::HashMap;
74 //! let shared_map: Rc<RefCell<_>> = Rc::new(RefCell::new(HashMap::new()));
75 //! // Create a new block to limit the scope of the dynamic borrow
77 //! let mut map: RefMut<_> = shared_map.borrow_mut();
78 //! map.insert("africa", 92388);
79 //! map.insert("kyoto", 11837);
80 //! map.insert("piccadilly", 11826);
81 //! map.insert("marbles", 38);
84 //! // Note that if we had not let the previous borrow of the cache fall out
85 //! // of scope then the subsequent borrow would cause a dynamic thread panic.
86 //! // This is the major hazard of using `RefCell`.
87 //! let total: i32 = shared_map.borrow().values().sum();
88 //! println!("{total}");
92 //! Note that this example uses `Rc<T>` and not `Arc<T>`. `RefCell<T>`s are for single-threaded
93 //! scenarios. Consider using [`RwLock<T>`] or [`Mutex<T>`] if you need shared mutability in a
94 //! multi-threaded situation.
96 //! ## Implementation details of logically-immutable methods
98 //! Occasionally it may be desirable not to expose in an API that there is mutation happening
99 //! "under the hood". This may be because logically the operation is immutable, but e.g., caching
100 //! forces the implementation to perform mutation; or because you must employ mutation to implement
101 //! a trait method that was originally defined to take `&self`.
104 //! # #![allow(dead_code)]
105 //! use std::cell::RefCell;
108 //! edges: Vec<(i32, i32)>,
109 //! span_tree_cache: RefCell<Option<Vec<(i32, i32)>>>
113 //! fn minimum_spanning_tree(&self) -> Vec<(i32, i32)> {
114 //! self.span_tree_cache.borrow_mut()
115 //! .get_or_insert_with(|| self.calc_span_tree())
119 //! fn calc_span_tree(&self) -> Vec<(i32, i32)> {
120 //! // Expensive computation goes here
126 //! ## Mutating implementations of `Clone`
128 //! This is simply a special - but common - case of the previous: hiding mutability for operations
129 //! that appear to be immutable. The [`clone`](Clone::clone) method is expected to not change the
130 //! source value, and is declared to take `&self`, not `&mut self`. Therefore, any mutation that
131 //! happens in the `clone` method must use cell types. For example, [`Rc<T>`] maintains its
132 //! reference counts within a `Cell<T>`.
135 //! use std::cell::Cell;
136 //! use std::ptr::NonNull;
137 //! use std::process::abort;
138 //! use std::marker::PhantomData;
140 //! struct Rc<T: ?Sized> {
141 //! ptr: NonNull<RcBox<T>>,
142 //! phantom: PhantomData<RcBox<T>>,
145 //! struct RcBox<T: ?Sized> {
146 //! strong: Cell<usize>,
147 //! refcount: Cell<usize>,
151 //! impl<T: ?Sized> Clone for Rc<T> {
152 //! fn clone(&self) -> Rc<T> {
153 //! self.inc_strong();
156 //! phantom: PhantomData,
161 //! trait RcBoxPtr<T: ?Sized> {
163 //! fn inner(&self) -> &RcBox<T>;
165 //! fn strong(&self) -> usize {
166 //! self.inner().strong.get()
169 //! fn inc_strong(&self) {
172 //! .set(self.strong()
174 //! .unwrap_or_else(|| abort() ));
178 //! impl<T: ?Sized> RcBoxPtr<T> for Rc<T> {
179 //! fn inner(&self) -> &RcBox<T> {
181 //! self.ptr.as_ref()
187 //! [`Arc<T>`]: ../../std/sync/struct.Arc.html
188 //! [`Rc<T>`]: ../../std/rc/struct.Rc.html
189 //! [`RwLock<T>`]: ../../std/sync/struct.RwLock.html
190 //! [`Mutex<T>`]: ../../std/sync/struct.Mutex.html
191 //! [`atomic`]: crate::sync::atomic
193 #![stable(feature = "rust1", since = "1.0.0")]
195 use crate::cmp::Ordering;
196 use crate::fmt::{self, Debug, Display};
197 use crate::marker::{PhantomData, Unsize};
199 use crate::ops::{CoerceUnsized, Deref, DerefMut};
200 use crate::ptr::{self, NonNull};
205 #[unstable(feature = "once_cell", issue = "74465")]
206 pub use lazy::LazyCell;
207 #[unstable(feature = "once_cell", issue = "74465")]
208 pub use once::OnceCell;
210 /// A mutable memory location.
214 /// In this example, you can see that `Cell<T>` enables mutation inside an
215 /// immutable struct. In other words, it enables "interior mutability".
218 /// use std::cell::Cell;
220 /// struct SomeStruct {
221 /// regular_field: u8,
222 /// special_field: Cell<u8>,
225 /// let my_struct = SomeStruct {
226 /// regular_field: 0,
227 /// special_field: Cell::new(1),
230 /// let new_value = 100;
232 /// // ERROR: `my_struct` is immutable
233 /// // my_struct.regular_field = new_value;
235 /// // WORKS: although `my_struct` is immutable, `special_field` is a `Cell`,
236 /// // which can always be mutated
237 /// my_struct.special_field.set(new_value);
238 /// assert_eq!(my_struct.special_field.get(), new_value);
241 /// See the [module-level documentation](self) for more.
242 #[stable(feature = "rust1", since = "1.0.0")]
244 pub struct Cell<T: ?Sized> {
245 value: UnsafeCell<T>,
248 #[stable(feature = "rust1", since = "1.0.0")]
249 unsafe impl<T: ?Sized> Send for Cell<T> where T: Send {}
251 // Note that this negative impl isn't strictly necessary for correctness,
252 // as `Cell` wraps `UnsafeCell`, which is itself `!Sync`.
253 // However, given how important `Cell`'s `!Sync`-ness is,
254 // having an explicit negative impl is nice for documentation purposes
255 // and results in nicer error messages.
256 #[stable(feature = "rust1", since = "1.0.0")]
257 impl<T: ?Sized> !Sync for Cell<T> {}
259 #[stable(feature = "rust1", since = "1.0.0")]
260 impl<T: Copy> Clone for Cell<T> {
262 fn clone(&self) -> Cell<T> {
263 Cell::new(self.get())
267 #[stable(feature = "rust1", since = "1.0.0")]
268 impl<T: Default> Default for Cell<T> {
269 /// Creates a `Cell<T>`, with the `Default` value for T.
271 fn default() -> Cell<T> {
272 Cell::new(Default::default())
276 #[stable(feature = "rust1", since = "1.0.0")]
277 impl<T: PartialEq + Copy> PartialEq for Cell<T> {
279 fn eq(&self, other: &Cell<T>) -> bool {
280 self.get() == other.get()
284 #[stable(feature = "cell_eq", since = "1.2.0")]
285 impl<T: Eq + Copy> Eq for Cell<T> {}
287 #[stable(feature = "cell_ord", since = "1.10.0")]
288 impl<T: PartialOrd + Copy> PartialOrd for Cell<T> {
290 fn partial_cmp(&self, other: &Cell<T>) -> Option<Ordering> {
291 self.get().partial_cmp(&other.get())
295 fn lt(&self, other: &Cell<T>) -> bool {
296 self.get() < other.get()
300 fn le(&self, other: &Cell<T>) -> bool {
301 self.get() <= other.get()
305 fn gt(&self, other: &Cell<T>) -> bool {
306 self.get() > other.get()
310 fn ge(&self, other: &Cell<T>) -> bool {
311 self.get() >= other.get()
315 #[stable(feature = "cell_ord", since = "1.10.0")]
316 impl<T: Ord + Copy> Ord for Cell<T> {
318 fn cmp(&self, other: &Cell<T>) -> Ordering {
319 self.get().cmp(&other.get())
323 #[stable(feature = "cell_from", since = "1.12.0")]
324 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
325 impl<T> const From<T> for Cell<T> {
326 /// Creates a new `Cell<T>` containing the given value.
327 fn from(t: T) -> Cell<T> {
333 /// Creates a new `Cell` containing the given value.
338 /// use std::cell::Cell;
340 /// let c = Cell::new(5);
342 #[stable(feature = "rust1", since = "1.0.0")]
343 #[rustc_const_stable(feature = "const_cell_new", since = "1.24.0")]
345 pub const fn new(value: T) -> Cell<T> {
346 Cell { value: UnsafeCell::new(value) }
349 /// Sets the contained value.
354 /// use std::cell::Cell;
356 /// let c = Cell::new(5);
361 #[stable(feature = "rust1", since = "1.0.0")]
362 pub fn set(&self, val: T) {
363 let old = self.replace(val);
367 /// Swaps the values of two `Cell`s.
368 /// Difference with `std::mem::swap` is that this function doesn't require `&mut` reference.
373 /// use std::cell::Cell;
375 /// let c1 = Cell::new(5i32);
376 /// let c2 = Cell::new(10i32);
378 /// assert_eq!(10, c1.get());
379 /// assert_eq!(5, c2.get());
382 #[stable(feature = "move_cell", since = "1.17.0")]
383 pub fn swap(&self, other: &Self) {
384 if ptr::eq(self, other) {
387 // SAFETY: This can be risky if called from separate threads, but `Cell`
388 // is `!Sync` so this won't happen. This also won't invalidate any
389 // pointers since `Cell` makes sure nothing else will be pointing into
390 // either of these `Cell`s.
392 ptr::swap(self.value.get(), other.value.get());
396 /// Replaces the contained value with `val`, and returns the old contained value.
401 /// use std::cell::Cell;
403 /// let cell = Cell::new(5);
404 /// assert_eq!(cell.get(), 5);
405 /// assert_eq!(cell.replace(10), 5);
406 /// assert_eq!(cell.get(), 10);
408 #[stable(feature = "move_cell", since = "1.17.0")]
409 pub fn replace(&self, val: T) -> T {
410 // SAFETY: This can cause data races if called from a separate thread,
411 // but `Cell` is `!Sync` so this won't happen.
412 mem::replace(unsafe { &mut *self.value.get() }, val)
415 /// Unwraps the value.
420 /// use std::cell::Cell;
422 /// let c = Cell::new(5);
423 /// let five = c.into_inner();
425 /// assert_eq!(five, 5);
427 #[stable(feature = "move_cell", since = "1.17.0")]
428 #[rustc_const_unstable(feature = "const_cell_into_inner", issue = "78729")]
429 pub const fn into_inner(self) -> T {
430 self.value.into_inner()
434 impl<T: Copy> Cell<T> {
435 /// Returns a copy of the contained value.
440 /// use std::cell::Cell;
442 /// let c = Cell::new(5);
444 /// let five = c.get();
447 #[stable(feature = "rust1", since = "1.0.0")]
448 pub fn get(&self) -> T {
449 // SAFETY: This can cause data races if called from a separate thread,
450 // but `Cell` is `!Sync` so this won't happen.
451 unsafe { *self.value.get() }
454 /// Updates the contained value using a function and returns the new value.
459 /// #![feature(cell_update)]
461 /// use std::cell::Cell;
463 /// let c = Cell::new(5);
464 /// let new = c.update(|x| x + 1);
466 /// assert_eq!(new, 6);
467 /// assert_eq!(c.get(), 6);
470 #[unstable(feature = "cell_update", issue = "50186")]
471 pub fn update<F>(&self, f: F) -> T
475 let old = self.get();
482 impl<T: ?Sized> Cell<T> {
483 /// Returns a raw pointer to the underlying data in this cell.
488 /// use std::cell::Cell;
490 /// let c = Cell::new(5);
492 /// let ptr = c.as_ptr();
495 #[stable(feature = "cell_as_ptr", since = "1.12.0")]
496 #[rustc_const_stable(feature = "const_cell_as_ptr", since = "1.32.0")]
497 pub const fn as_ptr(&self) -> *mut T {
501 /// Returns a mutable reference to the underlying data.
503 /// This call borrows `Cell` mutably (at compile-time) which guarantees
504 /// that we possess the only reference.
506 /// However be cautious: this method expects `self` to be mutable, which is
507 /// generally not the case when using a `Cell`. If you require interior
508 /// mutability by reference, consider using `RefCell` which provides
509 /// run-time checked mutable borrows through its [`borrow_mut`] method.
511 /// [`borrow_mut`]: RefCell::borrow_mut()
516 /// use std::cell::Cell;
518 /// let mut c = Cell::new(5);
519 /// *c.get_mut() += 1;
521 /// assert_eq!(c.get(), 6);
524 #[stable(feature = "cell_get_mut", since = "1.11.0")]
525 pub fn get_mut(&mut self) -> &mut T {
529 /// Returns a `&Cell<T>` from a `&mut T`
534 /// use std::cell::Cell;
536 /// let slice: &mut [i32] = &mut [1, 2, 3];
537 /// let cell_slice: &Cell<[i32]> = Cell::from_mut(slice);
538 /// let slice_cell: &[Cell<i32>] = cell_slice.as_slice_of_cells();
540 /// assert_eq!(slice_cell.len(), 3);
543 #[stable(feature = "as_cell", since = "1.37.0")]
544 pub fn from_mut(t: &mut T) -> &Cell<T> {
545 // SAFETY: `&mut` ensures unique access.
546 unsafe { &*(t as *mut T as *const Cell<T>) }
550 impl<T: Default> Cell<T> {
551 /// Takes the value of the cell, leaving `Default::default()` in its place.
556 /// use std::cell::Cell;
558 /// let c = Cell::new(5);
559 /// let five = c.take();
561 /// assert_eq!(five, 5);
562 /// assert_eq!(c.into_inner(), 0);
564 #[stable(feature = "move_cell", since = "1.17.0")]
565 pub fn take(&self) -> T {
566 self.replace(Default::default())
570 #[unstable(feature = "coerce_unsized", issue = "27732")]
571 impl<T: CoerceUnsized<U>, U> CoerceUnsized<Cell<U>> for Cell<T> {}
574 /// Returns a `&[Cell<T>]` from a `&Cell<[T]>`
579 /// use std::cell::Cell;
581 /// let slice: &mut [i32] = &mut [1, 2, 3];
582 /// let cell_slice: &Cell<[i32]> = Cell::from_mut(slice);
583 /// let slice_cell: &[Cell<i32>] = cell_slice.as_slice_of_cells();
585 /// assert_eq!(slice_cell.len(), 3);
587 #[stable(feature = "as_cell", since = "1.37.0")]
588 pub fn as_slice_of_cells(&self) -> &[Cell<T>] {
589 // SAFETY: `Cell<T>` has the same memory layout as `T`.
590 unsafe { &*(self as *const Cell<[T]> as *const [Cell<T>]) }
594 impl<T, const N: usize> Cell<[T; N]> {
595 /// Returns a `&[Cell<T>; N]` from a `&Cell<[T; N]>`
600 /// #![feature(as_array_of_cells)]
601 /// use std::cell::Cell;
603 /// let mut array: [i32; 3] = [1, 2, 3];
604 /// let cell_array: &Cell<[i32; 3]> = Cell::from_mut(&mut array);
605 /// let array_cell: &[Cell<i32>; 3] = cell_array.as_array_of_cells();
607 #[unstable(feature = "as_array_of_cells", issue = "88248")]
608 pub fn as_array_of_cells(&self) -> &[Cell<T>; N] {
609 // SAFETY: `Cell<T>` has the same memory layout as `T`.
610 unsafe { &*(self as *const Cell<[T; N]> as *const [Cell<T>; N]) }
614 /// A mutable memory location with dynamically checked borrow rules
616 /// See the [module-level documentation](self) for more.
617 #[stable(feature = "rust1", since = "1.0.0")]
618 pub struct RefCell<T: ?Sized> {
619 borrow: Cell<BorrowFlag>,
620 // Stores the location of the earliest currently active borrow.
621 // This gets updated whenever we go from having zero borrows
622 // to having a single borrow. When a borrow occurs, this gets included
623 // in the generated `BorrowError/`BorrowMutError`
624 #[cfg(feature = "debug_refcell")]
625 borrowed_at: Cell<Option<&'static crate::panic::Location<'static>>>,
626 value: UnsafeCell<T>,
629 /// An error returned by [`RefCell::try_borrow`].
630 #[stable(feature = "try_borrow", since = "1.13.0")]
632 pub struct BorrowError {
633 #[cfg(feature = "debug_refcell")]
634 location: &'static crate::panic::Location<'static>,
637 #[stable(feature = "try_borrow", since = "1.13.0")]
638 impl Debug for BorrowError {
639 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
640 let mut builder = f.debug_struct("BorrowError");
642 #[cfg(feature = "debug_refcell")]
643 builder.field("location", self.location);
649 #[stable(feature = "try_borrow", since = "1.13.0")]
650 impl Display for BorrowError {
651 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
652 Display::fmt("already mutably borrowed", f)
656 /// An error returned by [`RefCell::try_borrow_mut`].
657 #[stable(feature = "try_borrow", since = "1.13.0")]
659 pub struct BorrowMutError {
660 #[cfg(feature = "debug_refcell")]
661 location: &'static crate::panic::Location<'static>,
664 #[stable(feature = "try_borrow", since = "1.13.0")]
665 impl Debug for BorrowMutError {
666 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
667 let mut builder = f.debug_struct("BorrowMutError");
669 #[cfg(feature = "debug_refcell")]
670 builder.field("location", self.location);
676 #[stable(feature = "try_borrow", since = "1.13.0")]
677 impl Display for BorrowMutError {
678 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
679 Display::fmt("already borrowed", f)
683 // Positive values represent the number of `Ref` active. Negative values
684 // represent the number of `RefMut` active. Multiple `RefMut`s can only be
685 // active at a time if they refer to distinct, nonoverlapping components of a
686 // `RefCell` (e.g., different ranges of a slice).
688 // `Ref` and `RefMut` are both two words in size, and so there will likely never
689 // be enough `Ref`s or `RefMut`s in existence to overflow half of the `usize`
690 // range. Thus, a `BorrowFlag` will probably never overflow or underflow.
691 // However, this is not a guarantee, as a pathological program could repeatedly
692 // create and then mem::forget `Ref`s or `RefMut`s. Thus, all code must
693 // explicitly check for overflow and underflow in order to avoid unsafety, or at
694 // least behave correctly in the event that overflow or underflow happens (e.g.,
695 // see BorrowRef::new).
696 type BorrowFlag = isize;
697 const UNUSED: BorrowFlag = 0;
700 fn is_writing(x: BorrowFlag) -> bool {
705 fn is_reading(x: BorrowFlag) -> bool {
710 /// Creates a new `RefCell` containing `value`.
715 /// use std::cell::RefCell;
717 /// let c = RefCell::new(5);
719 #[stable(feature = "rust1", since = "1.0.0")]
720 #[rustc_const_stable(feature = "const_refcell_new", since = "1.24.0")]
722 pub const fn new(value: T) -> RefCell<T> {
724 value: UnsafeCell::new(value),
725 borrow: Cell::new(UNUSED),
726 #[cfg(feature = "debug_refcell")]
727 borrowed_at: Cell::new(None),
731 /// Consumes the `RefCell`, returning the wrapped value.
736 /// use std::cell::RefCell;
738 /// let c = RefCell::new(5);
740 /// let five = c.into_inner();
742 #[stable(feature = "rust1", since = "1.0.0")]
743 #[rustc_const_unstable(feature = "const_cell_into_inner", issue = "78729")]
745 pub const fn into_inner(self) -> T {
746 // Since this function takes `self` (the `RefCell`) by value, the
747 // compiler statically verifies that it is not currently borrowed.
748 self.value.into_inner()
751 /// Replaces the wrapped value with a new one, returning the old value,
752 /// without deinitializing either one.
754 /// This function corresponds to [`std::mem::replace`](../mem/fn.replace.html).
758 /// Panics if the value is currently borrowed.
763 /// use std::cell::RefCell;
764 /// let cell = RefCell::new(5);
765 /// let old_value = cell.replace(6);
766 /// assert_eq!(old_value, 5);
767 /// assert_eq!(cell, RefCell::new(6));
770 #[stable(feature = "refcell_replace", since = "1.24.0")]
772 pub fn replace(&self, t: T) -> T {
773 mem::replace(&mut *self.borrow_mut(), t)
776 /// Replaces the wrapped value with a new one computed from `f`, returning
777 /// the old value, without deinitializing either one.
781 /// Panics if the value is currently borrowed.
786 /// use std::cell::RefCell;
787 /// let cell = RefCell::new(5);
788 /// let old_value = cell.replace_with(|&mut old| old + 1);
789 /// assert_eq!(old_value, 5);
790 /// assert_eq!(cell, RefCell::new(6));
793 #[stable(feature = "refcell_replace_swap", since = "1.35.0")]
795 pub fn replace_with<F: FnOnce(&mut T) -> T>(&self, f: F) -> T {
796 let mut_borrow = &mut *self.borrow_mut();
797 let replacement = f(mut_borrow);
798 mem::replace(mut_borrow, replacement)
801 /// Swaps the wrapped value of `self` with the wrapped value of `other`,
802 /// without deinitializing either one.
804 /// This function corresponds to [`std::mem::swap`](../mem/fn.swap.html).
808 /// Panics if the value in either `RefCell` is currently borrowed.
813 /// use std::cell::RefCell;
814 /// let c = RefCell::new(5);
815 /// let d = RefCell::new(6);
817 /// assert_eq!(c, RefCell::new(6));
818 /// assert_eq!(d, RefCell::new(5));
821 #[stable(feature = "refcell_swap", since = "1.24.0")]
822 pub fn swap(&self, other: &Self) {
823 mem::swap(&mut *self.borrow_mut(), &mut *other.borrow_mut())
827 impl<T: ?Sized> RefCell<T> {
828 /// Immutably borrows the wrapped value.
830 /// The borrow lasts until the returned `Ref` exits scope. Multiple
831 /// immutable borrows can be taken out at the same time.
835 /// Panics if the value is currently mutably borrowed. For a non-panicking variant, use
836 /// [`try_borrow`](#method.try_borrow).
841 /// use std::cell::RefCell;
843 /// let c = RefCell::new(5);
845 /// let borrowed_five = c.borrow();
846 /// let borrowed_five2 = c.borrow();
849 /// An example of panic:
852 /// use std::cell::RefCell;
854 /// let c = RefCell::new(5);
856 /// let m = c.borrow_mut();
857 /// let b = c.borrow(); // this causes a panic
859 #[stable(feature = "rust1", since = "1.0.0")]
862 pub fn borrow(&self) -> Ref<'_, T> {
863 self.try_borrow().expect("already mutably borrowed")
866 /// Immutably borrows the wrapped value, returning an error if the value is currently mutably
869 /// The borrow lasts until the returned `Ref` exits scope. Multiple immutable borrows can be
870 /// taken out at the same time.
872 /// This is the non-panicking variant of [`borrow`](#method.borrow).
877 /// use std::cell::RefCell;
879 /// let c = RefCell::new(5);
882 /// let m = c.borrow_mut();
883 /// assert!(c.try_borrow().is_err());
887 /// let m = c.borrow();
888 /// assert!(c.try_borrow().is_ok());
891 #[stable(feature = "try_borrow", since = "1.13.0")]
893 #[cfg_attr(feature = "debug_refcell", track_caller)]
894 pub fn try_borrow(&self) -> Result<Ref<'_, T>, BorrowError> {
895 match BorrowRef::new(&self.borrow) {
897 #[cfg(feature = "debug_refcell")]
899 // `borrowed_at` is always the *first* active borrow
900 if b.borrow.get() == 1 {
901 self.borrowed_at.set(Some(crate::panic::Location::caller()));
905 // SAFETY: `BorrowRef` ensures that there is only immutable access
906 // to the value while borrowed.
907 let value = unsafe { NonNull::new_unchecked(self.value.get()) };
908 Ok(Ref { value, borrow: b })
910 None => Err(BorrowError {
911 // If a borrow occurred, then we must already have an outstanding borrow,
912 // so `borrowed_at` will be `Some`
913 #[cfg(feature = "debug_refcell")]
914 location: self.borrowed_at.get().unwrap(),
919 /// Mutably borrows the wrapped value.
921 /// The borrow lasts until the returned `RefMut` or all `RefMut`s derived
922 /// from it exit scope. The value cannot be borrowed while this borrow is
927 /// Panics if the value is currently borrowed. For a non-panicking variant, use
928 /// [`try_borrow_mut`](#method.try_borrow_mut).
933 /// use std::cell::RefCell;
935 /// let c = RefCell::new("hello".to_owned());
937 /// *c.borrow_mut() = "bonjour".to_owned();
939 /// assert_eq!(&*c.borrow(), "bonjour");
942 /// An example of panic:
945 /// use std::cell::RefCell;
947 /// let c = RefCell::new(5);
948 /// let m = c.borrow();
950 /// let b = c.borrow_mut(); // this causes a panic
952 #[stable(feature = "rust1", since = "1.0.0")]
955 pub fn borrow_mut(&self) -> RefMut<'_, T> {
956 self.try_borrow_mut().expect("already borrowed")
959 /// Mutably borrows the wrapped value, returning an error if the value is currently borrowed.
961 /// The borrow lasts until the returned `RefMut` or all `RefMut`s derived
962 /// from it exit scope. The value cannot be borrowed while this borrow is
965 /// This is the non-panicking variant of [`borrow_mut`](#method.borrow_mut).
970 /// use std::cell::RefCell;
972 /// let c = RefCell::new(5);
975 /// let m = c.borrow();
976 /// assert!(c.try_borrow_mut().is_err());
979 /// assert!(c.try_borrow_mut().is_ok());
981 #[stable(feature = "try_borrow", since = "1.13.0")]
983 #[cfg_attr(feature = "debug_refcell", track_caller)]
984 pub fn try_borrow_mut(&self) -> Result<RefMut<'_, T>, BorrowMutError> {
985 match BorrowRefMut::new(&self.borrow) {
987 #[cfg(feature = "debug_refcell")]
989 self.borrowed_at.set(Some(crate::panic::Location::caller()));
992 // SAFETY: `BorrowRefMut` guarantees unique access.
993 let value = unsafe { NonNull::new_unchecked(self.value.get()) };
994 Ok(RefMut { value, borrow: b, marker: PhantomData })
996 None => Err(BorrowMutError {
997 // If a borrow occurred, then we must already have an outstanding borrow,
998 // so `borrowed_at` will be `Some`
999 #[cfg(feature = "debug_refcell")]
1000 location: self.borrowed_at.get().unwrap(),
1005 /// Returns a raw pointer to the underlying data in this cell.
1010 /// use std::cell::RefCell;
1012 /// let c = RefCell::new(5);
1014 /// let ptr = c.as_ptr();
1017 #[stable(feature = "cell_as_ptr", since = "1.12.0")]
1018 pub fn as_ptr(&self) -> *mut T {
1022 /// Returns a mutable reference to the underlying data.
1024 /// This call borrows `RefCell` mutably (at compile-time) so there is no
1025 /// need for dynamic checks.
1027 /// However be cautious: this method expects `self` to be mutable, which is
1028 /// generally not the case when using a `RefCell`. Take a look at the
1029 /// [`borrow_mut`] method instead if `self` isn't mutable.
1031 /// Also, please be aware that this method is only for special circumstances and is usually
1032 /// not what you want. In case of doubt, use [`borrow_mut`] instead.
1034 /// [`borrow_mut`]: RefCell::borrow_mut()
1039 /// use std::cell::RefCell;
1041 /// let mut c = RefCell::new(5);
1042 /// *c.get_mut() += 1;
1044 /// assert_eq!(c, RefCell::new(6));
1047 #[stable(feature = "cell_get_mut", since = "1.11.0")]
1048 pub fn get_mut(&mut self) -> &mut T {
1049 self.value.get_mut()
1052 /// Undo the effect of leaked guards on the borrow state of the `RefCell`.
1054 /// This call is similar to [`get_mut`] but more specialized. It borrows `RefCell` mutably to
1055 /// ensure no borrows exist and then resets the state tracking shared borrows. This is relevant
1056 /// if some `Ref` or `RefMut` borrows have been leaked.
1058 /// [`get_mut`]: RefCell::get_mut()
1063 /// #![feature(cell_leak)]
1064 /// use std::cell::RefCell;
1066 /// let mut c = RefCell::new(0);
1067 /// std::mem::forget(c.borrow_mut());
1069 /// assert!(c.try_borrow().is_err());
1071 /// assert!(c.try_borrow().is_ok());
1073 #[unstable(feature = "cell_leak", issue = "69099")]
1074 pub fn undo_leak(&mut self) -> &mut T {
1075 *self.borrow.get_mut() = UNUSED;
1079 /// Immutably borrows the wrapped value, returning an error if the value is
1080 /// currently mutably borrowed.
1084 /// Unlike `RefCell::borrow`, this method is unsafe because it does not
1085 /// return a `Ref`, thus leaving the borrow flag untouched. Mutably
1086 /// borrowing the `RefCell` while the reference returned by this method
1087 /// is alive is undefined behaviour.
1092 /// use std::cell::RefCell;
1094 /// let c = RefCell::new(5);
1097 /// let m = c.borrow_mut();
1098 /// assert!(unsafe { c.try_borrow_unguarded() }.is_err());
1102 /// let m = c.borrow();
1103 /// assert!(unsafe { c.try_borrow_unguarded() }.is_ok());
1106 #[stable(feature = "borrow_state", since = "1.37.0")]
1108 pub unsafe fn try_borrow_unguarded(&self) -> Result<&T, BorrowError> {
1109 if !is_writing(self.borrow.get()) {
1110 // SAFETY: We check that nobody is actively writing now, but it is
1111 // the caller's responsibility to ensure that nobody writes until
1112 // the returned reference is no longer in use.
1113 // Also, `self.value.get()` refers to the value owned by `self`
1114 // and is thus guaranteed to be valid for the lifetime of `self`.
1115 Ok(unsafe { &*self.value.get() })
1118 // If a borrow occurred, then we must already have an outstanding borrow,
1119 // so `borrowed_at` will be `Some`
1120 #[cfg(feature = "debug_refcell")]
1121 location: self.borrowed_at.get().unwrap(),
1127 impl<T: Default> RefCell<T> {
1128 /// Takes the wrapped value, leaving `Default::default()` in its place.
1132 /// Panics if the value is currently borrowed.
1137 /// use std::cell::RefCell;
1139 /// let c = RefCell::new(5);
1140 /// let five = c.take();
1142 /// assert_eq!(five, 5);
1143 /// assert_eq!(c.into_inner(), 0);
1145 #[stable(feature = "refcell_take", since = "1.50.0")]
1146 pub fn take(&self) -> T {
1147 self.replace(Default::default())
1151 #[stable(feature = "rust1", since = "1.0.0")]
1152 unsafe impl<T: ?Sized> Send for RefCell<T> where T: Send {}
1154 #[stable(feature = "rust1", since = "1.0.0")]
1155 impl<T: ?Sized> !Sync for RefCell<T> {}
1157 #[stable(feature = "rust1", since = "1.0.0")]
1158 impl<T: Clone> Clone for RefCell<T> {
1161 /// Panics if the value is currently mutably borrowed.
1164 fn clone(&self) -> RefCell<T> {
1165 RefCell::new(self.borrow().clone())
1170 /// Panics if `other` is currently mutably borrowed.
1173 fn clone_from(&mut self, other: &Self) {
1174 self.get_mut().clone_from(&other.borrow())
1178 #[stable(feature = "rust1", since = "1.0.0")]
1179 impl<T: Default> Default for RefCell<T> {
1180 /// Creates a `RefCell<T>`, with the `Default` value for T.
1182 fn default() -> RefCell<T> {
1183 RefCell::new(Default::default())
1187 #[stable(feature = "rust1", since = "1.0.0")]
1188 impl<T: ?Sized + PartialEq> PartialEq for RefCell<T> {
1191 /// Panics if the value in either `RefCell` is currently borrowed.
1193 fn eq(&self, other: &RefCell<T>) -> bool {
1194 *self.borrow() == *other.borrow()
1198 #[stable(feature = "cell_eq", since = "1.2.0")]
1199 impl<T: ?Sized + Eq> Eq for RefCell<T> {}
1201 #[stable(feature = "cell_ord", since = "1.10.0")]
1202 impl<T: ?Sized + PartialOrd> PartialOrd for RefCell<T> {
1205 /// Panics if the value in either `RefCell` is currently borrowed.
1207 fn partial_cmp(&self, other: &RefCell<T>) -> Option<Ordering> {
1208 self.borrow().partial_cmp(&*other.borrow())
1213 /// Panics if the value in either `RefCell` is currently borrowed.
1215 fn lt(&self, other: &RefCell<T>) -> bool {
1216 *self.borrow() < *other.borrow()
1221 /// Panics if the value in either `RefCell` is currently borrowed.
1223 fn le(&self, other: &RefCell<T>) -> bool {
1224 *self.borrow() <= *other.borrow()
1229 /// Panics if the value in either `RefCell` is currently borrowed.
1231 fn gt(&self, other: &RefCell<T>) -> bool {
1232 *self.borrow() > *other.borrow()
1237 /// Panics if the value in either `RefCell` is currently borrowed.
1239 fn ge(&self, other: &RefCell<T>) -> bool {
1240 *self.borrow() >= *other.borrow()
1244 #[stable(feature = "cell_ord", since = "1.10.0")]
1245 impl<T: ?Sized + Ord> Ord for RefCell<T> {
1248 /// Panics if the value in either `RefCell` is currently borrowed.
1250 fn cmp(&self, other: &RefCell<T>) -> Ordering {
1251 self.borrow().cmp(&*other.borrow())
1255 #[stable(feature = "cell_from", since = "1.12.0")]
1256 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
1257 impl<T> const From<T> for RefCell<T> {
1258 /// Creates a new `RefCell<T>` containing the given value.
1259 fn from(t: T) -> RefCell<T> {
1264 #[unstable(feature = "coerce_unsized", issue = "27732")]
1265 impl<T: CoerceUnsized<U>, U> CoerceUnsized<RefCell<U>> for RefCell<T> {}
1267 struct BorrowRef<'b> {
1268 borrow: &'b Cell<BorrowFlag>,
1271 impl<'b> BorrowRef<'b> {
1273 fn new(borrow: &'b Cell<BorrowFlag>) -> Option<BorrowRef<'b>> {
1274 let b = borrow.get().wrapping_add(1);
1276 // Incrementing borrow can result in a non-reading value (<= 0) in these cases:
1277 // 1. It was < 0, i.e. there are writing borrows, so we can't allow a read borrow
1278 // due to Rust's reference aliasing rules
1279 // 2. It was isize::MAX (the max amount of reading borrows) and it overflowed
1280 // into isize::MIN (the max amount of writing borrows) so we can't allow
1281 // an additional read borrow because isize can't represent so many read borrows
1282 // (this can only happen if you mem::forget more than a small constant amount of
1283 // `Ref`s, which is not good practice)
1286 // Incrementing borrow can result in a reading value (> 0) in these cases:
1287 // 1. It was = 0, i.e. it wasn't borrowed, and we are taking the first read borrow
1288 // 2. It was > 0 and < isize::MAX, i.e. there were read borrows, and isize
1289 // is large enough to represent having one more read borrow
1291 Some(BorrowRef { borrow })
1296 impl Drop for BorrowRef<'_> {
1298 fn drop(&mut self) {
1299 let borrow = self.borrow.get();
1300 debug_assert!(is_reading(borrow));
1301 self.borrow.set(borrow - 1);
1305 impl Clone for BorrowRef<'_> {
1307 fn clone(&self) -> Self {
1308 // Since this Ref exists, we know the borrow flag
1309 // is a reading borrow.
1310 let borrow = self.borrow.get();
1311 debug_assert!(is_reading(borrow));
1312 // Prevent the borrow counter from overflowing into
1313 // a writing borrow.
1314 assert!(borrow != isize::MAX);
1315 self.borrow.set(borrow + 1);
1316 BorrowRef { borrow: self.borrow }
1320 /// Wraps a borrowed reference to a value in a `RefCell` box.
1321 /// A wrapper type for an immutably borrowed value from a `RefCell<T>`.
1323 /// See the [module-level documentation](self) for more.
1324 #[stable(feature = "rust1", since = "1.0.0")]
1325 #[must_not_suspend = "holding a Ref across suspend points can cause BorrowErrors"]
1326 pub struct Ref<'b, T: ?Sized + 'b> {
1327 // NB: we use a pointer instead of `&'b T` to avoid `noalias` violations, because a
1328 // `Ref` argument doesn't hold immutability for its whole scope, only until it drops.
1329 // `NonNull` is also covariant over `T`, just like we would have with `&T`.
1331 borrow: BorrowRef<'b>,
1334 #[stable(feature = "rust1", since = "1.0.0")]
1335 impl<T: ?Sized> Deref for Ref<'_, T> {
1339 fn deref(&self) -> &T {
1340 // SAFETY: the value is accessible as long as we hold our borrow.
1341 unsafe { self.value.as_ref() }
1345 impl<'b, T: ?Sized> Ref<'b, T> {
1348 /// The `RefCell` is already immutably borrowed, so this cannot fail.
1350 /// This is an associated function that needs to be used as
1351 /// `Ref::clone(...)`. A `Clone` implementation or a method would interfere
1352 /// with the widespread use of `r.borrow().clone()` to clone the contents of
1354 #[stable(feature = "cell_extras", since = "1.15.0")]
1357 pub fn clone(orig: &Ref<'b, T>) -> Ref<'b, T> {
1358 Ref { value: orig.value, borrow: orig.borrow.clone() }
1361 /// Makes a new `Ref` for a component of the borrowed data.
1363 /// The `RefCell` is already immutably borrowed, so this cannot fail.
1365 /// This is an associated function that needs to be used as `Ref::map(...)`.
1366 /// A method would interfere with methods of the same name on the contents
1367 /// of a `RefCell` used through `Deref`.
1372 /// use std::cell::{RefCell, Ref};
1374 /// let c = RefCell::new((5, 'b'));
1375 /// let b1: Ref<(u32, char)> = c.borrow();
1376 /// let b2: Ref<u32> = Ref::map(b1, |t| &t.0);
1377 /// assert_eq!(*b2, 5)
1379 #[stable(feature = "cell_map", since = "1.8.0")]
1381 pub fn map<U: ?Sized, F>(orig: Ref<'b, T>, f: F) -> Ref<'b, U>
1383 F: FnOnce(&T) -> &U,
1385 Ref { value: NonNull::from(f(&*orig)), borrow: orig.borrow }
1388 /// Makes a new `Ref` for an optional component of the borrowed data. The
1389 /// original guard is returned as an `Err(..)` if the closure returns
1392 /// The `RefCell` is already immutably borrowed, so this cannot fail.
1394 /// This is an associated function that needs to be used as
1395 /// `Ref::filter_map(...)`. A method would interfere with methods of the same
1396 /// name on the contents of a `RefCell` used through `Deref`.
1401 /// use std::cell::{RefCell, Ref};
1403 /// let c = RefCell::new(vec![1, 2, 3]);
1404 /// let b1: Ref<Vec<u32>> = c.borrow();
1405 /// let b2: Result<Ref<u32>, _> = Ref::filter_map(b1, |v| v.get(1));
1406 /// assert_eq!(*b2.unwrap(), 2);
1408 #[stable(feature = "cell_filter_map", since = "1.63.0")]
1410 pub fn filter_map<U: ?Sized, F>(orig: Ref<'b, T>, f: F) -> Result<Ref<'b, U>, Self>
1412 F: FnOnce(&T) -> Option<&U>,
1415 Some(value) => Ok(Ref { value: NonNull::from(value), borrow: orig.borrow }),
1420 /// Splits a `Ref` into multiple `Ref`s for different components of the
1423 /// The `RefCell` is already immutably borrowed, so this cannot fail.
1425 /// This is an associated function that needs to be used as
1426 /// `Ref::map_split(...)`. A method would interfere with methods of the same
1427 /// name on the contents of a `RefCell` used through `Deref`.
1432 /// use std::cell::{Ref, RefCell};
1434 /// let cell = RefCell::new([1, 2, 3, 4]);
1435 /// let borrow = cell.borrow();
1436 /// let (begin, end) = Ref::map_split(borrow, |slice| slice.split_at(2));
1437 /// assert_eq!(*begin, [1, 2]);
1438 /// assert_eq!(*end, [3, 4]);
1440 #[stable(feature = "refcell_map_split", since = "1.35.0")]
1442 pub fn map_split<U: ?Sized, V: ?Sized, F>(orig: Ref<'b, T>, f: F) -> (Ref<'b, U>, Ref<'b, V>)
1444 F: FnOnce(&T) -> (&U, &V),
1446 let (a, b) = f(&*orig);
1447 let borrow = orig.borrow.clone();
1449 Ref { value: NonNull::from(a), borrow },
1450 Ref { value: NonNull::from(b), borrow: orig.borrow },
1454 /// Convert into a reference to the underlying data.
1456 /// The underlying `RefCell` can never be mutably borrowed from again and will always appear
1457 /// already immutably borrowed. It is not a good idea to leak more than a constant number of
1458 /// references. The `RefCell` can be immutably borrowed again if only a smaller number of leaks
1459 /// have occurred in total.
1461 /// This is an associated function that needs to be used as
1462 /// `Ref::leak(...)`. A method would interfere with methods of the
1463 /// same name on the contents of a `RefCell` used through `Deref`.
1468 /// #![feature(cell_leak)]
1469 /// use std::cell::{RefCell, Ref};
1470 /// let cell = RefCell::new(0);
1472 /// let value = Ref::leak(cell.borrow());
1473 /// assert_eq!(*value, 0);
1475 /// assert!(cell.try_borrow().is_ok());
1476 /// assert!(cell.try_borrow_mut().is_err());
1478 #[unstable(feature = "cell_leak", issue = "69099")]
1479 pub fn leak(orig: Ref<'b, T>) -> &'b T {
1480 // By forgetting this Ref we ensure that the borrow counter in the RefCell can't go back to
1481 // UNUSED within the lifetime `'b`. Resetting the reference tracking state would require a
1482 // unique reference to the borrowed RefCell. No further mutable references can be created
1483 // from the original cell.
1484 mem::forget(orig.borrow);
1485 // SAFETY: after forgetting, we can form a reference for the rest of lifetime `'b`.
1486 unsafe { orig.value.as_ref() }
1490 #[unstable(feature = "coerce_unsized", issue = "27732")]
1491 impl<'b, T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Ref<'b, U>> for Ref<'b, T> {}
1493 #[stable(feature = "std_guard_impls", since = "1.20.0")]
1494 impl<T: ?Sized + fmt::Display> fmt::Display for Ref<'_, T> {
1495 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1500 impl<'b, T: ?Sized> RefMut<'b, T> {
1501 /// Makes a new `RefMut` for a component of the borrowed data, e.g., an enum
1504 /// The `RefCell` is already mutably borrowed, so this cannot fail.
1506 /// This is an associated function that needs to be used as
1507 /// `RefMut::map(...)`. A method would interfere with methods of the same
1508 /// name on the contents of a `RefCell` used through `Deref`.
1513 /// use std::cell::{RefCell, RefMut};
1515 /// let c = RefCell::new((5, 'b'));
1517 /// let b1: RefMut<(u32, char)> = c.borrow_mut();
1518 /// let mut b2: RefMut<u32> = RefMut::map(b1, |t| &mut t.0);
1519 /// assert_eq!(*b2, 5);
1522 /// assert_eq!(*c.borrow(), (42, 'b'));
1524 #[stable(feature = "cell_map", since = "1.8.0")]
1526 pub fn map<U: ?Sized, F>(mut orig: RefMut<'b, T>, f: F) -> RefMut<'b, U>
1528 F: FnOnce(&mut T) -> &mut U,
1530 let value = NonNull::from(f(&mut *orig));
1531 RefMut { value, borrow: orig.borrow, marker: PhantomData }
1534 /// Makes a new `RefMut` for an optional component of the borrowed data. The
1535 /// original guard is returned as an `Err(..)` if the closure returns
1538 /// The `RefCell` is already mutably borrowed, so this cannot fail.
1540 /// This is an associated function that needs to be used as
1541 /// `RefMut::filter_map(...)`. A method would interfere with methods of the
1542 /// same name on the contents of a `RefCell` used through `Deref`.
1547 /// use std::cell::{RefCell, RefMut};
1549 /// let c = RefCell::new(vec![1, 2, 3]);
1552 /// let b1: RefMut<Vec<u32>> = c.borrow_mut();
1553 /// let mut b2: Result<RefMut<u32>, _> = RefMut::filter_map(b1, |v| v.get_mut(1));
1555 /// if let Ok(mut b2) = b2 {
1560 /// assert_eq!(*c.borrow(), vec![1, 4, 3]);
1562 #[stable(feature = "cell_filter_map", since = "1.63.0")]
1564 pub fn filter_map<U: ?Sized, F>(mut orig: RefMut<'b, T>, f: F) -> Result<RefMut<'b, U>, Self>
1566 F: FnOnce(&mut T) -> Option<&mut U>,
1568 // SAFETY: function holds onto an exclusive reference for the duration
1569 // of its call through `orig`, and the pointer is only de-referenced
1570 // inside of the function call never allowing the exclusive reference to
1572 match f(&mut *orig) {
1574 Ok(RefMut { value: NonNull::from(value), borrow: orig.borrow, marker: PhantomData })
1580 /// Splits a `RefMut` into multiple `RefMut`s for different components of the
1583 /// The underlying `RefCell` will remain mutably borrowed until both
1584 /// returned `RefMut`s go out of scope.
1586 /// The `RefCell` is already mutably borrowed, so this cannot fail.
1588 /// This is an associated function that needs to be used as
1589 /// `RefMut::map_split(...)`. A method would interfere with methods of the
1590 /// same name on the contents of a `RefCell` used through `Deref`.
1595 /// use std::cell::{RefCell, RefMut};
1597 /// let cell = RefCell::new([1, 2, 3, 4]);
1598 /// let borrow = cell.borrow_mut();
1599 /// let (mut begin, mut end) = RefMut::map_split(borrow, |slice| slice.split_at_mut(2));
1600 /// assert_eq!(*begin, [1, 2]);
1601 /// assert_eq!(*end, [3, 4]);
1602 /// begin.copy_from_slice(&[4, 3]);
1603 /// end.copy_from_slice(&[2, 1]);
1605 #[stable(feature = "refcell_map_split", since = "1.35.0")]
1607 pub fn map_split<U: ?Sized, V: ?Sized, F>(
1608 mut orig: RefMut<'b, T>,
1610 ) -> (RefMut<'b, U>, RefMut<'b, V>)
1612 F: FnOnce(&mut T) -> (&mut U, &mut V),
1614 let borrow = orig.borrow.clone();
1615 let (a, b) = f(&mut *orig);
1617 RefMut { value: NonNull::from(a), borrow, marker: PhantomData },
1618 RefMut { value: NonNull::from(b), borrow: orig.borrow, marker: PhantomData },
1622 /// Convert into a mutable reference to the underlying data.
1624 /// The underlying `RefCell` can not be borrowed from again and will always appear already
1625 /// mutably borrowed, making the returned reference the only to the interior.
1627 /// This is an associated function that needs to be used as
1628 /// `RefMut::leak(...)`. A method would interfere with methods of the
1629 /// same name on the contents of a `RefCell` used through `Deref`.
1634 /// #![feature(cell_leak)]
1635 /// use std::cell::{RefCell, RefMut};
1636 /// let cell = RefCell::new(0);
1638 /// let value = RefMut::leak(cell.borrow_mut());
1639 /// assert_eq!(*value, 0);
1642 /// assert!(cell.try_borrow_mut().is_err());
1644 #[unstable(feature = "cell_leak", issue = "69099")]
1645 pub fn leak(mut orig: RefMut<'b, T>) -> &'b mut T {
1646 // By forgetting this BorrowRefMut we ensure that the borrow counter in the RefCell can't
1647 // go back to UNUSED within the lifetime `'b`. Resetting the reference tracking state would
1648 // require a unique reference to the borrowed RefCell. No further references can be created
1649 // from the original cell within that lifetime, making the current borrow the only
1650 // reference for the remaining lifetime.
1651 mem::forget(orig.borrow);
1652 // SAFETY: after forgetting, we can form a reference for the rest of lifetime `'b`.
1653 unsafe { orig.value.as_mut() }
1657 struct BorrowRefMut<'b> {
1658 borrow: &'b Cell<BorrowFlag>,
1661 impl Drop for BorrowRefMut<'_> {
1663 fn drop(&mut self) {
1664 let borrow = self.borrow.get();
1665 debug_assert!(is_writing(borrow));
1666 self.borrow.set(borrow + 1);
1670 impl<'b> BorrowRefMut<'b> {
1672 fn new(borrow: &'b Cell<BorrowFlag>) -> Option<BorrowRefMut<'b>> {
1673 // NOTE: Unlike BorrowRefMut::clone, new is called to create the initial
1674 // mutable reference, and so there must currently be no existing
1675 // references. Thus, while clone increments the mutable refcount, here
1676 // we explicitly only allow going from UNUSED to UNUSED - 1.
1677 match borrow.get() {
1679 borrow.set(UNUSED - 1);
1680 Some(BorrowRefMut { borrow })
1686 // Clones a `BorrowRefMut`.
1688 // This is only valid if each `BorrowRefMut` is used to track a mutable
1689 // reference to a distinct, nonoverlapping range of the original object.
1690 // This isn't in a Clone impl so that code doesn't call this implicitly.
1692 fn clone(&self) -> BorrowRefMut<'b> {
1693 let borrow = self.borrow.get();
1694 debug_assert!(is_writing(borrow));
1695 // Prevent the borrow counter from underflowing.
1696 assert!(borrow != isize::MIN);
1697 self.borrow.set(borrow - 1);
1698 BorrowRefMut { borrow: self.borrow }
1702 /// A wrapper type for a mutably borrowed value from a `RefCell<T>`.
1704 /// See the [module-level documentation](self) for more.
1705 #[stable(feature = "rust1", since = "1.0.0")]
1706 #[must_not_suspend = "holding a RefMut across suspend points can cause BorrowErrors"]
1707 pub struct RefMut<'b, T: ?Sized + 'b> {
1708 // NB: we use a pointer instead of `&'b mut T` to avoid `noalias` violations, because a
1709 // `RefMut` argument doesn't hold exclusivity for its whole scope, only until it drops.
1711 borrow: BorrowRefMut<'b>,
1712 // `NonNull` is covariant over `T`, so we need to reintroduce invariance.
1713 marker: PhantomData<&'b mut T>,
1716 #[stable(feature = "rust1", since = "1.0.0")]
1717 impl<T: ?Sized> Deref for RefMut<'_, T> {
1721 fn deref(&self) -> &T {
1722 // SAFETY: the value is accessible as long as we hold our borrow.
1723 unsafe { self.value.as_ref() }
1727 #[stable(feature = "rust1", since = "1.0.0")]
1728 impl<T: ?Sized> DerefMut for RefMut<'_, T> {
1730 fn deref_mut(&mut self) -> &mut T {
1731 // SAFETY: the value is accessible as long as we hold our borrow.
1732 unsafe { self.value.as_mut() }
1736 #[unstable(feature = "coerce_unsized", issue = "27732")]
1737 impl<'b, T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<RefMut<'b, U>> for RefMut<'b, T> {}
1739 #[stable(feature = "std_guard_impls", since = "1.20.0")]
1740 impl<T: ?Sized + fmt::Display> fmt::Display for RefMut<'_, T> {
1741 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1746 /// The core primitive for interior mutability in Rust.
1748 /// If you have a reference `&T`, then normally in Rust the compiler performs optimizations based on
1749 /// the knowledge that `&T` points to immutable data. Mutating that data, for example through an
1750 /// alias or by transmuting an `&T` into an `&mut T`, is considered undefined behavior.
1751 /// `UnsafeCell<T>` opts-out of the immutability guarantee for `&T`: a shared reference
1752 /// `&UnsafeCell<T>` may point to data that is being mutated. This is called "interior mutability".
1754 /// All other types that allow internal mutability, such as `Cell<T>` and `RefCell<T>`, internally
1755 /// use `UnsafeCell` to wrap their data.
1757 /// Note that only the immutability guarantee for shared references is affected by `UnsafeCell`. The
1758 /// uniqueness guarantee for mutable references is unaffected. There is *no* legal way to obtain
1759 /// aliasing `&mut`, not even with `UnsafeCell<T>`.
1761 /// The `UnsafeCell` API itself is technically very simple: [`.get()`] gives you a raw pointer
1762 /// `*mut T` to its contents. It is up to _you_ as the abstraction designer to use that raw pointer
1765 /// [`.get()`]: `UnsafeCell::get`
1767 /// The precise Rust aliasing rules are somewhat in flux, but the main points are not contentious:
1769 /// - If you create a safe reference with lifetime `'a` (either a `&T` or `&mut T` reference), then
1770 /// you must not access the data in any way that contradicts that reference for the remainder of
1771 /// `'a`. For example, this means that if you take the `*mut T` from an `UnsafeCell<T>` and cast it
1772 /// to an `&T`, then the data in `T` must remain immutable (modulo any `UnsafeCell` data found
1773 /// within `T`, of course) until that reference's lifetime expires. Similarly, if you create a `&mut
1774 /// T` reference that is released to safe code, then you must not access the data within the
1775 /// `UnsafeCell` until that reference expires.
1777 /// - For both `&T` without `UnsafeCell<_>` and `&mut T`, you must also not deallocate the data
1778 /// until the reference expires. As a special exception, given an `&T`, any part of it that is
1779 /// inside an `UnsafeCell<_>` may be deallocated during the lifetime of the reference, after the
1780 /// last time the reference is used (dereferenced or reborrowed). Since you cannot deallocate a part
1781 /// of what a reference points to, this means the memory an `&T` points to can be deallocted only if
1782 /// *every part of it* (including padding) is inside an `UnsafeCell`.
1784 /// However, whenever a `&UnsafeCell<T>` is constructed or dereferenced, it must still point to
1785 /// live memory and the compiler is allowed to insert spurious reads if it can prove that this
1786 /// memory has not yet been deallocated.
1788 /// - At all times, you must avoid data races. If multiple threads have access to
1789 /// the same `UnsafeCell`, then any writes must have a proper happens-before relation to all other
1790 /// accesses (or use atomics).
1792 /// To assist with proper design, the following scenarios are explicitly declared legal
1793 /// for single-threaded code:
1795 /// 1. A `&T` reference can be released to safe code and there it can co-exist with other `&T`
1796 /// references, but not with a `&mut T`
1798 /// 2. A `&mut T` reference may be released to safe code provided neither other `&mut T` nor `&T`
1799 /// co-exist with it. A `&mut T` must always be unique.
1801 /// Note that whilst mutating the contents of an `&UnsafeCell<T>` (even while other
1802 /// `&UnsafeCell<T>` references alias the cell) is
1803 /// ok (provided you enforce the above invariants some other way), it is still undefined behavior
1804 /// to have multiple `&mut UnsafeCell<T>` aliases. That is, `UnsafeCell` is a wrapper
1805 /// designed to have a special interaction with _shared_ accesses (_i.e._, through an
1806 /// `&UnsafeCell<_>` reference); there is no magic whatsoever when dealing with _exclusive_
1807 /// accesses (_e.g._, through an `&mut UnsafeCell<_>`): neither the cell nor the wrapped value
1808 /// may be aliased for the duration of that `&mut` borrow.
1809 /// This is showcased by the [`.get_mut()`] accessor, which is a _safe_ getter that yields
1812 /// [`.get_mut()`]: `UnsafeCell::get_mut`
1814 /// `UnsafeCell<T>` has the same in-memory representation as its inner type `T` if and only if
1815 /// the type `T` does not contain a [niche] (e.g. the type `Option<NonNull<u8>>` is typically
1816 /// 8 bytes large on 64-bit platforms, but the type `Option<UnsafeCell<NonNull<u8>>>` takes
1817 /// up 16 bytes of space). A consequence of this guarantee is that it is possible to convert
1818 /// between `T` and `UnsafeCell<T>` when `T` has no niches. However, it is only valid to obtain
1819 /// a `*mut T` pointer to the contents of a _shared_ `UnsafeCell<T>` through [`.get()`] or
1820 /// [`.raw_get()`]. A `&mut T` reference can be obtained by either dereferencing this pointer
1821 /// or by calling [`.get_mut()`] on an _exclusive_ `UnsafeCell<T>`, e.g.:
1824 /// use std::cell::UnsafeCell;
1826 /// let mut x: UnsafeCell<u32> = UnsafeCell::new(5);
1827 /// let shared: &UnsafeCell<u32> = &x;
1828 /// // using `.get()` is okay:
1830 /// // SAFETY: there exist no other references to the contents of `x`
1831 /// let exclusive: &mut u32 = &mut *shared.get();
1833 /// // using `.raw_get()` is also okay:
1835 /// // SAFETY: there exist no other references to the contents of `x` in this scope
1836 /// let exclusive: &mut u32 = &mut *UnsafeCell::raw_get(shared as *const _);
1838 /// // using `.get_mut()` is always safe:
1839 /// let exclusive: &mut u32 = x.get_mut();
1841 /// // when we have exclusive access, we can convert it to a shared `&UnsafeCell`:
1843 /// // SAFETY: `u32` has no niche, therefore it has the same layout as `UnsafeCell<u32>`
1844 /// let shared: &UnsafeCell<u32> = &*(exclusive as *mut _ as *const UnsafeCell<u32>);
1845 /// // SAFETY: there exist no other *active* references to the contents of `x` in this scope
1846 /// let exclusive: &mut u32 = &mut *shared.get();
1850 /// [niche]: https://rust-lang.github.io/unsafe-code-guidelines/glossary.html#niche
1851 /// [`.raw_get()`]: `UnsafeCell::raw_get`
1855 /// Here is an example showcasing how to soundly mutate the contents of an `UnsafeCell<_>` despite
1856 /// there being multiple references aliasing the cell:
1859 /// use std::cell::UnsafeCell;
1861 /// let x: UnsafeCell<i32> = 42.into();
1862 /// // Get multiple / concurrent / shared references to the same `x`.
1863 /// let (p1, p2): (&UnsafeCell<i32>, &UnsafeCell<i32>) = (&x, &x);
1866 /// // SAFETY: within this scope there are no other references to `x`'s contents,
1867 /// // so ours is effectively unique.
1868 /// let p1_exclusive: &mut i32 = &mut *p1.get(); // -- borrow --+
1869 /// *p1_exclusive += 27; // |
1870 /// } // <---------- cannot go beyond this point -------------------+
1873 /// // SAFETY: within this scope nobody expects to have exclusive access to `x`'s contents,
1874 /// // so we can have multiple shared accesses concurrently.
1875 /// let p2_shared: &i32 = &*p2.get();
1876 /// assert_eq!(*p2_shared, 42 + 27);
1877 /// let p1_shared: &i32 = &*p1.get();
1878 /// assert_eq!(*p1_shared, *p2_shared);
1882 /// The following example showcases the fact that exclusive access to an `UnsafeCell<T>`
1883 /// implies exclusive access to its `T`:
1886 /// #![forbid(unsafe_code)] // with exclusive accesses,
1887 /// // `UnsafeCell` is a transparent no-op wrapper,
1888 /// // so no need for `unsafe` here.
1889 /// use std::cell::UnsafeCell;
1891 /// let mut x: UnsafeCell<i32> = 42.into();
1893 /// // Get a compile-time-checked unique reference to `x`.
1894 /// let p_unique: &mut UnsafeCell<i32> = &mut x;
1895 /// // With an exclusive reference, we can mutate the contents for free.
1896 /// *p_unique.get_mut() = 0;
1897 /// // Or, equivalently:
1898 /// x = UnsafeCell::new(0);
1900 /// // When we own the value, we can extract the contents for free.
1901 /// let contents: i32 = x.into_inner();
1902 /// assert_eq!(contents, 0);
1904 #[lang = "unsafe_cell"]
1905 #[stable(feature = "rust1", since = "1.0.0")]
1906 #[repr(transparent)]
1907 pub struct UnsafeCell<T: ?Sized> {
1911 #[stable(feature = "rust1", since = "1.0.0")]
1912 impl<T: ?Sized> !Sync for UnsafeCell<T> {}
1914 impl<T> UnsafeCell<T> {
1915 /// Constructs a new instance of `UnsafeCell` which will wrap the specified
1918 /// All access to the inner value through methods is `unsafe`.
1923 /// use std::cell::UnsafeCell;
1925 /// let uc = UnsafeCell::new(5);
1927 #[stable(feature = "rust1", since = "1.0.0")]
1928 #[rustc_const_stable(feature = "const_unsafe_cell_new", since = "1.32.0")]
1930 pub const fn new(value: T) -> UnsafeCell<T> {
1931 UnsafeCell { value }
1934 /// Unwraps the value.
1939 /// use std::cell::UnsafeCell;
1941 /// let uc = UnsafeCell::new(5);
1943 /// let five = uc.into_inner();
1946 #[stable(feature = "rust1", since = "1.0.0")]
1947 #[rustc_const_unstable(feature = "const_cell_into_inner", issue = "78729")]
1948 pub const fn into_inner(self) -> T {
1953 impl<T: ?Sized> UnsafeCell<T> {
1954 /// Gets a mutable pointer to the wrapped value.
1956 /// This can be cast to a pointer of any kind.
1957 /// Ensure that the access is unique (no active references, mutable or not)
1958 /// when casting to `&mut T`, and ensure that there are no mutations
1959 /// or mutable aliases going on when casting to `&T`
1964 /// use std::cell::UnsafeCell;
1966 /// let uc = UnsafeCell::new(5);
1968 /// let five = uc.get();
1971 #[stable(feature = "rust1", since = "1.0.0")]
1972 #[rustc_const_stable(feature = "const_unsafecell_get", since = "1.32.0")]
1973 pub const fn get(&self) -> *mut T {
1974 // We can just cast the pointer from `UnsafeCell<T>` to `T` because of
1975 // #[repr(transparent)]. This exploits libstd's special status, there is
1976 // no guarantee for user code that this will work in future versions of the compiler!
1977 self as *const UnsafeCell<T> as *const T as *mut T
1980 /// Returns a mutable reference to the underlying data.
1982 /// This call borrows the `UnsafeCell` mutably (at compile-time) which
1983 /// guarantees that we possess the only reference.
1988 /// use std::cell::UnsafeCell;
1990 /// let mut c = UnsafeCell::new(5);
1991 /// *c.get_mut() += 1;
1993 /// assert_eq!(*c.get_mut(), 6);
1996 #[stable(feature = "unsafe_cell_get_mut", since = "1.50.0")]
1997 #[rustc_const_unstable(feature = "const_unsafecell_get_mut", issue = "88836")]
1998 pub const fn get_mut(&mut self) -> &mut T {
2002 /// Gets a mutable pointer to the wrapped value.
2003 /// The difference from [`get`] is that this function accepts a raw pointer,
2004 /// which is useful to avoid the creation of temporary references.
2006 /// The result can be cast to a pointer of any kind.
2007 /// Ensure that the access is unique (no active references, mutable or not)
2008 /// when casting to `&mut T`, and ensure that there are no mutations
2009 /// or mutable aliases going on when casting to `&T`.
2011 /// [`get`]: UnsafeCell::get()
2015 /// Gradual initialization of an `UnsafeCell` requires `raw_get`, as
2016 /// calling `get` would require creating a reference to uninitialized data:
2019 /// use std::cell::UnsafeCell;
2020 /// use std::mem::MaybeUninit;
2022 /// let m = MaybeUninit::<UnsafeCell<i32>>::uninit();
2023 /// unsafe { UnsafeCell::raw_get(m.as_ptr()).write(5); }
2024 /// let uc = unsafe { m.assume_init() };
2026 /// assert_eq!(uc.into_inner(), 5);
2029 #[stable(feature = "unsafe_cell_raw_get", since = "1.56.0")]
2030 #[rustc_const_stable(feature = "unsafe_cell_raw_get", since = "1.56.0")]
2031 pub const fn raw_get(this: *const Self) -> *mut T {
2032 // We can just cast the pointer from `UnsafeCell<T>` to `T` because of
2033 // #[repr(transparent)]. This exploits libstd's special status, there is
2034 // no guarantee for user code that this will work in future versions of the compiler!
2035 this as *const T as *mut T
2039 #[stable(feature = "unsafe_cell_default", since = "1.10.0")]
2040 impl<T: Default> Default for UnsafeCell<T> {
2041 /// Creates an `UnsafeCell`, with the `Default` value for T.
2042 fn default() -> UnsafeCell<T> {
2043 UnsafeCell::new(Default::default())
2047 #[stable(feature = "cell_from", since = "1.12.0")]
2048 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
2049 impl<T> const From<T> for UnsafeCell<T> {
2050 /// Creates a new `UnsafeCell<T>` containing the given value.
2051 fn from(t: T) -> UnsafeCell<T> {
2056 #[unstable(feature = "coerce_unsized", issue = "27732")]
2057 impl<T: CoerceUnsized<U>, U> CoerceUnsized<UnsafeCell<U>> for UnsafeCell<T> {}
2059 /// [`UnsafeCell`], but [`Sync`].
2061 /// This is just an `UnsafeCell`, except it implements `Sync`
2062 /// if `T` implements `Sync`.
2064 /// `UnsafeCell` doesn't implement `Sync`, to prevent accidental mis-use.
2065 /// You can use `SyncUnsafeCell` instead of `UnsafeCell` to allow it to be
2066 /// shared between threads, if that's intentional.
2067 /// Providing proper synchronization is still the task of the user,
2068 /// making this type just as unsafe to use.
2070 /// See [`UnsafeCell`] for details.
2071 #[unstable(feature = "sync_unsafe_cell", issue = "95439")]
2072 #[repr(transparent)]
2073 pub struct SyncUnsafeCell<T: ?Sized> {
2074 value: UnsafeCell<T>,
2077 #[unstable(feature = "sync_unsafe_cell", issue = "95439")]
2078 unsafe impl<T: ?Sized + Sync> Sync for SyncUnsafeCell<T> {}
2080 #[unstable(feature = "sync_unsafe_cell", issue = "95439")]
2081 impl<T> SyncUnsafeCell<T> {
2082 /// Constructs a new instance of `SyncUnsafeCell` which will wrap the specified value.
2084 pub const fn new(value: T) -> Self {
2085 Self { value: UnsafeCell { value } }
2088 /// Unwraps the value.
2090 pub const fn into_inner(self) -> T {
2091 self.value.into_inner()
2095 #[unstable(feature = "sync_unsafe_cell", issue = "95439")]
2096 impl<T: ?Sized> SyncUnsafeCell<T> {
2097 /// Gets a mutable pointer to the wrapped value.
2099 /// This can be cast to a pointer of any kind.
2100 /// Ensure that the access is unique (no active references, mutable or not)
2101 /// when casting to `&mut T`, and ensure that there are no mutations
2102 /// or mutable aliases going on when casting to `&T`
2104 pub const fn get(&self) -> *mut T {
2108 /// Returns a mutable reference to the underlying data.
2110 /// This call borrows the `SyncUnsafeCell` mutably (at compile-time) which
2111 /// guarantees that we possess the only reference.
2113 pub const fn get_mut(&mut self) -> &mut T {
2114 self.value.get_mut()
2117 /// Gets a mutable pointer to the wrapped value.
2119 /// See [`UnsafeCell::get`] for details.
2121 pub const fn raw_get(this: *const Self) -> *mut T {
2122 // We can just cast the pointer from `SyncUnsafeCell<T>` to `T` because
2123 // of #[repr(transparent)] on both SyncUnsafeCell and UnsafeCell.
2124 // See UnsafeCell::raw_get.
2125 this as *const T as *mut T
2129 #[unstable(feature = "sync_unsafe_cell", issue = "95439")]
2130 impl<T: Default> Default for SyncUnsafeCell<T> {
2131 /// Creates an `SyncUnsafeCell`, with the `Default` value for T.
2132 fn default() -> SyncUnsafeCell<T> {
2133 SyncUnsafeCell::new(Default::default())
2137 #[unstable(feature = "sync_unsafe_cell", issue = "95439")]
2138 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
2139 impl<T> const From<T> for SyncUnsafeCell<T> {
2140 /// Creates a new `SyncUnsafeCell<T>` containing the given value.
2141 fn from(t: T) -> SyncUnsafeCell<T> {
2142 SyncUnsafeCell::new(t)
2146 #[unstable(feature = "coerce_unsized", issue = "27732")]
2147 //#[unstable(feature = "sync_unsafe_cell", issue = "95439")]
2148 impl<T: CoerceUnsized<U>, U> CoerceUnsized<SyncUnsafeCell<U>> for SyncUnsafeCell<T> {}
2151 fn assert_coerce_unsized(
2152 a: UnsafeCell<&i32>,
2153 b: SyncUnsafeCell<&i32>,
2157 let _: UnsafeCell<&dyn Send> = a;
2158 let _: SyncUnsafeCell<&dyn Send> = b;
2159 let _: Cell<&dyn Send> = c;
2160 let _: RefCell<&dyn Send> = d;