rust/src/libcore/cell.rs

1611 lines
50 KiB
Rust
Raw Normal View History

2014-05-22 12:50:31 +00:00
//! Shareable mutable containers.
2014-05-19 04:47:51 +00:00
//!
2018-02-24 23:06:01 +00:00
//! Rust memory safety is based on this rule: Given an object `T`, it is only possible to
2018-02-22 18:53:59 +00:00
//! have one of the following:
//!
2018-02-26 16:14:40 +00:00
//! - Having several immutable references (`&T`) to the object (also known as **aliasing**).
//! - Having one mutable reference (`&mut T`) to the object (also known as **mutability**).
2018-02-22 18:53:59 +00:00
//!
//! This is enforced by the Rust compiler. However, there are situations where this rule is not
2018-02-24 23:06:01 +00:00
//! flexible enough. Sometimes it is required to have multiple references to an object and yet
2018-02-22 18:53:59 +00:00
//! mutate it.
//!
2018-02-26 16:14:40 +00:00
//! Shareable mutable containers exist to permit mutability in a controlled manner, even in the
2019-05-19 17:53:35 +00:00
//! presence of aliasing. Both `Cell<T>` and `RefCell<T>` allow doing this in a single-threaded
2018-02-23 20:12:28 +00:00
//! way. However, neither `Cell<T>` nor `RefCell<T>` are thread safe (they do not implement
2018-02-26 16:14:40 +00:00
//! `Sync`). If you need to do aliasing and mutation between multiple threads it is possible to
//! use [`Mutex`](../../std/sync/struct.Mutex.html),
//! [`RwLock`](../../std/sync/struct.RwLock.html) or
2018-02-25 03:43:30 +00:00
//! [`atomic`](../../core/sync/atomic/index.html) types.
2018-02-22 18:53:59 +00:00
//!
2015-01-23 20:02:05 +00:00
//! Values of the `Cell<T>` and `RefCell<T>` types may be mutated through shared references (i.e.
//! the common `&T` type), whereas most Rust types can only be mutated through unique (`&mut T`)
//! references. We say that `Cell<T>` and `RefCell<T>` provide 'interior mutability', in contrast
//! with typical Rust types that exhibit 'inherited mutability'.
2014-05-19 04:47:51 +00:00
//!
2017-01-27 03:23:32 +00:00
//! Cell types come in two flavors: `Cell<T>` and `RefCell<T>`. `Cell<T>` implements interior
//! mutability by moving values in and out of the `Cell<T>`. To use references instead of values,
//! one must use the `RefCell<T>` type, acquiring a write lock before mutating. `Cell<T>` provides
//! methods to retrieve and change the current interior value:
//!
//! - For types that implement `Copy`, the `get` method retrieves the current interior value.
//! - For types that implement `Default`, the `take` method replaces the current interior value
//! with `Default::default()` and returns the replaced value.
//! - For all types, the `replace` method replaces the current interior value and returns the
//! replaced value and the `into_inner` method consumes the `Cell<T>` and returns the interior
//! value. Additionally, the `set` method replaces the interior value, dropping the replaced
//! value.
2014-05-19 04:47:51 +00:00
//!
2015-01-23 20:02:05 +00:00
//! `RefCell<T>` uses Rust's lifetimes to implement 'dynamic borrowing', a process whereby one can
//! claim temporary, exclusive, mutable access to the inner value. Borrows for `RefCell<T>`s are
//! tracked 'at runtime', unlike Rust's native reference types which are entirely tracked
//! statically, at compile time. Because `RefCell<T>` borrows are dynamic it is possible to attempt
2015-05-08 15:56:50 +00:00
//! to borrow a value that is already mutably borrowed; when this happens it results in thread
//! panic.
2014-05-19 04:47:51 +00:00
//!
//! # When to choose interior mutability
//!
2015-01-23 20:02:05 +00:00
//! The more common inherited mutability, where one must have unique access to mutate a value, is
//! one of the key language elements that enables Rust to reason strongly about pointer aliasing,
//! statically preventing crash bugs. Because of that, inherited mutability is preferred, and
//! interior mutability is something of a last resort. Since cell types enable mutation where it
//! would otherwise be disallowed though, there are occasions when interior mutability might be
//! appropriate, or even *must* be used, e.g.
2014-05-19 04:47:51 +00:00
//!
//! * Introducing mutability 'inside' of something immutable
2014-05-19 04:47:51 +00:00
//! * Implementation details of logically-immutable methods.
//! * Mutating implementations of `Clone`.
2014-05-19 04:47:51 +00:00
//!
//! ## Introducing mutability 'inside' of something immutable
2014-05-19 04:47:51 +00:00
//!
//! Many shared smart pointer types, including `Rc<T>` and `Arc<T>`, provide containers that can be
2015-01-23 20:02:05 +00:00
//! cloned and shared between multiple parties. Because the contained values may be
//! multiply-aliased, they can only be borrowed with `&`, not `&mut`. Without cells it would be
//! impossible to mutate data inside of these smart pointers at all.
2014-05-19 04:47:51 +00:00
//!
2015-01-23 20:02:05 +00:00
//! It's very common then to put a `RefCell<T>` inside shared pointer types to reintroduce
//! mutability:
2014-05-19 04:47:51 +00:00
//!
//! ```
//! use std::cell::{RefCell, RefMut};
std: Recreate a `collections` module As with the previous commit with `librand`, this commit shuffles around some `collections` code. The new state of the world is similar to that of librand: * The libcollections crate now only depends on libcore and liballoc. * The standard library has a new module, `std::collections`. All functionality of libcollections is reexported through this module. I would like to stress that this change is purely cosmetic. There are very few alterations to these primitives. There are a number of notable points about the new organization: * std::{str, slice, string, vec} all moved to libcollections. There is no reason that these primitives shouldn't be necessarily usable in a freestanding context that has allocation. These are all reexported in their usual places in the standard library. * The `hashmap`, and transitively the `lru_cache`, modules no longer reside in `libcollections`, but rather in libstd. The reason for this is because the `HashMap::new` contructor requires access to the OSRng for initially seeding the hash map. Beyond this requirement, there is no reason that the hashmap could not move to libcollections. I do, however, have a plan to move the hash map to the collections module. The `HashMap::new` function could be altered to require that the `H` hasher parameter ascribe to the `Default` trait, allowing the entire `hashmap` module to live in libcollections. The key idea would be that the default hasher would be different in libstd. Something along the lines of: // src/libstd/collections/mod.rs pub type HashMap<K, V, H = RandomizedSipHasher> = core_collections::HashMap<K, V, H>; This is not possible today because you cannot invoke static methods through type aliases. If we modified the compiler, however, to allow invocation of static methods through type aliases, then this type definition would essentially be switching the default hasher from `SipHasher` in libcollections to a libstd-defined `RandomizedSipHasher` type. This type's `Default` implementation would randomly seed the `SipHasher` instance, and otherwise perform the same as `SipHasher`. This future state doesn't seem incredibly far off, but until that time comes, the hashmap module will live in libstd to not compromise on functionality. * In preparation for the hashmap moving to libcollections, the `hash` module has moved from libstd to libcollections. A previously snapshotted commit enables a distinct `Writer` trait to live in the `hash` module which `Hash` implementations are now parameterized over. Due to using a custom trait, the `SipHasher` implementation has lost its specialized methods for writing integers. These can be re-added backwards-compatibly in the future via default methods if necessary, but the FNV hashing should satisfy much of the need for speedier hashing. A list of breaking changes: * HashMap::{get, get_mut} no longer fails with the key formatted into the error message with `{:?}`, instead, a generic message is printed. With backtraces, it should still be not-too-hard to track down errors. * The HashMap, HashSet, and LruCache types are now available through std::collections instead of the collections crate. * Manual implementations of hash should be parameterized over `hash::Writer` instead of just `Writer`. [breaking-change]
2014-05-30 01:50:12 +00:00
//! use std::collections::HashMap;
2014-05-19 04:47:51 +00:00
//! use std::rc::Rc;
//!
//! fn main() {
//! let shared_map: Rc<RefCell<_>> = Rc::new(RefCell::new(HashMap::new()));
//! // Create a new block to limit the scope of the dynamic borrow
//! {
//! let mut map: RefMut<_> = shared_map.borrow_mut();
//! map.insert("africa", 92388);
//! map.insert("kyoto", 11837);
//! map.insert("piccadilly", 11826);
//! map.insert("marbles", 38);
//! }
//!
//! // Note that if we had not let the previous borrow of the cache fall out
//! // of scope then the subsequent borrow would cause a dynamic thread panic.
//! // This is the major hazard of using `RefCell`.
//! let total: i32 = shared_map.borrow().values().sum();
//! println!("{}", total);
2014-05-19 04:47:51 +00:00
//! }
//! ```
//!
//! Note that this example uses `Rc<T>` and not `Arc<T>`. `RefCell<T>`s are for single-threaded
//! scenarios. Consider using `RwLock<T>` or `Mutex<T>` if you need shared mutability in a
//! multi-threaded situation.
//!
2014-05-19 04:47:51 +00:00
//! ## Implementation details of logically-immutable methods
//!
2015-01-23 20:02:05 +00:00
//! Occasionally it may be desirable not to expose in an API that there is mutation happening
//! "under the hood". This may be because logically the operation is immutable, but e.g., caching
2015-01-23 20:02:05 +00:00
//! forces the implementation to perform mutation; or because you must employ mutation to implement
//! a trait method that was originally defined to take `&self`.
2014-05-19 04:47:51 +00:00
//!
//! ```
2015-11-03 15:27:03 +00:00
//! # #![allow(dead_code)]
2014-05-19 04:47:51 +00:00
//! use std::cell::RefCell;
//!
//! struct Graph {
//! edges: Vec<(i32, i32)>,
//! span_tree_cache: RefCell<Option<Vec<(i32, i32)>>>
2014-05-19 04:47:51 +00:00
//! }
//!
//! impl Graph {
//! fn minimum_spanning_tree(&self) -> Vec<(i32, i32)> {
//! self.span_tree_cache.borrow_mut()
//! .get_or_insert_with(|| self.calc_span_tree())
//! .clone()
//! }
//!
//! fn calc_span_tree(&self) -> Vec<(i32, i32)> {
//! // Expensive computation goes here
//! vec![]
2014-05-19 04:47:51 +00:00
//! }
//! }
//! ```
//!
//! ## Mutating implementations of `Clone`
2014-05-19 04:47:51 +00:00
//!
2015-01-23 20:02:05 +00:00
//! This is simply a special - but common - case of the previous: hiding mutability for operations
//! that appear to be immutable. The `clone` method is expected to not change the source value, and
2019-02-09 22:16:58 +00:00
//! is declared to take `&self`, not `&mut self`. Therefore, any mutation that happens in the
2015-01-23 20:02:05 +00:00
//! `clone` method must use cell types. For example, `Rc<T>` maintains its reference counts within a
//! `Cell<T>`.
2014-05-19 04:47:51 +00:00
//!
//! ```
2016-08-22 07:37:08 +00:00
//! #![feature(core_intrinsics)]
2014-05-19 04:47:51 +00:00
//! use std::cell::Cell;
//! use std::ptr::NonNull;
2016-08-22 07:37:08 +00:00
//! use std::intrinsics::abort;
//! use std::marker::PhantomData;
2014-05-19 04:47:51 +00:00
//!
2016-08-22 07:37:08 +00:00
//! struct Rc<T: ?Sized> {
//! ptr: NonNull<RcBox<T>>,
//! phantom: PhantomData<RcBox<T>>,
2014-05-19 04:47:51 +00:00
//! }
//!
2016-08-22 07:37:08 +00:00
//! struct RcBox<T: ?Sized> {
//! strong: Cell<usize>,
//! refcount: Cell<usize>,
2014-05-19 04:47:51 +00:00
//! value: T,
//! }
//!
2016-08-22 07:37:08 +00:00
//! impl<T: ?Sized> Clone for Rc<T> {
2014-05-19 04:47:51 +00:00
//! fn clone(&self) -> Rc<T> {
2016-08-22 07:37:08 +00:00
//! self.inc_strong();
2019-11-05 22:03:31 +00:00
//! Rc {
//! ptr: self.ptr,
//! phantom: PhantomData,
//! }
2016-08-22 07:37:08 +00:00
//! }
//! }
//!
//! trait RcBoxPtr<T: ?Sized> {
//!
//! fn inner(&self) -> &RcBox<T>;
//!
//! fn strong(&self) -> usize {
//! self.inner().strong.get()
//! }
//!
//! fn inc_strong(&self) {
//! self.inner()
//! .strong
//! .set(self.strong()
//! .checked_add(1)
//! .unwrap_or_else(|| unsafe { abort() }));
2014-05-19 04:47:51 +00:00
//! }
//! }
2016-08-22 07:37:08 +00:00
//!
//! impl<T: ?Sized> RcBoxPtr<T> for Rc<T> {
//! fn inner(&self) -> &RcBox<T> {
//! unsafe {
//! self.ptr.as_ref()
2016-08-22 07:37:08 +00:00
//! }
//! }
//! }
2014-05-19 04:47:51 +00:00
//! ```
//!
2015-01-24 05:48:20 +00:00
#![stable(feature = "rust1", since = "1.0.0")]
2014-12-29 23:03:01 +00:00
2019-04-15 02:23:21 +00:00
use crate::cmp::Ordering;
use crate::fmt::{self, Debug, Display};
use crate::marker::Unsize;
use crate::mem;
2019-12-22 22:42:04 +00:00
use crate::ops::{CoerceUnsized, Deref, DerefMut};
2019-04-15 02:23:21 +00:00
use crate::ptr;
2013-11-22 05:30:34 +00:00
2017-01-27 03:23:32 +00:00
/// A mutable memory location.
2017-07-24 19:45:21 +00:00
///
2017-07-24 16:01:50 +00:00
/// # Examples
2017-07-24 19:45:21 +00:00
///
/// In this example, you can see that `Cell<T>` enables mutation inside an
/// immutable struct. In other words, it enables "interior mutability".
2017-07-24 19:45:21 +00:00
///
/// ```
/// use std::cell::Cell;
///
/// struct SomeStruct {
/// regular_field: u8,
/// special_field: Cell<u8>,
/// }
///
/// let my_struct = SomeStruct {
/// regular_field: 0,
/// special_field: Cell::new(1),
/// };
///
/// let new_value = 100;
2017-07-24 19:45:21 +00:00
///
/// // ERROR: `my_struct` is immutable
2017-07-24 21:43:34 +00:00
/// // my_struct.regular_field = new_value;
2017-07-24 19:45:21 +00:00
///
/// // WORKS: although `my_struct` is immutable, `special_field` is a `Cell`,
/// // which can always be mutated
2017-07-24 21:43:34 +00:00
/// my_struct.special_field.set(new_value);
/// assert_eq!(my_struct.special_field.get(), new_value);
/// ```
2015-01-23 20:02:05 +00:00
///
/// See the [module-level documentation](index.html) for more.
2015-01-24 05:48:20 +00:00
#[stable(feature = "rust1", since = "1.0.0")]
#[repr(transparent)]
2018-05-07 07:24:45 +00:00
pub struct Cell<T: ?Sized> {
std: Stabilize unit, bool, ty, tuple, arc, any This commit applies stability attributes to the contents of these modules, summarized here: * The `unit` and `bool` modules have become #[unstable] as they are purely meant for documentation purposes and are candidates for removal. * The `ty` module has been deprecated, and the inner `Unsafe` type has been renamed to `UnsafeCell` and moved to the `cell` module. The `marker1` field has been removed as the compiler now always infers `UnsafeCell` to be invariant. The `new` method i stable, but the `value` field, `get` and `unwrap` methods are all unstable. * The `tuple` module has its name as stable, the naming of the `TupleN` traits as stable while the methods are all #[unstable]. The other impls in the module have appropriate stability for the corresponding trait. * The `arc` module has received the exact same treatment as the `rc` module previously did. * The `any` module has its name as stable. The `Any` trait is also stable, with a new private supertrait which now contains the `get_type_id` method. This is to make the method a private implementation detail rather than a public-facing detail. The two extension traits in the module are marked #[unstable] as they will not be necessary with DST. The `is` method is #[stable], the as_{mut,ref} methods have been renamed to downcast_{mut,ref} and are #[unstable]. The extension trait `BoxAny` has been clarified as to why it is unstable as it will not be necessary with DST. This is a breaking change because the `marker1` field was removed from the `UnsafeCell` type. To deal with this change, you can simply delete the field and only specify the value of the `data` field in static initializers. [breaking-change]
2014-07-24 02:10:12 +00:00
value: UnsafeCell<T>,
2013-12-11 22:54:27 +00:00
}
2015-01-24 05:48:20 +00:00
#[stable(feature = "rust1", since = "1.0.0")]
2018-05-07 07:24:45 +00:00
unsafe impl<T: ?Sized> Send for Cell<T> where T: Send {}
#[stable(feature = "rust1", since = "1.0.0")]
2018-05-07 07:24:45 +00:00
impl<T: ?Sized> !Sync for Cell<T> {}
2015-01-24 05:48:20 +00:00
#[stable(feature = "rust1", since = "1.0.0")]
2019-12-22 22:42:04 +00:00
impl<T: Copy> Clone for Cell<T> {
#[inline]
fn clone(&self) -> Cell<T> {
Cell::new(self.get())
}
}
2015-01-24 05:48:20 +00:00
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Default> Default for Cell<T> {
/// Creates a `Cell<T>`, with the `Default` value for T.
#[inline]
fn default() -> Cell<T> {
Cell::new(Default::default())
}
}
2015-01-24 05:48:20 +00:00
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: PartialEq + Copy> PartialEq for Cell<T> {
#[inline]
2014-02-25 01:38:40 +00:00
fn eq(&self, other: &Cell<T>) -> bool {
self.get() == other.get()
}
}
#[stable(feature = "cell_eq", since = "1.2.0")]
impl<T: Eq + Copy> Eq for Cell<T> {}
#[stable(feature = "cell_ord", since = "1.10.0")]
impl<T: PartialOrd + Copy> PartialOrd for Cell<T> {
#[inline]
fn partial_cmp(&self, other: &Cell<T>) -> Option<Ordering> {
self.get().partial_cmp(&other.get())
}
#[inline]
fn lt(&self, other: &Cell<T>) -> bool {
self.get() < other.get()
}
#[inline]
fn le(&self, other: &Cell<T>) -> bool {
self.get() <= other.get()
}
#[inline]
fn gt(&self, other: &Cell<T>) -> bool {
self.get() > other.get()
}
#[inline]
fn ge(&self, other: &Cell<T>) -> bool {
self.get() >= other.get()
}
}
#[stable(feature = "cell_ord", since = "1.10.0")]
impl<T: Ord + Copy> Ord for Cell<T> {
#[inline]
fn cmp(&self, other: &Cell<T>) -> Ordering {
self.get().cmp(&other.get())
}
}
#[stable(feature = "cell_from", since = "1.12.0")]
impl<T> From<T> for Cell<T> {
fn from(t: T) -> Cell<T> {
Cell::new(t)
}
}
impl<T> Cell<T> {
/// Creates a new `Cell` containing the given value.
///
/// # Examples
///
/// ```
/// use std::cell::Cell;
///
/// let c = Cell::new(5);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
2019-12-18 17:00:59 +00:00
#[rustc_const_stable(feature = "const_cell_new", since = "1.32.0")]
#[inline]
pub const fn new(value: T) -> Cell<T> {
2019-12-22 22:42:04 +00:00
Cell { value: UnsafeCell::new(value) }
}
/// Sets the contained value.
///
/// # Examples
///
/// ```
/// use std::cell::Cell;
///
/// let c = Cell::new(5);
///
/// c.set(10);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn set(&self, val: T) {
let old = self.replace(val);
drop(old);
}
2017-02-10 08:38:59 +00:00
/// Swaps the values of two Cells.
/// Difference with `std::mem::swap` is that this function doesn't require `&mut` reference.
///
/// # Examples
///
/// ```
/// use std::cell::Cell;
///
/// let c1 = Cell::new(5i32);
/// let c2 = Cell::new(10i32);
/// c1.swap(&c2);
/// assert_eq!(10, c1.get());
/// assert_eq!(5, c2.get());
/// ```
#[inline]
#[stable(feature = "move_cell", since = "1.17.0")]
2017-02-10 08:38:59 +00:00
pub fn swap(&self, other: &Self) {
if ptr::eq(self, other) {
return;
}
2019-12-26 20:56:34 +00:00
// SAFETY: This can be risky if called from separate threads, but `Cell`
// is `!Sync` so this won't happen. This also won't invalidate any
// pointers since `Cell` makes sure nothing else will be pointing into
// either of these `Cell`s.
2017-02-10 08:38:59 +00:00
unsafe {
ptr::swap(self.value.get(), other.value.get());
}
}
/// Replaces the contained value, and returns it.
///
/// # Examples
///
/// ```
/// use std::cell::Cell;
///
/// let cell = Cell::new(5);
/// assert_eq!(cell.get(), 5);
/// assert_eq!(cell.replace(10), 5);
/// assert_eq!(cell.get(), 10);
/// ```
#[stable(feature = "move_cell", since = "1.17.0")]
pub fn replace(&self, val: T) -> T {
2019-12-26 20:56:34 +00:00
// SAFETY: This can cause data races if called from a separate thread,
// but `Cell` is `!Sync` so this won't happen.
mem::replace(unsafe { &mut *self.value.get() }, val)
}
/// Unwraps the value.
///
/// # Examples
///
/// ```
/// use std::cell::Cell;
///
/// let c = Cell::new(5);
/// let five = c.into_inner();
///
/// assert_eq!(five, 5);
/// ```
#[stable(feature = "move_cell", since = "1.17.0")]
pub fn into_inner(self) -> T {
self.value.into_inner()
}
}
2019-12-22 22:42:04 +00:00
impl<T: Copy> Cell<T> {
/// Returns a copy of the contained value.
///
/// # Examples
///
/// ```
/// use std::cell::Cell;
///
/// let c = Cell::new(5);
///
/// let five = c.get();
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn get(&self) -> T {
2019-12-26 20:56:34 +00:00
// SAFETY: This can cause data races if called from a separate thread,
// but `Cell` is `!Sync` so this won't happen.
2019-12-22 22:42:04 +00:00
unsafe { *self.value.get() }
}
/// Updates the contained value using a function and returns the new value.
///
/// # Examples
///
/// ```
/// #![feature(cell_update)]
///
/// use std::cell::Cell;
///
/// let c = Cell::new(5);
/// let new = c.update(|x| x + 1);
///
/// assert_eq!(new, 6);
/// assert_eq!(c.get(), 6);
/// ```
#[inline]
#[unstable(feature = "cell_update", issue = "50186")]
pub fn update<F>(&self, f: F) -> T
where
F: FnOnce(T) -> T,
{
let old = self.get();
let new = f(old);
self.set(new);
new
}
}
2018-05-07 07:24:45 +00:00
impl<T: ?Sized> Cell<T> {
/// Returns a raw pointer to the underlying data in this cell.
///
/// # Examples
///
/// ```
/// use std::cell::Cell;
///
/// let c = Cell::new(5);
///
/// let ptr = c.as_ptr();
/// ```
#[inline]
#[stable(feature = "cell_as_ptr", since = "1.12.0")]
2019-12-18 17:00:59 +00:00
#[rustc_const_stable(feature = "const_cell_as_ptr", since = "1.32.0")]
2018-10-23 00:04:14 +00:00
pub const fn as_ptr(&self) -> *mut T {
2018-05-07 07:24:45 +00:00
self.value.get()
}
/// Returns a mutable reference to the underlying data.
///
/// This call borrows `Cell` mutably (at compile-time) which guarantees
/// that we possess the only reference.
///
/// # Examples
///
/// ```
/// use std::cell::Cell;
///
/// let mut c = Cell::new(5);
/// *c.get_mut() += 1;
///
/// assert_eq!(c.get(), 6);
/// ```
#[inline]
#[stable(feature = "cell_get_mut", since = "1.11.0")]
pub fn get_mut(&mut self) -> &mut T {
2019-12-26 20:56:34 +00:00
// SAFETY: This can cause data races if called from a separate thread,
// but `Cell` is `!Sync` so this won't happen, and `&mut` guarantees
// unique access.
2019-12-22 22:42:04 +00:00
unsafe { &mut *self.value.get() }
2018-05-07 07:24:45 +00:00
}
/// Returns a `&Cell<T>` from a `&mut T`
///
/// # Examples
///
/// ```
/// use std::cell::Cell;
2018-05-28 06:35:12 +00:00
///
/// let slice: &mut [i32] = &mut [1, 2, 3];
2018-05-07 07:24:45 +00:00
/// let cell_slice: &Cell<[i32]> = Cell::from_mut(slice);
2018-07-23 11:20:50 +00:00
/// let slice_cell: &[Cell<i32>] = cell_slice.as_slice_of_cells();
2018-05-28 06:35:12 +00:00
///
2018-05-27 23:52:39 +00:00
/// assert_eq!(slice_cell.len(), 3);
2018-05-07 07:24:45 +00:00
/// ```
#[inline]
#[stable(feature = "as_cell", since = "1.37.0")]
2018-05-27 12:07:10 +00:00
pub fn from_mut(t: &mut T) -> &Cell<T> {
2019-12-26 20:56:34 +00:00
// SAFETY: `&mut` ensures unique access.
2019-12-22 22:42:04 +00:00
unsafe { &*(t as *mut T as *const Cell<T>) }
2018-05-07 07:24:45 +00:00
}
}
impl<T: Default> Cell<T> {
/// Takes the value of the cell, leaving `Default::default()` in its place.
///
/// # Examples
///
/// ```
/// use std::cell::Cell;
///
/// let c = Cell::new(5);
/// let five = c.take();
///
/// assert_eq!(five, 5);
/// assert_eq!(c.into_inner(), 0);
/// ```
#[stable(feature = "move_cell", since = "1.17.0")]
pub fn take(&self) -> T {
self.replace(Default::default())
}
}
#[unstable(feature = "coerce_unsized", issue = "27732")]
impl<T: CoerceUnsized<U>, U> CoerceUnsized<Cell<U>> for Cell<T> {}
2018-07-23 11:20:50 +00:00
impl<T> Cell<[T]> {
/// Returns a `&[Cell<T>]` from a `&Cell<[T]>`
///
/// # Examples
///
/// ```
/// use std::cell::Cell;
///
/// let slice: &mut [i32] = &mut [1, 2, 3];
/// let cell_slice: &Cell<[i32]> = Cell::from_mut(slice);
/// let slice_cell: &[Cell<i32>] = cell_slice.as_slice_of_cells();
///
/// assert_eq!(slice_cell.len(), 3);
/// ```
#[stable(feature = "as_cell", since = "1.37.0")]
2018-07-23 11:20:50 +00:00
pub fn as_slice_of_cells(&self) -> &[Cell<T>] {
2019-12-26 20:56:34 +00:00
// SAFETY: `Cell<T>` has the same memory layout as `T`.
2019-12-22 22:42:04 +00:00
unsafe { &*(self as *const Cell<[T]> as *const [Cell<T>]) }
2018-06-07 09:47:55 +00:00
}
}
2013-11-22 05:30:34 +00:00
/// A mutable memory location with dynamically checked borrow rules
2015-01-23 20:02:05 +00:00
///
/// See the [module-level documentation](index.html) for more.
2015-01-24 05:48:20 +00:00
#[stable(feature = "rust1", since = "1.0.0")]
pub struct RefCell<T: ?Sized> {
borrow: Cell<BorrowFlag>,
value: UnsafeCell<T>,
2013-11-22 05:30:34 +00:00
}
/// An error returned by [`RefCell::try_borrow`](struct.RefCell.html#method.try_borrow).
#[stable(feature = "try_borrow", since = "1.13.0")]
pub struct BorrowError {
_private: (),
}
#[stable(feature = "try_borrow", since = "1.13.0")]
impl Debug for BorrowError {
2019-04-18 23:37:12 +00:00
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("BorrowError").finish()
}
}
#[stable(feature = "try_borrow", since = "1.13.0")]
impl Display for BorrowError {
2019-04-18 23:37:12 +00:00
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Display::fmt("already mutably borrowed", f)
}
}
/// An error returned by [`RefCell::try_borrow_mut`](struct.RefCell.html#method.try_borrow_mut).
#[stable(feature = "try_borrow", since = "1.13.0")]
pub struct BorrowMutError {
_private: (),
}
#[stable(feature = "try_borrow", since = "1.13.0")]
impl Debug for BorrowMutError {
2019-04-18 23:37:12 +00:00
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("BorrowMutError").finish()
}
}
#[stable(feature = "try_borrow", since = "1.13.0")]
impl Display for BorrowMutError {
2019-04-18 23:37:12 +00:00
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Display::fmt("already borrowed", f)
}
}
2018-06-27 07:07:18 +00:00
// Positive values represent the number of `Ref` active. Negative values
// represent the number of `RefMut` active. Multiple `RefMut`s can only be
// active at a time if they refer to distinct, nonoverlapping components of a
// `RefCell` (e.g., different ranges of a slice).
2018-06-10 05:32:05 +00:00
//
// `Ref` and `RefMut` are both two words in size, and so there will likely never
// be enough `Ref`s or `RefMut`s in existence to overflow half of the `usize`
2018-06-27 07:07:18 +00:00
// range. Thus, a `BorrowFlag` will probably never overflow or underflow.
// However, this is not a guarantee, as a pathological program could repeatedly
// create and then mem::forget `Ref`s or `RefMut`s. Thus, all code must
// explicitly check for overflow and underflow in order to avoid unsafety, or at
// least behave correctly in the event that overflow or underflow happens (e.g.,
// see BorrowRef::new).
type BorrowFlag = isize;
2014-10-06 23:14:00 +00:00
const UNUSED: BorrowFlag = 0;
2018-06-27 07:07:18 +00:00
#[inline(always)]
2018-10-23 21:09:44 +00:00
fn is_writing(x: BorrowFlag) -> bool {
2018-06-27 07:07:18 +00:00
x < UNUSED
}
#[inline(always)]
2018-10-23 21:09:44 +00:00
fn is_reading(x: BorrowFlag) -> bool {
2018-06-27 07:07:18 +00:00
x > UNUSED
}
2013-11-22 05:30:34 +00:00
impl<T> RefCell<T> {
2015-01-23 20:02:05 +00:00
/// Creates a new `RefCell` containing `value`.
///
/// # Examples
///
/// ```
/// use std::cell::RefCell;
///
/// let c = RefCell::new(5);
/// ```
2015-01-24 05:48:20 +00:00
#[stable(feature = "rust1", since = "1.0.0")]
2019-12-18 17:00:59 +00:00
#[rustc_const_stable(feature = "const_refcell_new", since = "1.32.0")]
#[inline]
pub const fn new(value: T) -> RefCell<T> {
2019-12-22 22:42:04 +00:00
RefCell { value: UnsafeCell::new(value), borrow: Cell::new(UNUSED) }
2013-11-22 05:30:34 +00:00
}
/// Consumes the `RefCell`, returning the wrapped value.
2015-01-23 20:02:05 +00:00
///
/// # Examples
///
/// ```
/// use std::cell::RefCell;
///
/// let c = RefCell::new(5);
///
/// let five = c.into_inner();
/// ```
2015-01-24 05:48:20 +00:00
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn into_inner(self) -> T {
// Since this function takes `self` (the `RefCell`) by value, the
// compiler statically verifies that it is not currently borrowed.
// Therefore the following assertion is just a `debug_assert!`.
debug_assert!(self.borrow.get() == UNUSED);
self.value.into_inner()
2013-11-22 05:30:34 +00:00
}
/// Replaces the wrapped value with a new one, returning the old value,
/// without deinitializing either one.
///
/// This function corresponds to [`std::mem::replace`](../mem/fn.replace.html).
///
2017-11-07 02:53:23 +00:00
/// # Panics
///
/// Panics if the value is currently borrowed.
///
/// # Examples
///
/// ```
/// use std::cell::RefCell;
2017-11-07 02:53:23 +00:00
/// let cell = RefCell::new(5);
/// let old_value = cell.replace(6);
/// assert_eq!(old_value, 5);
/// assert_eq!(cell, RefCell::new(6));
/// ```
2017-11-07 02:53:23 +00:00
#[inline]
2019-12-22 22:42:04 +00:00
#[stable(feature = "refcell_replace", since = "1.24.0")]
2017-11-07 02:53:23 +00:00
pub fn replace(&self, t: T) -> T {
mem::replace(&mut *self.borrow_mut(), t)
}
/// Replaces the wrapped value with a new one computed from `f`, returning
/// the old value, without deinitializing either one.
///
/// # Panics
///
2017-11-07 02:53:23 +00:00
/// Panics if the value is currently borrowed.
///
/// # Examples
///
/// ```
/// use std::cell::RefCell;
/// let cell = RefCell::new(5);
/// let old_value = cell.replace_with(|&mut old| old + 1);
/// assert_eq!(old_value, 5);
/// assert_eq!(cell, RefCell::new(6));
/// ```
#[inline]
2019-12-22 22:42:04 +00:00
#[stable(feature = "refcell_replace_swap", since = "1.35.0")]
2017-11-07 02:53:23 +00:00
pub fn replace_with<F: FnOnce(&mut T) -> T>(&self, f: F) -> T {
let mut_borrow = &mut *self.borrow_mut();
let replacement = f(mut_borrow);
mem::replace(mut_borrow, replacement)
}
/// Swaps the wrapped value of `self` with the wrapped value of `other`,
/// without deinitializing either one.
///
/// This function corresponds to [`std::mem::swap`](../mem/fn.swap.html).
///
2017-11-07 02:53:23 +00:00
/// # Panics
///
/// Panics if the value in either `RefCell` is currently borrowed.
///
/// # Examples
///
/// ```
/// use std::cell::RefCell;
/// let c = RefCell::new(5);
/// let d = RefCell::new(6);
/// c.swap(&d);
/// assert_eq!(c, RefCell::new(6));
/// assert_eq!(d, RefCell::new(5));
/// ```
#[inline]
2019-12-22 22:42:04 +00:00
#[stable(feature = "refcell_swap", since = "1.24.0")]
pub fn swap(&self, other: &Self) {
mem::swap(&mut *self.borrow_mut(), &mut *other.borrow_mut())
}
}
2013-11-22 05:30:34 +00:00
impl<T: ?Sized> RefCell<T> {
2013-11-22 05:30:34 +00:00
/// Immutably borrows the wrapped value.
///
/// The borrow lasts until the returned `Ref` exits scope. Multiple
/// immutable borrows can be taken out at the same time.
2013-11-22 05:30:34 +00:00
///
/// # Panics
2013-11-22 05:30:34 +00:00
///
/// Panics if the value is currently mutably borrowed. For a non-panicking variant, use
/// [`try_borrow`](#method.try_borrow).
2015-01-23 20:02:05 +00:00
///
/// # Examples
///
/// ```
/// use std::cell::RefCell;
///
/// let c = RefCell::new(5);
///
/// let borrowed_five = c.borrow();
/// let borrowed_five2 = c.borrow();
/// ```
///
/// An example of panic:
///
/// ```
/// use std::cell::RefCell;
2015-02-17 23:10:25 +00:00
/// use std::thread;
2015-01-23 20:02:05 +00:00
///
2015-02-17 23:10:25 +00:00
/// let result = thread::spawn(move || {
2015-01-23 20:02:05 +00:00
/// let c = RefCell::new(5);
/// let m = c.borrow_mut();
///
/// let b = c.borrow(); // this causes a panic
/// }).join();
///
/// assert!(result.is_err());
/// ```
2015-01-24 05:48:20 +00:00
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
2019-04-18 23:37:12 +00:00
pub fn borrow(&self) -> Ref<'_, T> {
self.try_borrow().expect("already mutably borrowed")
}
/// Immutably borrows the wrapped value, returning an error if the value is currently mutably
/// borrowed.
///
/// The borrow lasts until the returned `Ref` exits scope. Multiple immutable borrows can be
/// taken out at the same time.
///
/// This is the non-panicking variant of [`borrow`](#method.borrow).
///
/// # Examples
///
/// ```
/// use std::cell::RefCell;
///
/// let c = RefCell::new(5);
///
/// {
/// let m = c.borrow_mut();
/// assert!(c.try_borrow().is_err());
/// }
///
/// {
/// let m = c.borrow();
/// assert!(c.try_borrow().is_ok());
/// }
/// ```
#[stable(feature = "try_borrow", since = "1.13.0")]
#[inline]
2019-04-18 23:37:12 +00:00
pub fn try_borrow(&self) -> Result<Ref<'_, T>, BorrowError> {
match BorrowRef::new(&self.borrow) {
// SAFETY: `BorrowRef` ensures that there is only immutable access
2019-12-26 20:56:34 +00:00
// to the value while borrowed.
2019-12-22 22:42:04 +00:00
Some(b) => Ok(Ref { value: unsafe { &*self.value.get() }, borrow: b }),
None => Err(BorrowError { _private: () }),
2013-11-22 05:30:34 +00:00
}
}
/// Mutably borrows the wrapped value.
///
2018-06-10 05:32:05 +00:00
/// The borrow lasts until the returned `RefMut` or all `RefMut`s derived
/// from it exit scope. The value cannot be borrowed while this borrow is
/// active.
2013-11-22 05:30:34 +00:00
///
/// # Panics
2013-11-22 05:30:34 +00:00
///
/// Panics if the value is currently borrowed. For a non-panicking variant, use
/// [`try_borrow_mut`](#method.try_borrow_mut).
2015-01-23 20:02:05 +00:00
///
/// # Examples
///
/// ```
/// use std::cell::RefCell;
///
/// let c = RefCell::new(5);
///
/// *c.borrow_mut() = 7;
///
/// assert_eq!(*c.borrow(), 7);
2015-01-23 20:02:05 +00:00
/// ```
///
/// An example of panic:
///
/// ```
/// use std::cell::RefCell;
2015-02-17 23:10:25 +00:00
/// use std::thread;
2015-01-23 20:02:05 +00:00
///
2015-02-17 23:10:25 +00:00
/// let result = thread::spawn(move || {
2015-01-23 20:02:05 +00:00
/// let c = RefCell::new(5);
/// let m = c.borrow();
2015-01-23 20:02:05 +00:00
///
/// let b = c.borrow_mut(); // this causes a panic
/// }).join();
///
/// assert!(result.is_err());
/// ```
2015-01-24 05:48:20 +00:00
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
2019-04-18 23:37:12 +00:00
pub fn borrow_mut(&self) -> RefMut<'_, T> {
self.try_borrow_mut().expect("already borrowed")
}
/// Mutably borrows the wrapped value, returning an error if the value is currently borrowed.
///
2018-06-10 05:32:05 +00:00
/// The borrow lasts until the returned `RefMut` or all `RefMut`s derived
/// from it exit scope. The value cannot be borrowed while this borrow is
/// active.
///
/// This is the non-panicking variant of [`borrow_mut`](#method.borrow_mut).
///
/// # Examples
///
/// ```
/// use std::cell::RefCell;
///
/// let c = RefCell::new(5);
///
/// {
/// let m = c.borrow();
/// assert!(c.try_borrow_mut().is_err());
/// }
///
/// assert!(c.try_borrow_mut().is_ok());
/// ```
#[stable(feature = "try_borrow", since = "1.13.0")]
#[inline]
2019-04-18 23:37:12 +00:00
pub fn try_borrow_mut(&self) -> Result<RefMut<'_, T>, BorrowMutError> {
match BorrowRefMut::new(&self.borrow) {
2019-12-26 20:56:34 +00:00
// SAFETY: `BorrowRef` guarantees unique access.
2019-12-22 22:42:04 +00:00
Some(b) => Ok(RefMut { value: unsafe { &mut *self.value.get() }, borrow: b }),
None => Err(BorrowMutError { _private: () }),
2013-11-22 05:30:34 +00:00
}
}
/// Returns a raw pointer to the underlying data in this cell.
///
/// # Examples
///
/// ```
/// use std::cell::RefCell;
///
/// let c = RefCell::new(5);
///
/// let ptr = c.as_ptr();
/// ```
#[inline]
#[stable(feature = "cell_as_ptr", since = "1.12.0")]
pub fn as_ptr(&self) -> *mut T {
self.value.get()
}
/// Returns a mutable reference to the underlying data.
///
/// This call borrows `RefCell` mutably (at compile-time) so there is no
/// need for dynamic checks.
///
/// However be cautious: this method expects `self` to be mutable, which is
/// generally not the case when using a `RefCell`. Take a look at the
/// [`borrow_mut`] method instead if `self` isn't mutable.
///
/// Also, please be aware that this method is only for special circumstances and is usually
2017-08-17 08:57:17 +00:00
/// not what you want. In case of doubt, use [`borrow_mut`] instead.
///
/// [`borrow_mut`]: #method.borrow_mut
///
/// # Examples
///
/// ```
/// use std::cell::RefCell;
///
/// let mut c = RefCell::new(5);
/// *c.get_mut() += 1;
///
/// assert_eq!(c, RefCell::new(6));
/// ```
#[inline]
#[stable(feature = "cell_get_mut", since = "1.11.0")]
pub fn get_mut(&mut self) -> &mut T {
2019-12-26 20:56:34 +00:00
// SAFETY: `&mut` guarantees unique access.
2019-12-22 22:42:04 +00:00
unsafe { &mut *self.value.get() }
}
/// Immutably borrows the wrapped value, returning an error if the value is
/// currently mutably borrowed.
///
/// # Safety
///
/// Unlike `RefCell::borrow`, this method is unsafe because it does not
/// return a `Ref`, thus leaving the borrow flag untouched. Mutably
/// borrowing the `RefCell` while the reference returned by this method
/// is alive is undefined behaviour.
///
/// # Examples
///
/// ```
/// use std::cell::RefCell;
///
/// let c = RefCell::new(5);
///
/// {
/// let m = c.borrow_mut();
/// assert!(unsafe { c.try_borrow_unguarded() }.is_err());
/// }
///
/// {
/// let m = c.borrow();
/// assert!(unsafe { c.try_borrow_unguarded() }.is_ok());
/// }
/// ```
#[stable(feature = "borrow_state", since = "1.37.0")]
#[inline]
pub unsafe fn try_borrow_unguarded(&self) -> Result<&T, BorrowError> {
if !is_writing(self.borrow.get()) {
Ok(&*self.value.get())
} else {
Err(BorrowError { _private: () })
}
}
2013-12-11 22:54:27 +00:00
}
2015-01-24 05:48:20 +00:00
#[stable(feature = "rust1", since = "1.0.0")]
unsafe impl<T: ?Sized> Send for RefCell<T> where T: Send {}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> !Sync for RefCell<T> {}
2015-01-24 05:48:20 +00:00
#[stable(feature = "rust1", since = "1.0.0")]
2013-11-22 05:30:34 +00:00
impl<T: Clone> Clone for RefCell<T> {
/// # Panics
///
/// Panics if the value is currently mutably borrowed.
#[inline]
2013-11-22 05:30:34 +00:00
fn clone(&self) -> RefCell<T> {
RefCell::new(self.borrow().clone())
2013-11-22 05:30:34 +00:00
}
}
2015-01-24 05:48:20 +00:00
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Default> Default for RefCell<T> {
/// Creates a `RefCell<T>`, with the `Default` value for T.
#[inline]
fn default() -> RefCell<T> {
RefCell::new(Default::default())
}
}
2015-01-24 05:48:20 +00:00
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized + PartialEq> PartialEq for RefCell<T> {
/// # Panics
///
/// Panics if the value in either `RefCell` is currently borrowed.
#[inline]
2013-11-22 05:30:34 +00:00
fn eq(&self, other: &RefCell<T>) -> bool {
*self.borrow() == *other.borrow()
2013-11-22 05:30:34 +00:00
}
}
#[stable(feature = "cell_eq", since = "1.2.0")]
impl<T: ?Sized + Eq> Eq for RefCell<T> {}
#[stable(feature = "cell_ord", since = "1.10.0")]
impl<T: ?Sized + PartialOrd> PartialOrd for RefCell<T> {
/// # Panics
///
/// Panics if the value in either `RefCell` is currently borrowed.
#[inline]
fn partial_cmp(&self, other: &RefCell<T>) -> Option<Ordering> {
self.borrow().partial_cmp(&*other.borrow())
}
/// # Panics
///
/// Panics if the value in either `RefCell` is currently borrowed.
#[inline]
fn lt(&self, other: &RefCell<T>) -> bool {
*self.borrow() < *other.borrow()
}
/// # Panics
///
/// Panics if the value in either `RefCell` is currently borrowed.
#[inline]
fn le(&self, other: &RefCell<T>) -> bool {
*self.borrow() <= *other.borrow()
}
/// # Panics
///
/// Panics if the value in either `RefCell` is currently borrowed.
#[inline]
fn gt(&self, other: &RefCell<T>) -> bool {
*self.borrow() > *other.borrow()
}
/// # Panics
///
/// Panics if the value in either `RefCell` is currently borrowed.
#[inline]
fn ge(&self, other: &RefCell<T>) -> bool {
*self.borrow() >= *other.borrow()
}
}
#[stable(feature = "cell_ord", since = "1.10.0")]
impl<T: ?Sized + Ord> Ord for RefCell<T> {
/// # Panics
///
/// Panics if the value in either `RefCell` is currently borrowed.
#[inline]
fn cmp(&self, other: &RefCell<T>) -> Ordering {
self.borrow().cmp(&*other.borrow())
}
}
#[stable(feature = "cell_from", since = "1.12.0")]
impl<T> From<T> for RefCell<T> {
fn from(t: T) -> RefCell<T> {
RefCell::new(t)
}
}
#[unstable(feature = "coerce_unsized", issue = "27732")]
impl<T: CoerceUnsized<U>, U> CoerceUnsized<RefCell<U>> for RefCell<T> {}
struct BorrowRef<'b> {
borrow: &'b Cell<BorrowFlag>,
}
impl<'b> BorrowRef<'b> {
#[inline]
fn new(borrow: &'b Cell<BorrowFlag>) -> Option<BorrowRef<'b>> {
let b = borrow.get().wrapping_add(1);
if !is_reading(b) {
2019-07-21 09:49:36 +00:00
// Incrementing borrow can result in a non-reading value (<= 0) in these cases:
// 1. It was < 0, i.e. there are writing borrows, so we can't allow a read borrow
// due to Rust's reference aliasing rules
// 2. It was isize::max_value() (the max amount of reading borrows) and it overflowed
// into isize::min_value() (the max amount of writing borrows) so we can't allow
// an additional read borrow because isize can't represent so many read borrows
// (this can only happen if you mem::forget more than a small constant amount of
// `Ref`s, which is not good practice)
2018-06-10 05:32:05 +00:00
None
} else {
2019-07-21 10:50:16 +00:00
// Incrementing borrow can result in a reading value (> 0) in these cases:
2019-07-21 09:49:36 +00:00
// 1. It was = 0, i.e. it wasn't borrowed, and we are taking the first read borrow
// 2. It was > 0 and < isize::max_value(), i.e. there were read borrows, and isize
// is large enough to represent having one more read borrow
borrow.set(b);
2018-06-10 05:32:05 +00:00
Some(BorrowRef { borrow })
}
}
}
impl Drop for BorrowRef<'_> {
#[inline]
2013-11-22 05:30:34 +00:00
fn drop(&mut self) {
let borrow = self.borrow.get();
2018-06-27 07:07:18 +00:00
debug_assert!(is_reading(borrow));
self.borrow.set(borrow - 1);
2013-11-22 05:30:34 +00:00
}
}
impl Clone for BorrowRef<'_> {
#[inline]
fn clone(&self) -> Self {
// Since this Ref exists, we know the borrow flag
2018-06-27 07:07:18 +00:00
// is a reading borrow.
let borrow = self.borrow.get();
2018-06-27 07:07:18 +00:00
debug_assert!(is_reading(borrow));
2018-06-10 05:32:05 +00:00
// Prevent the borrow counter from overflowing into
// a writing borrow.
2018-06-27 07:07:18 +00:00
assert!(borrow != isize::max_value());
self.borrow.set(borrow + 1);
BorrowRef { borrow: self.borrow }
}
}
/// Wraps a borrowed reference to a value in a `RefCell` box.
2015-01-23 20:02:05 +00:00
/// A wrapper type for an immutably borrowed value from a `RefCell<T>`.
///
/// See the [module-level documentation](index.html) for more.
2015-01-24 05:48:20 +00:00
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Ref<'b, T: ?Sized + 'b> {
value: &'b T,
borrow: BorrowRef<'b>,
}
2015-01-24 05:48:20 +00:00
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> Deref for Ref<'_, T> {
2015-01-01 19:53:20 +00:00
type Target = T;
#[inline]
2015-09-03 09:49:08 +00:00
fn deref(&self) -> &T {
self.value
}
}
impl<'b, T: ?Sized> Ref<'b, T> {
/// Copies a `Ref`.
///
/// The `RefCell` is already immutably borrowed, so this cannot fail.
///
/// This is an associated function that needs to be used as
2019-02-09 21:23:30 +00:00
/// `Ref::clone(...)`. A `Clone` implementation or a method would interfere
/// with the widespread use of `r.borrow().clone()` to clone the contents of
/// a `RefCell`.
2016-12-14 20:36:49 +00:00
#[stable(feature = "cell_extras", since = "1.15.0")]
#[inline]
pub fn clone(orig: &Ref<'b, T>) -> Ref<'b, T> {
2019-12-22 22:42:04 +00:00
Ref { value: orig.value, borrow: orig.borrow.clone() }
}
2019-02-09 22:16:58 +00:00
/// Makes a new `Ref` for a component of the borrowed data.
///
/// The `RefCell` is already immutably borrowed, so this cannot fail.
///
/// This is an associated function that needs to be used as `Ref::map(...)`.
/// A method would interfere with methods of the same name on the contents
/// of a `RefCell` used through `Deref`.
///
/// # Examples
///
/// ```
/// use std::cell::{RefCell, Ref};
///
/// let c = RefCell::new((5, 'b'));
/// let b1: Ref<(u32, char)> = c.borrow();
/// let b2: Ref<u32> = Ref::map(b1, |t| &t.0);
/// assert_eq!(*b2, 5)
/// ```
#[stable(feature = "cell_map", since = "1.8.0")]
#[inline]
pub fn map<U: ?Sized, F>(orig: Ref<'b, T>, f: F) -> Ref<'b, U>
2019-12-22 22:42:04 +00:00
where
F: FnOnce(&T) -> &U,
{
2019-12-22 22:42:04 +00:00
Ref { value: f(orig.value), borrow: orig.borrow }
}
2018-06-10 05:32:05 +00:00
2019-02-09 21:23:30 +00:00
/// Splits a `Ref` into multiple `Ref`s for different components of the
2018-06-10 05:32:05 +00:00
/// borrowed data.
///
/// The `RefCell` is already immutably borrowed, so this cannot fail.
///
/// This is an associated function that needs to be used as
/// `Ref::map_split(...)`. A method would interfere with methods of the same
/// name on the contents of a `RefCell` used through `Deref`.
///
/// # Examples
///
/// ```
/// use std::cell::{Ref, RefCell};
///
/// let cell = RefCell::new([1, 2, 3, 4]);
/// let borrow = cell.borrow();
/// let (begin, end) = Ref::map_split(borrow, |slice| slice.split_at(2));
/// assert_eq!(*begin, [1, 2]);
/// assert_eq!(*end, [3, 4]);
/// ```
#[stable(feature = "refcell_map_split", since = "1.35.0")]
2018-06-10 05:32:05 +00:00
#[inline]
pub fn map_split<U: ?Sized, V: ?Sized, F>(orig: Ref<'b, T>, f: F) -> (Ref<'b, U>, Ref<'b, V>)
2019-12-22 22:42:04 +00:00
where
F: FnOnce(&T) -> (&U, &V),
2018-06-10 05:32:05 +00:00
{
let (a, b) = f(orig.value);
let borrow = orig.borrow.clone();
(Ref { value: a, borrow }, Ref { value: b, borrow: orig.borrow })
}
}
#[unstable(feature = "coerce_unsized", issue = "27732")]
impl<'b, T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Ref<'b, U>> for Ref<'b, T> {}
#[stable(feature = "std_guard_impls", since = "1.20.0")]
impl<T: ?Sized + fmt::Display> fmt::Display for Ref<'_, T> {
2019-04-18 23:37:12 +00:00
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.value.fmt(f)
}
}
impl<'b, T: ?Sized> RefMut<'b, T> {
2019-02-09 22:16:58 +00:00
/// Makes a new `RefMut` for a component of the borrowed data, e.g., an enum
/// variant.
///
/// The `RefCell` is already mutably borrowed, so this cannot fail.
///
/// This is an associated function that needs to be used as
2019-02-09 21:23:30 +00:00
/// `RefMut::map(...)`. A method would interfere with methods of the same
/// name on the contents of a `RefCell` used through `Deref`.
///
/// # Examples
///
/// ```
/// use std::cell::{RefCell, RefMut};
///
/// let c = RefCell::new((5, 'b'));
/// {
/// let b1: RefMut<(u32, char)> = c.borrow_mut();
/// let mut b2: RefMut<u32> = RefMut::map(b1, |t| &mut t.0);
/// assert_eq!(*b2, 5);
/// *b2 = 42;
/// }
/// assert_eq!(*c.borrow(), (42, 'b'));
/// ```
#[stable(feature = "cell_map", since = "1.8.0")]
#[inline]
pub fn map<U: ?Sized, F>(orig: RefMut<'b, T>, f: F) -> RefMut<'b, U>
2019-12-22 22:42:04 +00:00
where
F: FnOnce(&mut T) -> &mut U,
{
2017-12-05 22:51:47 +00:00
// FIXME(nll-rfc#40): fix borrow-check
2017-12-05 12:09:16 +00:00
let RefMut { value, borrow } = orig;
2019-12-22 22:42:04 +00:00
RefMut { value: f(value), borrow }
}
2018-06-10 05:32:05 +00:00
2019-02-09 21:23:30 +00:00
/// Splits a `RefMut` into multiple `RefMut`s for different components of the
2018-06-10 05:32:05 +00:00
/// borrowed data.
///
/// The underlying `RefCell` will remain mutably borrowed until both
/// returned `RefMut`s go out of scope.
///
/// The `RefCell` is already mutably borrowed, so this cannot fail.
///
/// This is an associated function that needs to be used as
/// `RefMut::map_split(...)`. A method would interfere with methods of the
/// same name on the contents of a `RefCell` used through `Deref`.
///
/// # Examples
///
/// ```
/// use std::cell::{RefCell, RefMut};
///
/// let cell = RefCell::new([1, 2, 3, 4]);
/// let borrow = cell.borrow_mut();
/// let (mut begin, mut end) = RefMut::map_split(borrow, |slice| slice.split_at_mut(2));
/// assert_eq!(*begin, [1, 2]);
/// assert_eq!(*end, [3, 4]);
/// begin.copy_from_slice(&[4, 3]);
/// end.copy_from_slice(&[2, 1]);
/// ```
#[stable(feature = "refcell_map_split", since = "1.35.0")]
2018-06-10 05:32:05 +00:00
#[inline]
pub fn map_split<U: ?Sized, V: ?Sized, F>(
2019-12-22 22:42:04 +00:00
orig: RefMut<'b, T>,
f: F,
2018-06-10 05:32:05 +00:00
) -> (RefMut<'b, U>, RefMut<'b, V>)
2019-12-22 22:42:04 +00:00
where
F: FnOnce(&mut T) -> (&mut U, &mut V),
2018-06-10 05:32:05 +00:00
{
let (a, b) = f(orig.value);
let borrow = orig.borrow.clone();
(RefMut { value: a, borrow }, RefMut { value: b, borrow: orig.borrow })
}
}
struct BorrowRefMut<'b> {
borrow: &'b Cell<BorrowFlag>,
}
impl Drop for BorrowRefMut<'_> {
#[inline]
2013-11-22 05:30:34 +00:00
fn drop(&mut self) {
let borrow = self.borrow.get();
2018-06-27 07:07:18 +00:00
debug_assert!(is_writing(borrow));
self.borrow.set(borrow + 1);
2013-11-22 05:30:34 +00:00
}
}
impl<'b> BorrowRefMut<'b> {
#[inline]
fn new(borrow: &'b Cell<BorrowFlag>) -> Option<BorrowRefMut<'b>> {
2018-06-10 05:32:05 +00:00
// NOTE: Unlike BorrowRefMut::clone, new is called to create the initial
// mutable reference, and so there must currently be no existing
// references. Thus, while clone increments the mutable refcount, here
2018-06-27 07:07:18 +00:00
// we explicitly only allow going from UNUSED to UNUSED - 1.
match borrow.get() {
UNUSED => {
2018-06-27 07:07:18 +00:00
borrow.set(UNUSED - 1);
Some(BorrowRefMut { borrow })
2019-12-22 22:42:04 +00:00
}
_ => None,
}
}
2018-06-10 05:32:05 +00:00
// Clones a `BorrowRefMut`.
2018-06-10 05:32:05 +00:00
//
// This is only valid if each `BorrowRefMut` is used to track a mutable
// reference to a distinct, nonoverlapping range of the original object.
// This isn't in a Clone impl so that code doesn't call this implicitly.
#[inline]
fn clone(&self) -> BorrowRefMut<'b> {
let borrow = self.borrow.get();
2018-06-27 07:07:18 +00:00
debug_assert!(is_writing(borrow));
// Prevent the borrow counter from underflowing.
assert!(borrow != isize::min_value());
self.borrow.set(borrow - 1);
2018-06-10 05:32:05 +00:00
BorrowRefMut { borrow: self.borrow }
}
}
2015-01-23 20:02:05 +00:00
/// A wrapper type for a mutably borrowed value from a `RefCell<T>`.
///
/// See the [module-level documentation](index.html) for more.
2015-01-24 05:48:20 +00:00
#[stable(feature = "rust1", since = "1.0.0")]
pub struct RefMut<'b, T: ?Sized + 'b> {
value: &'b mut T,
borrow: BorrowRefMut<'b>,
}
2015-01-24 05:48:20 +00:00
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> Deref for RefMut<'_, T> {
2015-01-01 19:53:20 +00:00
type Target = T;
#[inline]
2015-09-03 09:49:08 +00:00
fn deref(&self) -> &T {
self.value
}
}
2015-01-24 05:48:20 +00:00
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> DerefMut for RefMut<'_, T> {
#[inline]
2015-09-03 09:49:08 +00:00
fn deref_mut(&mut self) -> &mut T {
self.value
}
}
std: Stabilize unit, bool, ty, tuple, arc, any This commit applies stability attributes to the contents of these modules, summarized here: * The `unit` and `bool` modules have become #[unstable] as they are purely meant for documentation purposes and are candidates for removal. * The `ty` module has been deprecated, and the inner `Unsafe` type has been renamed to `UnsafeCell` and moved to the `cell` module. The `marker1` field has been removed as the compiler now always infers `UnsafeCell` to be invariant. The `new` method i stable, but the `value` field, `get` and `unwrap` methods are all unstable. * The `tuple` module has its name as stable, the naming of the `TupleN` traits as stable while the methods are all #[unstable]. The other impls in the module have appropriate stability for the corresponding trait. * The `arc` module has received the exact same treatment as the `rc` module previously did. * The `any` module has its name as stable. The `Any` trait is also stable, with a new private supertrait which now contains the `get_type_id` method. This is to make the method a private implementation detail rather than a public-facing detail. The two extension traits in the module are marked #[unstable] as they will not be necessary with DST. The `is` method is #[stable], the as_{mut,ref} methods have been renamed to downcast_{mut,ref} and are #[unstable]. The extension trait `BoxAny` has been clarified as to why it is unstable as it will not be necessary with DST. This is a breaking change because the `marker1` field was removed from the `UnsafeCell` type. To deal with this change, you can simply delete the field and only specify the value of the `data` field in static initializers. [breaking-change]
2014-07-24 02:10:12 +00:00
#[unstable(feature = "coerce_unsized", issue = "27732")]
impl<'b, T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<RefMut<'b, U>> for RefMut<'b, T> {}
#[stable(feature = "std_guard_impls", since = "1.20.0")]
impl<T: ?Sized + fmt::Display> fmt::Display for RefMut<'_, T> {
2019-04-18 23:37:12 +00:00
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.value.fmt(f)
}
}
std: Stabilize unit, bool, ty, tuple, arc, any This commit applies stability attributes to the contents of these modules, summarized here: * The `unit` and `bool` modules have become #[unstable] as they are purely meant for documentation purposes and are candidates for removal. * The `ty` module has been deprecated, and the inner `Unsafe` type has been renamed to `UnsafeCell` and moved to the `cell` module. The `marker1` field has been removed as the compiler now always infers `UnsafeCell` to be invariant. The `new` method i stable, but the `value` field, `get` and `unwrap` methods are all unstable. * The `tuple` module has its name as stable, the naming of the `TupleN` traits as stable while the methods are all #[unstable]. The other impls in the module have appropriate stability for the corresponding trait. * The `arc` module has received the exact same treatment as the `rc` module previously did. * The `any` module has its name as stable. The `Any` trait is also stable, with a new private supertrait which now contains the `get_type_id` method. This is to make the method a private implementation detail rather than a public-facing detail. The two extension traits in the module are marked #[unstable] as they will not be necessary with DST. The `is` method is #[stable], the as_{mut,ref} methods have been renamed to downcast_{mut,ref} and are #[unstable]. The extension trait `BoxAny` has been clarified as to why it is unstable as it will not be necessary with DST. This is a breaking change because the `marker1` field was removed from the `UnsafeCell` type. To deal with this change, you can simply delete the field and only specify the value of the `data` field in static initializers. [breaking-change]
2014-07-24 02:10:12 +00:00
/// The core primitive for interior mutability in Rust.
///
2015-01-23 20:02:05 +00:00
/// `UnsafeCell<T>` is a type that wraps some `T` and indicates unsafe interior operations on the
/// wrapped type. Types with an `UnsafeCell<T>` field are considered to have an 'unsafe interior'.
/// The `UnsafeCell<T>` type is the only legal way to obtain aliasable data that is considered
/// mutable. In general, transmuting an `&T` type into an `&mut T` is considered undefined behavior.
std: Stabilize unit, bool, ty, tuple, arc, any This commit applies stability attributes to the contents of these modules, summarized here: * The `unit` and `bool` modules have become #[unstable] as they are purely meant for documentation purposes and are candidates for removal. * The `ty` module has been deprecated, and the inner `Unsafe` type has been renamed to `UnsafeCell` and moved to the `cell` module. The `marker1` field has been removed as the compiler now always infers `UnsafeCell` to be invariant. The `new` method i stable, but the `value` field, `get` and `unwrap` methods are all unstable. * The `tuple` module has its name as stable, the naming of the `TupleN` traits as stable while the methods are all #[unstable]. The other impls in the module have appropriate stability for the corresponding trait. * The `arc` module has received the exact same treatment as the `rc` module previously did. * The `any` module has its name as stable. The `Any` trait is also stable, with a new private supertrait which now contains the `get_type_id` method. This is to make the method a private implementation detail rather than a public-facing detail. The two extension traits in the module are marked #[unstable] as they will not be necessary with DST. The `is` method is #[stable], the as_{mut,ref} methods have been renamed to downcast_{mut,ref} and are #[unstable]. The extension trait `BoxAny` has been clarified as to why it is unstable as it will not be necessary with DST. This is a breaking change because the `marker1` field was removed from the `UnsafeCell` type. To deal with this change, you can simply delete the field and only specify the value of the `data` field in static initializers. [breaking-change]
2014-07-24 02:10:12 +00:00
///
/// If you have a reference `&SomeStruct`, then normally in Rust all fields of `SomeStruct` are
/// immutable. The compiler makes optimizations based on the knowledge that `&T` is not mutably
/// aliased or mutated, and that `&mut T` is unique. `UnsafeCell<T>` is the only core language
/// feature to work around the restriction that `&T` may not be mutated. All other types that
/// allow internal mutability, such as `Cell<T>` and `RefCell<T>`, use `UnsafeCell` to wrap their
/// internal data. There is *no* legal way to obtain aliasing `&mut`, not even with `UnsafeCell<T>`.
2016-06-28 06:23:37 +00:00
///
2018-03-08 21:16:31 +00:00
/// The `UnsafeCell` API itself is technically very simple: it gives you a raw pointer `*mut T` to
/// its contents. It is up to _you_ as the abstraction designer to use that raw pointer correctly.
///
/// The precise Rust aliasing rules are somewhat in flux, but the main points are not contentious:
///
/// - If you create a safe reference with lifetime `'a` (either a `&T` or `&mut T`
/// reference) that is accessible by safe code (for example, because you returned it),
/// then you must not access the data in any way that contradicts that reference for the
/// remainder of `'a`. For example, this means that if you take the `*mut T` from an
/// `UnsafeCell<T>` and cast it to an `&T`, then the data in `T` must remain immutable
/// (modulo any `UnsafeCell` data found within `T`, of course) until that reference's
/// lifetime expires. Similarly, if you create a `&mut T` reference that is released to
/// safe code, then you must not access the data within the `UnsafeCell` until that
/// reference expires.
///
/// - At all times, you must avoid data races. If multiple threads have access to
2018-03-08 21:16:31 +00:00
/// the same `UnsafeCell`, then any writes must have a proper happens-before relation to all other
/// accesses (or use atomics).
2016-06-28 06:23:37 +00:00
///
/// To assist with proper design, the following scenarios are explicitly declared legal
/// for single-threaded code:
2016-06-28 06:23:37 +00:00
///
2018-05-20 03:40:11 +00:00
/// 1. A `&T` reference can be released to safe code and there it can co-exist with other `&T`
2018-03-08 21:26:27 +00:00
/// references, but not with a `&mut T`
///
/// 2. A `&mut T` reference may be released to safe code provided neither other `&mut T` nor `&T`
/// co-exist with it. A `&mut T` must always be unique.
2016-06-28 06:23:37 +00:00
///
/// Note that while mutating or mutably aliasing the contents of an `&UnsafeCell<T>` is
2019-02-09 22:16:58 +00:00
/// ok (provided you enforce the invariants some other way), it is still undefined behavior
2016-06-28 06:23:37 +00:00
/// to have multiple `&mut UnsafeCell<T>` aliases.
std: Stabilize unit, bool, ty, tuple, arc, any This commit applies stability attributes to the contents of these modules, summarized here: * The `unit` and `bool` modules have become #[unstable] as they are purely meant for documentation purposes and are candidates for removal. * The `ty` module has been deprecated, and the inner `Unsafe` type has been renamed to `UnsafeCell` and moved to the `cell` module. The `marker1` field has been removed as the compiler now always infers `UnsafeCell` to be invariant. The `new` method i stable, but the `value` field, `get` and `unwrap` methods are all unstable. * The `tuple` module has its name as stable, the naming of the `TupleN` traits as stable while the methods are all #[unstable]. The other impls in the module have appropriate stability for the corresponding trait. * The `arc` module has received the exact same treatment as the `rc` module previously did. * The `any` module has its name as stable. The `Any` trait is also stable, with a new private supertrait which now contains the `get_type_id` method. This is to make the method a private implementation detail rather than a public-facing detail. The two extension traits in the module are marked #[unstable] as they will not be necessary with DST. The `is` method is #[stable], the as_{mut,ref} methods have been renamed to downcast_{mut,ref} and are #[unstable]. The extension trait `BoxAny` has been clarified as to why it is unstable as it will not be necessary with DST. This is a breaking change because the `marker1` field was removed from the `UnsafeCell` type. To deal with this change, you can simply delete the field and only specify the value of the `data` field in static initializers. [breaking-change]
2014-07-24 02:10:12 +00:00
///
2015-01-23 20:02:05 +00:00
/// # Examples
std: Stabilize unit, bool, ty, tuple, arc, any This commit applies stability attributes to the contents of these modules, summarized here: * The `unit` and `bool` modules have become #[unstable] as they are purely meant for documentation purposes and are candidates for removal. * The `ty` module has been deprecated, and the inner `Unsafe` type has been renamed to `UnsafeCell` and moved to the `cell` module. The `marker1` field has been removed as the compiler now always infers `UnsafeCell` to be invariant. The `new` method i stable, but the `value` field, `get` and `unwrap` methods are all unstable. * The `tuple` module has its name as stable, the naming of the `TupleN` traits as stable while the methods are all #[unstable]. The other impls in the module have appropriate stability for the corresponding trait. * The `arc` module has received the exact same treatment as the `rc` module previously did. * The `any` module has its name as stable. The `Any` trait is also stable, with a new private supertrait which now contains the `get_type_id` method. This is to make the method a private implementation detail rather than a public-facing detail. The two extension traits in the module are marked #[unstable] as they will not be necessary with DST. The `is` method is #[stable], the as_{mut,ref} methods have been renamed to downcast_{mut,ref} and are #[unstable]. The extension trait `BoxAny` has been clarified as to why it is unstable as it will not be necessary with DST. This is a breaking change because the `marker1` field was removed from the `UnsafeCell` type. To deal with this change, you can simply delete the field and only specify the value of the `data` field in static initializers. [breaking-change]
2014-07-24 02:10:12 +00:00
///
2015-01-23 20:02:05 +00:00
/// ```
std: Stabilize unit, bool, ty, tuple, arc, any This commit applies stability attributes to the contents of these modules, summarized here: * The `unit` and `bool` modules have become #[unstable] as they are purely meant for documentation purposes and are candidates for removal. * The `ty` module has been deprecated, and the inner `Unsafe` type has been renamed to `UnsafeCell` and moved to the `cell` module. The `marker1` field has been removed as the compiler now always infers `UnsafeCell` to be invariant. The `new` method i stable, but the `value` field, `get` and `unwrap` methods are all unstable. * The `tuple` module has its name as stable, the naming of the `TupleN` traits as stable while the methods are all #[unstable]. The other impls in the module have appropriate stability for the corresponding trait. * The `arc` module has received the exact same treatment as the `rc` module previously did. * The `any` module has its name as stable. The `Any` trait is also stable, with a new private supertrait which now contains the `get_type_id` method. This is to make the method a private implementation detail rather than a public-facing detail. The two extension traits in the module are marked #[unstable] as they will not be necessary with DST. The `is` method is #[stable], the as_{mut,ref} methods have been renamed to downcast_{mut,ref} and are #[unstable]. The extension trait `BoxAny` has been clarified as to why it is unstable as it will not be necessary with DST. This is a breaking change because the `marker1` field was removed from the `UnsafeCell` type. To deal with this change, you can simply delete the field and only specify the value of the `data` field in static initializers. [breaking-change]
2014-07-24 02:10:12 +00:00
/// use std::cell::UnsafeCell;
///
2015-11-03 15:27:03 +00:00
/// # #[allow(dead_code)]
std: Stabilize unit, bool, ty, tuple, arc, any This commit applies stability attributes to the contents of these modules, summarized here: * The `unit` and `bool` modules have become #[unstable] as they are purely meant for documentation purposes and are candidates for removal. * The `ty` module has been deprecated, and the inner `Unsafe` type has been renamed to `UnsafeCell` and moved to the `cell` module. The `marker1` field has been removed as the compiler now always infers `UnsafeCell` to be invariant. The `new` method i stable, but the `value` field, `get` and `unwrap` methods are all unstable. * The `tuple` module has its name as stable, the naming of the `TupleN` traits as stable while the methods are all #[unstable]. The other impls in the module have appropriate stability for the corresponding trait. * The `arc` module has received the exact same treatment as the `rc` module previously did. * The `any` module has its name as stable. The `Any` trait is also stable, with a new private supertrait which now contains the `get_type_id` method. This is to make the method a private implementation detail rather than a public-facing detail. The two extension traits in the module are marked #[unstable] as they will not be necessary with DST. The `is` method is #[stable], the as_{mut,ref} methods have been renamed to downcast_{mut,ref} and are #[unstable]. The extension trait `BoxAny` has been clarified as to why it is unstable as it will not be necessary with DST. This is a breaking change because the `marker1` field was removed from the `UnsafeCell` type. To deal with this change, you can simply delete the field and only specify the value of the `data` field in static initializers. [breaking-change]
2014-07-24 02:10:12 +00:00
/// struct NotThreadSafe<T> {
/// value: UnsafeCell<T>,
/// }
2015-01-16 07:18:39 +00:00
///
/// unsafe impl<T> Sync for NotThreadSafe<T> {}
std: Stabilize unit, bool, ty, tuple, arc, any This commit applies stability attributes to the contents of these modules, summarized here: * The `unit` and `bool` modules have become #[unstable] as they are purely meant for documentation purposes and are candidates for removal. * The `ty` module has been deprecated, and the inner `Unsafe` type has been renamed to `UnsafeCell` and moved to the `cell` module. The `marker1` field has been removed as the compiler now always infers `UnsafeCell` to be invariant. The `new` method i stable, but the `value` field, `get` and `unwrap` methods are all unstable. * The `tuple` module has its name as stable, the naming of the `TupleN` traits as stable while the methods are all #[unstable]. The other impls in the module have appropriate stability for the corresponding trait. * The `arc` module has received the exact same treatment as the `rc` module previously did. * The `any` module has its name as stable. The `Any` trait is also stable, with a new private supertrait which now contains the `get_type_id` method. This is to make the method a private implementation detail rather than a public-facing detail. The two extension traits in the module are marked #[unstable] as they will not be necessary with DST. The `is` method is #[stable], the as_{mut,ref} methods have been renamed to downcast_{mut,ref} and are #[unstable]. The extension trait `BoxAny` has been clarified as to why it is unstable as it will not be necessary with DST. This is a breaking change because the `marker1` field was removed from the `UnsafeCell` type. To deal with this change, you can simply delete the field and only specify the value of the `data` field in static initializers. [breaking-change]
2014-07-24 02:10:12 +00:00
/// ```
#[lang = "unsafe_cell"]
2015-01-24 05:48:20 +00:00
#[stable(feature = "rust1", since = "1.0.0")]
#[repr(transparent)]
pub struct UnsafeCell<T: ?Sized> {
value: T,
std: Stabilize unit, bool, ty, tuple, arc, any This commit applies stability attributes to the contents of these modules, summarized here: * The `unit` and `bool` modules have become #[unstable] as they are purely meant for documentation purposes and are candidates for removal. * The `ty` module has been deprecated, and the inner `Unsafe` type has been renamed to `UnsafeCell` and moved to the `cell` module. The `marker1` field has been removed as the compiler now always infers `UnsafeCell` to be invariant. The `new` method i stable, but the `value` field, `get` and `unwrap` methods are all unstable. * The `tuple` module has its name as stable, the naming of the `TupleN` traits as stable while the methods are all #[unstable]. The other impls in the module have appropriate stability for the corresponding trait. * The `arc` module has received the exact same treatment as the `rc` module previously did. * The `any` module has its name as stable. The `Any` trait is also stable, with a new private supertrait which now contains the `get_type_id` method. This is to make the method a private implementation detail rather than a public-facing detail. The two extension traits in the module are marked #[unstable] as they will not be necessary with DST. The `is` method is #[stable], the as_{mut,ref} methods have been renamed to downcast_{mut,ref} and are #[unstable]. The extension trait `BoxAny` has been clarified as to why it is unstable as it will not be necessary with DST. This is a breaking change because the `marker1` field was removed from the `UnsafeCell` type. To deal with this change, you can simply delete the field and only specify the value of the `data` field in static initializers. [breaking-change]
2014-07-24 02:10:12 +00:00
}
2015-11-16 16:54:28 +00:00
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> !Sync for UnsafeCell<T> {}
2015-01-26 22:10:24 +00:00
std: Stabilize unit, bool, ty, tuple, arc, any This commit applies stability attributes to the contents of these modules, summarized here: * The `unit` and `bool` modules have become #[unstable] as they are purely meant for documentation purposes and are candidates for removal. * The `ty` module has been deprecated, and the inner `Unsafe` type has been renamed to `UnsafeCell` and moved to the `cell` module. The `marker1` field has been removed as the compiler now always infers `UnsafeCell` to be invariant. The `new` method i stable, but the `value` field, `get` and `unwrap` methods are all unstable. * The `tuple` module has its name as stable, the naming of the `TupleN` traits as stable while the methods are all #[unstable]. The other impls in the module have appropriate stability for the corresponding trait. * The `arc` module has received the exact same treatment as the `rc` module previously did. * The `any` module has its name as stable. The `Any` trait is also stable, with a new private supertrait which now contains the `get_type_id` method. This is to make the method a private implementation detail rather than a public-facing detail. The two extension traits in the module are marked #[unstable] as they will not be necessary with DST. The `is` method is #[stable], the as_{mut,ref} methods have been renamed to downcast_{mut,ref} and are #[unstable]. The extension trait `BoxAny` has been clarified as to why it is unstable as it will not be necessary with DST. This is a breaking change because the `marker1` field was removed from the `UnsafeCell` type. To deal with this change, you can simply delete the field and only specify the value of the `data` field in static initializers. [breaking-change]
2014-07-24 02:10:12 +00:00
impl<T> UnsafeCell<T> {
/// Constructs a new instance of `UnsafeCell` which will wrap the specified
std: Stabilize unit, bool, ty, tuple, arc, any This commit applies stability attributes to the contents of these modules, summarized here: * The `unit` and `bool` modules have become #[unstable] as they are purely meant for documentation purposes and are candidates for removal. * The `ty` module has been deprecated, and the inner `Unsafe` type has been renamed to `UnsafeCell` and moved to the `cell` module. The `marker1` field has been removed as the compiler now always infers `UnsafeCell` to be invariant. The `new` method i stable, but the `value` field, `get` and `unwrap` methods are all unstable. * The `tuple` module has its name as stable, the naming of the `TupleN` traits as stable while the methods are all #[unstable]. The other impls in the module have appropriate stability for the corresponding trait. * The `arc` module has received the exact same treatment as the `rc` module previously did. * The `any` module has its name as stable. The `Any` trait is also stable, with a new private supertrait which now contains the `get_type_id` method. This is to make the method a private implementation detail rather than a public-facing detail. The two extension traits in the module are marked #[unstable] as they will not be necessary with DST. The `is` method is #[stable], the as_{mut,ref} methods have been renamed to downcast_{mut,ref} and are #[unstable]. The extension trait `BoxAny` has been clarified as to why it is unstable as it will not be necessary with DST. This is a breaking change because the `marker1` field was removed from the `UnsafeCell` type. To deal with this change, you can simply delete the field and only specify the value of the `data` field in static initializers. [breaking-change]
2014-07-24 02:10:12 +00:00
/// value.
///
/// All access to the inner value through methods is `unsafe`.
2015-01-23 20:02:05 +00:00
///
/// # Examples
///
/// ```
/// use std::cell::UnsafeCell;
///
/// let uc = UnsafeCell::new(5);
/// ```
2015-01-24 05:48:20 +00:00
#[stable(feature = "rust1", since = "1.0.0")]
2019-12-18 17:00:59 +00:00
#[rustc_const_stable(feature = "const_unsafe_cell_new", since = "1.32.0")]
#[inline]
pub const fn new(value: T) -> UnsafeCell<T> {
UnsafeCell { value }
std: Stabilize unit, bool, ty, tuple, arc, any This commit applies stability attributes to the contents of these modules, summarized here: * The `unit` and `bool` modules have become #[unstable] as they are purely meant for documentation purposes and are candidates for removal. * The `ty` module has been deprecated, and the inner `Unsafe` type has been renamed to `UnsafeCell` and moved to the `cell` module. The `marker1` field has been removed as the compiler now always infers `UnsafeCell` to be invariant. The `new` method i stable, but the `value` field, `get` and `unwrap` methods are all unstable. * The `tuple` module has its name as stable, the naming of the `TupleN` traits as stable while the methods are all #[unstable]. The other impls in the module have appropriate stability for the corresponding trait. * The `arc` module has received the exact same treatment as the `rc` module previously did. * The `any` module has its name as stable. The `Any` trait is also stable, with a new private supertrait which now contains the `get_type_id` method. This is to make the method a private implementation detail rather than a public-facing detail. The two extension traits in the module are marked #[unstable] as they will not be necessary with DST. The `is` method is #[stable], the as_{mut,ref} methods have been renamed to downcast_{mut,ref} and are #[unstable]. The extension trait `BoxAny` has been clarified as to why it is unstable as it will not be necessary with DST. This is a breaking change because the `marker1` field was removed from the `UnsafeCell` type. To deal with this change, you can simply delete the field and only specify the value of the `data` field in static initializers. [breaking-change]
2014-07-24 02:10:12 +00:00
}
/// Unwraps the value.
///
2015-01-23 20:02:05 +00:00
/// # Examples
///
/// ```
/// use std::cell::UnsafeCell;
///
/// let uc = UnsafeCell::new(5);
///
/// let five = uc.into_inner();
2015-01-23 20:02:05 +00:00
/// ```
std: Stabilize unit, bool, ty, tuple, arc, any This commit applies stability attributes to the contents of these modules, summarized here: * The `unit` and `bool` modules have become #[unstable] as they are purely meant for documentation purposes and are candidates for removal. * The `ty` module has been deprecated, and the inner `Unsafe` type has been renamed to `UnsafeCell` and moved to the `cell` module. The `marker1` field has been removed as the compiler now always infers `UnsafeCell` to be invariant. The `new` method i stable, but the `value` field, `get` and `unwrap` methods are all unstable. * The `tuple` module has its name as stable, the naming of the `TupleN` traits as stable while the methods are all #[unstable]. The other impls in the module have appropriate stability for the corresponding trait. * The `arc` module has received the exact same treatment as the `rc` module previously did. * The `any` module has its name as stable. The `Any` trait is also stable, with a new private supertrait which now contains the `get_type_id` method. This is to make the method a private implementation detail rather than a public-facing detail. The two extension traits in the module are marked #[unstable] as they will not be necessary with DST. The `is` method is #[stable], the as_{mut,ref} methods have been renamed to downcast_{mut,ref} and are #[unstable]. The extension trait `BoxAny` has been clarified as to why it is unstable as it will not be necessary with DST. This is a breaking change because the `marker1` field was removed from the `UnsafeCell` type. To deal with this change, you can simply delete the field and only specify the value of the `data` field in static initializers. [breaking-change]
2014-07-24 02:10:12 +00:00
#[inline]
2015-01-24 05:48:20 +00:00
#[stable(feature = "rust1", since = "1.0.0")]
pub fn into_inner(self) -> T {
2015-05-30 09:15:19 +00:00
self.value
}
}
std: Stabilize unit, bool, ty, tuple, arc, any This commit applies stability attributes to the contents of these modules, summarized here: * The `unit` and `bool` modules have become #[unstable] as they are purely meant for documentation purposes and are candidates for removal. * The `ty` module has been deprecated, and the inner `Unsafe` type has been renamed to `UnsafeCell` and moved to the `cell` module. The `marker1` field has been removed as the compiler now always infers `UnsafeCell` to be invariant. The `new` method i stable, but the `value` field, `get` and `unwrap` methods are all unstable. * The `tuple` module has its name as stable, the naming of the `TupleN` traits as stable while the methods are all #[unstable]. The other impls in the module have appropriate stability for the corresponding trait. * The `arc` module has received the exact same treatment as the `rc` module previously did. * The `any` module has its name as stable. The `Any` trait is also stable, with a new private supertrait which now contains the `get_type_id` method. This is to make the method a private implementation detail rather than a public-facing detail. The two extension traits in the module are marked #[unstable] as they will not be necessary with DST. The `is` method is #[stable], the as_{mut,ref} methods have been renamed to downcast_{mut,ref} and are #[unstable]. The extension trait `BoxAny` has been clarified as to why it is unstable as it will not be necessary with DST. This is a breaking change because the `marker1` field was removed from the `UnsafeCell` type. To deal with this change, you can simply delete the field and only specify the value of the `data` field in static initializers. [breaking-change]
2014-07-24 02:10:12 +00:00
impl<T: ?Sized> UnsafeCell<T> {
/// Gets a mutable pointer to the wrapped value.
2015-01-23 20:02:05 +00:00
///
2016-06-28 06:23:37 +00:00
/// This can be cast to a pointer of any kind.
/// Ensure that the access is unique (no active references, mutable or not)
/// when casting to `&mut T`, and ensure that there are no mutations
2018-02-14 08:11:37 +00:00
/// or mutable aliases going on when casting to `&T`
2016-06-28 06:23:37 +00:00
///
2015-01-23 20:02:05 +00:00
/// # Examples
///
/// ```
/// use std::cell::UnsafeCell;
///
/// let uc = UnsafeCell::new(5);
///
/// let five = uc.get();
2015-01-23 20:02:05 +00:00
/// ```
std: Stabilize unit, bool, ty, tuple, arc, any This commit applies stability attributes to the contents of these modules, summarized here: * The `unit` and `bool` modules have become #[unstable] as they are purely meant for documentation purposes and are candidates for removal. * The `ty` module has been deprecated, and the inner `Unsafe` type has been renamed to `UnsafeCell` and moved to the `cell` module. The `marker1` field has been removed as the compiler now always infers `UnsafeCell` to be invariant. The `new` method i stable, but the `value` field, `get` and `unwrap` methods are all unstable. * The `tuple` module has its name as stable, the naming of the `TupleN` traits as stable while the methods are all #[unstable]. The other impls in the module have appropriate stability for the corresponding trait. * The `arc` module has received the exact same treatment as the `rc` module previously did. * The `any` module has its name as stable. The `Any` trait is also stable, with a new private supertrait which now contains the `get_type_id` method. This is to make the method a private implementation detail rather than a public-facing detail. The two extension traits in the module are marked #[unstable] as they will not be necessary with DST. The `is` method is #[stable], the as_{mut,ref} methods have been renamed to downcast_{mut,ref} and are #[unstable]. The extension trait `BoxAny` has been clarified as to why it is unstable as it will not be necessary with DST. This is a breaking change because the `marker1` field was removed from the `UnsafeCell` type. To deal with this change, you can simply delete the field and only specify the value of the `data` field in static initializers. [breaking-change]
2014-07-24 02:10:12 +00:00
#[inline]
2015-01-24 05:48:20 +00:00
#[stable(feature = "rust1", since = "1.0.0")]
2019-12-18 17:00:59 +00:00
#[rustc_const_stable(feature = "const_unsafecell_get", since = "1.32.0")]
2018-10-23 00:04:14 +00:00
pub const fn get(&self) -> *mut T {
// We can just cast the pointer from `UnsafeCell<T>` to `T` because of
2019-11-13 08:07:52 +00:00
// #[repr(transparent)]. This exploits libstd's special status, there is
// no guarantee for user code that this will work in future versions of the compiler!
2018-11-16 21:17:26 +00:00
self as *const UnsafeCell<T> as *const T as *mut T
}
2019-11-09 11:34:29 +00:00
/// Gets a mutable pointer to the wrapped value.
2019-11-13 08:11:09 +00:00
/// The difference to [`get`] is that this function accepts a raw pointer,
/// which is useful to avoid the creation of temporary references.
2019-11-09 11:34:29 +00:00
///
2019-11-13 08:11:09 +00:00
/// The result can be cast to a pointer of any kind.
2019-11-09 11:34:29 +00:00
/// Ensure that the access is unique (no active references, mutable or not)
/// when casting to `&mut T`, and ensure that there are no mutations
/// or mutable aliases going on when casting to `&T`.
2019-11-09 11:34:29 +00:00
///
2019-11-13 08:11:09 +00:00
/// [`get`]: #method.get
///
2019-11-09 11:34:29 +00:00
/// # Examples
///
2019-11-13 08:11:09 +00:00
/// Gradual initialization of an `UnsafeCell` requires `raw_get`, as
/// calling `get` would require creating a reference to uninitialized data:
2019-11-09 11:34:29 +00:00
///
/// ```
/// #![feature(unsafe_cell_raw_get)]
/// use std::cell::UnsafeCell;
/// use std::mem::MaybeUninit;
///
/// let m = MaybeUninit::<UnsafeCell<i32>>::uninit();
2019-11-13 08:31:08 +00:00
/// unsafe { UnsafeCell::raw_get(m.as_ptr()).write(5); }
2019-11-09 11:34:29 +00:00
/// let uc = unsafe { m.assume_init() };
///
/// assert_eq!(uc.into_inner(), 5);
/// ```
#[inline]
2019-11-13 08:07:52 +00:00
#[unstable(feature = "unsafe_cell_raw_get", issue = "66358")]
2019-11-13 08:31:08 +00:00
pub const fn raw_get(this: *const Self) -> *mut T {
2019-11-09 11:34:29 +00:00
// We can just cast the pointer from `UnsafeCell<T>` to `T` because of
2019-11-13 08:07:52 +00:00
// #[repr(transparent)]. This exploits libstd's special status, there is
// no guarantee for user code that this will work in future versions of the compiler!
2019-11-13 08:31:08 +00:00
this as *const T as *mut T
2019-11-09 11:34:29 +00:00
}
std: Stabilize unit, bool, ty, tuple, arc, any This commit applies stability attributes to the contents of these modules, summarized here: * The `unit` and `bool` modules have become #[unstable] as they are purely meant for documentation purposes and are candidates for removal. * The `ty` module has been deprecated, and the inner `Unsafe` type has been renamed to `UnsafeCell` and moved to the `cell` module. The `marker1` field has been removed as the compiler now always infers `UnsafeCell` to be invariant. The `new` method i stable, but the `value` field, `get` and `unwrap` methods are all unstable. * The `tuple` module has its name as stable, the naming of the `TupleN` traits as stable while the methods are all #[unstable]. The other impls in the module have appropriate stability for the corresponding trait. * The `arc` module has received the exact same treatment as the `rc` module previously did. * The `any` module has its name as stable. The `Any` trait is also stable, with a new private supertrait which now contains the `get_type_id` method. This is to make the method a private implementation detail rather than a public-facing detail. The two extension traits in the module are marked #[unstable] as they will not be necessary with DST. The `is` method is #[stable], the as_{mut,ref} methods have been renamed to downcast_{mut,ref} and are #[unstable]. The extension trait `BoxAny` has been clarified as to why it is unstable as it will not be necessary with DST. This is a breaking change because the `marker1` field was removed from the `UnsafeCell` type. To deal with this change, you can simply delete the field and only specify the value of the `data` field in static initializers. [breaking-change]
2014-07-24 02:10:12 +00:00
}
#[stable(feature = "unsafe_cell_default", since = "1.10.0")]
impl<T: Default> Default for UnsafeCell<T> {
/// Creates an `UnsafeCell`, with the `Default` value for T.
fn default() -> UnsafeCell<T> {
UnsafeCell::new(Default::default())
}
}
#[stable(feature = "cell_from", since = "1.12.0")]
impl<T> From<T> for UnsafeCell<T> {
fn from(t: T) -> UnsafeCell<T> {
UnsafeCell::new(t)
}
}
#[unstable(feature = "coerce_unsized", issue = "27732")]
impl<T: CoerceUnsized<U>, U> CoerceUnsized<UnsafeCell<U>> for UnsafeCell<T> {}
#[allow(unused)]
fn assert_coerce_unsized(a: UnsafeCell<&i32>, b: Cell<&i32>, c: RefCell<&i32>) {
let _: UnsafeCell<&dyn Send> = a;
let _: Cell<&dyn Send> = b;
let _: RefCell<&dyn Send> = c;
}