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>` provides `get` and `set`
19 //! methods that change the interior value with a single method call. `Cell<T>` though is only
20 //! compatible with types that implement `Copy`. For other types, one must use the `RefCell<T>`
21 //! type, acquiring a write lock before mutating.
23 //! `RefCell<T>` uses Rust's lifetimes to implement 'dynamic borrowing', a process whereby one can
24 //! claim temporary, exclusive, mutable access to the inner value. Borrows for `RefCell<T>`s are
25 //! tracked 'at runtime', unlike Rust's native reference types which are entirely tracked
26 //! statically, at compile time. Because `RefCell<T>` borrows are dynamic it is possible to attempt
27 //! to borrow a value that is already mutably borrowed; when this happens it results in thread
30 //! # When to choose interior mutability
32 //! The more common inherited mutability, where one must have unique access to mutate a value, is
33 //! one of the key language elements that enables Rust to reason strongly about pointer aliasing,
34 //! statically preventing crash bugs. Because of that, inherited mutability is preferred, and
35 //! interior mutability is something of a last resort. Since cell types enable mutation where it
36 //! would otherwise be disallowed though, there are occasions when interior mutability might be
37 //! appropriate, or even *must* be used, e.g.
39 //! * Introducing mutability 'inside' of something immutable
40 //! * Implementation details of logically-immutable methods.
41 //! * Mutating implementations of `Clone`.
43 //! ## Introducing mutability 'inside' of something immutable
45 //! Many shared smart pointer types, including `Rc<T>` and `Arc<T>`, provide containers that can be
46 //! cloned and shared between multiple parties. Because the contained values may be
47 //! multiply-aliased, they can only be borrowed with `&`, not `&mut`. Without cells it would be
48 //! impossible to mutate data inside of these smart pointers at all.
50 //! It's very common then to put a `RefCell<T>` inside shared pointer types to reintroduce
54 //! use std::collections::HashMap;
55 //! use std::cell::RefCell;
59 //! let shared_map: Rc<RefCell<_>> = Rc::new(RefCell::new(HashMap::new()));
60 //! shared_map.borrow_mut().insert("africa", 92388);
61 //! shared_map.borrow_mut().insert("kyoto", 11837);
62 //! shared_map.borrow_mut().insert("piccadilly", 11826);
63 //! shared_map.borrow_mut().insert("marbles", 38);
67 //! Note that this example uses `Rc<T>` and not `Arc<T>`. `RefCell<T>`s are for single-threaded
68 //! scenarios. Consider using `RwLock<T>` or `Mutex<T>` if you need shared mutability in a
69 //! multi-threaded situation.
71 //! ## Implementation details of logically-immutable methods
73 //! Occasionally it may be desirable not to expose in an API that there is mutation happening
74 //! "under the hood". This may be because logically the operation is immutable, but e.g. caching
75 //! forces the implementation to perform mutation; or because you must employ mutation to implement
76 //! a trait method that was originally defined to take `&self`.
79 //! # #![allow(dead_code)]
80 //! use std::cell::RefCell;
83 //! edges: Vec<(i32, i32)>,
84 //! span_tree_cache: RefCell<Option<Vec<(i32, i32)>>>
88 //! fn minimum_spanning_tree(&self) -> Vec<(i32, i32)> {
89 //! // Create a new scope to contain the lifetime of the
92 //! // Take a reference to the inside of cache cell
93 //! let mut cache = self.span_tree_cache.borrow_mut();
94 //! if cache.is_some() {
95 //! return cache.as_ref().unwrap().clone();
98 //! let span_tree = self.calc_span_tree();
99 //! *cache = Some(span_tree);
102 //! // Recursive call to return the just-cached value.
103 //! // Note that if we had not let the previous borrow
104 //! // of the cache fall out of scope then the subsequent
105 //! // recursive borrow would cause a dynamic thread panic.
106 //! // This is the major hazard of using `RefCell`.
107 //! self.minimum_spanning_tree()
109 //! # fn calc_span_tree(&self) -> Vec<(i32, i32)> { vec![] }
113 //! ## Mutating implementations of `Clone`
115 //! This is simply a special - but common - case of the previous: hiding mutability for operations
116 //! that appear to be immutable. The `clone` method is expected to not change the source value, and
117 //! is declared to take `&self`, not `&mut self`. Therefore any mutation that happens in the
118 //! `clone` method must use cell types. For example, `Rc<T>` maintains its reference counts within a
122 //! use std::cell::Cell;
125 //! ptr: *mut RcBox<T>
128 //! struct RcBox<T> {
129 //! # #[allow(dead_code)]
131 //! refcount: Cell<usize>
134 //! impl<T> Clone for Rc<T> {
135 //! fn clone(&self) -> Rc<T> {
137 //! (*self.ptr).refcount.set((*self.ptr).refcount.get() + 1);
138 //! Rc { ptr: self.ptr }
145 #![stable(feature = "rust1", since = "1.0.0")]
148 use cmp::{PartialEq, Eq, PartialOrd, Ord, Ordering};
150 use default::Default;
151 use fmt::{self, Debug, Display};
152 use marker::{Copy, PhantomData, Send, Sync, Sized, Unsize};
153 use ops::{Deref, DerefMut, Drop, FnOnce, CoerceUnsized};
155 use option::Option::{None, Some};
157 use result::Result::{Ok, Err};
159 /// A mutable memory location that admits only `Copy` data.
161 /// See the [module-level documentation](index.html) for more.
162 #[stable(feature = "rust1", since = "1.0.0")]
164 value: UnsafeCell<T>,
167 impl<T:Copy> Cell<T> {
168 /// Creates a new `Cell` containing the given value.
173 /// use std::cell::Cell;
175 /// let c = Cell::new(5);
177 #[stable(feature = "rust1", since = "1.0.0")]
179 pub const fn new(value: T) -> Cell<T> {
181 value: UnsafeCell::new(value),
185 /// Returns a copy of the contained value.
190 /// use std::cell::Cell;
192 /// let c = Cell::new(5);
194 /// let five = c.get();
197 #[stable(feature = "rust1", since = "1.0.0")]
198 pub fn get(&self) -> T {
199 unsafe{ *self.value.get() }
202 /// Sets the contained value.
207 /// use std::cell::Cell;
209 /// let c = Cell::new(5);
214 #[stable(feature = "rust1", since = "1.0.0")]
215 pub fn set(&self, value: T) {
217 *self.value.get() = value;
221 /// Returns a reference to the underlying `UnsafeCell`.
226 /// #![feature(as_unsafe_cell)]
228 /// use std::cell::Cell;
230 /// let c = Cell::new(5);
232 /// let uc = c.as_unsafe_cell();
235 #[unstable(feature = "as_unsafe_cell", issue = "27708")]
236 #[rustc_deprecated(since = "1.12.0", reason = "renamed to as_ptr")]
237 pub fn as_unsafe_cell(&self) -> &UnsafeCell<T> {
241 /// Returns a raw pointer to the underlying data in this cell.
246 /// use std::cell::Cell;
248 /// let c = Cell::new(5);
250 /// let ptr = c.as_ptr();
253 #[stable(feature = "cell_as_ptr", since = "1.12.0")]
254 pub fn as_ptr(&self) -> *mut T {
258 /// Returns a mutable reference to the underlying data.
260 /// This call borrows `Cell` mutably (at compile-time) which guarantees
261 /// that we possess the only reference.
266 /// use std::cell::Cell;
268 /// let mut c = Cell::new(5);
269 /// *c.get_mut() += 1;
271 /// assert_eq!(c.get(), 6);
274 #[stable(feature = "cell_get_mut", since = "1.11.0")]
275 pub fn get_mut(&mut self) -> &mut T {
277 &mut *self.value.get()
282 #[stable(feature = "rust1", since = "1.0.0")]
283 unsafe impl<T> Send for Cell<T> where T: Send {}
285 #[stable(feature = "rust1", since = "1.0.0")]
286 impl<T> !Sync for Cell<T> {}
288 #[stable(feature = "rust1", since = "1.0.0")]
289 impl<T:Copy> Clone for Cell<T> {
291 fn clone(&self) -> Cell<T> {
292 Cell::new(self.get())
296 #[stable(feature = "rust1", since = "1.0.0")]
297 impl<T:Default + Copy> Default for Cell<T> {
299 fn default() -> Cell<T> {
300 Cell::new(Default::default())
304 #[stable(feature = "rust1", since = "1.0.0")]
305 impl<T:PartialEq + Copy> PartialEq for Cell<T> {
307 fn eq(&self, other: &Cell<T>) -> bool {
308 self.get() == other.get()
312 #[stable(feature = "cell_eq", since = "1.2.0")]
313 impl<T:Eq + Copy> Eq for Cell<T> {}
315 #[stable(feature = "cell_ord", since = "1.10.0")]
316 impl<T:PartialOrd + Copy> PartialOrd for Cell<T> {
318 fn partial_cmp(&self, other: &Cell<T>) -> Option<Ordering> {
319 self.get().partial_cmp(&other.get())
323 fn lt(&self, other: &Cell<T>) -> bool {
324 self.get() < other.get()
328 fn le(&self, other: &Cell<T>) -> bool {
329 self.get() <= other.get()
333 fn gt(&self, other: &Cell<T>) -> bool {
334 self.get() > other.get()
338 fn ge(&self, other: &Cell<T>) -> bool {
339 self.get() >= other.get()
343 #[stable(feature = "cell_ord", since = "1.10.0")]
344 impl<T:Ord + Copy> Ord for Cell<T> {
346 fn cmp(&self, other: &Cell<T>) -> Ordering {
347 self.get().cmp(&other.get())
351 #[stable(feature = "cell_from", since = "1.12.0")]
352 impl<T: Copy> From<T> for Cell<T> {
353 fn from(t: T) -> Cell<T> {
358 #[unstable(feature = "coerce_unsized", issue = "27732")]
359 impl<T: CoerceUnsized<U>, U> CoerceUnsized<Cell<U>> for Cell<T> {}
361 /// A mutable memory location with dynamically checked borrow rules
363 /// See the [module-level documentation](index.html) for more.
364 #[stable(feature = "rust1", since = "1.0.0")]
365 pub struct RefCell<T: ?Sized> {
366 borrow: Cell<BorrowFlag>,
367 value: UnsafeCell<T>,
370 /// An enumeration of values returned from the `state` method on a `RefCell<T>`.
371 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
372 #[unstable(feature = "borrow_state", issue = "27733")]
373 pub enum BorrowState {
374 /// The cell is currently being read, there is at least one active `borrow`.
376 /// The cell is currently being written to, there is an active `borrow_mut`.
378 /// There are no outstanding borrows on this cell.
382 /// An error returned by [`RefCell::try_borrow`](struct.RefCell.html#method.try_borrow).
383 #[unstable(feature = "try_borrow", issue = "35070")]
384 pub struct BorrowError<'a, T: 'a + ?Sized> {
385 marker: PhantomData<&'a RefCell<T>>,
388 #[unstable(feature = "try_borrow", issue = "35070")]
389 impl<'a, T: ?Sized> Debug for BorrowError<'a, T> {
390 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
391 f.debug_struct("BorrowError").finish()
395 #[unstable(feature = "try_borrow", issue = "35070")]
396 impl<'a, T: ?Sized> Display for BorrowError<'a, T> {
397 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
398 Display::fmt("already mutably borrowed", f)
402 /// An error returned by [`RefCell::try_borrow_mut`](struct.RefCell.html#method.try_borrow_mut).
403 #[unstable(feature = "try_borrow", issue = "35070")]
404 pub struct BorrowMutError<'a, T: 'a + ?Sized> {
405 marker: PhantomData<&'a RefCell<T>>,
408 #[unstable(feature = "try_borrow", issue = "35070")]
409 impl<'a, T: ?Sized> Debug for BorrowMutError<'a, T> {
410 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
411 f.debug_struct("BorrowMutError").finish()
415 #[unstable(feature = "try_borrow", issue = "35070")]
416 impl<'a, T: ?Sized> Display for BorrowMutError<'a, T> {
417 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
418 Display::fmt("already borrowed", f)
422 // Values [1, MAX-1] represent the number of `Ref` active
423 // (will not outgrow its range since `usize` is the size of the address space)
424 type BorrowFlag = usize;
425 const UNUSED: BorrowFlag = 0;
426 const WRITING: BorrowFlag = !0;
429 /// Creates a new `RefCell` containing `value`.
434 /// use std::cell::RefCell;
436 /// let c = RefCell::new(5);
438 #[stable(feature = "rust1", since = "1.0.0")]
440 pub const fn new(value: T) -> RefCell<T> {
442 value: UnsafeCell::new(value),
443 borrow: Cell::new(UNUSED),
447 /// Consumes the `RefCell`, returning the wrapped value.
452 /// use std::cell::RefCell;
454 /// let c = RefCell::new(5);
456 /// let five = c.into_inner();
458 #[stable(feature = "rust1", since = "1.0.0")]
460 pub fn into_inner(self) -> T {
461 // Since this function takes `self` (the `RefCell`) by value, the
462 // compiler statically verifies that it is not currently borrowed.
463 // Therefore the following assertion is just a `debug_assert!`.
464 debug_assert!(self.borrow.get() == UNUSED);
465 unsafe { self.value.into_inner() }
469 impl<T: ?Sized> RefCell<T> {
470 /// Query the current state of this `RefCell`
472 /// The returned value can be dispatched on to determine if a call to
473 /// `borrow` or `borrow_mut` would succeed.
478 /// #![feature(borrow_state)]
480 /// use std::cell::{BorrowState, RefCell};
482 /// let c = RefCell::new(5);
484 /// match c.borrow_state() {
485 /// BorrowState::Writing => println!("Cannot be borrowed"),
486 /// BorrowState::Reading => println!("Cannot be borrowed mutably"),
487 /// BorrowState::Unused => println!("Can be borrowed (mutably as well)"),
490 #[unstable(feature = "borrow_state", issue = "27733")]
492 pub fn borrow_state(&self) -> BorrowState {
493 match self.borrow.get() {
494 WRITING => BorrowState::Writing,
495 UNUSED => BorrowState::Unused,
496 _ => BorrowState::Reading,
500 /// Immutably borrows the wrapped value.
502 /// The borrow lasts until the returned `Ref` exits scope. Multiple
503 /// immutable borrows can be taken out at the same time.
507 /// Panics if the value is currently mutably borrowed. For a non-panicking variant, use
508 /// [`try_borrow`](#method.try_borrow).
513 /// use std::cell::RefCell;
515 /// let c = RefCell::new(5);
517 /// let borrowed_five = c.borrow();
518 /// let borrowed_five2 = c.borrow();
521 /// An example of panic:
524 /// use std::cell::RefCell;
527 /// let result = thread::spawn(move || {
528 /// let c = RefCell::new(5);
529 /// let m = c.borrow_mut();
531 /// let b = c.borrow(); // this causes a panic
534 /// assert!(result.is_err());
536 #[stable(feature = "rust1", since = "1.0.0")]
538 pub fn borrow(&self) -> Ref<T> {
539 self.try_borrow().expect("already mutably borrowed")
542 /// Immutably borrows the wrapped value, returning an error if the value is currently mutably
545 /// The borrow lasts until the returned `Ref` exits scope. Multiple immutable borrows can be
546 /// taken out at the same time.
548 /// This is the non-panicking variant of [`borrow`](#method.borrow).
553 /// #![feature(try_borrow)]
555 /// use std::cell::RefCell;
557 /// let c = RefCell::new(5);
560 /// let m = c.borrow_mut();
561 /// assert!(c.try_borrow().is_err());
565 /// let m = c.borrow();
566 /// assert!(c.try_borrow().is_ok());
569 #[unstable(feature = "try_borrow", issue = "35070")]
571 pub fn try_borrow(&self) -> Result<Ref<T>, BorrowError<T>> {
572 match BorrowRef::new(&self.borrow) {
574 value: unsafe { &*self.value.get() },
577 None => Err(BorrowError { marker: PhantomData }),
581 /// Mutably borrows the wrapped value.
583 /// The borrow lasts until the returned `RefMut` exits scope. The value
584 /// cannot be borrowed while this borrow is active.
588 /// Panics if the value is currently borrowed. For a non-panicking variant, use
589 /// [`try_borrow_mut`](#method.try_borrow_mut).
594 /// use std::cell::RefCell;
596 /// let c = RefCell::new(5);
598 /// *c.borrow_mut() = 7;
600 /// assert_eq!(*c.borrow(), 7);
603 /// An example of panic:
606 /// use std::cell::RefCell;
609 /// let result = thread::spawn(move || {
610 /// let c = RefCell::new(5);
611 /// let m = c.borrow();
613 /// let b = c.borrow_mut(); // this causes a panic
616 /// assert!(result.is_err());
618 #[stable(feature = "rust1", since = "1.0.0")]
620 pub fn borrow_mut(&self) -> RefMut<T> {
621 self.try_borrow_mut().expect("already borrowed")
624 /// Mutably borrows the wrapped value, returning an error if the value is currently borrowed.
626 /// The borrow lasts until the returned `RefMut` exits scope. The value cannot be borrowed
627 /// while this borrow is active.
629 /// This is the non-panicking variant of [`borrow_mut`](#method.borrow_mut).
634 /// #![feature(try_borrow)]
636 /// use std::cell::RefCell;
638 /// let c = RefCell::new(5);
641 /// let m = c.borrow();
642 /// assert!(c.try_borrow_mut().is_err());
645 /// assert!(c.try_borrow_mut().is_ok());
647 #[unstable(feature = "try_borrow", issue = "35070")]
649 pub fn try_borrow_mut(&self) -> Result<RefMut<T>, BorrowMutError<T>> {
650 match BorrowRefMut::new(&self.borrow) {
651 Some(b) => Ok(RefMut {
652 value: unsafe { &mut *self.value.get() },
655 None => Err(BorrowMutError { marker: PhantomData }),
659 /// Returns a reference to the underlying `UnsafeCell`.
661 /// This can be used to circumvent `RefCell`'s safety checks.
663 /// This function is `unsafe` because `UnsafeCell`'s field is public.
668 /// #![feature(as_unsafe_cell)]
670 /// use std::cell::RefCell;
672 /// let c = RefCell::new(5);
673 /// let c = unsafe { c.as_unsafe_cell() };
676 #[unstable(feature = "as_unsafe_cell", issue = "27708")]
677 #[rustc_deprecated(since = "1.12.0", reason = "renamed to as_ptr")]
678 pub unsafe fn as_unsafe_cell(&self) -> &UnsafeCell<T> {
682 /// Returns a raw pointer to the underlying data in this cell.
687 /// use std::cell::RefCell;
689 /// let c = RefCell::new(5);
691 /// let ptr = c.as_ptr();
694 #[stable(feature = "cell_as_ptr", since = "1.12.0")]
695 pub fn as_ptr(&self) -> *mut T {
699 /// Returns a mutable reference to the underlying data.
701 /// This call borrows `RefCell` mutably (at compile-time) so there is no
702 /// need for dynamic checks.
707 /// use std::cell::RefCell;
709 /// let mut c = RefCell::new(5);
710 /// *c.get_mut() += 1;
712 /// assert_eq!(c, RefCell::new(6));
715 #[stable(feature = "cell_get_mut", since = "1.11.0")]
716 pub fn get_mut(&mut self) -> &mut T {
718 &mut *self.value.get()
723 #[stable(feature = "rust1", since = "1.0.0")]
724 unsafe impl<T: ?Sized> Send for RefCell<T> where T: Send {}
726 #[stable(feature = "rust1", since = "1.0.0")]
727 impl<T: ?Sized> !Sync for RefCell<T> {}
729 #[stable(feature = "rust1", since = "1.0.0")]
730 impl<T: Clone> Clone for RefCell<T> {
732 fn clone(&self) -> RefCell<T> {
733 RefCell::new(self.borrow().clone())
737 #[stable(feature = "rust1", since = "1.0.0")]
738 impl<T:Default> Default for RefCell<T> {
740 fn default() -> RefCell<T> {
741 RefCell::new(Default::default())
745 #[stable(feature = "rust1", since = "1.0.0")]
746 impl<T: ?Sized + PartialEq> PartialEq for RefCell<T> {
748 fn eq(&self, other: &RefCell<T>) -> bool {
749 *self.borrow() == *other.borrow()
753 #[stable(feature = "cell_eq", since = "1.2.0")]
754 impl<T: ?Sized + Eq> Eq for RefCell<T> {}
756 #[stable(feature = "cell_ord", since = "1.10.0")]
757 impl<T: ?Sized + PartialOrd> PartialOrd for RefCell<T> {
759 fn partial_cmp(&self, other: &RefCell<T>) -> Option<Ordering> {
760 self.borrow().partial_cmp(&*other.borrow())
764 fn lt(&self, other: &RefCell<T>) -> bool {
765 *self.borrow() < *other.borrow()
769 fn le(&self, other: &RefCell<T>) -> bool {
770 *self.borrow() <= *other.borrow()
774 fn gt(&self, other: &RefCell<T>) -> bool {
775 *self.borrow() > *other.borrow()
779 fn ge(&self, other: &RefCell<T>) -> bool {
780 *self.borrow() >= *other.borrow()
784 #[stable(feature = "cell_ord", since = "1.10.0")]
785 impl<T: ?Sized + Ord> Ord for RefCell<T> {
787 fn cmp(&self, other: &RefCell<T>) -> Ordering {
788 self.borrow().cmp(&*other.borrow())
792 #[stable(feature = "cell_from", since = "1.12.0")]
793 impl<T> From<T> for RefCell<T> {
794 fn from(t: T) -> RefCell<T> {
799 #[unstable(feature = "coerce_unsized", issue = "27732")]
800 impl<T: CoerceUnsized<U>, U> CoerceUnsized<RefCell<U>> for RefCell<T> {}
802 struct BorrowRef<'b> {
803 borrow: &'b Cell<BorrowFlag>,
806 impl<'b> BorrowRef<'b> {
808 fn new(borrow: &'b Cell<BorrowFlag>) -> Option<BorrowRef<'b>> {
813 Some(BorrowRef { borrow: borrow })
819 impl<'b> Drop for BorrowRef<'b> {
822 let borrow = self.borrow.get();
823 debug_assert!(borrow != WRITING && borrow != UNUSED);
824 self.borrow.set(borrow - 1);
828 impl<'b> Clone for BorrowRef<'b> {
830 fn clone(&self) -> BorrowRef<'b> {
831 // Since this Ref exists, we know the borrow flag
832 // is not set to WRITING.
833 let borrow = self.borrow.get();
834 debug_assert!(borrow != UNUSED);
835 // Prevent the borrow counter from overflowing.
836 assert!(borrow != WRITING);
837 self.borrow.set(borrow + 1);
838 BorrowRef { borrow: self.borrow }
842 /// Wraps a borrowed reference to a value in a `RefCell` box.
843 /// A wrapper type for an immutably borrowed value from a `RefCell<T>`.
845 /// See the [module-level documentation](index.html) for more.
846 #[stable(feature = "rust1", since = "1.0.0")]
847 pub struct Ref<'b, T: ?Sized + 'b> {
849 borrow: BorrowRef<'b>,
852 #[stable(feature = "rust1", since = "1.0.0")]
853 impl<'b, T: ?Sized> Deref for Ref<'b, T> {
857 fn deref(&self) -> &T {
862 impl<'b, T: ?Sized> Ref<'b, T> {
865 /// The `RefCell` is already immutably borrowed, so this cannot fail.
867 /// This is an associated function that needs to be used as
868 /// `Ref::clone(...)`. A `Clone` implementation or a method would interfere
869 /// with the widespread use of `r.borrow().clone()` to clone the contents of
871 #[unstable(feature = "cell_extras",
872 reason = "likely to be moved to a method, pending language changes",
875 pub fn clone(orig: &Ref<'b, T>) -> Ref<'b, T> {
878 borrow: orig.borrow.clone(),
882 /// Make a new `Ref` for a component of the borrowed data.
884 /// The `RefCell` is already immutably borrowed, so this cannot fail.
886 /// This is an associated function that needs to be used as `Ref::map(...)`.
887 /// A method would interfere with methods of the same name on the contents
888 /// of a `RefCell` used through `Deref`.
893 /// use std::cell::{RefCell, Ref};
895 /// let c = RefCell::new((5, 'b'));
896 /// let b1: Ref<(u32, char)> = c.borrow();
897 /// let b2: Ref<u32> = Ref::map(b1, |t| &t.0);
898 /// assert_eq!(*b2, 5)
900 #[stable(feature = "cell_map", since = "1.8.0")]
902 pub fn map<U: ?Sized, F>(orig: Ref<'b, T>, f: F) -> Ref<'b, U>
903 where F: FnOnce(&T) -> &U
906 value: f(orig.value),
912 #[unstable(feature = "coerce_unsized", issue = "27732")]
913 impl<'b, T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Ref<'b, U>> for Ref<'b, T> {}
915 impl<'b, T: ?Sized> RefMut<'b, T> {
916 /// Make a new `RefMut` for a component of the borrowed data, e.g. an enum
919 /// The `RefCell` is already mutably borrowed, so this cannot fail.
921 /// This is an associated function that needs to be used as
922 /// `RefMut::map(...)`. A method would interfere with methods of the same
923 /// name on the contents of a `RefCell` used through `Deref`.
928 /// use std::cell::{RefCell, RefMut};
930 /// let c = RefCell::new((5, 'b'));
932 /// let b1: RefMut<(u32, char)> = c.borrow_mut();
933 /// let mut b2: RefMut<u32> = RefMut::map(b1, |t| &mut t.0);
934 /// assert_eq!(*b2, 5);
937 /// assert_eq!(*c.borrow(), (42, 'b'));
939 #[stable(feature = "cell_map", since = "1.8.0")]
941 pub fn map<U: ?Sized, F>(orig: RefMut<'b, T>, f: F) -> RefMut<'b, U>
942 where F: FnOnce(&mut T) -> &mut U
945 value: f(orig.value),
951 struct BorrowRefMut<'b> {
952 borrow: &'b Cell<BorrowFlag>,
955 impl<'b> Drop for BorrowRefMut<'b> {
958 let borrow = self.borrow.get();
959 debug_assert!(borrow == WRITING);
960 self.borrow.set(UNUSED);
964 impl<'b> BorrowRefMut<'b> {
966 fn new(borrow: &'b Cell<BorrowFlag>) -> Option<BorrowRefMut<'b>> {
970 Some(BorrowRefMut { borrow: borrow })
977 /// A wrapper type for a mutably borrowed value from a `RefCell<T>`.
979 /// See the [module-level documentation](index.html) for more.
980 #[stable(feature = "rust1", since = "1.0.0")]
981 pub struct RefMut<'b, T: ?Sized + 'b> {
983 borrow: BorrowRefMut<'b>,
986 #[stable(feature = "rust1", since = "1.0.0")]
987 impl<'b, T: ?Sized> Deref for RefMut<'b, T> {
991 fn deref(&self) -> &T {
996 #[stable(feature = "rust1", since = "1.0.0")]
997 impl<'b, T: ?Sized> DerefMut for RefMut<'b, T> {
999 fn deref_mut(&mut self) -> &mut T {
1004 #[unstable(feature = "coerce_unsized", issue = "27732")]
1005 impl<'b, T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<RefMut<'b, U>> for RefMut<'b, T> {}
1007 /// The core primitive for interior mutability in Rust.
1009 /// `UnsafeCell<T>` is a type that wraps some `T` and indicates unsafe interior operations on the
1010 /// wrapped type. Types with an `UnsafeCell<T>` field are considered to have an 'unsafe interior'.
1011 /// The `UnsafeCell<T>` type is the only legal way to obtain aliasable data that is considered
1012 /// mutable. In general, transmuting an `&T` type into an `&mut T` is considered undefined behavior.
1014 /// The compiler makes optimizations based on the knowledge that `&T` is not mutably aliased or
1015 /// mutated, and that `&mut T` is unique. When building abstractions like `Cell`, `RefCell`,
1016 /// `Mutex`, etc, you need to turn these optimizations off. `UnsafeCell` is the only legal way
1017 /// to do this. When `UnsafeCell<T>` is immutably aliased, it is still safe to obtain a mutable
1018 /// reference to its interior and/or to mutate it. However, it is up to the abstraction designer
1019 /// to ensure that no two mutable references obtained this way are active at the same time, and
1020 /// that there are no active mutable references or mutations when an immutable reference is obtained
1021 /// from the cell. This is often done via runtime checks.
1023 /// Note that while mutating or mutably aliasing the contents of an `& UnsafeCell<T>` is
1024 /// okay (provided you enforce the invariants some other way); it is still undefined behavior
1025 /// to have multiple `&mut UnsafeCell<T>` aliases.
1028 /// Types like `Cell<T>` and `RefCell<T>` use this type to wrap their internal data.
1033 /// use std::cell::UnsafeCell;
1034 /// use std::marker::Sync;
1036 /// # #[allow(dead_code)]
1037 /// struct NotThreadSafe<T> {
1038 /// value: UnsafeCell<T>,
1041 /// unsafe impl<T> Sync for NotThreadSafe<T> {}
1043 #[lang = "unsafe_cell"]
1044 #[stable(feature = "rust1", since = "1.0.0")]
1045 pub struct UnsafeCell<T: ?Sized> {
1049 #[stable(feature = "rust1", since = "1.0.0")]
1050 impl<T: ?Sized> !Sync for UnsafeCell<T> {}
1052 impl<T> UnsafeCell<T> {
1053 /// Constructs a new instance of `UnsafeCell` which will wrap the specified
1056 /// All access to the inner value through methods is `unsafe`.
1061 /// use std::cell::UnsafeCell;
1063 /// let uc = UnsafeCell::new(5);
1065 #[stable(feature = "rust1", since = "1.0.0")]
1067 pub const fn new(value: T) -> UnsafeCell<T> {
1068 UnsafeCell { value: value }
1071 /// Unwraps the value.
1075 /// This function is unsafe because this thread or another thread may currently be
1076 /// inspecting the inner value.
1081 /// use std::cell::UnsafeCell;
1083 /// let uc = UnsafeCell::new(5);
1085 /// let five = unsafe { uc.into_inner() };
1088 #[stable(feature = "rust1", since = "1.0.0")]
1089 pub unsafe fn into_inner(self) -> T {
1094 impl<T: ?Sized> UnsafeCell<T> {
1095 /// Gets a mutable pointer to the wrapped value.
1097 /// This can be cast to a pointer of any kind.
1098 /// Ensure that the access is unique when casting to
1099 /// `&mut T`, and ensure that there are no mutations or mutable
1100 /// aliases going on when casting to `&T`
1105 /// use std::cell::UnsafeCell;
1107 /// let uc = UnsafeCell::new(5);
1109 /// let five = uc.get();
1112 #[stable(feature = "rust1", since = "1.0.0")]
1113 pub fn get(&self) -> *mut T {
1114 &self.value as *const T as *mut T
1118 #[stable(feature = "unsafe_cell_default", since = "1.9.0")]
1119 impl<T: Default> Default for UnsafeCell<T> {
1120 fn default() -> UnsafeCell<T> {
1121 UnsafeCell::new(Default::default())
1125 #[stable(feature = "cell_from", since = "1.12.0")]
1126 impl<T> From<T> for UnsafeCell<T> {
1127 fn from(t: T) -> UnsafeCell<T> {
1132 #[unstable(feature = "coerce_unsized", issue = "27732")]
1133 impl<T: CoerceUnsized<U>, U> CoerceUnsized<UnsafeCell<U>> for UnsafeCell<T> {}
1136 fn assert_coerce_unsized(a: UnsafeCell<&i32>, b: Cell<&i32>, c: RefCell<&i32>) {
1137 let _: UnsafeCell<&Send> = a;
1138 let _: Cell<&Send> = b;
1139 let _: RefCell<&Send> = c;