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;
136 //! struct Rc<T: ?Sized> {
137 //! ptr: Shared<RcBox<T>>
140 //! struct RcBox<T: ?Sized> {
141 //! strong: Cell<usize>,
142 //! refcount: Cell<usize>,
146 //! impl<T: ?Sized> Clone for Rc<T> {
147 //! fn clone(&self) -> Rc<T> {
148 //! self.inc_strong();
149 //! Rc { ptr: self.ptr }
153 //! trait RcBoxPtr<T: ?Sized> {
155 //! fn inner(&self) -> &RcBox<T>;
157 //! fn strong(&self) -> usize {
158 //! self.inner().strong.get()
161 //! fn inc_strong(&self) {
164 //! .set(self.strong()
166 //! .unwrap_or_else(|| unsafe { abort() }));
170 //! impl<T: ?Sized> RcBoxPtr<T> for Rc<T> {
171 //! fn inner(&self) -> &RcBox<T> {
173 //! self.ptr.as_ref()
180 #![stable(feature = "rust1", since = "1.0.0")]
183 use fmt::{self, Debug, Display};
186 use ops::{Deref, DerefMut, CoerceUnsized};
189 /// A mutable memory location.
193 /// Here you can see how using `Cell<T>` allows to use mutable field inside
194 /// immutable struct (which is also called 'interior mutability').
197 /// use std::cell::Cell;
199 /// struct SomeStruct {
200 /// regular_field: u8,
201 /// special_field: Cell<u8>,
204 /// let my_struct = SomeStruct {
205 /// regular_field: 0,
206 /// special_field: Cell::new(1),
209 /// let new_value = 100;
211 /// // ERROR, because my_struct is immutable
212 /// // my_struct.regular_field = new_value;
214 /// // WORKS, although `my_struct` is immutable, field `special_field` is mutable because it is Cell
215 /// my_struct.special_field.set(new_value);
216 /// assert_eq!(my_struct.special_field.get(), new_value);
219 /// See the [module-level documentation](index.html) for more.
220 #[stable(feature = "rust1", since = "1.0.0")]
222 value: UnsafeCell<T>,
225 impl<T:Copy> Cell<T> {
226 /// Returns a copy of the contained value.
231 /// use std::cell::Cell;
233 /// let c = Cell::new(5);
235 /// let five = c.get();
238 #[stable(feature = "rust1", since = "1.0.0")]
239 pub fn get(&self) -> T {
240 unsafe{ *self.value.get() }
244 #[stable(feature = "rust1", since = "1.0.0")]
245 unsafe impl<T> Send for Cell<T> where T: Send {}
247 #[stable(feature = "rust1", since = "1.0.0")]
248 impl<T> !Sync for Cell<T> {}
250 #[stable(feature = "rust1", since = "1.0.0")]
251 impl<T:Copy> Clone for Cell<T> {
253 fn clone(&self) -> Cell<T> {
254 Cell::new(self.get())
258 #[stable(feature = "rust1", since = "1.0.0")]
259 impl<T:Default> Default for Cell<T> {
260 /// Creates a `Cell<T>`, with the `Default` value for T.
262 fn default() -> Cell<T> {
263 Cell::new(Default::default())
267 #[stable(feature = "rust1", since = "1.0.0")]
268 impl<T:PartialEq + Copy> PartialEq for Cell<T> {
270 fn eq(&self, other: &Cell<T>) -> bool {
271 self.get() == other.get()
275 #[stable(feature = "cell_eq", since = "1.2.0")]
276 impl<T:Eq + Copy> Eq for Cell<T> {}
278 #[stable(feature = "cell_ord", since = "1.10.0")]
279 impl<T:PartialOrd + Copy> PartialOrd for Cell<T> {
281 fn partial_cmp(&self, other: &Cell<T>) -> Option<Ordering> {
282 self.get().partial_cmp(&other.get())
286 fn lt(&self, other: &Cell<T>) -> bool {
287 self.get() < other.get()
291 fn le(&self, other: &Cell<T>) -> bool {
292 self.get() <= other.get()
296 fn gt(&self, other: &Cell<T>) -> bool {
297 self.get() > other.get()
301 fn ge(&self, other: &Cell<T>) -> bool {
302 self.get() >= other.get()
306 #[stable(feature = "cell_ord", since = "1.10.0")]
307 impl<T:Ord + Copy> Ord for Cell<T> {
309 fn cmp(&self, other: &Cell<T>) -> Ordering {
310 self.get().cmp(&other.get())
314 #[stable(feature = "cell_from", since = "1.12.0")]
315 impl<T> From<T> for Cell<T> {
316 fn from(t: T) -> Cell<T> {
322 /// Creates a new `Cell` containing the given value.
327 /// use std::cell::Cell;
329 /// let c = Cell::new(5);
331 #[stable(feature = "rust1", since = "1.0.0")]
333 pub const fn new(value: T) -> Cell<T> {
335 value: UnsafeCell::new(value),
339 /// Returns a raw pointer to the underlying data in this cell.
344 /// use std::cell::Cell;
346 /// let c = Cell::new(5);
348 /// let ptr = c.as_ptr();
351 #[stable(feature = "cell_as_ptr", since = "1.12.0")]
352 pub fn as_ptr(&self) -> *mut T {
356 /// Returns a mutable reference to the underlying data.
358 /// This call borrows `Cell` mutably (at compile-time) which guarantees
359 /// that we possess the only reference.
364 /// use std::cell::Cell;
366 /// let mut c = Cell::new(5);
367 /// *c.get_mut() += 1;
369 /// assert_eq!(c.get(), 6);
372 #[stable(feature = "cell_get_mut", since = "1.11.0")]
373 pub fn get_mut(&mut self) -> &mut T {
375 &mut *self.value.get()
379 /// Sets the contained value.
384 /// use std::cell::Cell;
386 /// let c = Cell::new(5);
391 #[stable(feature = "rust1", since = "1.0.0")]
392 pub fn set(&self, val: T) {
393 let old = self.replace(val);
397 /// Swaps the values of two Cells.
398 /// Difference with `std::mem::swap` is that this function doesn't require `&mut` reference.
403 /// use std::cell::Cell;
405 /// let c1 = Cell::new(5i32);
406 /// let c2 = Cell::new(10i32);
408 /// assert_eq!(10, c1.get());
409 /// assert_eq!(5, c2.get());
412 #[stable(feature = "move_cell", since = "1.17.0")]
413 pub fn swap(&self, other: &Self) {
414 if ptr::eq(self, other) {
418 ptr::swap(self.value.get(), other.value.get());
422 /// Replaces the contained value, and returns it.
427 /// use std::cell::Cell;
429 /// let cell = Cell::new(5);
430 /// assert_eq!(cell.get(), 5);
431 /// assert_eq!(cell.replace(10), 5);
432 /// assert_eq!(cell.get(), 10);
434 #[stable(feature = "move_cell", since = "1.17.0")]
435 pub fn replace(&self, val: T) -> T {
436 mem::replace(unsafe { &mut *self.value.get() }, val)
439 /// Unwraps the value.
444 /// use std::cell::Cell;
446 /// let c = Cell::new(5);
447 /// let five = c.into_inner();
449 /// assert_eq!(five, 5);
451 #[stable(feature = "move_cell", since = "1.17.0")]
452 pub fn into_inner(self) -> T {
453 unsafe { self.value.into_inner() }
457 impl<T: Default> Cell<T> {
458 /// Takes the value of the cell, leaving `Default::default()` in its place.
463 /// use std::cell::Cell;
465 /// let c = Cell::new(5);
466 /// let five = c.take();
468 /// assert_eq!(five, 5);
469 /// assert_eq!(c.into_inner(), 0);
471 #[stable(feature = "move_cell", since = "1.17.0")]
472 pub fn take(&self) -> T {
473 self.replace(Default::default())
477 #[unstable(feature = "coerce_unsized", issue = "27732")]
478 impl<T: CoerceUnsized<U>, U> CoerceUnsized<Cell<U>> for Cell<T> {}
480 /// A mutable memory location with dynamically checked borrow rules
482 /// See the [module-level documentation](index.html) for more.
483 #[stable(feature = "rust1", since = "1.0.0")]
484 pub struct RefCell<T: ?Sized> {
485 borrow: Cell<BorrowFlag>,
486 value: UnsafeCell<T>,
489 /// An error returned by [`RefCell::try_borrow`](struct.RefCell.html#method.try_borrow).
490 #[stable(feature = "try_borrow", since = "1.13.0")]
491 pub struct BorrowError {
495 #[stable(feature = "try_borrow", since = "1.13.0")]
496 impl Debug for BorrowError {
497 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
498 f.debug_struct("BorrowError").finish()
502 #[stable(feature = "try_borrow", since = "1.13.0")]
503 impl Display for BorrowError {
504 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
505 Display::fmt("already mutably borrowed", f)
509 /// An error returned by [`RefCell::try_borrow_mut`](struct.RefCell.html#method.try_borrow_mut).
510 #[stable(feature = "try_borrow", since = "1.13.0")]
511 pub struct BorrowMutError {
515 #[stable(feature = "try_borrow", since = "1.13.0")]
516 impl Debug for BorrowMutError {
517 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
518 f.debug_struct("BorrowMutError").finish()
522 #[stable(feature = "try_borrow", since = "1.13.0")]
523 impl Display for BorrowMutError {
524 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
525 Display::fmt("already borrowed", f)
529 // Values [1, MAX-1] represent the number of `Ref` active
530 // (will not outgrow its range since `usize` is the size of the address space)
531 type BorrowFlag = usize;
532 const UNUSED: BorrowFlag = 0;
533 const WRITING: BorrowFlag = !0;
536 /// Creates a new `RefCell` containing `value`.
541 /// use std::cell::RefCell;
543 /// let c = RefCell::new(5);
545 #[stable(feature = "rust1", since = "1.0.0")]
547 pub const fn new(value: T) -> RefCell<T> {
549 value: UnsafeCell::new(value),
550 borrow: Cell::new(UNUSED),
554 /// Consumes the `RefCell`, returning the wrapped value.
559 /// use std::cell::RefCell;
561 /// let c = RefCell::new(5);
563 /// let five = c.into_inner();
565 #[stable(feature = "rust1", since = "1.0.0")]
567 pub fn into_inner(self) -> T {
568 // Since this function takes `self` (the `RefCell`) by value, the
569 // compiler statically verifies that it is not currently borrowed.
570 // Therefore the following assertion is just a `debug_assert!`.
571 debug_assert!(self.borrow.get() == UNUSED);
572 unsafe { self.value.into_inner() }
575 /// Replaces the wrapped value with a new one, returning the old value,
576 /// without deinitializing either one.
578 /// This function corresponds to [`std::mem::replace`](../mem/fn.replace.html).
583 /// #![feature(refcell_replace_swap)]
584 /// use std::cell::RefCell;
585 /// let c = RefCell::new(5);
586 /// let u = c.replace(6);
587 /// assert_eq!(u, 5);
588 /// assert_eq!(c, RefCell::new(6));
593 /// This function will panic if the `RefCell` has any outstanding borrows,
594 /// whether or not they are full mutable borrows.
596 #[unstable(feature = "refcell_replace_swap", issue="43570")]
597 pub fn replace(&self, t: T) -> T {
598 mem::replace(&mut *self.borrow_mut(), t)
601 /// Swaps the wrapped value of `self` with the wrapped value of `other`,
602 /// without deinitializing either one.
604 /// This function corresponds to [`std::mem::swap`](../mem/fn.swap.html).
609 /// #![feature(refcell_replace_swap)]
610 /// use std::cell::RefCell;
611 /// let c = RefCell::new(5);
612 /// let d = RefCell::new(6);
614 /// assert_eq!(c, RefCell::new(6));
615 /// assert_eq!(d, RefCell::new(5));
620 /// This function will panic if either `RefCell` has any outstanding borrows,
621 /// whether or not they are full mutable borrows.
623 #[unstable(feature = "refcell_replace_swap", issue="43570")]
624 pub fn swap(&self, other: &Self) {
625 mem::swap(&mut *self.borrow_mut(), &mut *other.borrow_mut())
629 impl<T: ?Sized> RefCell<T> {
630 /// Immutably borrows the wrapped value.
632 /// The borrow lasts until the returned `Ref` exits scope. Multiple
633 /// immutable borrows can be taken out at the same time.
637 /// Panics if the value is currently mutably borrowed. For a non-panicking variant, use
638 /// [`try_borrow`](#method.try_borrow).
643 /// use std::cell::RefCell;
645 /// let c = RefCell::new(5);
647 /// let borrowed_five = c.borrow();
648 /// let borrowed_five2 = c.borrow();
651 /// An example of panic:
654 /// use std::cell::RefCell;
657 /// let result = thread::spawn(move || {
658 /// let c = RefCell::new(5);
659 /// let m = c.borrow_mut();
661 /// let b = c.borrow(); // this causes a panic
664 /// assert!(result.is_err());
666 #[stable(feature = "rust1", since = "1.0.0")]
668 pub fn borrow(&self) -> Ref<T> {
669 self.try_borrow().expect("already mutably borrowed")
672 /// Immutably borrows the wrapped value, returning an error if the value is currently mutably
675 /// The borrow lasts until the returned `Ref` exits scope. Multiple immutable borrows can be
676 /// taken out at the same time.
678 /// This is the non-panicking variant of [`borrow`](#method.borrow).
683 /// use std::cell::RefCell;
685 /// let c = RefCell::new(5);
688 /// let m = c.borrow_mut();
689 /// assert!(c.try_borrow().is_err());
693 /// let m = c.borrow();
694 /// assert!(c.try_borrow().is_ok());
697 #[stable(feature = "try_borrow", since = "1.13.0")]
699 pub fn try_borrow(&self) -> Result<Ref<T>, BorrowError> {
700 match BorrowRef::new(&self.borrow) {
702 value: unsafe { &*self.value.get() },
705 None => Err(BorrowError { _private: () }),
709 /// Mutably borrows the wrapped value.
711 /// The borrow lasts until the returned `RefMut` exits scope. The value
712 /// cannot be borrowed while this borrow is active.
716 /// Panics if the value is currently borrowed. For a non-panicking variant, use
717 /// [`try_borrow_mut`](#method.try_borrow_mut).
722 /// use std::cell::RefCell;
724 /// let c = RefCell::new(5);
726 /// *c.borrow_mut() = 7;
728 /// assert_eq!(*c.borrow(), 7);
731 /// An example of panic:
734 /// use std::cell::RefCell;
737 /// let result = thread::spawn(move || {
738 /// let c = RefCell::new(5);
739 /// let m = c.borrow();
741 /// let b = c.borrow_mut(); // this causes a panic
744 /// assert!(result.is_err());
746 #[stable(feature = "rust1", since = "1.0.0")]
748 pub fn borrow_mut(&self) -> RefMut<T> {
749 self.try_borrow_mut().expect("already borrowed")
752 /// Mutably borrows the wrapped value, returning an error if the value is currently borrowed.
754 /// The borrow lasts until the returned `RefMut` exits scope. The value cannot be borrowed
755 /// while this borrow is active.
757 /// This is the non-panicking variant of [`borrow_mut`](#method.borrow_mut).
762 /// use std::cell::RefCell;
764 /// let c = RefCell::new(5);
767 /// let m = c.borrow();
768 /// assert!(c.try_borrow_mut().is_err());
771 /// assert!(c.try_borrow_mut().is_ok());
773 #[stable(feature = "try_borrow", since = "1.13.0")]
775 pub fn try_borrow_mut(&self) -> Result<RefMut<T>, BorrowMutError> {
776 match BorrowRefMut::new(&self.borrow) {
777 Some(b) => Ok(RefMut {
778 value: unsafe { &mut *self.value.get() },
781 None => Err(BorrowMutError { _private: () }),
785 /// Returns a raw pointer to the underlying data in this cell.
790 /// use std::cell::RefCell;
792 /// let c = RefCell::new(5);
794 /// let ptr = c.as_ptr();
797 #[stable(feature = "cell_as_ptr", since = "1.12.0")]
798 pub fn as_ptr(&self) -> *mut T {
802 /// Returns a mutable reference to the underlying data.
804 /// This call borrows `RefCell` mutably (at compile-time) so there is no
805 /// need for dynamic checks.
807 /// However be cautious: this method expects `self` to be mutable, which is
808 /// generally not the case when using a `RefCell`. Take a look at the
809 /// [`borrow_mut`] method instead if `self` isn't mutable.
811 /// Also, please be aware that this method is only for special circumstances and is usually
812 /// not what you want. In case of doubt, use [`borrow_mut`] instead.
814 /// [`borrow_mut`]: #method.borrow_mut
819 /// use std::cell::RefCell;
821 /// let mut c = RefCell::new(5);
822 /// *c.get_mut() += 1;
824 /// assert_eq!(c, RefCell::new(6));
827 #[stable(feature = "cell_get_mut", since = "1.11.0")]
828 pub fn get_mut(&mut self) -> &mut T {
830 &mut *self.value.get()
835 #[stable(feature = "rust1", since = "1.0.0")]
836 unsafe impl<T: ?Sized> Send for RefCell<T> where T: Send {}
838 #[stable(feature = "rust1", since = "1.0.0")]
839 impl<T: ?Sized> !Sync for RefCell<T> {}
841 #[stable(feature = "rust1", since = "1.0.0")]
842 impl<T: Clone> Clone for RefCell<T> {
844 fn clone(&self) -> RefCell<T> {
845 RefCell::new(self.borrow().clone())
849 #[stable(feature = "rust1", since = "1.0.0")]
850 impl<T:Default> Default for RefCell<T> {
851 /// Creates a `RefCell<T>`, with the `Default` value for T.
853 fn default() -> RefCell<T> {
854 RefCell::new(Default::default())
858 #[stable(feature = "rust1", since = "1.0.0")]
859 impl<T: ?Sized + PartialEq> PartialEq for RefCell<T> {
861 fn eq(&self, other: &RefCell<T>) -> bool {
862 *self.borrow() == *other.borrow()
866 #[stable(feature = "cell_eq", since = "1.2.0")]
867 impl<T: ?Sized + Eq> Eq for RefCell<T> {}
869 #[stable(feature = "cell_ord", since = "1.10.0")]
870 impl<T: ?Sized + PartialOrd> PartialOrd for RefCell<T> {
872 fn partial_cmp(&self, other: &RefCell<T>) -> Option<Ordering> {
873 self.borrow().partial_cmp(&*other.borrow())
877 fn lt(&self, other: &RefCell<T>) -> bool {
878 *self.borrow() < *other.borrow()
882 fn le(&self, other: &RefCell<T>) -> bool {
883 *self.borrow() <= *other.borrow()
887 fn gt(&self, other: &RefCell<T>) -> bool {
888 *self.borrow() > *other.borrow()
892 fn ge(&self, other: &RefCell<T>) -> bool {
893 *self.borrow() >= *other.borrow()
897 #[stable(feature = "cell_ord", since = "1.10.0")]
898 impl<T: ?Sized + Ord> Ord for RefCell<T> {
900 fn cmp(&self, other: &RefCell<T>) -> Ordering {
901 self.borrow().cmp(&*other.borrow())
905 #[stable(feature = "cell_from", since = "1.12.0")]
906 impl<T> From<T> for RefCell<T> {
907 fn from(t: T) -> RefCell<T> {
912 #[unstable(feature = "coerce_unsized", issue = "27732")]
913 impl<T: CoerceUnsized<U>, U> CoerceUnsized<RefCell<U>> for RefCell<T> {}
915 struct BorrowRef<'b> {
916 borrow: &'b Cell<BorrowFlag>,
919 impl<'b> BorrowRef<'b> {
921 fn new(borrow: &'b Cell<BorrowFlag>) -> Option<BorrowRef<'b>> {
926 Some(BorrowRef { borrow: borrow })
932 impl<'b> Drop for BorrowRef<'b> {
935 let borrow = self.borrow.get();
936 debug_assert!(borrow != WRITING && borrow != UNUSED);
937 self.borrow.set(borrow - 1);
941 impl<'b> Clone for BorrowRef<'b> {
943 fn clone(&self) -> BorrowRef<'b> {
944 // Since this Ref exists, we know the borrow flag
945 // is not set to WRITING.
946 let borrow = self.borrow.get();
947 debug_assert!(borrow != UNUSED);
948 // Prevent the borrow counter from overflowing.
949 assert!(borrow != WRITING);
950 self.borrow.set(borrow + 1);
951 BorrowRef { borrow: self.borrow }
955 /// Wraps a borrowed reference to a value in a `RefCell` box.
956 /// A wrapper type for an immutably borrowed value from a `RefCell<T>`.
958 /// See the [module-level documentation](index.html) for more.
959 #[stable(feature = "rust1", since = "1.0.0")]
960 pub struct Ref<'b, T: ?Sized + 'b> {
962 borrow: BorrowRef<'b>,
965 #[stable(feature = "rust1", since = "1.0.0")]
966 impl<'b, T: ?Sized> Deref for Ref<'b, T> {
970 fn deref(&self) -> &T {
975 impl<'b, T: ?Sized> Ref<'b, T> {
978 /// The `RefCell` is already immutably borrowed, so this cannot fail.
980 /// This is an associated function that needs to be used as
981 /// `Ref::clone(...)`. A `Clone` implementation or a method would interfere
982 /// with the widespread use of `r.borrow().clone()` to clone the contents of
984 #[stable(feature = "cell_extras", since = "1.15.0")]
986 pub fn clone(orig: &Ref<'b, T>) -> Ref<'b, T> {
989 borrow: orig.borrow.clone(),
993 /// Make a new `Ref` for a component of the borrowed data.
995 /// The `RefCell` is already immutably borrowed, so this cannot fail.
997 /// This is an associated function that needs to be used as `Ref::map(...)`.
998 /// A method would interfere with methods of the same name on the contents
999 /// of a `RefCell` used through `Deref`.
1004 /// use std::cell::{RefCell, Ref};
1006 /// let c = RefCell::new((5, 'b'));
1007 /// let b1: Ref<(u32, char)> = c.borrow();
1008 /// let b2: Ref<u32> = Ref::map(b1, |t| &t.0);
1009 /// assert_eq!(*b2, 5)
1011 #[stable(feature = "cell_map", since = "1.8.0")]
1013 pub fn map<U: ?Sized, F>(orig: Ref<'b, T>, f: F) -> Ref<'b, U>
1014 where F: FnOnce(&T) -> &U
1017 value: f(orig.value),
1018 borrow: orig.borrow,
1023 #[unstable(feature = "coerce_unsized", issue = "27732")]
1024 impl<'b, T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Ref<'b, U>> for Ref<'b, T> {}
1026 #[stable(feature = "std_guard_impls", since = "1.20.0")]
1027 impl<'a, T: ?Sized + fmt::Display> fmt::Display for Ref<'a, T> {
1028 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1033 impl<'b, T: ?Sized> RefMut<'b, T> {
1034 /// Make a new `RefMut` for a component of the borrowed data, e.g. an enum
1037 /// The `RefCell` is already mutably borrowed, so this cannot fail.
1039 /// This is an associated function that needs to be used as
1040 /// `RefMut::map(...)`. A method would interfere with methods of the same
1041 /// name on the contents of a `RefCell` used through `Deref`.
1046 /// use std::cell::{RefCell, RefMut};
1048 /// let c = RefCell::new((5, 'b'));
1050 /// let b1: RefMut<(u32, char)> = c.borrow_mut();
1051 /// let mut b2: RefMut<u32> = RefMut::map(b1, |t| &mut t.0);
1052 /// assert_eq!(*b2, 5);
1055 /// assert_eq!(*c.borrow(), (42, 'b'));
1057 #[stable(feature = "cell_map", since = "1.8.0")]
1059 pub fn map<U: ?Sized, F>(orig: RefMut<'b, T>, f: F) -> RefMut<'b, U>
1060 where F: FnOnce(&mut T) -> &mut U
1063 value: f(orig.value),
1064 borrow: orig.borrow,
1069 struct BorrowRefMut<'b> {
1070 borrow: &'b Cell<BorrowFlag>,
1073 impl<'b> Drop for BorrowRefMut<'b> {
1075 fn drop(&mut self) {
1076 let borrow = self.borrow.get();
1077 debug_assert!(borrow == WRITING);
1078 self.borrow.set(UNUSED);
1082 impl<'b> BorrowRefMut<'b> {
1084 fn new(borrow: &'b Cell<BorrowFlag>) -> Option<BorrowRefMut<'b>> {
1085 match borrow.get() {
1087 borrow.set(WRITING);
1088 Some(BorrowRefMut { borrow: borrow })
1095 /// A wrapper type for a mutably borrowed value from a `RefCell<T>`.
1097 /// See the [module-level documentation](index.html) for more.
1098 #[stable(feature = "rust1", since = "1.0.0")]
1099 pub struct RefMut<'b, T: ?Sized + 'b> {
1101 borrow: BorrowRefMut<'b>,
1104 #[stable(feature = "rust1", since = "1.0.0")]
1105 impl<'b, T: ?Sized> Deref for RefMut<'b, T> {
1109 fn deref(&self) -> &T {
1114 #[stable(feature = "rust1", since = "1.0.0")]
1115 impl<'b, T: ?Sized> DerefMut for RefMut<'b, T> {
1117 fn deref_mut(&mut self) -> &mut T {
1122 #[unstable(feature = "coerce_unsized", issue = "27732")]
1123 impl<'b, T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<RefMut<'b, U>> for RefMut<'b, T> {}
1125 #[stable(feature = "std_guard_impls", since = "1.20.0")]
1126 impl<'a, T: ?Sized + fmt::Display> fmt::Display for RefMut<'a, T> {
1127 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1132 /// The core primitive for interior mutability in Rust.
1134 /// `UnsafeCell<T>` is a type that wraps some `T` and indicates unsafe interior operations on the
1135 /// wrapped type. Types with an `UnsafeCell<T>` field are considered to have an 'unsafe interior'.
1136 /// The `UnsafeCell<T>` type is the only legal way to obtain aliasable data that is considered
1137 /// mutable. In general, transmuting an `&T` type into an `&mut T` is considered undefined behavior.
1139 /// The compiler makes optimizations based on the knowledge that `&T` is not mutably aliased or
1140 /// mutated, and that `&mut T` is unique. When building abstractions like `Cell`, `RefCell`,
1141 /// `Mutex`, etc, you need to turn these optimizations off. `UnsafeCell` is the only legal way
1142 /// to do this. When `UnsafeCell<T>` is immutably aliased, it is still safe to obtain a mutable
1143 /// reference to its interior and/or to mutate it. However, it is up to the abstraction designer
1144 /// to ensure that no two mutable references obtained this way are active at the same time, and
1145 /// that there are no active mutable references or mutations when an immutable reference is obtained
1146 /// from the cell. This is often done via runtime checks.
1148 /// Note that while mutating or mutably aliasing the contents of an `& UnsafeCell<T>` is
1149 /// okay (provided you enforce the invariants some other way); it is still undefined behavior
1150 /// to have multiple `&mut UnsafeCell<T>` aliases.
1153 /// Types like `Cell<T>` and `RefCell<T>` use this type to wrap their internal data.
1158 /// use std::cell::UnsafeCell;
1159 /// use std::marker::Sync;
1161 /// # #[allow(dead_code)]
1162 /// struct NotThreadSafe<T> {
1163 /// value: UnsafeCell<T>,
1166 /// unsafe impl<T> Sync for NotThreadSafe<T> {}
1168 #[lang = "unsafe_cell"]
1169 #[stable(feature = "rust1", since = "1.0.0")]
1170 pub struct UnsafeCell<T: ?Sized> {
1174 #[stable(feature = "rust1", since = "1.0.0")]
1175 impl<T: ?Sized> !Sync for UnsafeCell<T> {}
1177 impl<T> UnsafeCell<T> {
1178 /// Constructs a new instance of `UnsafeCell` which will wrap the specified
1181 /// All access to the inner value through methods is `unsafe`.
1186 /// use std::cell::UnsafeCell;
1188 /// let uc = UnsafeCell::new(5);
1190 #[stable(feature = "rust1", since = "1.0.0")]
1192 pub const fn new(value: T) -> UnsafeCell<T> {
1193 UnsafeCell { value: value }
1196 /// Unwraps the value.
1200 /// This function is unsafe because this thread or another thread may currently be
1201 /// inspecting the inner value.
1206 /// use std::cell::UnsafeCell;
1208 /// let uc = UnsafeCell::new(5);
1210 /// let five = unsafe { uc.into_inner() };
1213 #[stable(feature = "rust1", since = "1.0.0")]
1214 pub unsafe fn into_inner(self) -> T {
1219 impl<T: ?Sized> UnsafeCell<T> {
1220 /// Gets a mutable pointer to the wrapped value.
1222 /// This can be cast to a pointer of any kind.
1223 /// Ensure that the access is unique when casting to
1224 /// `&mut T`, and ensure that there are no mutations or mutable
1225 /// aliases going on when casting to `&T`
1230 /// use std::cell::UnsafeCell;
1232 /// let uc = UnsafeCell::new(5);
1234 /// let five = uc.get();
1237 #[stable(feature = "rust1", since = "1.0.0")]
1238 pub fn get(&self) -> *mut T {
1239 &self.value as *const T as *mut T
1243 #[stable(feature = "unsafe_cell_default", since = "1.10.0")]
1244 impl<T: Default> Default for UnsafeCell<T> {
1245 /// Creates an `UnsafeCell`, with the `Default` value for T.
1246 fn default() -> UnsafeCell<T> {
1247 UnsafeCell::new(Default::default())
1251 #[stable(feature = "cell_from", since = "1.12.0")]
1252 impl<T> From<T> for UnsafeCell<T> {
1253 fn from(t: T) -> UnsafeCell<T> {
1258 #[unstable(feature = "coerce_unsized", issue = "27732")]
1259 impl<T: CoerceUnsized<U>, U> CoerceUnsized<UnsafeCell<U>> for UnsafeCell<T> {}
1262 fn assert_coerce_unsized(a: UnsafeCell<&i32>, b: Cell<&i32>, c: RefCell<&i32>) {
1263 let _: UnsafeCell<&Send> = a;
1264 let _: Cell<&Send> = b;
1265 let _: RefCell<&Send> = c;