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 //! Rust memory safety is based on this rule: Given an object `T`, it is only possible to
14 //! have one of the following:
16 //! - Having several immutable references (`&T`) to the object (also known as **aliasing**).
17 //! - Having one mutable reference (`&mut T`) to the object (also known as **mutability**).
19 //! This is enforced by the Rust compiler. However, there are situations where this rule is not
20 //! flexible enough. Sometimes it is required to have multiple references to an object and yet
23 //! Shareable mutable containers exist to permit mutability in a controlled manner, even in the
24 //! presence of aliasing. Both `Cell<T>` and `RefCell<T>` allows to do this in a single threaded
25 //! way. However, neither `Cell<T>` nor `RefCell<T>` are thread safe (they do not implement
26 //! `Sync`). If you need to do aliasing and mutation between multiple threads it is possible to
27 //! use [`Mutex`](../../std/sync/struct.Mutex.html),
28 //! [`RwLock`](../../std/sync/struct.RwLock.html) or
29 //! [`atomic`](../../core/sync/atomic/index.html) types.
31 //! Values of the `Cell<T>` and `RefCell<T>` types may be mutated through shared references (i.e.
32 //! the common `&T` type), whereas most Rust types can only be mutated through unique (`&mut T`)
33 //! references. We say that `Cell<T>` and `RefCell<T>` provide 'interior mutability', in contrast
34 //! with typical Rust types that exhibit 'inherited mutability'.
36 //! Cell types come in two flavors: `Cell<T>` and `RefCell<T>`. `Cell<T>` implements interior
37 //! mutability by moving values in and out of the `Cell<T>`. To use references instead of values,
38 //! one must use the `RefCell<T>` type, acquiring a write lock before mutating. `Cell<T>` provides
39 //! methods to retrieve and change the current interior value:
41 //! - For types that implement `Copy`, the `get` method retrieves the current interior value.
42 //! - For types that implement `Default`, the `take` method replaces the current interior value
43 //! with `Default::default()` and returns the replaced value.
44 //! - For all types, the `replace` method replaces the current interior value and returns the
45 //! replaced value and the `into_inner` method consumes the `Cell<T>` and returns the interior
46 //! value. Additionally, the `set` method replaces the interior value, dropping the replaced
49 //! `RefCell<T>` uses Rust's lifetimes to implement 'dynamic borrowing', a process whereby one can
50 //! claim temporary, exclusive, mutable access to the inner value. Borrows for `RefCell<T>`s are
51 //! tracked 'at runtime', unlike Rust's native reference types which are entirely tracked
52 //! statically, at compile time. Because `RefCell<T>` borrows are dynamic it is possible to attempt
53 //! to borrow a value that is already mutably borrowed; when this happens it results in thread
56 //! # When to choose interior mutability
58 //! The more common inherited mutability, where one must have unique access to mutate a value, is
59 //! one of the key language elements that enables Rust to reason strongly about pointer aliasing,
60 //! statically preventing crash bugs. Because of that, inherited mutability is preferred, and
61 //! interior mutability is something of a last resort. Since cell types enable mutation where it
62 //! would otherwise be disallowed though, there are occasions when interior mutability might be
63 //! appropriate, or even *must* be used, e.g.
65 //! * Introducing mutability 'inside' of something immutable
66 //! * Implementation details of logically-immutable methods.
67 //! * Mutating implementations of `Clone`.
69 //! ## Introducing mutability 'inside' of something immutable
71 //! Many shared smart pointer types, including `Rc<T>` and `Arc<T>`, provide containers that can be
72 //! cloned and shared between multiple parties. Because the contained values may be
73 //! multiply-aliased, they can only be borrowed with `&`, not `&mut`. Without cells it would be
74 //! impossible to mutate data inside of these smart pointers at all.
76 //! It's very common then to put a `RefCell<T>` inside shared pointer types to reintroduce
80 //! use std::collections::HashMap;
81 //! use std::cell::RefCell;
85 //! let shared_map: Rc<RefCell<_>> = Rc::new(RefCell::new(HashMap::new()));
86 //! shared_map.borrow_mut().insert("africa", 92388);
87 //! shared_map.borrow_mut().insert("kyoto", 11837);
88 //! shared_map.borrow_mut().insert("piccadilly", 11826);
89 //! shared_map.borrow_mut().insert("marbles", 38);
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 //! // Create a new scope to contain the lifetime of the
116 //! // dynamic borrow
118 //! // Take a reference to the inside of cache cell
119 //! let mut cache = self.span_tree_cache.borrow_mut();
120 //! if cache.is_some() {
121 //! return cache.as_ref().unwrap().clone();
124 //! let span_tree = self.calc_span_tree();
125 //! *cache = Some(span_tree);
128 //! // Recursive call to return the just-cached value.
129 //! // Note that if we had not let the previous borrow
130 //! // of the cache fall out of scope then the subsequent
131 //! // recursive borrow would cause a dynamic thread panic.
132 //! // This is the major hazard of using `RefCell`.
133 //! self.minimum_spanning_tree()
135 //! # fn calc_span_tree(&self) -> Vec<(i32, i32)> { vec![] }
139 //! ## Mutating implementations of `Clone`
141 //! This is simply a special - but common - case of the previous: hiding mutability for operations
142 //! that appear to be immutable. The `clone` method is expected to not change the source value, and
143 //! is declared to take `&self`, not `&mut self`. Therefore any mutation that happens in the
144 //! `clone` method must use cell types. For example, `Rc<T>` maintains its reference counts within a
148 //! #![feature(core_intrinsics)]
149 //! #![feature(shared)]
150 //! use std::cell::Cell;
151 //! use std::ptr::Shared;
152 //! use std::intrinsics::abort;
154 //! struct Rc<T: ?Sized> {
155 //! ptr: Shared<RcBox<T>>
158 //! struct RcBox<T: ?Sized> {
159 //! strong: Cell<usize>,
160 //! refcount: Cell<usize>,
164 //! impl<T: ?Sized> Clone for Rc<T> {
165 //! fn clone(&self) -> Rc<T> {
166 //! self.inc_strong();
167 //! Rc { ptr: self.ptr }
171 //! trait RcBoxPtr<T: ?Sized> {
173 //! fn inner(&self) -> &RcBox<T>;
175 //! fn strong(&self) -> usize {
176 //! self.inner().strong.get()
179 //! fn inc_strong(&self) {
182 //! .set(self.strong()
184 //! .unwrap_or_else(|| unsafe { abort() }));
188 //! impl<T: ?Sized> RcBoxPtr<T> for Rc<T> {
189 //! fn inner(&self) -> &RcBox<T> {
191 //! self.ptr.as_ref()
198 #![stable(feature = "rust1", since = "1.0.0")]
201 use fmt::{self, Debug, Display};
204 use ops::{Deref, DerefMut, CoerceUnsized};
207 /// A mutable memory location.
211 /// Here you can see how using `Cell<T>` allows to use mutable field inside
212 /// immutable struct (which is also called 'interior mutability').
215 /// use std::cell::Cell;
217 /// struct SomeStruct {
218 /// regular_field: u8,
219 /// special_field: Cell<u8>,
222 /// let my_struct = SomeStruct {
223 /// regular_field: 0,
224 /// special_field: Cell::new(1),
227 /// let new_value = 100;
229 /// // ERROR, because my_struct is immutable
230 /// // my_struct.regular_field = new_value;
232 /// // WORKS, although `my_struct` is immutable, field `special_field` is mutable because it is Cell
233 /// my_struct.special_field.set(new_value);
234 /// assert_eq!(my_struct.special_field.get(), new_value);
237 /// See the [module-level documentation](index.html) for more.
238 #[stable(feature = "rust1", since = "1.0.0")]
240 value: UnsafeCell<T>,
243 impl<T:Copy> Cell<T> {
244 /// Returns a copy of the contained value.
249 /// use std::cell::Cell;
251 /// let c = Cell::new(5);
253 /// let five = c.get();
256 #[stable(feature = "rust1", since = "1.0.0")]
257 pub fn get(&self) -> T {
258 unsafe{ *self.value.get() }
262 #[stable(feature = "rust1", since = "1.0.0")]
263 unsafe impl<T> Send for Cell<T> where T: Send {}
265 #[stable(feature = "rust1", since = "1.0.0")]
266 impl<T> !Sync for Cell<T> {}
268 #[stable(feature = "rust1", since = "1.0.0")]
269 impl<T:Copy> Clone for Cell<T> {
271 fn clone(&self) -> Cell<T> {
272 Cell::new(self.get())
276 #[stable(feature = "rust1", since = "1.0.0")]
277 impl<T:Default> Default for Cell<T> {
278 /// Creates a `Cell<T>`, with the `Default` value for T.
280 fn default() -> Cell<T> {
281 Cell::new(Default::default())
285 #[stable(feature = "rust1", since = "1.0.0")]
286 impl<T:PartialEq + Copy> PartialEq for Cell<T> {
288 fn eq(&self, other: &Cell<T>) -> bool {
289 self.get() == other.get()
293 #[stable(feature = "cell_eq", since = "1.2.0")]
294 impl<T:Eq + Copy> Eq for Cell<T> {}
296 #[stable(feature = "cell_ord", since = "1.10.0")]
297 impl<T:PartialOrd + Copy> PartialOrd for Cell<T> {
299 fn partial_cmp(&self, other: &Cell<T>) -> Option<Ordering> {
300 self.get().partial_cmp(&other.get())
304 fn lt(&self, other: &Cell<T>) -> bool {
305 self.get() < other.get()
309 fn le(&self, other: &Cell<T>) -> bool {
310 self.get() <= other.get()
314 fn gt(&self, other: &Cell<T>) -> bool {
315 self.get() > other.get()
319 fn ge(&self, other: &Cell<T>) -> bool {
320 self.get() >= other.get()
324 #[stable(feature = "cell_ord", since = "1.10.0")]
325 impl<T:Ord + Copy> Ord for Cell<T> {
327 fn cmp(&self, other: &Cell<T>) -> Ordering {
328 self.get().cmp(&other.get())
332 #[stable(feature = "cell_from", since = "1.12.0")]
333 impl<T> From<T> for Cell<T> {
334 fn from(t: T) -> Cell<T> {
340 /// Creates a new `Cell` containing the given value.
345 /// use std::cell::Cell;
347 /// let c = Cell::new(5);
349 #[stable(feature = "rust1", since = "1.0.0")]
351 pub const fn new(value: T) -> Cell<T> {
353 value: UnsafeCell::new(value),
357 /// Returns a raw pointer to the underlying data in this cell.
362 /// use std::cell::Cell;
364 /// let c = Cell::new(5);
366 /// let ptr = c.as_ptr();
369 #[stable(feature = "cell_as_ptr", since = "1.12.0")]
370 pub fn as_ptr(&self) -> *mut T {
374 /// Returns a mutable reference to the underlying data.
376 /// This call borrows `Cell` mutably (at compile-time) which guarantees
377 /// that we possess the only reference.
382 /// use std::cell::Cell;
384 /// let mut c = Cell::new(5);
385 /// *c.get_mut() += 1;
387 /// assert_eq!(c.get(), 6);
390 #[stable(feature = "cell_get_mut", since = "1.11.0")]
391 pub fn get_mut(&mut self) -> &mut T {
393 &mut *self.value.get()
397 /// Sets the contained value.
402 /// use std::cell::Cell;
404 /// let c = Cell::new(5);
409 #[stable(feature = "rust1", since = "1.0.0")]
410 pub fn set(&self, val: T) {
411 let old = self.replace(val);
415 /// Swaps the values of two Cells.
416 /// Difference with `std::mem::swap` is that this function doesn't require `&mut` reference.
421 /// use std::cell::Cell;
423 /// let c1 = Cell::new(5i32);
424 /// let c2 = Cell::new(10i32);
426 /// assert_eq!(10, c1.get());
427 /// assert_eq!(5, c2.get());
430 #[stable(feature = "move_cell", since = "1.17.0")]
431 pub fn swap(&self, other: &Self) {
432 if ptr::eq(self, other) {
436 ptr::swap(self.value.get(), other.value.get());
440 /// Replaces the contained value, and returns it.
445 /// use std::cell::Cell;
447 /// let cell = Cell::new(5);
448 /// assert_eq!(cell.get(), 5);
449 /// assert_eq!(cell.replace(10), 5);
450 /// assert_eq!(cell.get(), 10);
452 #[stable(feature = "move_cell", since = "1.17.0")]
453 pub fn replace(&self, val: T) -> T {
454 mem::replace(unsafe { &mut *self.value.get() }, val)
457 /// Unwraps the value.
462 /// use std::cell::Cell;
464 /// let c = Cell::new(5);
465 /// let five = c.into_inner();
467 /// assert_eq!(five, 5);
469 #[stable(feature = "move_cell", since = "1.17.0")]
470 pub fn into_inner(self) -> T {
471 self.value.into_inner()
475 impl<T: Default> Cell<T> {
476 /// Takes the value of the cell, leaving `Default::default()` in its place.
481 /// use std::cell::Cell;
483 /// let c = Cell::new(5);
484 /// let five = c.take();
486 /// assert_eq!(five, 5);
487 /// assert_eq!(c.into_inner(), 0);
489 #[stable(feature = "move_cell", since = "1.17.0")]
490 pub fn take(&self) -> T {
491 self.replace(Default::default())
495 #[unstable(feature = "coerce_unsized", issue = "27732")]
496 impl<T: CoerceUnsized<U>, U> CoerceUnsized<Cell<U>> for Cell<T> {}
498 /// A mutable memory location with dynamically checked borrow rules
500 /// See the [module-level documentation](index.html) for more.
501 #[stable(feature = "rust1", since = "1.0.0")]
502 pub struct RefCell<T: ?Sized> {
503 borrow: Cell<BorrowFlag>,
504 value: UnsafeCell<T>,
507 /// An error returned by [`RefCell::try_borrow`](struct.RefCell.html#method.try_borrow).
508 #[stable(feature = "try_borrow", since = "1.13.0")]
509 pub struct BorrowError {
513 #[stable(feature = "try_borrow", since = "1.13.0")]
514 impl Debug for BorrowError {
515 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
516 f.debug_struct("BorrowError").finish()
520 #[stable(feature = "try_borrow", since = "1.13.0")]
521 impl Display for BorrowError {
522 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
523 Display::fmt("already mutably borrowed", f)
527 /// An error returned by [`RefCell::try_borrow_mut`](struct.RefCell.html#method.try_borrow_mut).
528 #[stable(feature = "try_borrow", since = "1.13.0")]
529 pub struct BorrowMutError {
533 #[stable(feature = "try_borrow", since = "1.13.0")]
534 impl Debug for BorrowMutError {
535 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
536 f.debug_struct("BorrowMutError").finish()
540 #[stable(feature = "try_borrow", since = "1.13.0")]
541 impl Display for BorrowMutError {
542 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
543 Display::fmt("already borrowed", f)
547 // Values [1, MAX-1] represent the number of `Ref` active
548 // (will not outgrow its range since `usize` is the size of the address space)
549 type BorrowFlag = usize;
550 const UNUSED: BorrowFlag = 0;
551 const WRITING: BorrowFlag = !0;
554 /// Creates a new `RefCell` containing `value`.
559 /// use std::cell::RefCell;
561 /// let c = RefCell::new(5);
563 #[stable(feature = "rust1", since = "1.0.0")]
565 pub const fn new(value: T) -> RefCell<T> {
567 value: UnsafeCell::new(value),
568 borrow: Cell::new(UNUSED),
572 /// Consumes the `RefCell`, returning the wrapped value.
577 /// use std::cell::RefCell;
579 /// let c = RefCell::new(5);
581 /// let five = c.into_inner();
583 #[stable(feature = "rust1", since = "1.0.0")]
585 pub fn into_inner(self) -> T {
586 // Since this function takes `self` (the `RefCell`) by value, the
587 // compiler statically verifies that it is not currently borrowed.
588 // Therefore the following assertion is just a `debug_assert!`.
589 debug_assert!(self.borrow.get() == UNUSED);
590 self.value.into_inner()
593 /// Replaces the wrapped value with a new one, returning the old value,
594 /// without deinitializing either one.
596 /// This function corresponds to [`std::mem::replace`](../mem/fn.replace.html).
600 /// Panics if the value is currently borrowed.
605 /// use std::cell::RefCell;
606 /// let cell = RefCell::new(5);
607 /// let old_value = cell.replace(6);
608 /// assert_eq!(old_value, 5);
609 /// assert_eq!(cell, RefCell::new(6));
612 #[stable(feature = "refcell_replace", since="1.24.0")]
613 pub fn replace(&self, t: T) -> T {
614 mem::replace(&mut *self.borrow_mut(), t)
617 /// Replaces the wrapped value with a new one computed from `f`, returning
618 /// the old value, without deinitializing either one.
620 /// This function corresponds to [`std::mem::replace`](../mem/fn.replace.html).
624 /// Panics if the value is currently borrowed.
629 /// #![feature(refcell_replace_swap)]
630 /// use std::cell::RefCell;
631 /// let cell = RefCell::new(5);
632 /// let old_value = cell.replace_with(|&mut old| old + 1);
633 /// assert_eq!(old_value, 5);
634 /// assert_eq!(cell, RefCell::new(6));
637 #[unstable(feature = "refcell_replace_swap", issue="43570")]
638 pub fn replace_with<F: FnOnce(&mut T) -> T>(&self, f: F) -> T {
639 let mut_borrow = &mut *self.borrow_mut();
640 let replacement = f(mut_borrow);
641 mem::replace(mut_borrow, replacement)
644 /// Swaps the wrapped value of `self` with the wrapped value of `other`,
645 /// without deinitializing either one.
647 /// This function corresponds to [`std::mem::swap`](../mem/fn.swap.html).
651 /// Panics if the value in either `RefCell` is currently borrowed.
656 /// use std::cell::RefCell;
657 /// let c = RefCell::new(5);
658 /// let d = RefCell::new(6);
660 /// assert_eq!(c, RefCell::new(6));
661 /// assert_eq!(d, RefCell::new(5));
664 #[stable(feature = "refcell_swap", since="1.24.0")]
665 pub fn swap(&self, other: &Self) {
666 mem::swap(&mut *self.borrow_mut(), &mut *other.borrow_mut())
670 impl<T: ?Sized> RefCell<T> {
671 /// Immutably borrows the wrapped value.
673 /// The borrow lasts until the returned `Ref` exits scope. Multiple
674 /// immutable borrows can be taken out at the same time.
678 /// Panics if the value is currently mutably borrowed. For a non-panicking variant, use
679 /// [`try_borrow`](#method.try_borrow).
684 /// use std::cell::RefCell;
686 /// let c = RefCell::new(5);
688 /// let borrowed_five = c.borrow();
689 /// let borrowed_five2 = c.borrow();
692 /// An example of panic:
695 /// use std::cell::RefCell;
698 /// let result = thread::spawn(move || {
699 /// let c = RefCell::new(5);
700 /// let m = c.borrow_mut();
702 /// let b = c.borrow(); // this causes a panic
705 /// assert!(result.is_err());
707 #[stable(feature = "rust1", since = "1.0.0")]
709 pub fn borrow(&self) -> Ref<T> {
710 self.try_borrow().expect("already mutably borrowed")
713 /// Immutably borrows the wrapped value, returning an error if the value is currently mutably
716 /// The borrow lasts until the returned `Ref` exits scope. Multiple immutable borrows can be
717 /// taken out at the same time.
719 /// This is the non-panicking variant of [`borrow`](#method.borrow).
724 /// use std::cell::RefCell;
726 /// let c = RefCell::new(5);
729 /// let m = c.borrow_mut();
730 /// assert!(c.try_borrow().is_err());
734 /// let m = c.borrow();
735 /// assert!(c.try_borrow().is_ok());
738 #[stable(feature = "try_borrow", since = "1.13.0")]
740 pub fn try_borrow(&self) -> Result<Ref<T>, BorrowError> {
741 match BorrowRef::new(&self.borrow) {
743 value: unsafe { &*self.value.get() },
746 None => Err(BorrowError { _private: () }),
750 /// Mutably borrows the wrapped value.
752 /// The borrow lasts until the returned `RefMut` exits scope. The value
753 /// cannot be borrowed while this borrow is active.
757 /// Panics if the value is currently borrowed. For a non-panicking variant, use
758 /// [`try_borrow_mut`](#method.try_borrow_mut).
763 /// use std::cell::RefCell;
765 /// let c = RefCell::new(5);
767 /// *c.borrow_mut() = 7;
769 /// assert_eq!(*c.borrow(), 7);
772 /// An example of panic:
775 /// use std::cell::RefCell;
778 /// let result = thread::spawn(move || {
779 /// let c = RefCell::new(5);
780 /// let m = c.borrow();
782 /// let b = c.borrow_mut(); // this causes a panic
785 /// assert!(result.is_err());
787 #[stable(feature = "rust1", since = "1.0.0")]
789 pub fn borrow_mut(&self) -> RefMut<T> {
790 self.try_borrow_mut().expect("already borrowed")
793 /// Mutably borrows the wrapped value, returning an error if the value is currently borrowed.
795 /// The borrow lasts until the returned `RefMut` exits scope. The value cannot be borrowed
796 /// while this borrow is active.
798 /// This is the non-panicking variant of [`borrow_mut`](#method.borrow_mut).
803 /// use std::cell::RefCell;
805 /// let c = RefCell::new(5);
808 /// let m = c.borrow();
809 /// assert!(c.try_borrow_mut().is_err());
812 /// assert!(c.try_borrow_mut().is_ok());
814 #[stable(feature = "try_borrow", since = "1.13.0")]
816 pub fn try_borrow_mut(&self) -> Result<RefMut<T>, BorrowMutError> {
817 match BorrowRefMut::new(&self.borrow) {
818 Some(b) => Ok(RefMut {
819 value: unsafe { &mut *self.value.get() },
822 None => Err(BorrowMutError { _private: () }),
826 /// Returns a raw pointer to the underlying data in this cell.
831 /// use std::cell::RefCell;
833 /// let c = RefCell::new(5);
835 /// let ptr = c.as_ptr();
838 #[stable(feature = "cell_as_ptr", since = "1.12.0")]
839 pub fn as_ptr(&self) -> *mut T {
843 /// Returns a mutable reference to the underlying data.
845 /// This call borrows `RefCell` mutably (at compile-time) so there is no
846 /// need for dynamic checks.
848 /// However be cautious: this method expects `self` to be mutable, which is
849 /// generally not the case when using a `RefCell`. Take a look at the
850 /// [`borrow_mut`] method instead if `self` isn't mutable.
852 /// Also, please be aware that this method is only for special circumstances and is usually
853 /// not what you want. In case of doubt, use [`borrow_mut`] instead.
855 /// [`borrow_mut`]: #method.borrow_mut
860 /// use std::cell::RefCell;
862 /// let mut c = RefCell::new(5);
863 /// *c.get_mut() += 1;
865 /// assert_eq!(c, RefCell::new(6));
868 #[stable(feature = "cell_get_mut", since = "1.11.0")]
869 pub fn get_mut(&mut self) -> &mut T {
871 &mut *self.value.get()
876 #[stable(feature = "rust1", since = "1.0.0")]
877 unsafe impl<T: ?Sized> Send for RefCell<T> where T: Send {}
879 #[stable(feature = "rust1", since = "1.0.0")]
880 impl<T: ?Sized> !Sync for RefCell<T> {}
882 #[stable(feature = "rust1", since = "1.0.0")]
883 impl<T: Clone> Clone for RefCell<T> {
886 /// Panics if the value is currently mutably borrowed.
888 fn clone(&self) -> RefCell<T> {
889 RefCell::new(self.borrow().clone())
893 #[stable(feature = "rust1", since = "1.0.0")]
894 impl<T:Default> Default for RefCell<T> {
895 /// Creates a `RefCell<T>`, with the `Default` value for T.
897 fn default() -> RefCell<T> {
898 RefCell::new(Default::default())
902 #[stable(feature = "rust1", since = "1.0.0")]
903 impl<T: ?Sized + PartialEq> PartialEq for RefCell<T> {
906 /// Panics if the value in either `RefCell` is currently borrowed.
908 fn eq(&self, other: &RefCell<T>) -> bool {
909 *self.borrow() == *other.borrow()
913 #[stable(feature = "cell_eq", since = "1.2.0")]
914 impl<T: ?Sized + Eq> Eq for RefCell<T> {}
916 #[stable(feature = "cell_ord", since = "1.10.0")]
917 impl<T: ?Sized + PartialOrd> PartialOrd for RefCell<T> {
920 /// Panics if the value in either `RefCell` is currently borrowed.
922 fn partial_cmp(&self, other: &RefCell<T>) -> Option<Ordering> {
923 self.borrow().partial_cmp(&*other.borrow())
928 /// Panics if the value in either `RefCell` is currently borrowed.
930 fn lt(&self, other: &RefCell<T>) -> bool {
931 *self.borrow() < *other.borrow()
936 /// Panics if the value in either `RefCell` is currently borrowed.
938 fn le(&self, other: &RefCell<T>) -> bool {
939 *self.borrow() <= *other.borrow()
944 /// Panics if the value in either `RefCell` is currently borrowed.
946 fn gt(&self, other: &RefCell<T>) -> bool {
947 *self.borrow() > *other.borrow()
952 /// Panics if the value in either `RefCell` is currently borrowed.
954 fn ge(&self, other: &RefCell<T>) -> bool {
955 *self.borrow() >= *other.borrow()
959 #[stable(feature = "cell_ord", since = "1.10.0")]
960 impl<T: ?Sized + Ord> Ord for RefCell<T> {
963 /// Panics if the value in either `RefCell` is currently borrowed.
965 fn cmp(&self, other: &RefCell<T>) -> Ordering {
966 self.borrow().cmp(&*other.borrow())
970 #[stable(feature = "cell_from", since = "1.12.0")]
971 impl<T> From<T> for RefCell<T> {
972 fn from(t: T) -> RefCell<T> {
977 #[unstable(feature = "coerce_unsized", issue = "27732")]
978 impl<T: CoerceUnsized<U>, U> CoerceUnsized<RefCell<U>> for RefCell<T> {}
980 struct BorrowRef<'b> {
981 borrow: &'b Cell<BorrowFlag>,
984 impl<'b> BorrowRef<'b> {
986 fn new(borrow: &'b Cell<BorrowFlag>) -> Option<BorrowRef<'b>> {
991 Some(BorrowRef { borrow: borrow })
997 impl<'b> Drop for BorrowRef<'b> {
1000 let borrow = self.borrow.get();
1001 debug_assert!(borrow != WRITING && borrow != UNUSED);
1002 self.borrow.set(borrow - 1);
1006 impl<'b> Clone for BorrowRef<'b> {
1008 fn clone(&self) -> BorrowRef<'b> {
1009 // Since this Ref exists, we know the borrow flag
1010 // is not set to WRITING.
1011 let borrow = self.borrow.get();
1012 debug_assert!(borrow != UNUSED);
1013 // Prevent the borrow counter from overflowing.
1014 assert!(borrow != WRITING);
1015 self.borrow.set(borrow + 1);
1016 BorrowRef { borrow: self.borrow }
1020 /// Wraps a borrowed reference to a value in a `RefCell` box.
1021 /// A wrapper type for an immutably borrowed value from a `RefCell<T>`.
1023 /// See the [module-level documentation](index.html) for more.
1024 #[stable(feature = "rust1", since = "1.0.0")]
1025 pub struct Ref<'b, T: ?Sized + 'b> {
1027 borrow: BorrowRef<'b>,
1030 #[stable(feature = "rust1", since = "1.0.0")]
1031 impl<'b, T: ?Sized> Deref for Ref<'b, T> {
1035 fn deref(&self) -> &T {
1040 impl<'b, T: ?Sized> Ref<'b, T> {
1043 /// The `RefCell` is already immutably borrowed, so this cannot fail.
1045 /// This is an associated function that needs to be used as
1046 /// `Ref::clone(...)`. A `Clone` implementation or a method would interfere
1047 /// with the widespread use of `r.borrow().clone()` to clone the contents of
1049 #[stable(feature = "cell_extras", since = "1.15.0")]
1051 pub fn clone(orig: &Ref<'b, T>) -> Ref<'b, T> {
1054 borrow: orig.borrow.clone(),
1058 /// Make a new `Ref` for a component of the borrowed data.
1060 /// The `RefCell` is already immutably borrowed, so this cannot fail.
1062 /// This is an associated function that needs to be used as `Ref::map(...)`.
1063 /// A method would interfere with methods of the same name on the contents
1064 /// of a `RefCell` used through `Deref`.
1069 /// use std::cell::{RefCell, Ref};
1071 /// let c = RefCell::new((5, 'b'));
1072 /// let b1: Ref<(u32, char)> = c.borrow();
1073 /// let b2: Ref<u32> = Ref::map(b1, |t| &t.0);
1074 /// assert_eq!(*b2, 5)
1076 #[stable(feature = "cell_map", since = "1.8.0")]
1078 pub fn map<U: ?Sized, F>(orig: Ref<'b, T>, f: F) -> Ref<'b, U>
1079 where F: FnOnce(&T) -> &U
1082 value: f(orig.value),
1083 borrow: orig.borrow,
1088 #[unstable(feature = "coerce_unsized", issue = "27732")]
1089 impl<'b, T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Ref<'b, U>> for Ref<'b, T> {}
1091 #[stable(feature = "std_guard_impls", since = "1.20.0")]
1092 impl<'a, T: ?Sized + fmt::Display> fmt::Display for Ref<'a, T> {
1093 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1098 impl<'b, T: ?Sized> RefMut<'b, T> {
1099 /// Make a new `RefMut` for a component of the borrowed data, e.g. an enum
1102 /// The `RefCell` is already mutably borrowed, so this cannot fail.
1104 /// This is an associated function that needs to be used as
1105 /// `RefMut::map(...)`. A method would interfere with methods of the same
1106 /// name on the contents of a `RefCell` used through `Deref`.
1111 /// use std::cell::{RefCell, RefMut};
1113 /// let c = RefCell::new((5, 'b'));
1115 /// let b1: RefMut<(u32, char)> = c.borrow_mut();
1116 /// let mut b2: RefMut<u32> = RefMut::map(b1, |t| &mut t.0);
1117 /// assert_eq!(*b2, 5);
1120 /// assert_eq!(*c.borrow(), (42, 'b'));
1122 #[stable(feature = "cell_map", since = "1.8.0")]
1124 pub fn map<U: ?Sized, F>(orig: RefMut<'b, T>, f: F) -> RefMut<'b, U>
1125 where F: FnOnce(&mut T) -> &mut U
1127 // FIXME(nll-rfc#40): fix borrow-check
1128 let RefMut { value, borrow } = orig;
1136 struct BorrowRefMut<'b> {
1137 borrow: &'b Cell<BorrowFlag>,
1140 impl<'b> Drop for BorrowRefMut<'b> {
1142 fn drop(&mut self) {
1143 let borrow = self.borrow.get();
1144 debug_assert!(borrow == WRITING);
1145 self.borrow.set(UNUSED);
1149 impl<'b> BorrowRefMut<'b> {
1151 fn new(borrow: &'b Cell<BorrowFlag>) -> Option<BorrowRefMut<'b>> {
1152 match borrow.get() {
1154 borrow.set(WRITING);
1155 Some(BorrowRefMut { borrow: borrow })
1162 /// A wrapper type for a mutably borrowed value from a `RefCell<T>`.
1164 /// See the [module-level documentation](index.html) for more.
1165 #[stable(feature = "rust1", since = "1.0.0")]
1166 pub struct RefMut<'b, T: ?Sized + 'b> {
1168 borrow: BorrowRefMut<'b>,
1171 #[stable(feature = "rust1", since = "1.0.0")]
1172 impl<'b, T: ?Sized> Deref for RefMut<'b, T> {
1176 fn deref(&self) -> &T {
1181 #[stable(feature = "rust1", since = "1.0.0")]
1182 impl<'b, T: ?Sized> DerefMut for RefMut<'b, T> {
1184 fn deref_mut(&mut self) -> &mut T {
1189 #[unstable(feature = "coerce_unsized", issue = "27732")]
1190 impl<'b, T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<RefMut<'b, U>> for RefMut<'b, T> {}
1192 #[stable(feature = "std_guard_impls", since = "1.20.0")]
1193 impl<'a, T: ?Sized + fmt::Display> fmt::Display for RefMut<'a, T> {
1194 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1199 /// The core primitive for interior mutability in Rust.
1201 /// `UnsafeCell<T>` is a type that wraps some `T` and indicates unsafe interior operations on the
1202 /// wrapped type. Types with an `UnsafeCell<T>` field are considered to have an 'unsafe interior'.
1203 /// The `UnsafeCell<T>` type is the only legal way to obtain aliasable data that is considered
1204 /// mutable. In general, transmuting an `&T` type into an `&mut T` is considered undefined behavior.
1206 /// If you have a reference `&SomeStruct`, then normally in Rust all fields of `SomeStruct` are
1207 /// immutable. The compiler makes optimizations based on the knowledge that `&T` is not mutably
1208 /// aliased or mutated, and that `&mut T` is unique. `UnsafeCel<T>` is the only core language
1209 /// feature to work around this restriction. All other types that allow internal mutability, such as
1210 /// `Cell<T>` and `RefCell<T>` use `UnsafeCell` to wrap their internal data.
1212 /// The `UnsafeCell` API itself is technically very simple: it gives you a raw pointer `*mut T` to
1213 /// its contents. It is up to _you_ as the abstraction designer to use that raw pointer correctly.
1215 /// The precise Rust aliasing rules are somewhat in flux, but the main points are not contentious:
1217 /// - If you create a safe reference with lifetime `'a` (either a `&T` or `&mut T` reference) that
1218 /// is accessible by safe code (for example, because you returned it), then you must not access
1219 /// the data in any way that contradicts that reference for the remainder of `'a`. For example, that
1220 /// means that if you take the `*mut T` from an `UnsafeCell<T>` and case it to an `&T`, then until
1221 /// that reference's lifetime expires, the data in `T` must remain immutable (modulo any
1222 /// `UnsafeCell` data found within `T`, of course). Similarly, if you create an `&mut T` reference
1223 /// that is released to safe code, then you must not access the data within the `UnsafeCell` until
1224 /// that reference expires.
1226 /// - At all times, you must avoid data races, meaning that if multiple threads have access to
1227 /// the same `UnsafeCell`, then any writes must have a proper happens-before relation to all other
1228 /// accesses (or use atomics).
1230 /// To assist with proper design, the following scenarios are explicitly declared legal
1231 /// for single-threaded code:
1233 /// 1. A `&T` reference can be released to safe code and there it can co-exit with other `&T`
1234 /// references, but not with a `&mut T`
1236 /// 2. A `&mut T` reference may be released to safe code, provided neither other `&mut T` nor `&T`
1237 /// co-exist with it. A `&mut T` must always be unique.
1239 /// Note that while mutating or mutably aliasing the contents of an `& UnsafeCell<T>` is
1240 /// okay (provided you enforce the invariants some other way), it is still undefined behavior
1241 /// to have multiple `&mut UnsafeCell<T>` aliases.
1246 /// use std::cell::UnsafeCell;
1247 /// use std::marker::Sync;
1249 /// # #[allow(dead_code)]
1250 /// struct NotThreadSafe<T> {
1251 /// value: UnsafeCell<T>,
1254 /// unsafe impl<T> Sync for NotThreadSafe<T> {}
1256 #[lang = "unsafe_cell"]
1257 #[stable(feature = "rust1", since = "1.0.0")]
1258 pub struct UnsafeCell<T: ?Sized> {
1262 #[stable(feature = "rust1", since = "1.0.0")]
1263 impl<T: ?Sized> !Sync for UnsafeCell<T> {}
1265 impl<T> UnsafeCell<T> {
1266 /// Constructs a new instance of `UnsafeCell` which will wrap the specified
1269 /// All access to the inner value through methods is `unsafe`.
1274 /// use std::cell::UnsafeCell;
1276 /// let uc = UnsafeCell::new(5);
1278 #[stable(feature = "rust1", since = "1.0.0")]
1280 pub const fn new(value: T) -> UnsafeCell<T> {
1281 UnsafeCell { value: value }
1284 /// Unwraps the value.
1289 /// use std::cell::UnsafeCell;
1291 /// let uc = UnsafeCell::new(5);
1293 /// let five = uc.into_inner();
1296 #[stable(feature = "rust1", since = "1.0.0")]
1297 pub fn into_inner(self) -> T {
1302 impl<T: ?Sized> UnsafeCell<T> {
1303 /// Gets a mutable pointer to the wrapped value.
1305 /// This can be cast to a pointer of any kind.
1306 /// Ensure that the access is unique (no active references, mutable or not)
1307 /// when casting to `&mut T`, and ensure that there are no mutations
1308 /// or mutable aliases going on when casting to `&T`
1313 /// use std::cell::UnsafeCell;
1315 /// let uc = UnsafeCell::new(5);
1317 /// let five = uc.get();
1320 #[stable(feature = "rust1", since = "1.0.0")]
1321 pub fn get(&self) -> *mut T {
1322 &self.value as *const T as *mut T
1326 #[stable(feature = "unsafe_cell_default", since = "1.10.0")]
1327 impl<T: Default> Default for UnsafeCell<T> {
1328 /// Creates an `UnsafeCell`, with the `Default` value for T.
1329 fn default() -> UnsafeCell<T> {
1330 UnsafeCell::new(Default::default())
1334 #[stable(feature = "cell_from", since = "1.12.0")]
1335 impl<T> From<T> for UnsafeCell<T> {
1336 fn from(t: T) -> UnsafeCell<T> {
1341 #[unstable(feature = "coerce_unsized", issue = "27732")]
1342 impl<T: CoerceUnsized<U>, U> CoerceUnsized<UnsafeCell<U>> for UnsafeCell<T> {}
1345 fn assert_coerce_unsized(a: UnsafeCell<&i32>, b: Cell<&i32>, c: RefCell<&i32>) {
1346 let _: UnsafeCell<&Send> = a;
1347 let _: Cell<&Send> = b;
1348 let _: RefCell<&Send> = c;