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`](../../std/sync/struct.Mutex.html),
18 //! [`RwLock`](../../std/sync/struct.RwLock.html) or
19 //! [`atomic`](../../core/sync/atomic/index.html) types.
21 //! Values of the `Cell<T>` and `RefCell<T>` types may be mutated through shared references (i.e.
22 //! the common `&T` type), whereas most Rust types can only be mutated through unique (`&mut T`)
23 //! references. We say that `Cell<T>` and `RefCell<T>` provide 'interior mutability', in contrast
24 //! with typical Rust types that exhibit 'inherited mutability'.
26 //! Cell types come in two flavors: `Cell<T>` and `RefCell<T>`. `Cell<T>` implements interior
27 //! mutability by moving values in and out of the `Cell<T>`. To use references instead of values,
28 //! one must use the `RefCell<T>` type, acquiring a write lock before mutating. `Cell<T>` provides
29 //! methods to retrieve and change the current interior value:
31 //! - For types that implement `Copy`, the `get` method retrieves the current interior value.
32 //! - For types that implement `Default`, the `take` method replaces the current interior value
33 //! with `Default::default()` and returns the replaced value.
34 //! - For all types, the `replace` method replaces the current interior value and returns the
35 //! replaced value and the `into_inner` method consumes the `Cell<T>` and returns the interior
36 //! value. Additionally, the `set` method replaces the interior value, dropping the replaced
39 //! `RefCell<T>` uses Rust's lifetimes to implement 'dynamic borrowing', a process whereby one can
40 //! claim temporary, exclusive, mutable access to the inner value. Borrows for `RefCell<T>`s are
41 //! tracked 'at runtime', unlike Rust's native reference types which are entirely tracked
42 //! statically, at compile time. Because `RefCell<T>` borrows are dynamic it is possible to attempt
43 //! to borrow a value that is already mutably borrowed; when this happens it results in thread
46 //! # When to choose interior mutability
48 //! The more common inherited mutability, where one must have unique access to mutate a value, is
49 //! one of the key language elements that enables Rust to reason strongly about pointer aliasing,
50 //! statically preventing crash bugs. Because of that, inherited mutability is preferred, and
51 //! interior mutability is something of a last resort. Since cell types enable mutation where it
52 //! would otherwise be disallowed though, there are occasions when interior mutability might be
53 //! appropriate, or even *must* be used, e.g.
55 //! * Introducing mutability 'inside' of something immutable
56 //! * Implementation details of logically-immutable methods.
57 //! * Mutating implementations of `Clone`.
59 //! ## Introducing mutability 'inside' of something immutable
61 //! Many shared smart pointer types, including `Rc<T>` and `Arc<T>`, provide containers that can be
62 //! cloned and shared between multiple parties. Because the contained values may be
63 //! multiply-aliased, they can only be borrowed with `&`, not `&mut`. Without cells it would be
64 //! impossible to mutate data inside of these smart pointers at all.
66 //! It's very common then to put a `RefCell<T>` inside shared pointer types to reintroduce
70 //! use std::cell::{RefCell, RefMut};
71 //! use std::collections::HashMap;
75 //! let shared_map: Rc<RefCell<_>> = Rc::new(RefCell::new(HashMap::new()));
76 //! // Create a new block to limit the scope of the dynamic borrow
78 //! let mut map: RefMut<_> = shared_map.borrow_mut();
79 //! map.insert("africa", 92388);
80 //! map.insert("kyoto", 11837);
81 //! map.insert("piccadilly", 11826);
82 //! map.insert("marbles", 38);
85 //! // Note that if we had not let the previous borrow of the cache fall out
86 //! // of scope then the subsequent borrow would cause a dynamic thread panic.
87 //! // This is the major hazard of using `RefCell`.
88 //! let total: i32 = shared_map.borrow().values().sum();
89 //! println!("{}", total);
93 //! Note that this example uses `Rc<T>` and not `Arc<T>`. `RefCell<T>`s are for single-threaded
94 //! scenarios. Consider using `RwLock<T>` or `Mutex<T>` if you need shared mutability in a
95 //! multi-threaded situation.
97 //! ## Implementation details of logically-immutable methods
99 //! Occasionally it may be desirable not to expose in an API that there is mutation happening
100 //! "under the hood". This may be because logically the operation is immutable, but e.g., caching
101 //! forces the implementation to perform mutation; or because you must employ mutation to implement
102 //! a trait method that was originally defined to take `&self`.
105 //! # #![allow(dead_code)]
106 //! use std::cell::RefCell;
109 //! edges: Vec<(i32, i32)>,
110 //! span_tree_cache: RefCell<Option<Vec<(i32, i32)>>>
114 //! fn minimum_spanning_tree(&self) -> Vec<(i32, i32)> {
115 //! self.span_tree_cache.borrow_mut()
116 //! .get_or_insert_with(|| self.calc_span_tree())
120 //! fn calc_span_tree(&self) -> Vec<(i32, i32)> {
121 //! // Expensive computation goes here
127 //! ## Mutating implementations of `Clone`
129 //! This is simply a special - but common - case of the previous: hiding mutability for operations
130 //! that appear to be immutable. The `clone` method is expected to not change the source value, and
131 //! is declared to take `&self`, not `&mut self`. Therefore, any mutation that happens in the
132 //! `clone` method must use cell types. For example, `Rc<T>` maintains its reference counts within a
136 //! #![feature(core_intrinsics)]
137 //! use std::cell::Cell;
138 //! use std::ptr::NonNull;
139 //! use std::intrinsics::abort;
140 //! use std::marker::PhantomData;
142 //! struct Rc<T: ?Sized> {
143 //! ptr: NonNull<RcBox<T>>,
144 //! phantom: PhantomData<RcBox<T>>,
147 //! struct RcBox<T: ?Sized> {
148 //! strong: Cell<usize>,
149 //! refcount: Cell<usize>,
153 //! impl<T: ?Sized> Clone for Rc<T> {
154 //! fn clone(&self) -> Rc<T> {
155 //! self.inc_strong();
158 //! phantom: PhantomData,
163 //! trait RcBoxPtr<T: ?Sized> {
165 //! fn inner(&self) -> &RcBox<T>;
167 //! fn strong(&self) -> usize {
168 //! self.inner().strong.get()
171 //! fn inc_strong(&self) {
174 //! .set(self.strong()
176 //! .unwrap_or_else(|| unsafe { abort() }));
180 //! impl<T: ?Sized> RcBoxPtr<T> for Rc<T> {
181 //! fn inner(&self) -> &RcBox<T> {
183 //! self.ptr.as_ref()
190 #![stable(feature = "rust1", since = "1.0.0")]
192 use crate::cmp::Ordering;
193 use crate::fmt::{self, Debug, Display};
194 use crate::marker::Unsize;
196 use crate::ops::{Deref, DerefMut, CoerceUnsized};
199 /// A mutable memory location.
203 /// In this example, you can see that `Cell<T>` enables mutation inside an
204 /// immutable struct. In other words, it enables "interior mutability".
207 /// use std::cell::Cell;
209 /// struct SomeStruct {
210 /// regular_field: u8,
211 /// special_field: Cell<u8>,
214 /// let my_struct = SomeStruct {
215 /// regular_field: 0,
216 /// special_field: Cell::new(1),
219 /// let new_value = 100;
221 /// // ERROR: `my_struct` is immutable
222 /// // my_struct.regular_field = new_value;
224 /// // WORKS: although `my_struct` is immutable, `special_field` is a `Cell`,
225 /// // which can always be mutated
226 /// my_struct.special_field.set(new_value);
227 /// assert_eq!(my_struct.special_field.get(), new_value);
230 /// See the [module-level documentation](index.html) for more.
231 #[stable(feature = "rust1", since = "1.0.0")]
233 pub struct Cell<T: ?Sized> {
234 value: UnsafeCell<T>,
237 #[stable(feature = "rust1", since = "1.0.0")]
238 unsafe impl<T: ?Sized> Send for Cell<T> where T: Send {}
240 #[stable(feature = "rust1", since = "1.0.0")]
241 impl<T: ?Sized> !Sync for Cell<T> {}
243 #[stable(feature = "rust1", since = "1.0.0")]
244 impl<T:Copy> Clone for Cell<T> {
246 fn clone(&self) -> Cell<T> {
247 Cell::new(self.get())
251 #[stable(feature = "rust1", since = "1.0.0")]
252 impl<T: Default> Default for Cell<T> {
253 /// Creates a `Cell<T>`, with the `Default` value for T.
255 fn default() -> Cell<T> {
256 Cell::new(Default::default())
260 #[stable(feature = "rust1", since = "1.0.0")]
261 impl<T: PartialEq + Copy> PartialEq for Cell<T> {
263 fn eq(&self, other: &Cell<T>) -> bool {
264 self.get() == other.get()
268 #[stable(feature = "cell_eq", since = "1.2.0")]
269 impl<T: Eq + Copy> Eq for Cell<T> {}
271 #[stable(feature = "cell_ord", since = "1.10.0")]
272 impl<T: PartialOrd + Copy> PartialOrd for Cell<T> {
274 fn partial_cmp(&self, other: &Cell<T>) -> Option<Ordering> {
275 self.get().partial_cmp(&other.get())
279 fn lt(&self, other: &Cell<T>) -> bool {
280 self.get() < other.get()
284 fn le(&self, other: &Cell<T>) -> bool {
285 self.get() <= other.get()
289 fn gt(&self, other: &Cell<T>) -> bool {
290 self.get() > other.get()
294 fn ge(&self, other: &Cell<T>) -> bool {
295 self.get() >= other.get()
299 #[stable(feature = "cell_ord", since = "1.10.0")]
300 impl<T: Ord + Copy> Ord for Cell<T> {
302 fn cmp(&self, other: &Cell<T>) -> Ordering {
303 self.get().cmp(&other.get())
307 #[stable(feature = "cell_from", since = "1.12.0")]
308 impl<T> From<T> for Cell<T> {
309 fn from(t: T) -> Cell<T> {
315 /// Creates a new `Cell` containing the given value.
320 /// use std::cell::Cell;
322 /// let c = Cell::new(5);
324 #[stable(feature = "rust1", since = "1.0.0")]
326 pub const fn new(value: T) -> Cell<T> {
328 value: UnsafeCell::new(value),
332 /// Sets the contained value.
337 /// use std::cell::Cell;
339 /// let c = Cell::new(5);
344 #[stable(feature = "rust1", since = "1.0.0")]
345 pub fn set(&self, val: T) {
346 let old = self.replace(val);
350 /// Swaps the values of two Cells.
351 /// Difference with `std::mem::swap` is that this function doesn't require `&mut` reference.
356 /// use std::cell::Cell;
358 /// let c1 = Cell::new(5i32);
359 /// let c2 = Cell::new(10i32);
361 /// assert_eq!(10, c1.get());
362 /// assert_eq!(5, c2.get());
365 #[stable(feature = "move_cell", since = "1.17.0")]
366 pub fn swap(&self, other: &Self) {
367 if ptr::eq(self, other) {
371 ptr::swap(self.value.get(), other.value.get());
375 /// Replaces the contained value, and returns it.
380 /// use std::cell::Cell;
382 /// let cell = Cell::new(5);
383 /// assert_eq!(cell.get(), 5);
384 /// assert_eq!(cell.replace(10), 5);
385 /// assert_eq!(cell.get(), 10);
387 #[stable(feature = "move_cell", since = "1.17.0")]
388 pub fn replace(&self, val: T) -> T {
389 mem::replace(unsafe { &mut *self.value.get() }, val)
392 /// Unwraps the value.
397 /// use std::cell::Cell;
399 /// let c = Cell::new(5);
400 /// let five = c.into_inner();
402 /// assert_eq!(five, 5);
404 #[stable(feature = "move_cell", since = "1.17.0")]
405 pub fn into_inner(self) -> T {
406 self.value.into_inner()
410 impl<T:Copy> Cell<T> {
411 /// Returns a copy of the contained value.
416 /// use std::cell::Cell;
418 /// let c = Cell::new(5);
420 /// let five = c.get();
423 #[stable(feature = "rust1", since = "1.0.0")]
424 pub fn get(&self) -> T {
425 unsafe{ *self.value.get() }
428 /// Updates the contained value using a function and returns the new value.
433 /// #![feature(cell_update)]
435 /// use std::cell::Cell;
437 /// let c = Cell::new(5);
438 /// let new = c.update(|x| x + 1);
440 /// assert_eq!(new, 6);
441 /// assert_eq!(c.get(), 6);
444 #[unstable(feature = "cell_update", issue = "50186")]
445 pub fn update<F>(&self, f: F) -> T
449 let old = self.get();
456 impl<T: ?Sized> Cell<T> {
457 /// Returns a raw pointer to the underlying data in this cell.
462 /// use std::cell::Cell;
464 /// let c = Cell::new(5);
466 /// let ptr = c.as_ptr();
469 #[stable(feature = "cell_as_ptr", since = "1.12.0")]
470 pub const fn as_ptr(&self) -> *mut T {
474 /// Returns a mutable reference to the underlying data.
476 /// This call borrows `Cell` mutably (at compile-time) which guarantees
477 /// that we possess the only reference.
482 /// use std::cell::Cell;
484 /// let mut c = Cell::new(5);
485 /// *c.get_mut() += 1;
487 /// assert_eq!(c.get(), 6);
490 #[stable(feature = "cell_get_mut", since = "1.11.0")]
491 pub fn get_mut(&mut self) -> &mut T {
493 &mut *self.value.get()
497 /// Returns a `&Cell<T>` from a `&mut T`
502 /// use std::cell::Cell;
504 /// let slice: &mut [i32] = &mut [1, 2, 3];
505 /// let cell_slice: &Cell<[i32]> = Cell::from_mut(slice);
506 /// let slice_cell: &[Cell<i32>] = cell_slice.as_slice_of_cells();
508 /// assert_eq!(slice_cell.len(), 3);
511 #[stable(feature = "as_cell", since = "1.37.0")]
512 pub fn from_mut(t: &mut T) -> &Cell<T> {
514 &*(t as *mut T as *const Cell<T>)
519 impl<T: Default> Cell<T> {
520 /// Takes the value of the cell, leaving `Default::default()` in its place.
525 /// use std::cell::Cell;
527 /// let c = Cell::new(5);
528 /// let five = c.take();
530 /// assert_eq!(five, 5);
531 /// assert_eq!(c.into_inner(), 0);
533 #[stable(feature = "move_cell", since = "1.17.0")]
534 pub fn take(&self) -> T {
535 self.replace(Default::default())
539 #[unstable(feature = "coerce_unsized", issue = "27732")]
540 impl<T: CoerceUnsized<U>, U> CoerceUnsized<Cell<U>> for Cell<T> {}
543 /// Returns a `&[Cell<T>]` from a `&Cell<[T]>`
548 /// use std::cell::Cell;
550 /// let slice: &mut [i32] = &mut [1, 2, 3];
551 /// let cell_slice: &Cell<[i32]> = Cell::from_mut(slice);
552 /// let slice_cell: &[Cell<i32>] = cell_slice.as_slice_of_cells();
554 /// assert_eq!(slice_cell.len(), 3);
556 #[stable(feature = "as_cell", since = "1.37.0")]
557 pub fn as_slice_of_cells(&self) -> &[Cell<T>] {
559 &*(self as *const Cell<[T]> as *const [Cell<T>])
564 /// A mutable memory location with dynamically checked borrow rules
566 /// See the [module-level documentation](index.html) for more.
567 #[stable(feature = "rust1", since = "1.0.0")]
568 pub struct RefCell<T: ?Sized> {
569 borrow: Cell<BorrowFlag>,
570 value: UnsafeCell<T>,
573 /// An error returned by [`RefCell::try_borrow`](struct.RefCell.html#method.try_borrow).
574 #[stable(feature = "try_borrow", since = "1.13.0")]
575 pub struct BorrowError {
579 #[stable(feature = "try_borrow", since = "1.13.0")]
580 impl Debug for BorrowError {
581 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
582 f.debug_struct("BorrowError").finish()
586 #[stable(feature = "try_borrow", since = "1.13.0")]
587 impl Display for BorrowError {
588 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
589 Display::fmt("already mutably borrowed", f)
593 /// An error returned by [`RefCell::try_borrow_mut`](struct.RefCell.html#method.try_borrow_mut).
594 #[stable(feature = "try_borrow", since = "1.13.0")]
595 pub struct BorrowMutError {
599 #[stable(feature = "try_borrow", since = "1.13.0")]
600 impl Debug for BorrowMutError {
601 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
602 f.debug_struct("BorrowMutError").finish()
606 #[stable(feature = "try_borrow", since = "1.13.0")]
607 impl Display for BorrowMutError {
608 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
609 Display::fmt("already borrowed", f)
613 // Positive values represent the number of `Ref` active. Negative values
614 // represent the number of `RefMut` active. Multiple `RefMut`s can only be
615 // active at a time if they refer to distinct, nonoverlapping components of a
616 // `RefCell` (e.g., different ranges of a slice).
618 // `Ref` and `RefMut` are both two words in size, and so there will likely never
619 // be enough `Ref`s or `RefMut`s in existence to overflow half of the `usize`
620 // range. Thus, a `BorrowFlag` will probably never overflow or underflow.
621 // However, this is not a guarantee, as a pathological program could repeatedly
622 // create and then mem::forget `Ref`s or `RefMut`s. Thus, all code must
623 // explicitly check for overflow and underflow in order to avoid unsafety, or at
624 // least behave correctly in the event that overflow or underflow happens (e.g.,
625 // see BorrowRef::new).
626 type BorrowFlag = isize;
627 const UNUSED: BorrowFlag = 0;
630 fn is_writing(x: BorrowFlag) -> bool {
635 fn is_reading(x: BorrowFlag) -> bool {
640 /// Creates a new `RefCell` containing `value`.
645 /// use std::cell::RefCell;
647 /// let c = RefCell::new(5);
649 #[stable(feature = "rust1", since = "1.0.0")]
651 pub const fn new(value: T) -> RefCell<T> {
653 value: UnsafeCell::new(value),
654 borrow: Cell::new(UNUSED),
658 /// Consumes the `RefCell`, returning the wrapped value.
663 /// use std::cell::RefCell;
665 /// let c = RefCell::new(5);
667 /// let five = c.into_inner();
669 #[stable(feature = "rust1", since = "1.0.0")]
671 pub fn into_inner(self) -> T {
672 // Since this function takes `self` (the `RefCell`) by value, the
673 // compiler statically verifies that it is not currently borrowed.
674 // Therefore the following assertion is just a `debug_assert!`.
675 debug_assert!(self.borrow.get() == UNUSED);
676 self.value.into_inner()
679 /// Replaces the wrapped value with a new one, returning the old value,
680 /// without deinitializing either one.
682 /// This function corresponds to [`std::mem::replace`](../mem/fn.replace.html).
686 /// Panics if the value is currently borrowed.
691 /// use std::cell::RefCell;
692 /// let cell = RefCell::new(5);
693 /// let old_value = cell.replace(6);
694 /// assert_eq!(old_value, 5);
695 /// assert_eq!(cell, RefCell::new(6));
698 #[stable(feature = "refcell_replace", since="1.24.0")]
699 pub fn replace(&self, t: T) -> T {
700 mem::replace(&mut *self.borrow_mut(), t)
703 /// Replaces the wrapped value with a new one computed from `f`, returning
704 /// the old value, without deinitializing either one.
708 /// Panics if the value is currently borrowed.
713 /// use std::cell::RefCell;
714 /// let cell = RefCell::new(5);
715 /// let old_value = cell.replace_with(|&mut old| old + 1);
716 /// assert_eq!(old_value, 5);
717 /// assert_eq!(cell, RefCell::new(6));
720 #[stable(feature = "refcell_replace_swap", since="1.35.0")]
721 pub fn replace_with<F: FnOnce(&mut T) -> T>(&self, f: F) -> T {
722 let mut_borrow = &mut *self.borrow_mut();
723 let replacement = f(mut_borrow);
724 mem::replace(mut_borrow, replacement)
727 /// Swaps the wrapped value of `self` with the wrapped value of `other`,
728 /// without deinitializing either one.
730 /// This function corresponds to [`std::mem::swap`](../mem/fn.swap.html).
734 /// Panics if the value in either `RefCell` is currently borrowed.
739 /// use std::cell::RefCell;
740 /// let c = RefCell::new(5);
741 /// let d = RefCell::new(6);
743 /// assert_eq!(c, RefCell::new(6));
744 /// assert_eq!(d, RefCell::new(5));
747 #[stable(feature = "refcell_swap", since="1.24.0")]
748 pub fn swap(&self, other: &Self) {
749 mem::swap(&mut *self.borrow_mut(), &mut *other.borrow_mut())
753 impl<T: ?Sized> RefCell<T> {
754 /// Immutably borrows the wrapped value.
756 /// The borrow lasts until the returned `Ref` exits scope. Multiple
757 /// immutable borrows can be taken out at the same time.
761 /// Panics if the value is currently mutably borrowed. For a non-panicking variant, use
762 /// [`try_borrow`](#method.try_borrow).
767 /// use std::cell::RefCell;
769 /// let c = RefCell::new(5);
771 /// let borrowed_five = c.borrow();
772 /// let borrowed_five2 = c.borrow();
775 /// An example of panic:
778 /// use std::cell::RefCell;
781 /// let result = thread::spawn(move || {
782 /// let c = RefCell::new(5);
783 /// let m = c.borrow_mut();
785 /// let b = c.borrow(); // this causes a panic
788 /// assert!(result.is_err());
790 #[stable(feature = "rust1", since = "1.0.0")]
792 pub fn borrow(&self) -> Ref<'_, T> {
793 self.try_borrow().expect("already mutably borrowed")
796 /// Immutably borrows the wrapped value, returning an error if the value is currently mutably
799 /// The borrow lasts until the returned `Ref` exits scope. Multiple immutable borrows can be
800 /// taken out at the same time.
802 /// This is the non-panicking variant of [`borrow`](#method.borrow).
807 /// use std::cell::RefCell;
809 /// let c = RefCell::new(5);
812 /// let m = c.borrow_mut();
813 /// assert!(c.try_borrow().is_err());
817 /// let m = c.borrow();
818 /// assert!(c.try_borrow().is_ok());
821 #[stable(feature = "try_borrow", since = "1.13.0")]
823 pub fn try_borrow(&self) -> Result<Ref<'_, T>, BorrowError> {
824 match BorrowRef::new(&self.borrow) {
826 value: unsafe { &*self.value.get() },
829 None => Err(BorrowError { _private: () }),
833 /// Mutably borrows the wrapped value.
835 /// The borrow lasts until the returned `RefMut` or all `RefMut`s derived
836 /// from it exit scope. The value cannot be borrowed while this borrow is
841 /// Panics if the value is currently borrowed. For a non-panicking variant, use
842 /// [`try_borrow_mut`](#method.try_borrow_mut).
847 /// use std::cell::RefCell;
849 /// let c = RefCell::new(5);
851 /// *c.borrow_mut() = 7;
853 /// assert_eq!(*c.borrow(), 7);
856 /// An example of panic:
859 /// use std::cell::RefCell;
862 /// let result = thread::spawn(move || {
863 /// let c = RefCell::new(5);
864 /// let m = c.borrow();
866 /// let b = c.borrow_mut(); // this causes a panic
869 /// assert!(result.is_err());
871 #[stable(feature = "rust1", since = "1.0.0")]
873 pub fn borrow_mut(&self) -> RefMut<'_, T> {
874 self.try_borrow_mut().expect("already borrowed")
877 /// Mutably borrows the wrapped value, returning an error if the value is currently borrowed.
879 /// The borrow lasts until the returned `RefMut` or all `RefMut`s derived
880 /// from it exit scope. The value cannot be borrowed while this borrow is
883 /// This is the non-panicking variant of [`borrow_mut`](#method.borrow_mut).
888 /// use std::cell::RefCell;
890 /// let c = RefCell::new(5);
893 /// let m = c.borrow();
894 /// assert!(c.try_borrow_mut().is_err());
897 /// assert!(c.try_borrow_mut().is_ok());
899 #[stable(feature = "try_borrow", since = "1.13.0")]
901 pub fn try_borrow_mut(&self) -> Result<RefMut<'_, T>, BorrowMutError> {
902 match BorrowRefMut::new(&self.borrow) {
903 Some(b) => Ok(RefMut {
904 value: unsafe { &mut *self.value.get() },
907 None => Err(BorrowMutError { _private: () }),
911 /// Returns a raw pointer to the underlying data in this cell.
916 /// use std::cell::RefCell;
918 /// let c = RefCell::new(5);
920 /// let ptr = c.as_ptr();
923 #[stable(feature = "cell_as_ptr", since = "1.12.0")]
924 pub fn as_ptr(&self) -> *mut T {
928 /// Returns a mutable reference to the underlying data.
930 /// This call borrows `RefCell` mutably (at compile-time) so there is no
931 /// need for dynamic checks.
933 /// However be cautious: this method expects `self` to be mutable, which is
934 /// generally not the case when using a `RefCell`. Take a look at the
935 /// [`borrow_mut`] method instead if `self` isn't mutable.
937 /// Also, please be aware that this method is only for special circumstances and is usually
938 /// not what you want. In case of doubt, use [`borrow_mut`] instead.
940 /// [`borrow_mut`]: #method.borrow_mut
945 /// use std::cell::RefCell;
947 /// let mut c = RefCell::new(5);
948 /// *c.get_mut() += 1;
950 /// assert_eq!(c, RefCell::new(6));
953 #[stable(feature = "cell_get_mut", since = "1.11.0")]
954 pub fn get_mut(&mut self) -> &mut T {
956 &mut *self.value.get()
960 /// Immutably borrows the wrapped value, returning an error if the value is
961 /// currently mutably borrowed.
965 /// Unlike `RefCell::borrow`, this method is unsafe because it does not
966 /// return a `Ref`, thus leaving the borrow flag untouched. Mutably
967 /// borrowing the `RefCell` while the reference returned by this method
968 /// is alive is undefined behaviour.
973 /// use std::cell::RefCell;
975 /// let c = RefCell::new(5);
978 /// let m = c.borrow_mut();
979 /// assert!(unsafe { c.try_borrow_unguarded() }.is_err());
983 /// let m = c.borrow();
984 /// assert!(unsafe { c.try_borrow_unguarded() }.is_ok());
987 #[stable(feature = "borrow_state", since = "1.37.0")]
989 pub unsafe fn try_borrow_unguarded(&self) -> Result<&T, BorrowError> {
990 if !is_writing(self.borrow.get()) {
991 Ok(&*self.value.get())
993 Err(BorrowError { _private: () })
998 #[stable(feature = "rust1", since = "1.0.0")]
999 unsafe impl<T: ?Sized> Send for RefCell<T> where T: Send {}
1001 #[stable(feature = "rust1", since = "1.0.0")]
1002 impl<T: ?Sized> !Sync for RefCell<T> {}
1004 #[stable(feature = "rust1", since = "1.0.0")]
1005 impl<T: Clone> Clone for RefCell<T> {
1008 /// Panics if the value is currently mutably borrowed.
1010 fn clone(&self) -> RefCell<T> {
1011 RefCell::new(self.borrow().clone())
1015 #[stable(feature = "rust1", since = "1.0.0")]
1016 impl<T: Default> Default for RefCell<T> {
1017 /// Creates a `RefCell<T>`, with the `Default` value for T.
1019 fn default() -> RefCell<T> {
1020 RefCell::new(Default::default())
1024 #[stable(feature = "rust1", since = "1.0.0")]
1025 impl<T: ?Sized + PartialEq> PartialEq for RefCell<T> {
1028 /// Panics if the value in either `RefCell` is currently borrowed.
1030 fn eq(&self, other: &RefCell<T>) -> bool {
1031 *self.borrow() == *other.borrow()
1035 #[stable(feature = "cell_eq", since = "1.2.0")]
1036 impl<T: ?Sized + Eq> Eq for RefCell<T> {}
1038 #[stable(feature = "cell_ord", since = "1.10.0")]
1039 impl<T: ?Sized + PartialOrd> PartialOrd for RefCell<T> {
1042 /// Panics if the value in either `RefCell` is currently borrowed.
1044 fn partial_cmp(&self, other: &RefCell<T>) -> Option<Ordering> {
1045 self.borrow().partial_cmp(&*other.borrow())
1050 /// Panics if the value in either `RefCell` is currently borrowed.
1052 fn lt(&self, other: &RefCell<T>) -> bool {
1053 *self.borrow() < *other.borrow()
1058 /// Panics if the value in either `RefCell` is currently borrowed.
1060 fn le(&self, other: &RefCell<T>) -> bool {
1061 *self.borrow() <= *other.borrow()
1066 /// Panics if the value in either `RefCell` is currently borrowed.
1068 fn gt(&self, other: &RefCell<T>) -> bool {
1069 *self.borrow() > *other.borrow()
1074 /// Panics if the value in either `RefCell` is currently borrowed.
1076 fn ge(&self, other: &RefCell<T>) -> bool {
1077 *self.borrow() >= *other.borrow()
1081 #[stable(feature = "cell_ord", since = "1.10.0")]
1082 impl<T: ?Sized + Ord> Ord for RefCell<T> {
1085 /// Panics if the value in either `RefCell` is currently borrowed.
1087 fn cmp(&self, other: &RefCell<T>) -> Ordering {
1088 self.borrow().cmp(&*other.borrow())
1092 #[stable(feature = "cell_from", since = "1.12.0")]
1093 impl<T> From<T> for RefCell<T> {
1094 fn from(t: T) -> RefCell<T> {
1099 #[unstable(feature = "coerce_unsized", issue = "27732")]
1100 impl<T: CoerceUnsized<U>, U> CoerceUnsized<RefCell<U>> for RefCell<T> {}
1102 struct BorrowRef<'b> {
1103 borrow: &'b Cell<BorrowFlag>,
1106 impl<'b> BorrowRef<'b> {
1108 fn new(borrow: &'b Cell<BorrowFlag>) -> Option<BorrowRef<'b>> {
1109 let b = borrow.get().wrapping_add(1);
1111 // Incrementing borrow can result in a non-reading value (<= 0) in these cases:
1112 // 1. It was < 0, i.e. there are writing borrows, so we can't allow a read borrow
1113 // due to Rust's reference aliasing rules
1114 // 2. It was isize::max_value() (the max amount of reading borrows) and it overflowed
1115 // into isize::min_value() (the max amount of writing borrows) so we can't allow
1116 // an additional read borrow because isize can't represent so many read borrows
1117 // (this can only happen if you mem::forget more than a small constant amount of
1118 // `Ref`s, which is not good practice)
1121 // Incrementing borrow can result in a reading value (> 0) in these cases:
1122 // 1. It was = 0, i.e. it wasn't borrowed, and we are taking the first read borrow
1123 // 2. It was > 0 and < isize::max_value(), i.e. there were read borrows, and isize
1124 // is large enough to represent having one more read borrow
1126 Some(BorrowRef { borrow })
1131 impl Drop for BorrowRef<'_> {
1133 fn drop(&mut self) {
1134 let borrow = self.borrow.get();
1135 debug_assert!(is_reading(borrow));
1136 self.borrow.set(borrow - 1);
1140 impl Clone for BorrowRef<'_> {
1142 fn clone(&self) -> Self {
1143 // Since this Ref exists, we know the borrow flag
1144 // is a reading borrow.
1145 let borrow = self.borrow.get();
1146 debug_assert!(is_reading(borrow));
1147 // Prevent the borrow counter from overflowing into
1148 // a writing borrow.
1149 assert!(borrow != isize::max_value());
1150 self.borrow.set(borrow + 1);
1151 BorrowRef { borrow: self.borrow }
1155 /// Wraps a borrowed reference to a value in a `RefCell` box.
1156 /// A wrapper type for an immutably borrowed value from a `RefCell<T>`.
1158 /// See the [module-level documentation](index.html) for more.
1159 #[stable(feature = "rust1", since = "1.0.0")]
1160 pub struct Ref<'b, T: ?Sized + 'b> {
1162 borrow: BorrowRef<'b>,
1165 #[stable(feature = "rust1", since = "1.0.0")]
1166 impl<T: ?Sized> Deref for Ref<'_, T> {
1170 fn deref(&self) -> &T {
1175 impl<'b, T: ?Sized> Ref<'b, T> {
1178 /// The `RefCell` is already immutably borrowed, so this cannot fail.
1180 /// This is an associated function that needs to be used as
1181 /// `Ref::clone(...)`. A `Clone` implementation or a method would interfere
1182 /// with the widespread use of `r.borrow().clone()` to clone the contents of
1184 #[stable(feature = "cell_extras", since = "1.15.0")]
1186 pub fn clone(orig: &Ref<'b, T>) -> Ref<'b, T> {
1189 borrow: orig.borrow.clone(),
1193 /// Makes a new `Ref` for a component of the borrowed data.
1195 /// The `RefCell` is already immutably borrowed, so this cannot fail.
1197 /// This is an associated function that needs to be used as `Ref::map(...)`.
1198 /// A method would interfere with methods of the same name on the contents
1199 /// of a `RefCell` used through `Deref`.
1204 /// use std::cell::{RefCell, Ref};
1206 /// let c = RefCell::new((5, 'b'));
1207 /// let b1: Ref<(u32, char)> = c.borrow();
1208 /// let b2: Ref<u32> = Ref::map(b1, |t| &t.0);
1209 /// assert_eq!(*b2, 5)
1211 #[stable(feature = "cell_map", since = "1.8.0")]
1213 pub fn map<U: ?Sized, F>(orig: Ref<'b, T>, f: F) -> Ref<'b, U>
1214 where F: FnOnce(&T) -> &U
1217 value: f(orig.value),
1218 borrow: orig.borrow,
1222 /// Splits a `Ref` into multiple `Ref`s for different components of the
1225 /// The `RefCell` is already immutably borrowed, so this cannot fail.
1227 /// This is an associated function that needs to be used as
1228 /// `Ref::map_split(...)`. A method would interfere with methods of the same
1229 /// name on the contents of a `RefCell` used through `Deref`.
1234 /// use std::cell::{Ref, RefCell};
1236 /// let cell = RefCell::new([1, 2, 3, 4]);
1237 /// let borrow = cell.borrow();
1238 /// let (begin, end) = Ref::map_split(borrow, |slice| slice.split_at(2));
1239 /// assert_eq!(*begin, [1, 2]);
1240 /// assert_eq!(*end, [3, 4]);
1242 #[stable(feature = "refcell_map_split", since = "1.35.0")]
1244 pub fn map_split<U: ?Sized, V: ?Sized, F>(orig: Ref<'b, T>, f: F) -> (Ref<'b, U>, Ref<'b, V>)
1245 where F: FnOnce(&T) -> (&U, &V)
1247 let (a, b) = f(orig.value);
1248 let borrow = orig.borrow.clone();
1249 (Ref { value: a, borrow }, Ref { value: b, borrow: orig.borrow })
1253 #[unstable(feature = "coerce_unsized", issue = "27732")]
1254 impl<'b, T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Ref<'b, U>> for Ref<'b, T> {}
1256 #[stable(feature = "std_guard_impls", since = "1.20.0")]
1257 impl<T: ?Sized + fmt::Display> fmt::Display for Ref<'_, T> {
1258 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1263 impl<'b, T: ?Sized> RefMut<'b, T> {
1264 /// Makes a new `RefMut` for a component of the borrowed data, e.g., an enum
1267 /// The `RefCell` is already mutably borrowed, so this cannot fail.
1269 /// This is an associated function that needs to be used as
1270 /// `RefMut::map(...)`. A method would interfere with methods of the same
1271 /// name on the contents of a `RefCell` used through `Deref`.
1276 /// use std::cell::{RefCell, RefMut};
1278 /// let c = RefCell::new((5, 'b'));
1280 /// let b1: RefMut<(u32, char)> = c.borrow_mut();
1281 /// let mut b2: RefMut<u32> = RefMut::map(b1, |t| &mut t.0);
1282 /// assert_eq!(*b2, 5);
1285 /// assert_eq!(*c.borrow(), (42, 'b'));
1287 #[stable(feature = "cell_map", since = "1.8.0")]
1289 pub fn map<U: ?Sized, F>(orig: RefMut<'b, T>, f: F) -> RefMut<'b, U>
1290 where F: FnOnce(&mut T) -> &mut U
1292 // FIXME(nll-rfc#40): fix borrow-check
1293 let RefMut { value, borrow } = orig;
1300 /// Splits a `RefMut` into multiple `RefMut`s for different components of the
1303 /// The underlying `RefCell` will remain mutably borrowed until both
1304 /// returned `RefMut`s go out of scope.
1306 /// The `RefCell` is already mutably borrowed, so this cannot fail.
1308 /// This is an associated function that needs to be used as
1309 /// `RefMut::map_split(...)`. A method would interfere with methods of the
1310 /// same name on the contents of a `RefCell` used through `Deref`.
1315 /// use std::cell::{RefCell, RefMut};
1317 /// let cell = RefCell::new([1, 2, 3, 4]);
1318 /// let borrow = cell.borrow_mut();
1319 /// let (mut begin, mut end) = RefMut::map_split(borrow, |slice| slice.split_at_mut(2));
1320 /// assert_eq!(*begin, [1, 2]);
1321 /// assert_eq!(*end, [3, 4]);
1322 /// begin.copy_from_slice(&[4, 3]);
1323 /// end.copy_from_slice(&[2, 1]);
1325 #[stable(feature = "refcell_map_split", since = "1.35.0")]
1327 pub fn map_split<U: ?Sized, V: ?Sized, F>(
1328 orig: RefMut<'b, T>, f: F
1329 ) -> (RefMut<'b, U>, RefMut<'b, V>)
1330 where F: FnOnce(&mut T) -> (&mut U, &mut V)
1332 let (a, b) = f(orig.value);
1333 let borrow = orig.borrow.clone();
1334 (RefMut { value: a, borrow }, RefMut { value: b, borrow: orig.borrow })
1338 struct BorrowRefMut<'b> {
1339 borrow: &'b Cell<BorrowFlag>,
1342 impl Drop for BorrowRefMut<'_> {
1344 fn drop(&mut self) {
1345 let borrow = self.borrow.get();
1346 debug_assert!(is_writing(borrow));
1347 self.borrow.set(borrow + 1);
1351 impl<'b> BorrowRefMut<'b> {
1353 fn new(borrow: &'b Cell<BorrowFlag>) -> Option<BorrowRefMut<'b>> {
1354 // NOTE: Unlike BorrowRefMut::clone, new is called to create the initial
1355 // mutable reference, and so there must currently be no existing
1356 // references. Thus, while clone increments the mutable refcount, here
1357 // we explicitly only allow going from UNUSED to UNUSED - 1.
1358 match borrow.get() {
1360 borrow.set(UNUSED - 1);
1361 Some(BorrowRefMut { borrow })
1367 // Clones a `BorrowRefMut`.
1369 // This is only valid if each `BorrowRefMut` is used to track a mutable
1370 // reference to a distinct, nonoverlapping range of the original object.
1371 // This isn't in a Clone impl so that code doesn't call this implicitly.
1373 fn clone(&self) -> BorrowRefMut<'b> {
1374 let borrow = self.borrow.get();
1375 debug_assert!(is_writing(borrow));
1376 // Prevent the borrow counter from underflowing.
1377 assert!(borrow != isize::min_value());
1378 self.borrow.set(borrow - 1);
1379 BorrowRefMut { borrow: self.borrow }
1383 /// A wrapper type for a mutably borrowed value from a `RefCell<T>`.
1385 /// See the [module-level documentation](index.html) for more.
1386 #[stable(feature = "rust1", since = "1.0.0")]
1387 pub struct RefMut<'b, T: ?Sized + 'b> {
1389 borrow: BorrowRefMut<'b>,
1392 #[stable(feature = "rust1", since = "1.0.0")]
1393 impl<T: ?Sized> Deref for RefMut<'_, T> {
1397 fn deref(&self) -> &T {
1402 #[stable(feature = "rust1", since = "1.0.0")]
1403 impl<T: ?Sized> DerefMut for RefMut<'_, T> {
1405 fn deref_mut(&mut self) -> &mut T {
1410 #[unstable(feature = "coerce_unsized", issue = "27732")]
1411 impl<'b, T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<RefMut<'b, U>> for RefMut<'b, T> {}
1413 #[stable(feature = "std_guard_impls", since = "1.20.0")]
1414 impl<T: ?Sized + fmt::Display> fmt::Display for RefMut<'_, T> {
1415 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1420 /// The core primitive for interior mutability in Rust.
1422 /// `UnsafeCell<T>` is a type that wraps some `T` and indicates unsafe interior operations on the
1423 /// wrapped type. Types with an `UnsafeCell<T>` field are considered to have an 'unsafe interior'.
1424 /// The `UnsafeCell<T>` type is the only legal way to obtain aliasable data that is considered
1425 /// mutable. In general, transmuting an `&T` type into an `&mut T` is considered undefined behavior.
1427 /// If you have a reference `&SomeStruct`, then normally in Rust all fields of `SomeStruct` are
1428 /// immutable. The compiler makes optimizations based on the knowledge that `&T` is not mutably
1429 /// aliased or mutated, and that `&mut T` is unique. `UnsafeCell<T>` is the only core language
1430 /// feature to work around the restriction that `&T` may not be mutated. All other types that
1431 /// allow internal mutability, such as `Cell<T>` and `RefCell<T>`, use `UnsafeCell` to wrap their
1432 /// internal data. There is *no* legal way to obtain aliasing `&mut`, not even with `UnsafeCell<T>`.
1434 /// The `UnsafeCell` API itself is technically very simple: it gives you a raw pointer `*mut T` to
1435 /// its contents. It is up to _you_ as the abstraction designer to use that raw pointer correctly.
1437 /// The precise Rust aliasing rules are somewhat in flux, but the main points are not contentious:
1439 /// - If you create a safe reference with lifetime `'a` (either a `&T` or `&mut T`
1440 /// reference) that is accessible by safe code (for example, because you returned it),
1441 /// then you must not access the data in any way that contradicts that reference for the
1442 /// remainder of `'a`. For example, this means that if you take the `*mut T` from an
1443 /// `UnsafeCell<T>` and cast it to an `&T`, then the data in `T` must remain immutable
1444 /// (modulo any `UnsafeCell` data found within `T`, of course) until that reference's
1445 /// lifetime expires. Similarly, if you create a `&mut T` reference that is released to
1446 /// safe code, then you must not access the data within the `UnsafeCell` until that
1447 /// reference expires.
1449 /// - At all times, you must avoid data races. If multiple threads have access to
1450 /// the same `UnsafeCell`, then any writes must have a proper happens-before relation to all other
1451 /// accesses (or use atomics).
1453 /// To assist with proper design, the following scenarios are explicitly declared legal
1454 /// for single-threaded code:
1456 /// 1. A `&T` reference can be released to safe code and there it can co-exist with other `&T`
1457 /// references, but not with a `&mut T`
1459 /// 2. A `&mut T` reference may be released to safe code provided neither other `&mut T` nor `&T`
1460 /// co-exist with it. A `&mut T` must always be unique.
1462 /// Note that while mutating or mutably aliasing the contents of an `&UnsafeCell<T>` is
1463 /// ok (provided you enforce the invariants some other way), it is still undefined behavior
1464 /// to have multiple `&mut UnsafeCell<T>` aliases.
1469 /// use std::cell::UnsafeCell;
1471 /// # #[allow(dead_code)]
1472 /// struct NotThreadSafe<T> {
1473 /// value: UnsafeCell<T>,
1476 /// unsafe impl<T> Sync for NotThreadSafe<T> {}
1478 #[lang = "unsafe_cell"]
1479 #[stable(feature = "rust1", since = "1.0.0")]
1480 #[repr(transparent)]
1481 pub struct UnsafeCell<T: ?Sized> {
1485 #[stable(feature = "rust1", since = "1.0.0")]
1486 impl<T: ?Sized> !Sync for UnsafeCell<T> {}
1488 impl<T> UnsafeCell<T> {
1489 /// Constructs a new instance of `UnsafeCell` which will wrap the specified
1492 /// All access to the inner value through methods is `unsafe`.
1497 /// use std::cell::UnsafeCell;
1499 /// let uc = UnsafeCell::new(5);
1501 #[stable(feature = "rust1", since = "1.0.0")]
1503 pub const fn new(value: T) -> UnsafeCell<T> {
1504 UnsafeCell { value }
1507 /// Unwraps the value.
1512 /// use std::cell::UnsafeCell;
1514 /// let uc = UnsafeCell::new(5);
1516 /// let five = uc.into_inner();
1519 #[stable(feature = "rust1", since = "1.0.0")]
1520 pub fn into_inner(self) -> T {
1525 impl<T: ?Sized> UnsafeCell<T> {
1526 /// Gets a mutable pointer to the wrapped value.
1528 /// This can be cast to a pointer of any kind.
1529 /// Ensure that the access is unique (no active references, mutable or not)
1530 /// when casting to `&mut T`, and ensure that there are no mutations
1531 /// or mutable aliases going on when casting to `&T`
1536 /// use std::cell::UnsafeCell;
1538 /// let uc = UnsafeCell::new(5);
1540 /// let five = uc.get();
1543 #[stable(feature = "rust1", since = "1.0.0")]
1544 pub const fn get(&self) -> *mut T {
1545 // We can just cast the pointer from `UnsafeCell<T>` to `T` because of
1546 // #[repr(transparent)]
1547 self as *const UnsafeCell<T> as *const T as *mut T
1551 #[stable(feature = "unsafe_cell_default", since = "1.10.0")]
1552 impl<T: Default> Default for UnsafeCell<T> {
1553 /// Creates an `UnsafeCell`, with the `Default` value for T.
1554 fn default() -> UnsafeCell<T> {
1555 UnsafeCell::new(Default::default())
1559 #[stable(feature = "cell_from", since = "1.12.0")]
1560 impl<T> From<T> for UnsafeCell<T> {
1561 fn from(t: T) -> UnsafeCell<T> {
1566 #[unstable(feature = "coerce_unsized", issue = "27732")]
1567 impl<T: CoerceUnsized<U>, U> CoerceUnsized<UnsafeCell<U>> for UnsafeCell<T> {}
1570 fn assert_coerce_unsized(a: UnsafeCell<&i32>, b: Cell<&i32>, c: RefCell<&i32>) {
1571 let _: UnsafeCell<&dyn Send> = a;
1572 let _: Cell<&dyn Send> = b;
1573 let _: RefCell<&dyn Send> = c;