1 // Copyright 2012-2013 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` and `RefCell` types may be mutated through
14 //! shared references (i.e. the common `&T` type), whereas most Rust
15 //! types can only be mutated through unique (`&mut T`) references. We
16 //! say that `Cell` and `RefCell` provide *interior mutability*, in
17 //! contrast with typical Rust types that exhibit *inherited
20 //! Cell types come in two flavors: `Cell` and `RefCell`. `Cell`
21 //! provides `get` and `set` methods that change the
22 //! interior value with a single method call. `Cell` though is only
23 //! compatible with types that implement `Copy`. For other types,
24 //! one must use the `RefCell` type, acquiring a write lock before
27 //! `RefCell` uses Rust's lifetimes to implement *dynamic borrowing*,
28 //! a process whereby one can claim temporary, exclusive, mutable
29 //! access to the inner value. Borrows for `RefCell`s are tracked *at
30 //! runtime*, unlike Rust's native reference types which are entirely
31 //! tracked statically, at compile time. Because `RefCell` borrows are
32 //! dynamic it is possible to attempt to borrow a value that is
33 //! already mutably borrowed; when this happens it results in task
36 //! # When to choose interior mutability
38 //! The more common inherited mutability, where one must have unique
39 //! access to mutate a value, is one of the key language elements that
40 //! enables Rust to reason strongly about pointer aliasing, statically
41 //! preventing crash bugs. Because of that, inherited mutability is
42 //! preferred, and interior mutability is something of a last
43 //! resort. Since cell types enable mutation where it would otherwise
44 //! be disallowed though, there are occasions when interior
45 //! mutability might be appropriate, or even *must* be used, e.g.
47 //! * Introducing inherited mutability roots to shared types.
48 //! * Implementation details of logically-immutable methods.
49 //! * Mutating implementations of `clone`.
51 //! ## Introducing inherited mutability roots to shared types
53 //! Shared smart pointer types, including `Rc` and `Arc`, provide
54 //! containers that can be cloned and shared between multiple parties.
55 //! Because the contained values may be multiply-aliased, they can
56 //! only be borrowed as shared references, not mutable references.
57 //! Without cells it would be impossible to mutate data inside of
58 //! shared boxes at all!
60 //! It's very common then to put a `RefCell` inside shared pointer
61 //! types to reintroduce mutability:
64 //! use std::collections::HashMap;
65 //! use std::cell::RefCell;
69 //! let shared_map: Rc<RefCell<_>> = Rc::new(RefCell::new(HashMap::new()));
70 //! shared_map.borrow_mut().insert("africa", 92388i);
71 //! shared_map.borrow_mut().insert("kyoto", 11837i);
72 //! shared_map.borrow_mut().insert("piccadilly", 11826i);
73 //! shared_map.borrow_mut().insert("marbles", 38i);
77 //! ## Implementation details of logically-immutable methods
79 //! Occasionally it may be desirable not to expose in an API that
80 //! there is mutation happening "under the hood". This may be because
81 //! logically the operation is immutable, but e.g. caching forces the
82 //! implementation to perform mutation; or because you must employ
83 //! mutation to implement a trait method that was originally defined
87 //! use std::cell::RefCell;
90 //! edges: Vec<(uint, uint)>,
91 //! span_tree_cache: RefCell<Option<Vec<(uint, uint)>>>
95 //! fn minimum_spanning_tree(&self) -> Vec<(uint, uint)> {
96 //! // Create a new scope to contain the lifetime of the
99 //! // Take a reference to the inside of cache cell
100 //! let mut cache = self.span_tree_cache.borrow_mut();
101 //! if cache.is_some() {
102 //! return cache.as_ref().unwrap().clone();
105 //! let span_tree = self.calc_span_tree();
106 //! *cache = Some(span_tree);
109 //! // Recursive call to return the just-cached value.
110 //! // Note that if we had not let the previous borrow
111 //! // of the cache fall out of scope then the subsequent
112 //! // recursive borrow would cause a dynamic task panic.
113 //! // This is the major hazard of using `RefCell`.
114 //! self.minimum_spanning_tree()
116 //! # fn calc_span_tree(&self) -> Vec<(uint, uint)> { vec![] }
121 //! ## Mutating implementations of `clone`
123 //! This is simply a special - but common - case of the previous:
124 //! hiding mutability for operations that appear to be immutable.
125 //! The `clone` method is expected to not change the source value, and
126 //! is declared to take `&self`, not `&mut self`. Therefore any
127 //! mutation that happens in the `clone` method must use cell
128 //! types. For example, `Rc` maintains its reference counts within a
132 //! use std::cell::Cell;
135 //! ptr: *mut RcBox<T>
138 //! struct RcBox<T> {
140 //! refcount: Cell<uint>
143 //! impl<T> Clone for Rc<T> {
144 //! fn clone(&self) -> Rc<T> {
146 //! (*self.ptr).refcount.set((*self.ptr).refcount.get() + 1);
147 //! Rc { ptr: self.ptr }
153 // FIXME: Explain difference between Cell and RefCell
154 // FIXME: Downsides to interior mutability
155 // FIXME: Can't be shared between threads. Dynamic borrows
156 // FIXME: Relationship to Atomic types and RWLock
160 use default::Default;
161 use kinds::{marker, Copy};
162 use ops::{Deref, DerefMut, Drop};
163 use option::{None, Option, Some};
165 /// A mutable memory location that admits only `Copy` data.
166 #[unstable = "likely to be renamed; otherwise stable"]
168 value: UnsafeCell<T>,
169 noshare: marker::NoSync,
172 impl<T:Copy> Cell<T> {
173 /// Creates a new `Cell` containing the given value.
175 pub fn new(value: T) -> Cell<T> {
177 value: UnsafeCell::new(value),
178 noshare: marker::NoSync,
182 /// Returns a copy of the contained value.
185 pub fn get(&self) -> T {
186 unsafe{ *self.value.get() }
189 /// Sets the contained value.
192 pub fn set(&self, value: T) {
194 *self.value.get() = value;
198 /// Get a reference to the underlying `UnsafeCell`.
200 /// This can be used to circumvent `Cell`'s safety checks.
202 /// This function is `unsafe` because `UnsafeCell`'s field is public.
205 pub unsafe fn as_unsafe_cell<'a>(&'a self) -> &'a UnsafeCell<T> {
210 #[unstable = "waiting for `Clone` trait to become stable"]
211 impl<T:Copy> Clone for Cell<T> {
212 fn clone(&self) -> Cell<T> {
213 Cell::new(self.get())
218 impl<T:Default + Copy> Default for Cell<T> {
219 fn default() -> Cell<T> {
220 Cell::new(Default::default())
224 #[unstable = "waiting for `PartialEq` trait to become stable"]
225 impl<T:PartialEq + Copy> PartialEq for Cell<T> {
226 fn eq(&self, other: &Cell<T>) -> bool {
227 self.get() == other.get()
231 /// A mutable memory location with dynamically checked borrow rules
232 #[unstable = "likely to be renamed; otherwise stable"]
233 pub struct RefCell<T> {
234 value: UnsafeCell<T>,
235 borrow: Cell<BorrowFlag>,
236 nocopy: marker::NoCopy,
237 noshare: marker::NoSync,
240 // Values [1, MAX-1] represent the number of `Ref` active
241 // (will not outgrow its range since `uint` is the size of the address space)
242 type BorrowFlag = uint;
243 const UNUSED: BorrowFlag = 0;
244 const WRITING: BorrowFlag = -1;
247 /// Create a new `RefCell` containing `value`
249 pub fn new(value: T) -> RefCell<T> {
251 value: UnsafeCell::new(value),
252 borrow: Cell::new(UNUSED),
253 nocopy: marker::NoCopy,
254 noshare: marker::NoSync,
258 /// Consumes the `RefCell`, returning the wrapped value.
259 #[unstable = "recently renamed per RFC 430"]
260 pub fn into_inner(self) -> T {
261 // Since this function takes `self` (the `RefCell`) by value, the
262 // compiler statically verifies that it is not currently borrowed.
263 // Therefore the following assertion is just a `debug_assert!`.
264 debug_assert!(self.borrow.get() == UNUSED);
265 unsafe { self.value.into_inner() }
268 /// Deprecated, use into_inner() instead
269 #[deprecated = "renamed to into_inner()"]
270 pub fn unwrap(self) -> T { self.into_inner() }
272 /// Attempts to immutably borrow the wrapped value.
274 /// The borrow lasts until the returned `Ref` exits scope. Multiple
275 /// immutable borrows can be taken out at the same time.
277 /// Returns `None` if the value is currently mutably borrowed.
278 #[unstable = "may be renamed, depending on global conventions"]
279 pub fn try_borrow<'a>(&'a self) -> Option<Ref<'a, T>> {
280 match self.borrow.get() {
283 self.borrow.set(borrow + 1);
284 Some(Ref { _parent: self })
289 /// Immutably borrows the wrapped value.
291 /// The borrow lasts until the returned `Ref` exits scope. Multiple
292 /// immutable borrows can be taken out at the same time.
296 /// Panics if the value is currently mutably borrowed.
298 pub fn borrow<'a>(&'a self) -> Ref<'a, T> {
299 match self.try_borrow() {
301 None => panic!("RefCell<T> already mutably borrowed")
305 /// Mutably borrows the wrapped value.
307 /// The borrow lasts until the returned `RefMut` exits scope. The value
308 /// cannot be borrowed while this borrow is active.
310 /// Returns `None` if the value is currently borrowed.
311 #[unstable = "may be renamed, depending on global conventions"]
312 pub fn try_borrow_mut<'a>(&'a self) -> Option<RefMut<'a, T>> {
313 match self.borrow.get() {
315 self.borrow.set(WRITING);
316 Some(RefMut { _parent: self })
322 /// Mutably borrows the wrapped value.
324 /// The borrow lasts until the returned `RefMut` exits scope. The value
325 /// cannot be borrowed while this borrow is active.
329 /// Panics if the value is currently borrowed.
331 pub fn borrow_mut<'a>(&'a self) -> RefMut<'a, T> {
332 match self.try_borrow_mut() {
334 None => panic!("RefCell<T> already borrowed")
338 /// Get a reference to the underlying `UnsafeCell`.
340 /// This can be used to circumvent `RefCell`'s safety checks.
342 /// This function is `unsafe` because `UnsafeCell`'s field is public.
345 pub unsafe fn as_unsafe_cell<'a>(&'a self) -> &'a UnsafeCell<T> {
350 #[unstable = "waiting for `Clone` to become stable"]
351 impl<T: Clone> Clone for RefCell<T> {
352 fn clone(&self) -> RefCell<T> {
353 RefCell::new(self.borrow().clone())
358 impl<T:Default> Default for RefCell<T> {
359 fn default() -> RefCell<T> {
360 RefCell::new(Default::default())
364 #[unstable = "waiting for `PartialEq` to become stable"]
365 impl<T: PartialEq> PartialEq for RefCell<T> {
366 fn eq(&self, other: &RefCell<T>) -> bool {
367 *self.borrow() == *other.borrow()
371 /// Wraps a borrowed reference to a value in a `RefCell` box.
373 pub struct Ref<'b, T:'b> {
374 // FIXME #12808: strange name to try to avoid interfering with
375 // field accesses of the contained type via Deref
376 _parent: &'b RefCell<T>
381 impl<'b, T> Drop for Ref<'b, T> {
383 let borrow = self._parent.borrow.get();
384 debug_assert!(borrow != WRITING && borrow != UNUSED);
385 self._parent.borrow.set(borrow - 1);
389 #[unstable = "waiting for `Deref` to become stable"]
390 impl<'b, T> Deref<T> for Ref<'b, T> {
392 fn deref<'a>(&'a self) -> &'a T {
393 unsafe { &*self._parent.value.get() }
399 /// The `RefCell` is already immutably borrowed, so this cannot fail.
401 /// A `Clone` implementation would interfere with the widespread
402 /// use of `r.borrow().clone()` to clone the contents of a `RefCell`.
403 #[experimental = "likely to be moved to a method, pending language changes"]
404 pub fn clone_ref<'b, T>(orig: &Ref<'b, T>) -> Ref<'b, T> {
405 // Since this Ref exists, we know the borrow flag
406 // is not set to WRITING.
407 let borrow = orig._parent.borrow.get();
408 debug_assert!(borrow != WRITING && borrow != UNUSED);
409 orig._parent.borrow.set(borrow + 1);
412 _parent: orig._parent,
416 /// Wraps a mutable borrowed reference to a value in a `RefCell` box.
418 pub struct RefMut<'b, T:'b> {
419 // FIXME #12808: strange name to try to avoid interfering with
420 // field accesses of the contained type via Deref
421 _parent: &'b RefCell<T>
426 impl<'b, T> Drop for RefMut<'b, T> {
428 let borrow = self._parent.borrow.get();
429 debug_assert!(borrow == WRITING);
430 self._parent.borrow.set(UNUSED);
434 #[unstable = "waiting for `Deref` to become stable"]
435 impl<'b, T> Deref<T> for RefMut<'b, T> {
437 fn deref<'a>(&'a self) -> &'a T {
438 unsafe { &*self._parent.value.get() }
442 #[unstable = "waiting for `DerefMut` to become stable"]
443 impl<'b, T> DerefMut<T> for RefMut<'b, T> {
445 fn deref_mut<'a>(&'a mut self) -> &'a mut T {
446 unsafe { &mut *self._parent.value.get() }
450 /// The core primitive for interior mutability in Rust.
452 /// `UnsafeCell` type that wraps a type T and indicates unsafe interior
453 /// operations on the wrapped type. Types with an `UnsafeCell<T>` field are
454 /// considered to have an *unsafe interior*. The `UnsafeCell` type is the only
455 /// legal way to obtain aliasable data that is considered mutable. In general,
456 /// transmuting an &T type into an &mut T is considered undefined behavior.
458 /// Although it is possible to put an `UnsafeCell<T>` into static item, it is
459 /// not permitted to take the address of the static item if the item is not
460 /// declared as mutable. This rule exists because immutable static items are
461 /// stored in read-only memory, and thus any attempt to mutate their interior
462 /// can cause segfaults. Immutable static items containing `UnsafeCell<T>`
463 /// instances are still useful as read-only initializers, however, so we do not
464 /// forbid them altogether.
466 /// Types like `Cell` and `RefCell` use this type to wrap their internal data.
468 /// `UnsafeCell` doesn't opt-out from any kind, instead, types with an
469 /// `UnsafeCell` interior are expected to opt-out from kinds themselves.
474 /// use std::cell::UnsafeCell;
475 /// use std::kinds::marker;
477 /// struct NotThreadSafe<T> {
478 /// value: UnsafeCell<T>,
479 /// marker: marker::NoSync
483 /// **NOTE:** `UnsafeCell<T>` fields are public to allow static initializers. It
484 /// is not recommended to access its fields directly, `get` should be used
487 #[unstable = "this type may be renamed in the future"]
488 pub struct UnsafeCell<T> {
491 /// This field should not be accessed directly, it is made public for static
497 impl<T> UnsafeCell<T> {
498 /// Construct a new instance of `UnsafeCell` which will wrap the specified
501 /// All access to the inner value through methods is `unsafe`, and it is
502 /// highly discouraged to access the fields directly.
504 pub fn new(value: T) -> UnsafeCell<T> {
505 UnsafeCell { value: value }
508 /// Gets a mutable pointer to the wrapped value.
510 /// This function is unsafe as the pointer returned is an unsafe pointer and
511 /// no guarantees are made about the aliasing of the pointers being handed
512 /// out in this or other tasks.
514 #[unstable = "conventions around acquiring an inner reference are still \
516 pub unsafe fn get(&self) -> *mut T { &self.value as *const T as *mut T }
518 /// Unwraps the value
520 /// This function is unsafe because there is no guarantee that this or other
521 /// tasks are currently inspecting the inner value.
523 #[unstable = "conventions around the name `unwrap` are still under \
525 pub unsafe fn into_inner(self) -> T { self.value }
527 /// Deprecated, use into_inner() instead
528 #[deprecated = "renamed to into_inner()"]
529 pub unsafe fn unwrap(self) -> T { self.into_inner() }