1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Shareable mutable containers.
13 //! Values of the `Cell<T>` and `RefCell<T>` types may be mutated through shared references (i.e.
14 //! the common `&T` type), whereas most Rust types can only be mutated through unique (`&mut T`)
15 //! references. We say that `Cell<T>` and `RefCell<T>` provide 'interior mutability', in contrast
16 //! with typical Rust types that exhibit 'inherited mutability'.
18 //! Cell types come in two flavors: `Cell<T>` and `RefCell<T>`. `Cell<T>` implements interior
19 //! mutability by moving values in and out of the `Cell<T>`. To use references instead of values,
20 //! one must use the `RefCell<T>` type, acquiring a write lock before mutating. `Cell<T>` provides
21 //! methods to retrieve and change the current interior value:
23 //! - For types that implement `Copy`, the `get` method retrieves the current interior value.
24 //! - For types that implement `Default`, the `take` method replaces the current interior value
25 //! with `Default::default()` and returns the replaced value.
26 //! - For all types, the `replace` method replaces the current interior value and returns the
27 //! replaced value and the `into_inner` method consumes the `Cell<T>` and returns the interior
28 //! value. Additionally, the `set` method replaces the interior value, dropping the replaced
31 //! `RefCell<T>` uses Rust's lifetimes to implement 'dynamic borrowing', a process whereby one can
32 //! claim temporary, exclusive, mutable access to the inner value. Borrows for `RefCell<T>`s are
33 //! tracked 'at runtime', unlike Rust's native reference types which are entirely tracked
34 //! statically, at compile time. Because `RefCell<T>` borrows are dynamic it is possible to attempt
35 //! to borrow a value that is already mutably borrowed; when this happens it results in thread
38 //! # When to choose interior mutability
40 //! The more common inherited mutability, where one must have unique access to mutate a value, is
41 //! one of the key language elements that enables Rust to reason strongly about pointer aliasing,
42 //! statically preventing crash bugs. Because of that, inherited mutability is preferred, and
43 //! interior mutability is something of a last resort. Since cell types enable mutation where it
44 //! would otherwise be disallowed though, there are occasions when interior mutability might be
45 //! appropriate, or even *must* be used, e.g.
47 //! * Introducing mutability 'inside' of something immutable
48 //! * Implementation details of logically-immutable methods.
49 //! * Mutating implementations of `Clone`.
51 //! ## Introducing mutability 'inside' of something immutable
53 //! Many shared smart pointer types, including `Rc<T>` and `Arc<T>`, provide containers that can be
54 //! cloned and shared between multiple parties. Because the contained values may be
55 //! multiply-aliased, they can only be borrowed with `&`, not `&mut`. Without cells it would be
56 //! impossible to mutate data inside of these smart pointers at all.
58 //! It's very common then to put a `RefCell<T>` inside shared pointer types to reintroduce
62 //! use std::collections::HashMap;
63 //! use std::cell::RefCell;
67 //! let shared_map: Rc<RefCell<_>> = Rc::new(RefCell::new(HashMap::new()));
68 //! shared_map.borrow_mut().insert("africa", 92388);
69 //! shared_map.borrow_mut().insert("kyoto", 11837);
70 //! shared_map.borrow_mut().insert("piccadilly", 11826);
71 //! shared_map.borrow_mut().insert("marbles", 38);
75 //! Note that this example uses `Rc<T>` and not `Arc<T>`. `RefCell<T>`s are for single-threaded
76 //! scenarios. Consider using `RwLock<T>` or `Mutex<T>` if you need shared mutability in a
77 //! multi-threaded situation.
79 //! ## Implementation details of logically-immutable methods
81 //! Occasionally it may be desirable not to expose in an API that there is mutation happening
82 //! "under the hood". This may be because logically the operation is immutable, but e.g. caching
83 //! forces the implementation to perform mutation; or because you must employ mutation to implement
84 //! a trait method that was originally defined to take `&self`.
87 //! # #![allow(dead_code)]
88 //! use std::cell::RefCell;
91 //! edges: Vec<(i32, i32)>,
92 //! span_tree_cache: RefCell<Option<Vec<(i32, i32)>>>
96 //! fn minimum_spanning_tree(&self) -> Vec<(i32, i32)> {
97 //! // Create a new scope to contain the lifetime of the
100 //! // Take a reference to the inside of cache cell
101 //! let mut cache = self.span_tree_cache.borrow_mut();
102 //! if cache.is_some() {
103 //! return cache.as_ref().unwrap().clone();
106 //! let span_tree = self.calc_span_tree();
107 //! *cache = Some(span_tree);
110 //! // Recursive call to return the just-cached value.
111 //! // Note that if we had not let the previous borrow
112 //! // of the cache fall out of scope then the subsequent
113 //! // recursive borrow would cause a dynamic thread panic.
114 //! // This is the major hazard of using `RefCell`.
115 //! self.minimum_spanning_tree()
117 //! # fn calc_span_tree(&self) -> Vec<(i32, i32)> { vec![] }
121 //! ## Mutating implementations of `Clone`
123 //! This is simply a special - but common - case of the previous: hiding mutability for operations
124 //! that appear to be immutable. The `clone` method is expected to not change the source value, and
125 //! is declared to take `&self`, not `&mut self`. Therefore any mutation that happens in the
126 //! `clone` method must use cell types. For example, `Rc<T>` maintains its reference counts within a
130 //! #![feature(core_intrinsics)]
131 //! #![feature(shared)]
132 //! use std::cell::Cell;
133 //! use std::ptr::Shared;
134 //! use std::intrinsics::abort;
135 //! use std::intrinsics::assume;
137 //! struct Rc<T: ?Sized> {
138 //! ptr: Shared<RcBox<T>>
141 //! struct RcBox<T: ?Sized> {
142 //! strong: Cell<usize>,
143 //! refcount: Cell<usize>,
147 //! impl<T: ?Sized> Clone for Rc<T> {
148 //! fn clone(&self) -> Rc<T> {
149 //! self.inc_strong();
150 //! Rc { ptr: self.ptr }
154 //! trait RcBoxPtr<T: ?Sized> {
156 //! fn inner(&self) -> &RcBox<T>;
158 //! fn strong(&self) -> usize {
159 //! self.inner().strong.get()
162 //! fn inc_strong(&self) {
165 //! .set(self.strong()
167 //! .unwrap_or_else(|| unsafe { abort() }));
171 //! impl<T: ?Sized> RcBoxPtr<T> for Rc<T> {
172 //! fn inner(&self) -> &RcBox<T> {
174 //! assume(!(*(&self.ptr as *const _ as *const *const ())).is_null());
182 #![stable(feature = "rust1", since = "1.0.0")]
185 use fmt::{self, Debug, Display};
188 use ops::{Deref, DerefMut, CoerceUnsized};
191 /// A mutable memory location.
193 /// See the [module-level documentation](index.html) for more.
194 #[stable(feature = "rust1", since = "1.0.0")]
196 value: UnsafeCell<T>,
199 impl<T:Copy> Cell<T> {
200 /// Returns a copy of the contained value.
205 /// use std::cell::Cell;
207 /// let c = Cell::new(5);
209 /// let five = c.get();
212 #[stable(feature = "rust1", since = "1.0.0")]
213 pub fn get(&self) -> T {
214 unsafe{ *self.value.get() }
218 #[stable(feature = "rust1", since = "1.0.0")]
219 unsafe impl<T> Send for Cell<T> where T: Send {}
221 #[stable(feature = "rust1", since = "1.0.0")]
222 impl<T> !Sync for Cell<T> {}
224 #[stable(feature = "rust1", since = "1.0.0")]
225 impl<T:Copy> Clone for Cell<T> {
227 fn clone(&self) -> Cell<T> {
228 Cell::new(self.get())
232 #[stable(feature = "rust1", since = "1.0.0")]
233 impl<T:Default> Default for Cell<T> {
234 /// Creates a `Cell<T>`, with the `Default` value for T.
236 fn default() -> Cell<T> {
237 Cell::new(Default::default())
241 #[stable(feature = "rust1", since = "1.0.0")]
242 impl<T:PartialEq + Copy> PartialEq for Cell<T> {
244 fn eq(&self, other: &Cell<T>) -> bool {
245 self.get() == other.get()
249 #[stable(feature = "cell_eq", since = "1.2.0")]
250 impl<T:Eq + Copy> Eq for Cell<T> {}
252 #[stable(feature = "cell_ord", since = "1.10.0")]
253 impl<T:PartialOrd + Copy> PartialOrd for Cell<T> {
255 fn partial_cmp(&self, other: &Cell<T>) -> Option<Ordering> {
256 self.get().partial_cmp(&other.get())
260 fn lt(&self, other: &Cell<T>) -> bool {
261 self.get() < other.get()
265 fn le(&self, other: &Cell<T>) -> bool {
266 self.get() <= other.get()
270 fn gt(&self, other: &Cell<T>) -> bool {
271 self.get() > other.get()
275 fn ge(&self, other: &Cell<T>) -> bool {
276 self.get() >= other.get()
280 #[stable(feature = "cell_ord", since = "1.10.0")]
281 impl<T:Ord + Copy> Ord for Cell<T> {
283 fn cmp(&self, other: &Cell<T>) -> Ordering {
284 self.get().cmp(&other.get())
288 #[stable(feature = "cell_from", since = "1.12.0")]
289 impl<T> From<T> for Cell<T> {
290 fn from(t: T) -> Cell<T> {
296 /// Creates a new `Cell` containing the given value.
301 /// use std::cell::Cell;
303 /// let c = Cell::new(5);
305 #[stable(feature = "rust1", since = "1.0.0")]
307 pub const fn new(value: T) -> Cell<T> {
309 value: UnsafeCell::new(value),
313 /// Returns a reference to the underlying `UnsafeCell`.
318 /// #![feature(as_unsafe_cell)]
320 /// use std::cell::Cell;
322 /// let c = Cell::new(5);
324 /// let uc = c.as_unsafe_cell();
327 #[unstable(feature = "as_unsafe_cell", issue = "27708")]
328 #[rustc_deprecated(since = "1.12.0", reason = "renamed to as_ptr")]
329 pub fn as_unsafe_cell(&self) -> &UnsafeCell<T> {
333 /// Returns a raw pointer to the underlying data in this cell.
338 /// use std::cell::Cell;
340 /// let c = Cell::new(5);
342 /// let ptr = c.as_ptr();
345 #[stable(feature = "cell_as_ptr", since = "1.12.0")]
346 pub fn as_ptr(&self) -> *mut T {
350 /// Returns a mutable reference to the underlying data.
352 /// This call borrows `Cell` mutably (at compile-time) which guarantees
353 /// that we possess the only reference.
358 /// use std::cell::Cell;
360 /// let mut c = Cell::new(5);
361 /// *c.get_mut() += 1;
363 /// assert_eq!(c.get(), 6);
366 #[stable(feature = "cell_get_mut", since = "1.11.0")]
367 pub fn get_mut(&mut self) -> &mut T {
369 &mut *self.value.get()
373 /// Sets the contained value.
378 /// use std::cell::Cell;
380 /// let c = Cell::new(5);
385 #[stable(feature = "rust1", since = "1.0.0")]
386 pub fn set(&self, val: T) {
387 let old = self.replace(val);
391 /// Swaps the values of two Cells.
392 /// Difference with `std::mem::swap` is that this function doesn't require `&mut` reference.
397 /// use std::cell::Cell;
399 /// let c1 = Cell::new(5i32);
400 /// let c2 = Cell::new(10i32);
402 /// assert_eq!(10, c1.get());
403 /// assert_eq!(5, c2.get());
406 #[stable(feature = "move_cell", since = "1.17.0")]
407 pub fn swap(&self, other: &Self) {
408 if ptr::eq(self, other) {
412 ptr::swap(self.value.get(), other.value.get());
416 /// Replaces the contained value.
421 /// use std::cell::Cell;
423 /// let c = Cell::new(5);
424 /// let old = c.replace(10);
426 /// assert_eq!(5, old);
428 #[stable(feature = "move_cell", since = "1.17.0")]
429 pub fn replace(&self, val: T) -> T {
430 mem::replace(unsafe { &mut *self.value.get() }, val)
433 /// Unwraps the value.
438 /// use std::cell::Cell;
440 /// let c = Cell::new(5);
441 /// let five = c.into_inner();
443 /// assert_eq!(five, 5);
445 #[stable(feature = "move_cell", since = "1.17.0")]
446 pub fn into_inner(self) -> T {
447 unsafe { self.value.into_inner() }
451 impl<T: Default> Cell<T> {
452 /// Takes the value of the cell, leaving `Default::default()` in its place.
457 /// use std::cell::Cell;
459 /// let c = Cell::new(5);
460 /// let five = c.take();
462 /// assert_eq!(five, 5);
463 /// assert_eq!(c.into_inner(), 0);
465 #[stable(feature = "move_cell", since = "1.17.0")]
466 pub fn take(&self) -> T {
467 self.replace(Default::default())
471 #[unstable(feature = "coerce_unsized", issue = "27732")]
472 impl<T: CoerceUnsized<U>, U> CoerceUnsized<Cell<U>> for Cell<T> {}
474 /// A mutable memory location with dynamically checked borrow rules
476 /// See the [module-level documentation](index.html) for more.
477 #[stable(feature = "rust1", since = "1.0.0")]
478 pub struct RefCell<T: ?Sized> {
479 borrow: Cell<BorrowFlag>,
480 value: UnsafeCell<T>,
483 /// An enumeration of values returned from the `state` method on a `RefCell<T>`.
484 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
485 #[unstable(feature = "borrow_state", issue = "27733")]
486 #[rustc_deprecated(since = "1.15.0", reason = "use `try_borrow` instead")]
488 pub enum BorrowState {
489 /// The cell is currently being read, there is at least one active `borrow`.
491 /// The cell is currently being written to, there is an active `borrow_mut`.
493 /// There are no outstanding borrows on this cell.
497 /// An error returned by [`RefCell::try_borrow`](struct.RefCell.html#method.try_borrow).
498 #[stable(feature = "try_borrow", since = "1.13.0")]
499 pub struct BorrowError {
503 #[stable(feature = "try_borrow", since = "1.13.0")]
504 impl Debug for BorrowError {
505 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
506 f.debug_struct("BorrowError").finish()
510 #[stable(feature = "try_borrow", since = "1.13.0")]
511 impl Display for BorrowError {
512 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
513 Display::fmt("already mutably borrowed", f)
517 /// An error returned by [`RefCell::try_borrow_mut`](struct.RefCell.html#method.try_borrow_mut).
518 #[stable(feature = "try_borrow", since = "1.13.0")]
519 pub struct BorrowMutError {
523 #[stable(feature = "try_borrow", since = "1.13.0")]
524 impl Debug for BorrowMutError {
525 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
526 f.debug_struct("BorrowMutError").finish()
530 #[stable(feature = "try_borrow", since = "1.13.0")]
531 impl Display for BorrowMutError {
532 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
533 Display::fmt("already borrowed", f)
537 // Values [1, MAX-1] represent the number of `Ref` active
538 // (will not outgrow its range since `usize` is the size of the address space)
539 type BorrowFlag = usize;
540 const UNUSED: BorrowFlag = 0;
541 const WRITING: BorrowFlag = !0;
544 /// Creates a new `RefCell` containing `value`.
549 /// use std::cell::RefCell;
551 /// let c = RefCell::new(5);
553 #[stable(feature = "rust1", since = "1.0.0")]
555 pub const fn new(value: T) -> RefCell<T> {
557 value: UnsafeCell::new(value),
558 borrow: Cell::new(UNUSED),
562 /// Consumes the `RefCell`, returning the wrapped value.
567 /// use std::cell::RefCell;
569 /// let c = RefCell::new(5);
571 /// let five = c.into_inner();
573 #[stable(feature = "rust1", since = "1.0.0")]
575 pub fn into_inner(self) -> T {
576 // Since this function takes `self` (the `RefCell`) by value, the
577 // compiler statically verifies that it is not currently borrowed.
578 // Therefore the following assertion is just a `debug_assert!`.
579 debug_assert!(self.borrow.get() == UNUSED);
580 unsafe { self.value.into_inner() }
584 impl<T: ?Sized> RefCell<T> {
585 /// Query the current state of this `RefCell`
587 /// The returned value can be dispatched on to determine if a call to
588 /// `borrow` or `borrow_mut` would succeed.
593 /// #![feature(borrow_state)]
595 /// use std::cell::{BorrowState, RefCell};
597 /// let c = RefCell::new(5);
599 /// match c.borrow_state() {
600 /// BorrowState::Writing => println!("Cannot be borrowed"),
601 /// BorrowState::Reading => println!("Cannot be borrowed mutably"),
602 /// BorrowState::Unused => println!("Can be borrowed (mutably as well)"),
605 #[unstable(feature = "borrow_state", issue = "27733")]
606 #[rustc_deprecated(since = "1.15.0", reason = "use `try_borrow` instead")]
609 pub fn borrow_state(&self) -> BorrowState {
610 match self.borrow.get() {
611 WRITING => BorrowState::Writing,
612 UNUSED => BorrowState::Unused,
613 _ => BorrowState::Reading,
617 /// Immutably borrows the wrapped value.
619 /// The borrow lasts until the returned `Ref` exits scope. Multiple
620 /// immutable borrows can be taken out at the same time.
624 /// Panics if the value is currently mutably borrowed. For a non-panicking variant, use
625 /// [`try_borrow`](#method.try_borrow).
630 /// use std::cell::RefCell;
632 /// let c = RefCell::new(5);
634 /// let borrowed_five = c.borrow();
635 /// let borrowed_five2 = c.borrow();
638 /// An example of panic:
641 /// use std::cell::RefCell;
644 /// let result = thread::spawn(move || {
645 /// let c = RefCell::new(5);
646 /// let m = c.borrow_mut();
648 /// let b = c.borrow(); // this causes a panic
651 /// assert!(result.is_err());
653 #[stable(feature = "rust1", since = "1.0.0")]
655 pub fn borrow(&self) -> Ref<T> {
656 self.try_borrow().expect("already mutably borrowed")
659 /// Immutably borrows the wrapped value, returning an error if the value is currently mutably
662 /// The borrow lasts until the returned `Ref` exits scope. Multiple immutable borrows can be
663 /// taken out at the same time.
665 /// This is the non-panicking variant of [`borrow`](#method.borrow).
670 /// use std::cell::RefCell;
672 /// let c = RefCell::new(5);
675 /// let m = c.borrow_mut();
676 /// assert!(c.try_borrow().is_err());
680 /// let m = c.borrow();
681 /// assert!(c.try_borrow().is_ok());
684 #[stable(feature = "try_borrow", since = "1.13.0")]
686 pub fn try_borrow(&self) -> Result<Ref<T>, BorrowError> {
687 match BorrowRef::new(&self.borrow) {
689 value: unsafe { &*self.value.get() },
692 None => Err(BorrowError { _private: () }),
696 /// Mutably borrows the wrapped value.
698 /// The borrow lasts until the returned `RefMut` exits scope. The value
699 /// cannot be borrowed while this borrow is active.
703 /// Panics if the value is currently borrowed. For a non-panicking variant, use
704 /// [`try_borrow_mut`](#method.try_borrow_mut).
709 /// use std::cell::RefCell;
711 /// let c = RefCell::new(5);
713 /// *c.borrow_mut() = 7;
715 /// assert_eq!(*c.borrow(), 7);
718 /// An example of panic:
721 /// use std::cell::RefCell;
724 /// let result = thread::spawn(move || {
725 /// let c = RefCell::new(5);
726 /// let m = c.borrow();
728 /// let b = c.borrow_mut(); // this causes a panic
731 /// assert!(result.is_err());
733 #[stable(feature = "rust1", since = "1.0.0")]
735 pub fn borrow_mut(&self) -> RefMut<T> {
736 self.try_borrow_mut().expect("already borrowed")
739 /// Mutably borrows the wrapped value, returning an error if the value is currently borrowed.
741 /// The borrow lasts until the returned `RefMut` exits scope. The value cannot be borrowed
742 /// while this borrow is active.
744 /// This is the non-panicking variant of [`borrow_mut`](#method.borrow_mut).
749 /// use std::cell::RefCell;
751 /// let c = RefCell::new(5);
754 /// let m = c.borrow();
755 /// assert!(c.try_borrow_mut().is_err());
758 /// assert!(c.try_borrow_mut().is_ok());
760 #[stable(feature = "try_borrow", since = "1.13.0")]
762 pub fn try_borrow_mut(&self) -> Result<RefMut<T>, BorrowMutError> {
763 match BorrowRefMut::new(&self.borrow) {
764 Some(b) => Ok(RefMut {
765 value: unsafe { &mut *self.value.get() },
768 None => Err(BorrowMutError { _private: () }),
772 /// Returns a reference to the underlying `UnsafeCell`.
774 /// This can be used to circumvent `RefCell`'s safety checks.
776 /// This function is `unsafe` because `UnsafeCell`'s field is public.
781 /// #![feature(as_unsafe_cell)]
783 /// use std::cell::RefCell;
785 /// let c = RefCell::new(5);
786 /// let c = unsafe { c.as_unsafe_cell() };
789 #[unstable(feature = "as_unsafe_cell", issue = "27708")]
790 #[rustc_deprecated(since = "1.12.0", reason = "renamed to as_ptr")]
791 pub unsafe fn as_unsafe_cell(&self) -> &UnsafeCell<T> {
795 /// Returns a raw pointer to the underlying data in this cell.
800 /// use std::cell::RefCell;
802 /// let c = RefCell::new(5);
804 /// let ptr = c.as_ptr();
807 #[stable(feature = "cell_as_ptr", since = "1.12.0")]
808 pub fn as_ptr(&self) -> *mut T {
812 /// Returns a mutable reference to the underlying data.
814 /// This call borrows `RefCell` mutably (at compile-time) so there is no
815 /// need for dynamic checks.
820 /// use std::cell::RefCell;
822 /// let mut c = RefCell::new(5);
823 /// *c.get_mut() += 1;
825 /// assert_eq!(c, RefCell::new(6));
828 #[stable(feature = "cell_get_mut", since = "1.11.0")]
829 pub fn get_mut(&mut self) -> &mut T {
831 &mut *self.value.get()
836 #[stable(feature = "rust1", since = "1.0.0")]
837 unsafe impl<T: ?Sized> Send for RefCell<T> where T: Send {}
839 #[stable(feature = "rust1", since = "1.0.0")]
840 impl<T: ?Sized> !Sync for RefCell<T> {}
842 #[stable(feature = "rust1", since = "1.0.0")]
843 impl<T: Clone> Clone for RefCell<T> {
845 fn clone(&self) -> RefCell<T> {
846 RefCell::new(self.borrow().clone())
850 #[stable(feature = "rust1", since = "1.0.0")]
851 impl<T:Default> Default for RefCell<T> {
852 /// Creates a `RefCell<T>`, with the `Default` value for T.
854 fn default() -> RefCell<T> {
855 RefCell::new(Default::default())
859 #[stable(feature = "rust1", since = "1.0.0")]
860 impl<T: ?Sized + PartialEq> PartialEq for RefCell<T> {
862 fn eq(&self, other: &RefCell<T>) -> bool {
863 *self.borrow() == *other.borrow()
867 #[stable(feature = "cell_eq", since = "1.2.0")]
868 impl<T: ?Sized + Eq> Eq for RefCell<T> {}
870 #[stable(feature = "cell_ord", since = "1.10.0")]
871 impl<T: ?Sized + PartialOrd> PartialOrd for RefCell<T> {
873 fn partial_cmp(&self, other: &RefCell<T>) -> Option<Ordering> {
874 self.borrow().partial_cmp(&*other.borrow())
878 fn lt(&self, other: &RefCell<T>) -> bool {
879 *self.borrow() < *other.borrow()
883 fn le(&self, other: &RefCell<T>) -> bool {
884 *self.borrow() <= *other.borrow()
888 fn gt(&self, other: &RefCell<T>) -> bool {
889 *self.borrow() > *other.borrow()
893 fn ge(&self, other: &RefCell<T>) -> bool {
894 *self.borrow() >= *other.borrow()
898 #[stable(feature = "cell_ord", since = "1.10.0")]
899 impl<T: ?Sized + Ord> Ord for RefCell<T> {
901 fn cmp(&self, other: &RefCell<T>) -> Ordering {
902 self.borrow().cmp(&*other.borrow())
906 #[stable(feature = "cell_from", since = "1.12.0")]
907 impl<T> From<T> for RefCell<T> {
908 fn from(t: T) -> RefCell<T> {
913 #[unstable(feature = "coerce_unsized", issue = "27732")]
914 impl<T: CoerceUnsized<U>, U> CoerceUnsized<RefCell<U>> for RefCell<T> {}
916 struct BorrowRef<'b> {
917 borrow: &'b Cell<BorrowFlag>,
920 impl<'b> BorrowRef<'b> {
922 fn new(borrow: &'b Cell<BorrowFlag>) -> Option<BorrowRef<'b>> {
927 Some(BorrowRef { borrow: borrow })
933 impl<'b> Drop for BorrowRef<'b> {
936 let borrow = self.borrow.get();
937 debug_assert!(borrow != WRITING && borrow != UNUSED);
938 self.borrow.set(borrow - 1);
942 impl<'b> Clone for BorrowRef<'b> {
944 fn clone(&self) -> BorrowRef<'b> {
945 // Since this Ref exists, we know the borrow flag
946 // is not set to WRITING.
947 let borrow = self.borrow.get();
948 debug_assert!(borrow != UNUSED);
949 // Prevent the borrow counter from overflowing.
950 assert!(borrow != WRITING);
951 self.borrow.set(borrow + 1);
952 BorrowRef { borrow: self.borrow }
956 /// Wraps a borrowed reference to a value in a `RefCell` box.
957 /// A wrapper type for an immutably borrowed value from a `RefCell<T>`.
959 /// See the [module-level documentation](index.html) for more.
960 #[stable(feature = "rust1", since = "1.0.0")]
961 pub struct Ref<'b, T: ?Sized + 'b> {
963 borrow: BorrowRef<'b>,
966 #[stable(feature = "rust1", since = "1.0.0")]
967 impl<'b, T: ?Sized> Deref for Ref<'b, T> {
971 fn deref(&self) -> &T {
976 impl<'b, T: ?Sized> Ref<'b, T> {
979 /// The `RefCell` is already immutably borrowed, so this cannot fail.
981 /// This is an associated function that needs to be used as
982 /// `Ref::clone(...)`. A `Clone` implementation or a method would interfere
983 /// with the widespread use of `r.borrow().clone()` to clone the contents of
985 #[stable(feature = "cell_extras", since = "1.15.0")]
987 pub fn clone(orig: &Ref<'b, T>) -> Ref<'b, T> {
990 borrow: orig.borrow.clone(),
994 /// Make a new `Ref` for a component of the borrowed data.
996 /// The `RefCell` is already immutably borrowed, so this cannot fail.
998 /// This is an associated function that needs to be used as `Ref::map(...)`.
999 /// A method would interfere with methods of the same name on the contents
1000 /// of a `RefCell` used through `Deref`.
1005 /// use std::cell::{RefCell, Ref};
1007 /// let c = RefCell::new((5, 'b'));
1008 /// let b1: Ref<(u32, char)> = c.borrow();
1009 /// let b2: Ref<u32> = Ref::map(b1, |t| &t.0);
1010 /// assert_eq!(*b2, 5)
1012 #[stable(feature = "cell_map", since = "1.8.0")]
1014 pub fn map<U: ?Sized, F>(orig: Ref<'b, T>, f: F) -> Ref<'b, U>
1015 where F: FnOnce(&T) -> &U
1018 value: f(orig.value),
1019 borrow: orig.borrow,
1024 #[unstable(feature = "coerce_unsized", issue = "27732")]
1025 impl<'b, T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Ref<'b, U>> for Ref<'b, T> {}
1027 impl<'b, T: ?Sized> RefMut<'b, T> {
1028 /// Make a new `RefMut` for a component of the borrowed data, e.g. an enum
1031 /// The `RefCell` is already mutably borrowed, so this cannot fail.
1033 /// This is an associated function that needs to be used as
1034 /// `RefMut::map(...)`. A method would interfere with methods of the same
1035 /// name on the contents of a `RefCell` used through `Deref`.
1040 /// use std::cell::{RefCell, RefMut};
1042 /// let c = RefCell::new((5, 'b'));
1044 /// let b1: RefMut<(u32, char)> = c.borrow_mut();
1045 /// let mut b2: RefMut<u32> = RefMut::map(b1, |t| &mut t.0);
1046 /// assert_eq!(*b2, 5);
1049 /// assert_eq!(*c.borrow(), (42, 'b'));
1051 #[stable(feature = "cell_map", since = "1.8.0")]
1053 pub fn map<U: ?Sized, F>(orig: RefMut<'b, T>, f: F) -> RefMut<'b, U>
1054 where F: FnOnce(&mut T) -> &mut U
1057 value: f(orig.value),
1058 borrow: orig.borrow,
1063 struct BorrowRefMut<'b> {
1064 borrow: &'b Cell<BorrowFlag>,
1067 impl<'b> Drop for BorrowRefMut<'b> {
1069 fn drop(&mut self) {
1070 let borrow = self.borrow.get();
1071 debug_assert!(borrow == WRITING);
1072 self.borrow.set(UNUSED);
1076 impl<'b> BorrowRefMut<'b> {
1078 fn new(borrow: &'b Cell<BorrowFlag>) -> Option<BorrowRefMut<'b>> {
1079 match borrow.get() {
1081 borrow.set(WRITING);
1082 Some(BorrowRefMut { borrow: borrow })
1089 /// A wrapper type for a mutably borrowed value from a `RefCell<T>`.
1091 /// See the [module-level documentation](index.html) for more.
1092 #[stable(feature = "rust1", since = "1.0.0")]
1093 pub struct RefMut<'b, T: ?Sized + 'b> {
1095 borrow: BorrowRefMut<'b>,
1098 #[stable(feature = "rust1", since = "1.0.0")]
1099 impl<'b, T: ?Sized> Deref for RefMut<'b, T> {
1103 fn deref(&self) -> &T {
1108 #[stable(feature = "rust1", since = "1.0.0")]
1109 impl<'b, T: ?Sized> DerefMut for RefMut<'b, T> {
1111 fn deref_mut(&mut self) -> &mut T {
1116 #[unstable(feature = "coerce_unsized", issue = "27732")]
1117 impl<'b, T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<RefMut<'b, U>> for RefMut<'b, T> {}
1119 /// The core primitive for interior mutability in Rust.
1121 /// `UnsafeCell<T>` is a type that wraps some `T` and indicates unsafe interior operations on the
1122 /// wrapped type. Types with an `UnsafeCell<T>` field are considered to have an 'unsafe interior'.
1123 /// The `UnsafeCell<T>` type is the only legal way to obtain aliasable data that is considered
1124 /// mutable. In general, transmuting an `&T` type into an `&mut T` is considered undefined behavior.
1126 /// The compiler makes optimizations based on the knowledge that `&T` is not mutably aliased or
1127 /// mutated, and that `&mut T` is unique. When building abstractions like `Cell`, `RefCell`,
1128 /// `Mutex`, etc, you need to turn these optimizations off. `UnsafeCell` is the only legal way
1129 /// to do this. When `UnsafeCell<T>` is immutably aliased, it is still safe to obtain a mutable
1130 /// reference to its interior and/or to mutate it. However, it is up to the abstraction designer
1131 /// to ensure that no two mutable references obtained this way are active at the same time, and
1132 /// that there are no active mutable references or mutations when an immutable reference is obtained
1133 /// from the cell. This is often done via runtime checks.
1135 /// Note that while mutating or mutably aliasing the contents of an `& UnsafeCell<T>` is
1136 /// okay (provided you enforce the invariants some other way); it is still undefined behavior
1137 /// to have multiple `&mut UnsafeCell<T>` aliases.
1140 /// Types like `Cell<T>` and `RefCell<T>` use this type to wrap their internal data.
1145 /// use std::cell::UnsafeCell;
1146 /// use std::marker::Sync;
1148 /// # #[allow(dead_code)]
1149 /// struct NotThreadSafe<T> {
1150 /// value: UnsafeCell<T>,
1153 /// unsafe impl<T> Sync for NotThreadSafe<T> {}
1155 #[lang = "unsafe_cell"]
1156 #[stable(feature = "rust1", since = "1.0.0")]
1157 pub struct UnsafeCell<T: ?Sized> {
1161 #[stable(feature = "rust1", since = "1.0.0")]
1162 impl<T: ?Sized> !Sync for UnsafeCell<T> {}
1164 impl<T> UnsafeCell<T> {
1165 /// Constructs a new instance of `UnsafeCell` which will wrap the specified
1168 /// All access to the inner value through methods is `unsafe`.
1173 /// use std::cell::UnsafeCell;
1175 /// let uc = UnsafeCell::new(5);
1177 #[stable(feature = "rust1", since = "1.0.0")]
1179 pub const fn new(value: T) -> UnsafeCell<T> {
1180 UnsafeCell { value: value }
1183 /// Unwraps the value.
1187 /// This function is unsafe because this thread or another thread may currently be
1188 /// inspecting the inner value.
1193 /// use std::cell::UnsafeCell;
1195 /// let uc = UnsafeCell::new(5);
1197 /// let five = unsafe { uc.into_inner() };
1200 #[stable(feature = "rust1", since = "1.0.0")]
1201 pub unsafe fn into_inner(self) -> T {
1206 impl<T: ?Sized> UnsafeCell<T> {
1207 /// Gets a mutable pointer to the wrapped value.
1209 /// This can be cast to a pointer of any kind.
1210 /// Ensure that the access is unique when casting to
1211 /// `&mut T`, and ensure that there are no mutations or mutable
1212 /// aliases going on when casting to `&T`
1217 /// use std::cell::UnsafeCell;
1219 /// let uc = UnsafeCell::new(5);
1221 /// let five = uc.get();
1224 #[stable(feature = "rust1", since = "1.0.0")]
1225 pub fn get(&self) -> *mut T {
1226 &self.value as *const T as *mut T
1230 #[stable(feature = "unsafe_cell_default", since = "1.9.0")]
1231 impl<T: Default> Default for UnsafeCell<T> {
1232 /// Creates an `UnsafeCell`, with the `Default` value for T.
1233 fn default() -> UnsafeCell<T> {
1234 UnsafeCell::new(Default::default())
1238 #[stable(feature = "cell_from", since = "1.12.0")]
1239 impl<T> From<T> for UnsafeCell<T> {
1240 fn from(t: T) -> UnsafeCell<T> {
1245 #[unstable(feature = "coerce_unsized", issue = "27732")]
1246 impl<T: CoerceUnsized<U>, U> CoerceUnsized<UnsafeCell<U>> for UnsafeCell<T> {}
1249 fn assert_coerce_unsized(a: UnsafeCell<&i32>, b: Cell<&i32>, c: RefCell<&i32>) {
1250 let _: UnsafeCell<&Send> = a;
1251 let _: Cell<&Send> = b;
1252 let _: RefCell<&Send> = c;