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
|
2022-12-12 09:16:18 +00:00
|
|
|
//! presence of aliasing. [`Cell<T>`], [`RefCell<T>`], and [`OnceCell<T>`] allow doing this in
|
2023-03-29 19:25:27 +00:00
|
|
|
//! a single-threaded way—they do not implement [`Sync`]. (If you need to do aliasing and
|
2022-12-12 09:16:18 +00:00
|
|
|
//! mutation among multiple threads, [`Mutex<T>`], [`RwLock<T>`], [`OnceLock<T>`] or [`atomic`]
|
|
|
|
//! types are the correct data structures to do so).
|
2018-02-22 18:53:59 +00:00
|
|
|
//!
|
2022-12-12 09:16:18 +00:00
|
|
|
//! Values of the `Cell<T>`, `RefCell<T>`, and `OnceCell<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 these cell types provide 'interior mutability'
|
|
|
|
//! (mutable via `&T`), in contrast with typical Rust types that exhibit 'inherited mutability'
|
|
|
|
//! (mutable only via `&mut T`).
|
2014-05-19 04:47:51 +00:00
|
|
|
//!
|
2022-12-12 09:16:18 +00:00
|
|
|
//! Cell types come in three flavors: `Cell<T>`, `RefCell<T>`, and `OnceCell<T>`. Each provides
|
|
|
|
//! a different way of providing safe interior mutability.
|
|
|
|
//!
|
|
|
|
//! ## `Cell<T>`
|
|
|
|
//!
|
|
|
|
//! [`Cell<T>`] implements interior mutability by moving values in and out of the cell. That is, an
|
|
|
|
//! `&mut T` to the inner value can never be obtained, and the value itself cannot be directly
|
|
|
|
//! obtained without replacing it with something else. Both of these rules ensure that there is
|
|
|
|
//! never more than one reference pointing to the inner value. This type provides the following
|
|
|
|
//! methods:
|
2017-01-27 03:23:32 +00:00
|
|
|
//!
|
2021-01-30 21:07:24 +00:00
|
|
|
//! - For types that implement [`Copy`], the [`get`](Cell::get) method retrieves the current
|
2022-12-12 09:16:18 +00:00
|
|
|
//! interior value by duplicating it.
|
2021-01-30 21:07:24 +00:00
|
|
|
//! - For types that implement [`Default`], the [`take`](Cell::take) method replaces the current
|
|
|
|
//! interior value with [`Default::default()`] and returns the replaced value.
|
2022-12-12 09:16:18 +00:00
|
|
|
//! - All types have:
|
|
|
|
//! - [`replace`](Cell::replace): replaces the current interior value and returns the replaced
|
|
|
|
//! value.
|
|
|
|
//! - [`into_inner`](Cell::into_inner): this method consumes the `Cell<T>` and returns the
|
|
|
|
//! interior value.
|
|
|
|
//! - [`set`](Cell::set): this method replaces the interior value, dropping the replaced value.
|
|
|
|
//!
|
|
|
|
//! `Cell<T>` is typically used for more simple types where copying or moving values isn't too
|
|
|
|
//! resource intensive (e.g. numbers), and should usually be preferred over other cell types when
|
|
|
|
//! possible. For larger and non-copy types, `RefCell` provides some advantages.
|
2014-05-19 04:47:51 +00:00
|
|
|
//!
|
2022-12-12 09:16:18 +00:00
|
|
|
//! ## `RefCell<T>`
|
|
|
|
//!
|
|
|
|
//! [`RefCell<T>`] uses Rust's lifetimes to implement "dynamic borrowing", a process whereby one can
|
2015-01-23 20:02:05 +00:00
|
|
|
//! claim temporary, exclusive, mutable access to the inner value. Borrows for `RefCell<T>`s are
|
2022-12-12 09:16:18 +00:00
|
|
|
//! tracked at _runtime_, unlike Rust's native reference types which are entirely tracked
|
|
|
|
//! statically, at compile time.
|
|
|
|
//!
|
|
|
|
//! An immutable reference to a `RefCell`'s inner value (`&T`) can be obtained with
|
|
|
|
//! [`borrow`](`RefCell::borrow`), and a mutable borrow (`&mut T`) can be obtained with
|
|
|
|
//! [`borrow_mut`](`RefCell::borrow_mut`). When these functions are called, they first verify that
|
|
|
|
//! Rust's borrow rules will be satisfied: any number of immutable borrows are allowed or a
|
|
|
|
//! single immutable borrow is allowed, but never both. If a borrow is attempted that would violate
|
|
|
|
//! these rules, the thread will panic.
|
|
|
|
//!
|
|
|
|
//! The corresponding [`Sync`] version of `RefCell<T>` is [`RwLock<T>`].
|
|
|
|
//!
|
|
|
|
//! ## `OnceCell<T>`
|
|
|
|
//!
|
|
|
|
//! [`OnceCell<T>`] is somewhat of a hybrid of `Cell` and `RefCell` that works for values that
|
|
|
|
//! typically only need to be set once. This means that a reference `&T` can be obtained without
|
|
|
|
//! moving or copying the inner value (unlike `Cell`) but also without runtime checks (unlike
|
|
|
|
//! `RefCell`). However, its value can also not be updated once set unless you have a mutable
|
|
|
|
//! reference to the `OnceCell`.
|
|
|
|
//!
|
|
|
|
//! `OnceCell` provides the following methods:
|
|
|
|
//!
|
|
|
|
//! - [`get`](OnceCell::get): obtain a reference to the inner value
|
|
|
|
//! - [`set`](OnceCell::set): set the inner value if it is unset (returns a `Result`)
|
|
|
|
//! - [`get_or_init`](OnceCell::get_or_init): return the inner value, initializing it if needed
|
|
|
|
//! - [`get_mut`](OnceCell::get_mut): provide a mutable reference to the inner value, only available
|
|
|
|
//! if you have a mutable reference to the cell itself.
|
|
|
|
//!
|
|
|
|
//! The corresponding [`Sync`] version of `OnceCell<T>` is [`OnceLock<T>`].
|
|
|
|
//!
|
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
|
|
|
//!
|
2015-07-17 22:50:42 +00:00
|
|
|
//! * Introducing mutability 'inside' of something immutable
|
2014-05-19 04:47:51 +00:00
|
|
|
//! * Implementation details of logically-immutable methods.
|
2021-01-30 21:07:24 +00:00
|
|
|
//! * Mutating implementations of [`Clone`].
|
2014-05-19 04:47:51 +00:00
|
|
|
//!
|
2015-07-17 22:50:42 +00:00
|
|
|
//! ## Introducing mutability 'inside' of something immutable
|
2014-05-19 04:47:51 +00:00
|
|
|
//!
|
2021-01-30 21:07:24 +00:00
|
|
|
//! Many shared smart pointer types, including [`Rc<T>`] and [`Arc<T>`], provide containers that can
|
|
|
|
//! be cloned and shared between multiple parties. Because the contained values may be
|
2015-07-17 22:50:42 +00:00
|
|
|
//! 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
|
|
|
//!
|
|
|
|
//! ```
|
2019-05-22 03:52:21 +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()));
|
2019-05-22 03:52:21 +00:00
|
|
|
//! // 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();
|
2022-02-12 19:16:17 +00:00
|
|
|
//! println!("{total}");
|
2014-05-19 04:47:51 +00:00
|
|
|
//! }
|
|
|
|
//! ```
|
|
|
|
//!
|
2015-01-21 17:43:34 +00:00
|
|
|
//! Note that this example uses `Rc<T>` and not `Arc<T>`. `RefCell<T>`s are for single-threaded
|
2021-01-30 21:07:24 +00:00
|
|
|
//! scenarios. Consider using [`RwLock<T>`] or [`Mutex<T>`] if you need shared mutability in a
|
2015-07-17 22:50:42 +00:00
|
|
|
//! multi-threaded situation.
|
2015-01-21 17:43:34 +00:00
|
|
|
//!
|
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
|
2018-11-27 02:59:49 +00:00
|
|
|
//! "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 {
|
2015-02-16 13:41:33 +00:00
|
|
|
//! edges: Vec<(i32, i32)>,
|
|
|
|
//! span_tree_cache: RefCell<Option<Vec<(i32, i32)>>>
|
2014-05-19 04:47:51 +00:00
|
|
|
//! }
|
|
|
|
//!
|
|
|
|
//! impl Graph {
|
2015-02-16 13:41:33 +00:00
|
|
|
//! fn minimum_spanning_tree(&self) -> Vec<(i32, i32)> {
|
2019-05-22 03:52:21 +00:00
|
|
|
//! 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
|
|
|
//! }
|
|
|
|
//! }
|
|
|
|
//! ```
|
|
|
|
//!
|
2015-06-04 23:45:43 +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
|
2021-01-30 21:07:24 +00:00
|
|
|
//! that appear to be immutable. The [`clone`](Clone::clone) method is expected to not change the
|
|
|
|
//! source value, and is declared to take `&self`, not `&mut self`. Therefore, any mutation that
|
|
|
|
//! happens in the `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
|
|
|
//!
|
|
|
|
//! ```
|
|
|
|
//! use std::cell::Cell;
|
2018-03-08 15:55:51 +00:00
|
|
|
//! use std::ptr::NonNull;
|
2020-05-17 09:06:59 +00:00
|
|
|
//! use std::process::abort;
|
2019-11-05 20:34:54 +00:00
|
|
|
//! use std::marker::PhantomData;
|
2014-05-19 04:47:51 +00:00
|
|
|
//!
|
2016-08-22 07:37:08 +00:00
|
|
|
//! struct Rc<T: ?Sized> {
|
2019-11-05 20:34:54 +00:00
|
|
|
//! 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)
|
2020-05-17 09:06:59 +00:00
|
|
|
//! .unwrap_or_else(|| 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 {
|
2017-04-04 16:31:38 +00:00
|
|
|
//! self.ptr.as_ref()
|
2016-08-22 07:37:08 +00:00
|
|
|
//! }
|
|
|
|
//! }
|
|
|
|
//! }
|
2014-05-19 04:47:51 +00:00
|
|
|
//! ```
|
|
|
|
//!
|
2021-01-30 21:07:24 +00:00
|
|
|
//! [`Arc<T>`]: ../../std/sync/struct.Arc.html
|
|
|
|
//! [`Rc<T>`]: ../../std/rc/struct.Rc.html
|
|
|
|
//! [`RwLock<T>`]: ../../std/sync/struct.RwLock.html
|
|
|
|
//! [`Mutex<T>`]: ../../std/sync/struct.Mutex.html
|
2022-12-12 09:16:18 +00:00
|
|
|
//! [`OnceLock<T>`]: ../../std/sync/struct.OnceLock.html
|
|
|
|
//! [`Sync`]: ../../std/marker/trait.Sync.html
|
2021-03-24 13:42:49 +00:00
|
|
|
//! [`atomic`]: crate::sync::atomic
|
2013-03-25 01:59:04 +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};
|
2022-05-13 17:46:00 +00:00
|
|
|
use crate::marker::{PhantomData, Unsize};
|
2019-04-15 02:23:21 +00:00
|
|
|
use crate::mem;
|
2022-05-24 21:56:19 +00:00
|
|
|
use crate::ops::{CoerceUnsized, Deref, DerefMut, DispatchFromDyn};
|
2022-05-13 17:12:32 +00:00
|
|
|
use crate::ptr::{self, NonNull};
|
2013-11-22 05:30:34 +00:00
|
|
|
|
2022-06-16 15:41:40 +00:00
|
|
|
mod lazy;
|
|
|
|
mod once;
|
|
|
|
|
2022-12-12 05:42:45 +00:00
|
|
|
#[unstable(feature = "lazy_cell", issue = "109736")]
|
2022-06-16 15:41:40 +00:00
|
|
|
pub use lazy::LazyCell;
|
2022-12-12 05:42:45 +00:00
|
|
|
#[stable(feature = "once_cell", since = "CURRENT_RUSTC_VERSION")]
|
2022-06-16 15:41:40 +00:00
|
|
|
pub use once::OnceCell;
|
|
|
|
|
2017-01-27 03:23:32 +00:00
|
|
|
/// A mutable memory location.
|
2017-07-24 19:45:21 +00:00
|
|
|
///
|
2023-01-15 21:39:43 +00:00
|
|
|
/// # Memory layout
|
|
|
|
///
|
|
|
|
/// `Cell<T>` has the same [memory layout and caveats as
|
|
|
|
/// `UnsafeCell<T>`](UnsafeCell#memory-layout). In particular, this means that
|
|
|
|
/// `Cell<T>` has the same in-memory representation as its inner type `T`.
|
|
|
|
///
|
2017-07-24 16:01:50 +00:00
|
|
|
/// # Examples
|
2017-07-24 19:45:21 +00:00
|
|
|
///
|
2018-10-26 08:21:34 +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
|
|
|
///
|
2017-07-23 12:18:34 +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
|
|
|
///
|
2018-10-26 08:21:34 +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
|
|
|
///
|
2018-10-26 08:21:34 +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);
|
2017-07-23 12:18:34 +00:00
|
|
|
/// ```
|
2015-01-23 20:02:05 +00:00
|
|
|
///
|
2020-10-12 20:42:49 +00:00
|
|
|
/// See the [module-level documentation](self) for more.
|
2015-01-24 05:48:20 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2018-06-06 11:30:35 +00:00
|
|
|
#[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 {}
|
2014-12-29 18:58:22 +00:00
|
|
|
|
2021-07-27 22:50:34 +00:00
|
|
|
// Note that this negative impl isn't strictly necessary for correctness,
|
|
|
|
// as `Cell` wraps `UnsafeCell`, which is itself `!Sync`.
|
|
|
|
// However, given how important `Cell`'s `!Sync`-ness is,
|
|
|
|
// having an explicit negative impl is nice for documentation purposes
|
|
|
|
// and results in nicer error messages.
|
2016-03-01 03:03:23 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2018-05-07 07:24:45 +00:00
|
|
|
impl<T: ?Sized> !Sync for Cell<T> {}
|
2016-03-01 03:03:23 +00:00
|
|
|
|
2015-01-24 05:48:20 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2014-03-26 23:01:11 +00:00
|
|
|
impl<T: Copy> Clone for Cell<T> {
|
2015-03-18 23:44:37 +00:00
|
|
|
#[inline]
|
2014-01-22 19:03:02 +00:00
|
|
|
fn clone(&self) -> Cell<T> {
|
|
|
|
Cell::new(self.get())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-01-24 05:48:20 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2019-07-13 15:15:16 +00:00
|
|
|
impl<T: Default> Default for Cell<T> {
|
2016-09-11 11:30:09 +00:00
|
|
|
/// Creates a `Cell<T>`, with the `Default` value for T.
|
2015-03-18 23:44:37 +00:00
|
|
|
#[inline]
|
2014-11-14 19:22:42 +00:00
|
|
|
fn default() -> Cell<T> {
|
|
|
|
Cell::new(Default::default())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-01-24 05:48:20 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2019-07-13 15:15:16 +00:00
|
|
|
impl<T: PartialEq + Copy> PartialEq for Cell<T> {
|
2015-03-18 23:44:37 +00:00
|
|
|
#[inline]
|
2014-02-25 01:38:40 +00:00
|
|
|
fn eq(&self, other: &Cell<T>) -> bool {
|
|
|
|
self.get() == other.get()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-05-24 08:38:59 +00:00
|
|
|
#[stable(feature = "cell_eq", since = "1.2.0")]
|
2019-07-13 15:15:16 +00:00
|
|
|
impl<T: Eq + Copy> Eq for Cell<T> {}
|
2015-05-24 08:38:59 +00:00
|
|
|
|
2016-05-01 08:26:39 +00:00
|
|
|
#[stable(feature = "cell_ord", since = "1.10.0")]
|
2019-07-13 15:15:16 +00:00
|
|
|
impl<T: PartialOrd + Copy> PartialOrd for Cell<T> {
|
2016-05-01 08:07:47 +00:00
|
|
|
#[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()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-05-01 08:26:39 +00:00
|
|
|
#[stable(feature = "cell_ord", since = "1.10.0")]
|
2019-07-13 15:15:16 +00:00
|
|
|
impl<T: Ord + Copy> Ord for Cell<T> {
|
2016-05-01 08:07:47 +00:00
|
|
|
#[inline]
|
|
|
|
fn cmp(&self, other: &Cell<T>) -> Ordering {
|
|
|
|
self.get().cmp(&other.get())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-08-05 19:57:19 +00:00
|
|
|
#[stable(feature = "cell_from", since = "1.12.0")]
|
2021-10-18 10:19:28 +00:00
|
|
|
#[rustc_const_unstable(feature = "const_convert", issue = "88674")]
|
|
|
|
impl<T> const From<T> for Cell<T> {
|
2021-10-13 15:46:34 +00:00
|
|
|
/// Creates a new `Cell<T>` containing the given value.
|
2016-08-05 19:57:19 +00:00
|
|
|
fn from(t: T) -> Cell<T> {
|
|
|
|
Cell::new(t)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-01-25 03:44:33 +00:00
|
|
|
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")]
|
2021-03-12 13:45:13 +00:00
|
|
|
#[rustc_const_stable(feature = "const_cell_new", since = "1.24.0")]
|
2017-01-25 03:44:33 +00:00
|
|
|
#[inline]
|
|
|
|
pub const fn new(value: T) -> Cell<T> {
|
|
|
|
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);
|
|
|
|
}
|
|
|
|
|
2021-08-26 22:21:29 +00:00
|
|
|
/// Swaps the values of two `Cell`s.
|
2017-02-10 08:38:59 +00:00
|
|
|
/// 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]
|
2017-03-15 03:46:56 +00:00
|
|
|
#[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());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-12-26 18:09:41 +00:00
|
|
|
/// Replaces the contained value with `val`, and returns the old contained value.
|
2017-01-25 03:44:33 +00:00
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use std::cell::Cell;
|
|
|
|
///
|
2017-06-08 20:46:11 +00:00
|
|
|
/// let cell = Cell::new(5);
|
|
|
|
/// assert_eq!(cell.get(), 5);
|
|
|
|
/// assert_eq!(cell.replace(10), 5);
|
|
|
|
/// assert_eq!(cell.get(), 10);
|
2017-01-25 03:44:33 +00:00
|
|
|
/// ```
|
2022-10-01 15:30:54 +00:00
|
|
|
#[inline]
|
2017-03-15 03:46:56 +00:00
|
|
|
#[stable(feature = "move_cell", since = "1.17.0")]
|
2017-01-25 03:44:33 +00:00
|
|
|
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.
|
2017-01-25 03:44:33 +00:00
|
|
|
mem::replace(unsafe { &mut *self.value.get() }, val)
|
|
|
|
}
|
|
|
|
|
2022-12-12 09:16:18 +00:00
|
|
|
/// Unwraps the value, consuming the cell.
|
2017-01-25 03:44:33 +00:00
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use std::cell::Cell;
|
|
|
|
///
|
|
|
|
/// let c = Cell::new(5);
|
|
|
|
/// let five = c.into_inner();
|
|
|
|
///
|
|
|
|
/// assert_eq!(five, 5);
|
|
|
|
/// ```
|
2017-03-15 03:46:56 +00:00
|
|
|
#[stable(feature = "move_cell", since = "1.17.0")]
|
2020-11-04 10:58:41 +00:00
|
|
|
#[rustc_const_unstable(feature = "const_cell_into_inner", issue = "78729")]
|
2020-11-04 10:41:57 +00:00
|
|
|
pub const fn into_inner(self) -> T {
|
2018-01-05 01:11:20 +00:00
|
|
|
self.value.into_inner()
|
2017-01-25 03:44:33 +00:00
|
|
|
}
|
2019-10-03 06:24:00 +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-10-03 06:24:00 +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
|
|
|
|
}
|
2017-01-25 03:44:33 +00:00
|
|
|
}
|
|
|
|
|
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.
|
|
|
|
///
|
2021-06-17 10:02:16 +00:00
|
|
|
/// However be cautious: this method expects `self` to be mutable, which is
|
|
|
|
/// generally not the case when using a `Cell`. If you require interior
|
|
|
|
/// mutability by reference, consider using `RefCell` which provides
|
|
|
|
/// run-time checked mutable borrows through its [`borrow_mut`] method.
|
|
|
|
///
|
|
|
|
/// [`borrow_mut`]: RefCell::borrow_mut()
|
|
|
|
///
|
2018-05-07 07:24:45 +00:00
|
|
|
/// # 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 {
|
2020-09-19 19:33:40 +00:00
|
|
|
self.value.get_mut()
|
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]
|
2019-06-07 14:25:41 +00:00
|
|
|
#[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.
|
2018-05-07 07:24:45 +00:00
|
|
|
unsafe { &*(t as *mut T as *const Cell<T>) }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-01-25 03:44:33 +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);
|
|
|
|
/// ```
|
2017-03-15 03:46:56 +00:00
|
|
|
#[stable(feature = "move_cell", since = "1.17.0")]
|
2017-01-25 03:44:33 +00:00
|
|
|
pub fn take(&self) -> T {
|
|
|
|
self.replace(Default::default())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-12-20 07:08:38 +00:00
|
|
|
#[unstable(feature = "coerce_unsized", issue = "18598")]
|
2016-08-12 22:10:34 +00:00
|
|
|
impl<T: CoerceUnsized<U>, U> CoerceUnsized<Cell<U>> for Cell<T> {}
|
|
|
|
|
2022-05-24 21:56:19 +00:00
|
|
|
// Allow types that wrap `Cell` to also implement `DispatchFromDyn`
|
|
|
|
// and become object safe method receivers.
|
|
|
|
// Note that currently `Cell` itself cannot be a method receiver
|
|
|
|
// because it does not implement Deref.
|
|
|
|
// In other words:
|
|
|
|
// `self: Cell<&Self>` won't work
|
|
|
|
// `self: CellWrapper<Self>` becomes possible
|
|
|
|
#[unstable(feature = "dispatch_from_dyn", issue = "none")]
|
|
|
|
impl<T: DispatchFromDyn<U>, U> DispatchFromDyn<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);
|
|
|
|
/// ```
|
2019-06-07 14:25:41 +00:00
|
|
|
#[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`.
|
2018-07-23 11:20:50 +00:00
|
|
|
unsafe { &*(self as *const Cell<[T]> as *const [Cell<T>]) }
|
2018-06-07 09:47:55 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-08-11 18:38:20 +00:00
|
|
|
impl<T, const N: usize> Cell<[T; N]> {
|
|
|
|
/// Returns a `&[Cell<T>; N]` from a `&Cell<[T; N]>`
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// #![feature(as_array_of_cells)]
|
|
|
|
/// use std::cell::Cell;
|
|
|
|
///
|
|
|
|
/// let mut array: [i32; 3] = [1, 2, 3];
|
|
|
|
/// let cell_array: &Cell<[i32; 3]> = Cell::from_mut(&mut array);
|
|
|
|
/// let array_cell: &[Cell<i32>; 3] = cell_array.as_array_of_cells();
|
|
|
|
/// ```
|
|
|
|
#[unstable(feature = "as_array_of_cells", issue = "88248")]
|
|
|
|
pub fn as_array_of_cells(&self) -> &[Cell<T>; N] {
|
|
|
|
// SAFETY: `Cell<T>` has the same memory layout as `T`.
|
|
|
|
unsafe { &*(self as *const Cell<[T; N]> as *const [Cell<T>; N]) }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
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
|
|
|
///
|
2020-10-12 20:42:49 +00:00
|
|
|
/// See the [module-level documentation](self) for more.
|
2022-09-27 11:06:31 +00:00
|
|
|
#[cfg_attr(not(test), rustc_diagnostic_item = "RefCell")]
|
2015-01-24 05:48:20 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2015-04-23 10:53:54 +00:00
|
|
|
pub struct RefCell<T: ?Sized> {
|
2014-04-09 05:54:06 +00:00
|
|
|
borrow: Cell<BorrowFlag>,
|
Add `debug-refcell` feature to libcore
See https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Attaching.20backtraces.20to.20RefCell/near/226273614
for some background discussion
This PR adds a new off-by-default feature `debug-refcell` to libcore.
When enabled, this feature stores additional debugging information in
`RefCell`. This information is included in the panic message when
`borrow()` or `borrow_mut()` panics, to make it easier to track down the
source of the issue.
Currently, we store the caller location for the earliest active borrow.
This has a number of advantages:
* There is only a constant amount of overhead per `RefCell`
* We don't need any heap memory, so it can easily be implemented in core
* Since we are storing the *earliest* active borrow, we don't need any
extra logic in the `Drop` implementation for `Ref` and `RefMut`
Limitations:
* We only store the caller location, not a full `Backtrace`. Until
we get support for `Backtrace` in libcore, this is the best tha we can
do.
* The captured location is only displayed when `borrow()` or
`borrow_mut()` panics. If a crate calls `try_borrow().unwrap()`
or `try_borrow_mut().unwrap()`, this extra information will be lost.
To make testing easier, I've enabled the `debug-refcell` feature by
default. I'm not sure how to write a test for this feature - we would
need to rebuild core from the test framework, and create a separate
sysroot.
Since this feature will be off-by-default, users will need to use
`xargo` or `cargo -Z build-std` to enable this feature. For users using
a prebuilt standard library, this feature will be disabled with zero
overhead.
I've created a simple test program:
```rust
use std::cell::RefCell;
fn main() {
let _ = std::panic::catch_unwind(|| {
let val = RefCell::new(true);
let _first = val.borrow();
let _second = val.borrow();
let _third = val.borrow_mut();
});
let _ = std::panic::catch_unwind(|| {
let val = RefCell::new(true);
let first = val.borrow_mut();
drop(first);
let _second = val.borrow_mut();
let _thid = val.borrow();
});
}
```
which produces the following output:
```
thread 'main' panicked at 'already borrowed: BorrowMutError { location: Location { file: "refcell_test.rs", line: 6, col: 26 } }', refcell_test.rs:8:26
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread 'main' panicked at 'already mutably borrowed: BorrowError { location: Location { file: "refcell_test.rs", line: 16, col: 27 } }', refcell_test.rs:18:25
```
2021-02-18 02:30:39 +00:00
|
|
|
// Stores the location of the earliest currently active borrow.
|
2021-07-26 21:12:35 +00:00
|
|
|
// This gets updated whenever we go from having zero borrows
|
Add `debug-refcell` feature to libcore
See https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Attaching.20backtraces.20to.20RefCell/near/226273614
for some background discussion
This PR adds a new off-by-default feature `debug-refcell` to libcore.
When enabled, this feature stores additional debugging information in
`RefCell`. This information is included in the panic message when
`borrow()` or `borrow_mut()` panics, to make it easier to track down the
source of the issue.
Currently, we store the caller location for the earliest active borrow.
This has a number of advantages:
* There is only a constant amount of overhead per `RefCell`
* We don't need any heap memory, so it can easily be implemented in core
* Since we are storing the *earliest* active borrow, we don't need any
extra logic in the `Drop` implementation for `Ref` and `RefMut`
Limitations:
* We only store the caller location, not a full `Backtrace`. Until
we get support for `Backtrace` in libcore, this is the best tha we can
do.
* The captured location is only displayed when `borrow()` or
`borrow_mut()` panics. If a crate calls `try_borrow().unwrap()`
or `try_borrow_mut().unwrap()`, this extra information will be lost.
To make testing easier, I've enabled the `debug-refcell` feature by
default. I'm not sure how to write a test for this feature - we would
need to rebuild core from the test framework, and create a separate
sysroot.
Since this feature will be off-by-default, users will need to use
`xargo` or `cargo -Z build-std` to enable this feature. For users using
a prebuilt standard library, this feature will be disabled with zero
overhead.
I've created a simple test program:
```rust
use std::cell::RefCell;
fn main() {
let _ = std::panic::catch_unwind(|| {
let val = RefCell::new(true);
let _first = val.borrow();
let _second = val.borrow();
let _third = val.borrow_mut();
});
let _ = std::panic::catch_unwind(|| {
let val = RefCell::new(true);
let first = val.borrow_mut();
drop(first);
let _second = val.borrow_mut();
let _thid = val.borrow();
});
}
```
which produces the following output:
```
thread 'main' panicked at 'already borrowed: BorrowMutError { location: Location { file: "refcell_test.rs", line: 6, col: 26 } }', refcell_test.rs:8:26
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread 'main' panicked at 'already mutably borrowed: BorrowError { location: Location { file: "refcell_test.rs", line: 16, col: 27 } }', refcell_test.rs:18:25
```
2021-02-18 02:30:39 +00:00
|
|
|
// to having a single borrow. When a borrow occurs, this gets included
|
2023-03-03 01:35:10 +00:00
|
|
|
// in the generated `BorrowError`/`BorrowMutError`
|
Add `debug-refcell` feature to libcore
See https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Attaching.20backtraces.20to.20RefCell/near/226273614
for some background discussion
This PR adds a new off-by-default feature `debug-refcell` to libcore.
When enabled, this feature stores additional debugging information in
`RefCell`. This information is included in the panic message when
`borrow()` or `borrow_mut()` panics, to make it easier to track down the
source of the issue.
Currently, we store the caller location for the earliest active borrow.
This has a number of advantages:
* There is only a constant amount of overhead per `RefCell`
* We don't need any heap memory, so it can easily be implemented in core
* Since we are storing the *earliest* active borrow, we don't need any
extra logic in the `Drop` implementation for `Ref` and `RefMut`
Limitations:
* We only store the caller location, not a full `Backtrace`. Until
we get support for `Backtrace` in libcore, this is the best tha we can
do.
* The captured location is only displayed when `borrow()` or
`borrow_mut()` panics. If a crate calls `try_borrow().unwrap()`
or `try_borrow_mut().unwrap()`, this extra information will be lost.
To make testing easier, I've enabled the `debug-refcell` feature by
default. I'm not sure how to write a test for this feature - we would
need to rebuild core from the test framework, and create a separate
sysroot.
Since this feature will be off-by-default, users will need to use
`xargo` or `cargo -Z build-std` to enable this feature. For users using
a prebuilt standard library, this feature will be disabled with zero
overhead.
I've created a simple test program:
```rust
use std::cell::RefCell;
fn main() {
let _ = std::panic::catch_unwind(|| {
let val = RefCell::new(true);
let _first = val.borrow();
let _second = val.borrow();
let _third = val.borrow_mut();
});
let _ = std::panic::catch_unwind(|| {
let val = RefCell::new(true);
let first = val.borrow_mut();
drop(first);
let _second = val.borrow_mut();
let _thid = val.borrow();
});
}
```
which produces the following output:
```
thread 'main' panicked at 'already borrowed: BorrowMutError { location: Location { file: "refcell_test.rs", line: 6, col: 26 } }', refcell_test.rs:8:26
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread 'main' panicked at 'already mutably borrowed: BorrowError { location: Location { file: "refcell_test.rs", line: 16, col: 27 } }', refcell_test.rs:18:25
```
2021-02-18 02:30:39 +00:00
|
|
|
#[cfg(feature = "debug_refcell")]
|
|
|
|
borrowed_at: Cell<Option<&'static crate::panic::Location<'static>>>,
|
2015-04-23 10:53:54 +00:00
|
|
|
value: UnsafeCell<T>,
|
2013-11-22 05:30:34 +00:00
|
|
|
}
|
|
|
|
|
2020-11-07 20:22:24 +00:00
|
|
|
/// An error returned by [`RefCell::try_borrow`].
|
2016-09-29 00:23:36 +00:00
|
|
|
#[stable(feature = "try_borrow", since = "1.13.0")]
|
2021-06-24 08:16:11 +00:00
|
|
|
#[non_exhaustive]
|
2016-09-29 00:23:36 +00:00
|
|
|
pub struct BorrowError {
|
Add `debug-refcell` feature to libcore
See https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Attaching.20backtraces.20to.20RefCell/near/226273614
for some background discussion
This PR adds a new off-by-default feature `debug-refcell` to libcore.
When enabled, this feature stores additional debugging information in
`RefCell`. This information is included in the panic message when
`borrow()` or `borrow_mut()` panics, to make it easier to track down the
source of the issue.
Currently, we store the caller location for the earliest active borrow.
This has a number of advantages:
* There is only a constant amount of overhead per `RefCell`
* We don't need any heap memory, so it can easily be implemented in core
* Since we are storing the *earliest* active borrow, we don't need any
extra logic in the `Drop` implementation for `Ref` and `RefMut`
Limitations:
* We only store the caller location, not a full `Backtrace`. Until
we get support for `Backtrace` in libcore, this is the best tha we can
do.
* The captured location is only displayed when `borrow()` or
`borrow_mut()` panics. If a crate calls `try_borrow().unwrap()`
or `try_borrow_mut().unwrap()`, this extra information will be lost.
To make testing easier, I've enabled the `debug-refcell` feature by
default. I'm not sure how to write a test for this feature - we would
need to rebuild core from the test framework, and create a separate
sysroot.
Since this feature will be off-by-default, users will need to use
`xargo` or `cargo -Z build-std` to enable this feature. For users using
a prebuilt standard library, this feature will be disabled with zero
overhead.
I've created a simple test program:
```rust
use std::cell::RefCell;
fn main() {
let _ = std::panic::catch_unwind(|| {
let val = RefCell::new(true);
let _first = val.borrow();
let _second = val.borrow();
let _third = val.borrow_mut();
});
let _ = std::panic::catch_unwind(|| {
let val = RefCell::new(true);
let first = val.borrow_mut();
drop(first);
let _second = val.borrow_mut();
let _thid = val.borrow();
});
}
```
which produces the following output:
```
thread 'main' panicked at 'already borrowed: BorrowMutError { location: Location { file: "refcell_test.rs", line: 6, col: 26 } }', refcell_test.rs:8:26
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread 'main' panicked at 'already mutably borrowed: BorrowError { location: Location { file: "refcell_test.rs", line: 16, col: 27 } }', refcell_test.rs:18:25
```
2021-02-18 02:30:39 +00:00
|
|
|
#[cfg(feature = "debug_refcell")]
|
|
|
|
location: &'static crate::panic::Location<'static>,
|
2016-08-06 17:48:59 +00:00
|
|
|
}
|
|
|
|
|
2016-09-29 00:23:36 +00:00
|
|
|
#[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 {
|
Add `debug-refcell` feature to libcore
See https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Attaching.20backtraces.20to.20RefCell/near/226273614
for some background discussion
This PR adds a new off-by-default feature `debug-refcell` to libcore.
When enabled, this feature stores additional debugging information in
`RefCell`. This information is included in the panic message when
`borrow()` or `borrow_mut()` panics, to make it easier to track down the
source of the issue.
Currently, we store the caller location for the earliest active borrow.
This has a number of advantages:
* There is only a constant amount of overhead per `RefCell`
* We don't need any heap memory, so it can easily be implemented in core
* Since we are storing the *earliest* active borrow, we don't need any
extra logic in the `Drop` implementation for `Ref` and `RefMut`
Limitations:
* We only store the caller location, not a full `Backtrace`. Until
we get support for `Backtrace` in libcore, this is the best tha we can
do.
* The captured location is only displayed when `borrow()` or
`borrow_mut()` panics. If a crate calls `try_borrow().unwrap()`
or `try_borrow_mut().unwrap()`, this extra information will be lost.
To make testing easier, I've enabled the `debug-refcell` feature by
default. I'm not sure how to write a test for this feature - we would
need to rebuild core from the test framework, and create a separate
sysroot.
Since this feature will be off-by-default, users will need to use
`xargo` or `cargo -Z build-std` to enable this feature. For users using
a prebuilt standard library, this feature will be disabled with zero
overhead.
I've created a simple test program:
```rust
use std::cell::RefCell;
fn main() {
let _ = std::panic::catch_unwind(|| {
let val = RefCell::new(true);
let _first = val.borrow();
let _second = val.borrow();
let _third = val.borrow_mut();
});
let _ = std::panic::catch_unwind(|| {
let val = RefCell::new(true);
let first = val.borrow_mut();
drop(first);
let _second = val.borrow_mut();
let _thid = val.borrow();
});
}
```
which produces the following output:
```
thread 'main' panicked at 'already borrowed: BorrowMutError { location: Location { file: "refcell_test.rs", line: 6, col: 26 } }', refcell_test.rs:8:26
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread 'main' panicked at 'already mutably borrowed: BorrowError { location: Location { file: "refcell_test.rs", line: 16, col: 27 } }', refcell_test.rs:18:25
```
2021-02-18 02:30:39 +00:00
|
|
|
let mut builder = f.debug_struct("BorrowError");
|
|
|
|
|
|
|
|
#[cfg(feature = "debug_refcell")]
|
|
|
|
builder.field("location", self.location);
|
|
|
|
|
|
|
|
builder.finish()
|
2016-08-06 17:48:59 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-09-29 00:23:36 +00:00
|
|
|
#[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 {
|
2016-08-06 17:48:59 +00:00
|
|
|
Display::fmt("already mutably borrowed", f)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-11-07 20:22:24 +00:00
|
|
|
/// An error returned by [`RefCell::try_borrow_mut`].
|
2016-09-29 00:23:36 +00:00
|
|
|
#[stable(feature = "try_borrow", since = "1.13.0")]
|
2021-06-24 08:16:11 +00:00
|
|
|
#[non_exhaustive]
|
2016-09-29 00:23:36 +00:00
|
|
|
pub struct BorrowMutError {
|
Add `debug-refcell` feature to libcore
See https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Attaching.20backtraces.20to.20RefCell/near/226273614
for some background discussion
This PR adds a new off-by-default feature `debug-refcell` to libcore.
When enabled, this feature stores additional debugging information in
`RefCell`. This information is included in the panic message when
`borrow()` or `borrow_mut()` panics, to make it easier to track down the
source of the issue.
Currently, we store the caller location for the earliest active borrow.
This has a number of advantages:
* There is only a constant amount of overhead per `RefCell`
* We don't need any heap memory, so it can easily be implemented in core
* Since we are storing the *earliest* active borrow, we don't need any
extra logic in the `Drop` implementation for `Ref` and `RefMut`
Limitations:
* We only store the caller location, not a full `Backtrace`. Until
we get support for `Backtrace` in libcore, this is the best tha we can
do.
* The captured location is only displayed when `borrow()` or
`borrow_mut()` panics. If a crate calls `try_borrow().unwrap()`
or `try_borrow_mut().unwrap()`, this extra information will be lost.
To make testing easier, I've enabled the `debug-refcell` feature by
default. I'm not sure how to write a test for this feature - we would
need to rebuild core from the test framework, and create a separate
sysroot.
Since this feature will be off-by-default, users will need to use
`xargo` or `cargo -Z build-std` to enable this feature. For users using
a prebuilt standard library, this feature will be disabled with zero
overhead.
I've created a simple test program:
```rust
use std::cell::RefCell;
fn main() {
let _ = std::panic::catch_unwind(|| {
let val = RefCell::new(true);
let _first = val.borrow();
let _second = val.borrow();
let _third = val.borrow_mut();
});
let _ = std::panic::catch_unwind(|| {
let val = RefCell::new(true);
let first = val.borrow_mut();
drop(first);
let _second = val.borrow_mut();
let _thid = val.borrow();
});
}
```
which produces the following output:
```
thread 'main' panicked at 'already borrowed: BorrowMutError { location: Location { file: "refcell_test.rs", line: 6, col: 26 } }', refcell_test.rs:8:26
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread 'main' panicked at 'already mutably borrowed: BorrowError { location: Location { file: "refcell_test.rs", line: 16, col: 27 } }', refcell_test.rs:18:25
```
2021-02-18 02:30:39 +00:00
|
|
|
#[cfg(feature = "debug_refcell")]
|
|
|
|
location: &'static crate::panic::Location<'static>,
|
2016-08-06 17:48:59 +00:00
|
|
|
}
|
|
|
|
|
2016-09-29 00:23:36 +00:00
|
|
|
#[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 {
|
Add `debug-refcell` feature to libcore
See https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Attaching.20backtraces.20to.20RefCell/near/226273614
for some background discussion
This PR adds a new off-by-default feature `debug-refcell` to libcore.
When enabled, this feature stores additional debugging information in
`RefCell`. This information is included in the panic message when
`borrow()` or `borrow_mut()` panics, to make it easier to track down the
source of the issue.
Currently, we store the caller location for the earliest active borrow.
This has a number of advantages:
* There is only a constant amount of overhead per `RefCell`
* We don't need any heap memory, so it can easily be implemented in core
* Since we are storing the *earliest* active borrow, we don't need any
extra logic in the `Drop` implementation for `Ref` and `RefMut`
Limitations:
* We only store the caller location, not a full `Backtrace`. Until
we get support for `Backtrace` in libcore, this is the best tha we can
do.
* The captured location is only displayed when `borrow()` or
`borrow_mut()` panics. If a crate calls `try_borrow().unwrap()`
or `try_borrow_mut().unwrap()`, this extra information will be lost.
To make testing easier, I've enabled the `debug-refcell` feature by
default. I'm not sure how to write a test for this feature - we would
need to rebuild core from the test framework, and create a separate
sysroot.
Since this feature will be off-by-default, users will need to use
`xargo` or `cargo -Z build-std` to enable this feature. For users using
a prebuilt standard library, this feature will be disabled with zero
overhead.
I've created a simple test program:
```rust
use std::cell::RefCell;
fn main() {
let _ = std::panic::catch_unwind(|| {
let val = RefCell::new(true);
let _first = val.borrow();
let _second = val.borrow();
let _third = val.borrow_mut();
});
let _ = std::panic::catch_unwind(|| {
let val = RefCell::new(true);
let first = val.borrow_mut();
drop(first);
let _second = val.borrow_mut();
let _thid = val.borrow();
});
}
```
which produces the following output:
```
thread 'main' panicked at 'already borrowed: BorrowMutError { location: Location { file: "refcell_test.rs", line: 6, col: 26 } }', refcell_test.rs:8:26
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread 'main' panicked at 'already mutably borrowed: BorrowError { location: Location { file: "refcell_test.rs", line: 16, col: 27 } }', refcell_test.rs:18:25
```
2021-02-18 02:30:39 +00:00
|
|
|
let mut builder = f.debug_struct("BorrowMutError");
|
|
|
|
|
|
|
|
#[cfg(feature = "debug_refcell")]
|
|
|
|
builder.field("location", self.location);
|
|
|
|
|
|
|
|
builder.finish()
|
2016-08-06 17:48:59 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-09-29 00:23:36 +00:00
|
|
|
#[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 {
|
2016-08-06 17:48:59 +00:00
|
|
|
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")]
|
2021-03-12 13:45:13 +00:00
|
|
|
#[rustc_const_stable(feature = "const_refcell_new", since = "1.24.0")]
|
2015-03-18 23:44:37 +00:00
|
|
|
#[inline]
|
2015-05-27 08:18:36 +00:00
|
|
|
pub const fn new(value: T) -> RefCell<T> {
|
Add `debug-refcell` feature to libcore
See https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Attaching.20backtraces.20to.20RefCell/near/226273614
for some background discussion
This PR adds a new off-by-default feature `debug-refcell` to libcore.
When enabled, this feature stores additional debugging information in
`RefCell`. This information is included in the panic message when
`borrow()` or `borrow_mut()` panics, to make it easier to track down the
source of the issue.
Currently, we store the caller location for the earliest active borrow.
This has a number of advantages:
* There is only a constant amount of overhead per `RefCell`
* We don't need any heap memory, so it can easily be implemented in core
* Since we are storing the *earliest* active borrow, we don't need any
extra logic in the `Drop` implementation for `Ref` and `RefMut`
Limitations:
* We only store the caller location, not a full `Backtrace`. Until
we get support for `Backtrace` in libcore, this is the best tha we can
do.
* The captured location is only displayed when `borrow()` or
`borrow_mut()` panics. If a crate calls `try_borrow().unwrap()`
or `try_borrow_mut().unwrap()`, this extra information will be lost.
To make testing easier, I've enabled the `debug-refcell` feature by
default. I'm not sure how to write a test for this feature - we would
need to rebuild core from the test framework, and create a separate
sysroot.
Since this feature will be off-by-default, users will need to use
`xargo` or `cargo -Z build-std` to enable this feature. For users using
a prebuilt standard library, this feature will be disabled with zero
overhead.
I've created a simple test program:
```rust
use std::cell::RefCell;
fn main() {
let _ = std::panic::catch_unwind(|| {
let val = RefCell::new(true);
let _first = val.borrow();
let _second = val.borrow();
let _third = val.borrow_mut();
});
let _ = std::panic::catch_unwind(|| {
let val = RefCell::new(true);
let first = val.borrow_mut();
drop(first);
let _second = val.borrow_mut();
let _thid = val.borrow();
});
}
```
which produces the following output:
```
thread 'main' panicked at 'already borrowed: BorrowMutError { location: Location { file: "refcell_test.rs", line: 6, col: 26 } }', refcell_test.rs:8:26
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread 'main' panicked at 'already mutably borrowed: BorrowError { location: Location { file: "refcell_test.rs", line: 16, col: 27 } }', refcell_test.rs:18:25
```
2021-02-18 02:30:39 +00:00
|
|
|
RefCell {
|
|
|
|
value: UnsafeCell::new(value),
|
|
|
|
borrow: Cell::new(UNUSED),
|
|
|
|
#[cfg(feature = "debug_refcell")]
|
|
|
|
borrowed_at: Cell::new(None),
|
|
|
|
}
|
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")]
|
2020-11-04 10:58:41 +00:00
|
|
|
#[rustc_const_unstable(feature = "const_cell_into_inner", issue = "78729")]
|
2015-03-18 23:44:37 +00:00
|
|
|
#[inline]
|
2020-11-04 10:41:57 +00:00
|
|
|
pub const fn into_inner(self) -> T {
|
2014-11-20 10:20:10 +00:00
|
|
|
// Since this function takes `self` (the `RefCell`) by value, the
|
|
|
|
// compiler statically verifies that it is not currently borrowed.
|
2018-01-05 01:11:20 +00:00
|
|
|
self.value.into_inner()
|
2013-11-22 05:30:34 +00:00
|
|
|
}
|
2017-07-31 17:14:16 +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.
|
|
|
|
///
|
2017-08-02 17:58:27 +00:00
|
|
|
/// # Examples
|
2017-07-31 17:14:16 +00:00
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// 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-07-31 17:14:16 +00:00
|
|
|
/// ```
|
2017-11-07 02:53:23 +00:00
|
|
|
#[inline]
|
2017-12-05 20:15:35 +00:00
|
|
|
#[stable(feature = "refcell_replace", since = "1.24.0")]
|
2020-09-22 13:30:09 +00:00
|
|
|
#[track_caller]
|
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.
|
|
|
|
///
|
2017-07-31 17:14:16 +00:00
|
|
|
/// # 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));
|
|
|
|
/// ```
|
2017-07-31 17:14:16 +00:00
|
|
|
#[inline]
|
2019-03-31 08:54:00 +00:00
|
|
|
#[stable(feature = "refcell_replace_swap", since = "1.35.0")]
|
2020-09-22 13:30:09 +00:00
|
|
|
#[track_caller]
|
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)
|
2017-07-31 17:14:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// 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
|
|
|
|
///
|
2022-11-02 13:38:15 +00:00
|
|
|
/// Panics if the value in either `RefCell` is currently borrowed, or
|
|
|
|
/// if `self` and `other` point to the same `RefCell`.
|
2017-11-07 02:53:23 +00:00
|
|
|
///
|
2017-08-02 17:58:27 +00:00
|
|
|
/// # Examples
|
2017-07-31 17:14:16 +00:00
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// 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]
|
2017-12-05 20:15:35 +00:00
|
|
|
#[stable(feature = "refcell_swap", since = "1.24.0")]
|
2017-07-31 17:14:16 +00:00
|
|
|
pub fn swap(&self, other: &Self) {
|
|
|
|
mem::swap(&mut *self.borrow_mut(), &mut *other.borrow_mut())
|
|
|
|
}
|
2015-04-23 10:53:54 +00:00
|
|
|
}
|
2013-11-22 05:30:34 +00:00
|
|
|
|
2015-04-23 10:53:54 +00:00
|
|
|
impl<T: ?Sized> RefCell<T> {
|
2013-11-22 05:30:34 +00:00
|
|
|
/// Immutably borrows the wrapped value.
|
|
|
|
///
|
2015-02-02 02:53:47 +00:00
|
|
|
/// 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
|
|
|
///
|
2014-11-11 18:36:09 +00:00
|
|
|
/// # Panics
|
2013-11-22 05:30:34 +00:00
|
|
|
///
|
2016-08-06 17:48:59 +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:
|
|
|
|
///
|
2020-06-13 04:06:09 +00:00
|
|
|
/// ```should_panic
|
2015-01-23 20:02:05 +00:00
|
|
|
/// use std::cell::RefCell;
|
|
|
|
///
|
2020-06-13 04:06:09 +00:00
|
|
|
/// let c = RefCell::new(5);
|
2015-01-23 20:02:05 +00:00
|
|
|
///
|
2020-06-13 04:06:09 +00:00
|
|
|
/// let m = c.borrow_mut();
|
|
|
|
/// let b = c.borrow(); // this causes a panic
|
2015-01-23 20:02:05 +00:00
|
|
|
/// ```
|
2015-01-24 05:48:20 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2015-03-18 23:44:37 +00:00
|
|
|
#[inline]
|
2020-07-19 18:07:21 +00:00
|
|
|
#[track_caller]
|
2019-04-18 23:37:12 +00:00
|
|
|
pub fn borrow(&self) -> Ref<'_, T> {
|
2016-08-06 17:48:59 +00:00
|
|
|
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());
|
|
|
|
/// }
|
|
|
|
/// ```
|
2016-09-29 00:23:36 +00:00
|
|
|
#[stable(feature = "try_borrow", since = "1.13.0")]
|
2016-08-06 17:48:59 +00:00
|
|
|
#[inline]
|
Add `debug-refcell` feature to libcore
See https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Attaching.20backtraces.20to.20RefCell/near/226273614
for some background discussion
This PR adds a new off-by-default feature `debug-refcell` to libcore.
When enabled, this feature stores additional debugging information in
`RefCell`. This information is included in the panic message when
`borrow()` or `borrow_mut()` panics, to make it easier to track down the
source of the issue.
Currently, we store the caller location for the earliest active borrow.
This has a number of advantages:
* There is only a constant amount of overhead per `RefCell`
* We don't need any heap memory, so it can easily be implemented in core
* Since we are storing the *earliest* active borrow, we don't need any
extra logic in the `Drop` implementation for `Ref` and `RefMut`
Limitations:
* We only store the caller location, not a full `Backtrace`. Until
we get support for `Backtrace` in libcore, this is the best tha we can
do.
* The captured location is only displayed when `borrow()` or
`borrow_mut()` panics. If a crate calls `try_borrow().unwrap()`
or `try_borrow_mut().unwrap()`, this extra information will be lost.
To make testing easier, I've enabled the `debug-refcell` feature by
default. I'm not sure how to write a test for this feature - we would
need to rebuild core from the test framework, and create a separate
sysroot.
Since this feature will be off-by-default, users will need to use
`xargo` or `cargo -Z build-std` to enable this feature. For users using
a prebuilt standard library, this feature will be disabled with zero
overhead.
I've created a simple test program:
```rust
use std::cell::RefCell;
fn main() {
let _ = std::panic::catch_unwind(|| {
let val = RefCell::new(true);
let _first = val.borrow();
let _second = val.borrow();
let _third = val.borrow_mut();
});
let _ = std::panic::catch_unwind(|| {
let val = RefCell::new(true);
let first = val.borrow_mut();
drop(first);
let _second = val.borrow_mut();
let _thid = val.borrow();
});
}
```
which produces the following output:
```
thread 'main' panicked at 'already borrowed: BorrowMutError { location: Location { file: "refcell_test.rs", line: 6, col: 26 } }', refcell_test.rs:8:26
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread 'main' panicked at 'already mutably borrowed: BorrowError { location: Location { file: "refcell_test.rs", line: 16, col: 27 } }', refcell_test.rs:18:25
```
2021-02-18 02:30:39 +00:00
|
|
|
#[cfg_attr(feature = "debug_refcell", track_caller)]
|
2019-04-18 23:37:12 +00:00
|
|
|
pub fn try_borrow(&self) -> Result<Ref<'_, T>, BorrowError> {
|
2015-02-02 02:53:47 +00:00
|
|
|
match BorrowRef::new(&self.borrow) {
|
Add `debug-refcell` feature to libcore
See https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Attaching.20backtraces.20to.20RefCell/near/226273614
for some background discussion
This PR adds a new off-by-default feature `debug-refcell` to libcore.
When enabled, this feature stores additional debugging information in
`RefCell`. This information is included in the panic message when
`borrow()` or `borrow_mut()` panics, to make it easier to track down the
source of the issue.
Currently, we store the caller location for the earliest active borrow.
This has a number of advantages:
* There is only a constant amount of overhead per `RefCell`
* We don't need any heap memory, so it can easily be implemented in core
* Since we are storing the *earliest* active borrow, we don't need any
extra logic in the `Drop` implementation for `Ref` and `RefMut`
Limitations:
* We only store the caller location, not a full `Backtrace`. Until
we get support for `Backtrace` in libcore, this is the best tha we can
do.
* The captured location is only displayed when `borrow()` or
`borrow_mut()` panics. If a crate calls `try_borrow().unwrap()`
or `try_borrow_mut().unwrap()`, this extra information will be lost.
To make testing easier, I've enabled the `debug-refcell` feature by
default. I'm not sure how to write a test for this feature - we would
need to rebuild core from the test framework, and create a separate
sysroot.
Since this feature will be off-by-default, users will need to use
`xargo` or `cargo -Z build-std` to enable this feature. For users using
a prebuilt standard library, this feature will be disabled with zero
overhead.
I've created a simple test program:
```rust
use std::cell::RefCell;
fn main() {
let _ = std::panic::catch_unwind(|| {
let val = RefCell::new(true);
let _first = val.borrow();
let _second = val.borrow();
let _third = val.borrow_mut();
});
let _ = std::panic::catch_unwind(|| {
let val = RefCell::new(true);
let first = val.borrow_mut();
drop(first);
let _second = val.borrow_mut();
let _thid = val.borrow();
});
}
```
which produces the following output:
```
thread 'main' panicked at 'already borrowed: BorrowMutError { location: Location { file: "refcell_test.rs", line: 6, col: 26 } }', refcell_test.rs:8:26
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread 'main' panicked at 'already mutably borrowed: BorrowError { location: Location { file: "refcell_test.rs", line: 16, col: 27 } }', refcell_test.rs:18:25
```
2021-02-18 02:30:39 +00:00
|
|
|
Some(b) => {
|
|
|
|
#[cfg(feature = "debug_refcell")]
|
|
|
|
{
|
|
|
|
// `borrowed_at` is always the *first* active borrow
|
|
|
|
if b.borrow.get() == 1 {
|
|
|
|
self.borrowed_at.set(Some(crate::panic::Location::caller()));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// SAFETY: `BorrowRef` ensures that there is only immutable access
|
|
|
|
// to the value while borrowed.
|
2022-05-13 17:12:32 +00:00
|
|
|
let value = unsafe { NonNull::new_unchecked(self.value.get()) };
|
|
|
|
Ok(Ref { value, borrow: b })
|
Add `debug-refcell` feature to libcore
See https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Attaching.20backtraces.20to.20RefCell/near/226273614
for some background discussion
This PR adds a new off-by-default feature `debug-refcell` to libcore.
When enabled, this feature stores additional debugging information in
`RefCell`. This information is included in the panic message when
`borrow()` or `borrow_mut()` panics, to make it easier to track down the
source of the issue.
Currently, we store the caller location for the earliest active borrow.
This has a number of advantages:
* There is only a constant amount of overhead per `RefCell`
* We don't need any heap memory, so it can easily be implemented in core
* Since we are storing the *earliest* active borrow, we don't need any
extra logic in the `Drop` implementation for `Ref` and `RefMut`
Limitations:
* We only store the caller location, not a full `Backtrace`. Until
we get support for `Backtrace` in libcore, this is the best tha we can
do.
* The captured location is only displayed when `borrow()` or
`borrow_mut()` panics. If a crate calls `try_borrow().unwrap()`
or `try_borrow_mut().unwrap()`, this extra information will be lost.
To make testing easier, I've enabled the `debug-refcell` feature by
default. I'm not sure how to write a test for this feature - we would
need to rebuild core from the test framework, and create a separate
sysroot.
Since this feature will be off-by-default, users will need to use
`xargo` or `cargo -Z build-std` to enable this feature. For users using
a prebuilt standard library, this feature will be disabled with zero
overhead.
I've created a simple test program:
```rust
use std::cell::RefCell;
fn main() {
let _ = std::panic::catch_unwind(|| {
let val = RefCell::new(true);
let _first = val.borrow();
let _second = val.borrow();
let _third = val.borrow_mut();
});
let _ = std::panic::catch_unwind(|| {
let val = RefCell::new(true);
let first = val.borrow_mut();
drop(first);
let _second = val.borrow_mut();
let _thid = val.borrow();
});
}
```
which produces the following output:
```
thread 'main' panicked at 'already borrowed: BorrowMutError { location: Location { file: "refcell_test.rs", line: 6, col: 26 } }', refcell_test.rs:8:26
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread 'main' panicked at 'already mutably borrowed: BorrowError { location: Location { file: "refcell_test.rs", line: 16, col: 27 } }', refcell_test.rs:18:25
```
2021-02-18 02:30:39 +00:00
|
|
|
}
|
|
|
|
None => Err(BorrowError {
|
2021-12-14 14:23:34 +00:00
|
|
|
// If a borrow occurred, then we must already have an outstanding borrow,
|
Add `debug-refcell` feature to libcore
See https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Attaching.20backtraces.20to.20RefCell/near/226273614
for some background discussion
This PR adds a new off-by-default feature `debug-refcell` to libcore.
When enabled, this feature stores additional debugging information in
`RefCell`. This information is included in the panic message when
`borrow()` or `borrow_mut()` panics, to make it easier to track down the
source of the issue.
Currently, we store the caller location for the earliest active borrow.
This has a number of advantages:
* There is only a constant amount of overhead per `RefCell`
* We don't need any heap memory, so it can easily be implemented in core
* Since we are storing the *earliest* active borrow, we don't need any
extra logic in the `Drop` implementation for `Ref` and `RefMut`
Limitations:
* We only store the caller location, not a full `Backtrace`. Until
we get support for `Backtrace` in libcore, this is the best tha we can
do.
* The captured location is only displayed when `borrow()` or
`borrow_mut()` panics. If a crate calls `try_borrow().unwrap()`
or `try_borrow_mut().unwrap()`, this extra information will be lost.
To make testing easier, I've enabled the `debug-refcell` feature by
default. I'm not sure how to write a test for this feature - we would
need to rebuild core from the test framework, and create a separate
sysroot.
Since this feature will be off-by-default, users will need to use
`xargo` or `cargo -Z build-std` to enable this feature. For users using
a prebuilt standard library, this feature will be disabled with zero
overhead.
I've created a simple test program:
```rust
use std::cell::RefCell;
fn main() {
let _ = std::panic::catch_unwind(|| {
let val = RefCell::new(true);
let _first = val.borrow();
let _second = val.borrow();
let _third = val.borrow_mut();
});
let _ = std::panic::catch_unwind(|| {
let val = RefCell::new(true);
let first = val.borrow_mut();
drop(first);
let _second = val.borrow_mut();
let _thid = val.borrow();
});
}
```
which produces the following output:
```
thread 'main' panicked at 'already borrowed: BorrowMutError { location: Location { file: "refcell_test.rs", line: 6, col: 26 } }', refcell_test.rs:8:26
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread 'main' panicked at 'already mutably borrowed: BorrowError { location: Location { file: "refcell_test.rs", line: 16, col: 27 } }', refcell_test.rs:18:25
```
2021-02-18 02:30:39 +00:00
|
|
|
// so `borrowed_at` will be `Some`
|
|
|
|
#[cfg(feature = "debug_refcell")]
|
|
|
|
location: self.borrowed_at.get().unwrap(),
|
|
|
|
}),
|
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
|
|
|
///
|
2014-11-11 18:36:09 +00:00
|
|
|
/// # Panics
|
2013-11-22 05:30:34 +00:00
|
|
|
///
|
2016-08-06 17:48:59 +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;
|
|
|
|
///
|
2020-05-26 08:47:54 +00:00
|
|
|
/// let c = RefCell::new("hello".to_owned());
|
2015-01-23 20:02:05 +00:00
|
|
|
///
|
2020-05-26 08:47:54 +00:00
|
|
|
/// *c.borrow_mut() = "bonjour".to_owned();
|
2016-01-25 22:07:55 +00:00
|
|
|
///
|
2020-05-26 08:47:54 +00:00
|
|
|
/// assert_eq!(&*c.borrow(), "bonjour");
|
2015-01-23 20:02:05 +00:00
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// An example of panic:
|
|
|
|
///
|
2020-06-13 04:06:09 +00:00
|
|
|
/// ```should_panic
|
2015-01-23 20:02:05 +00:00
|
|
|
/// use std::cell::RefCell;
|
|
|
|
///
|
2020-06-13 04:06:09 +00:00
|
|
|
/// let c = RefCell::new(5);
|
|
|
|
/// let m = c.borrow();
|
2015-01-23 20:02:05 +00:00
|
|
|
///
|
2020-06-13 04:06:09 +00:00
|
|
|
/// let b = c.borrow_mut(); // this causes a panic
|
2015-01-23 20:02:05 +00:00
|
|
|
/// ```
|
2015-01-24 05:48:20 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2015-03-18 23:44:37 +00:00
|
|
|
#[inline]
|
2020-07-19 18:07:21 +00:00
|
|
|
#[track_caller]
|
2019-04-18 23:37:12 +00:00
|
|
|
pub fn borrow_mut(&self) -> RefMut<'_, T> {
|
2016-08-06 17:48:59 +00:00
|
|
|
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.
|
2016-08-06 17:48:59 +00:00
|
|
|
///
|
|
|
|
/// 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());
|
|
|
|
/// ```
|
2016-09-29 00:23:36 +00:00
|
|
|
#[stable(feature = "try_borrow", since = "1.13.0")]
|
2016-08-06 17:48:59 +00:00
|
|
|
#[inline]
|
Add `debug-refcell` feature to libcore
See https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Attaching.20backtraces.20to.20RefCell/near/226273614
for some background discussion
This PR adds a new off-by-default feature `debug-refcell` to libcore.
When enabled, this feature stores additional debugging information in
`RefCell`. This information is included in the panic message when
`borrow()` or `borrow_mut()` panics, to make it easier to track down the
source of the issue.
Currently, we store the caller location for the earliest active borrow.
This has a number of advantages:
* There is only a constant amount of overhead per `RefCell`
* We don't need any heap memory, so it can easily be implemented in core
* Since we are storing the *earliest* active borrow, we don't need any
extra logic in the `Drop` implementation for `Ref` and `RefMut`
Limitations:
* We only store the caller location, not a full `Backtrace`. Until
we get support for `Backtrace` in libcore, this is the best tha we can
do.
* The captured location is only displayed when `borrow()` or
`borrow_mut()` panics. If a crate calls `try_borrow().unwrap()`
or `try_borrow_mut().unwrap()`, this extra information will be lost.
To make testing easier, I've enabled the `debug-refcell` feature by
default. I'm not sure how to write a test for this feature - we would
need to rebuild core from the test framework, and create a separate
sysroot.
Since this feature will be off-by-default, users will need to use
`xargo` or `cargo -Z build-std` to enable this feature. For users using
a prebuilt standard library, this feature will be disabled with zero
overhead.
I've created a simple test program:
```rust
use std::cell::RefCell;
fn main() {
let _ = std::panic::catch_unwind(|| {
let val = RefCell::new(true);
let _first = val.borrow();
let _second = val.borrow();
let _third = val.borrow_mut();
});
let _ = std::panic::catch_unwind(|| {
let val = RefCell::new(true);
let first = val.borrow_mut();
drop(first);
let _second = val.borrow_mut();
let _thid = val.borrow();
});
}
```
which produces the following output:
```
thread 'main' panicked at 'already borrowed: BorrowMutError { location: Location { file: "refcell_test.rs", line: 6, col: 26 } }', refcell_test.rs:8:26
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread 'main' panicked at 'already mutably borrowed: BorrowError { location: Location { file: "refcell_test.rs", line: 16, col: 27 } }', refcell_test.rs:18:25
```
2021-02-18 02:30:39 +00:00
|
|
|
#[cfg_attr(feature = "debug_refcell", track_caller)]
|
2019-04-18 23:37:12 +00:00
|
|
|
pub fn try_borrow_mut(&self) -> Result<RefMut<'_, T>, BorrowMutError> {
|
2015-02-02 02:53:47 +00:00
|
|
|
match BorrowRefMut::new(&self.borrow) {
|
Add `debug-refcell` feature to libcore
See https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Attaching.20backtraces.20to.20RefCell/near/226273614
for some background discussion
This PR adds a new off-by-default feature `debug-refcell` to libcore.
When enabled, this feature stores additional debugging information in
`RefCell`. This information is included in the panic message when
`borrow()` or `borrow_mut()` panics, to make it easier to track down the
source of the issue.
Currently, we store the caller location for the earliest active borrow.
This has a number of advantages:
* There is only a constant amount of overhead per `RefCell`
* We don't need any heap memory, so it can easily be implemented in core
* Since we are storing the *earliest* active borrow, we don't need any
extra logic in the `Drop` implementation for `Ref` and `RefMut`
Limitations:
* We only store the caller location, not a full `Backtrace`. Until
we get support for `Backtrace` in libcore, this is the best tha we can
do.
* The captured location is only displayed when `borrow()` or
`borrow_mut()` panics. If a crate calls `try_borrow().unwrap()`
or `try_borrow_mut().unwrap()`, this extra information will be lost.
To make testing easier, I've enabled the `debug-refcell` feature by
default. I'm not sure how to write a test for this feature - we would
need to rebuild core from the test framework, and create a separate
sysroot.
Since this feature will be off-by-default, users will need to use
`xargo` or `cargo -Z build-std` to enable this feature. For users using
a prebuilt standard library, this feature will be disabled with zero
overhead.
I've created a simple test program:
```rust
use std::cell::RefCell;
fn main() {
let _ = std::panic::catch_unwind(|| {
let val = RefCell::new(true);
let _first = val.borrow();
let _second = val.borrow();
let _third = val.borrow_mut();
});
let _ = std::panic::catch_unwind(|| {
let val = RefCell::new(true);
let first = val.borrow_mut();
drop(first);
let _second = val.borrow_mut();
let _thid = val.borrow();
});
}
```
which produces the following output:
```
thread 'main' panicked at 'already borrowed: BorrowMutError { location: Location { file: "refcell_test.rs", line: 6, col: 26 } }', refcell_test.rs:8:26
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread 'main' panicked at 'already mutably borrowed: BorrowError { location: Location { file: "refcell_test.rs", line: 16, col: 27 } }', refcell_test.rs:18:25
```
2021-02-18 02:30:39 +00:00
|
|
|
Some(b) => {
|
|
|
|
#[cfg(feature = "debug_refcell")]
|
|
|
|
{
|
|
|
|
self.borrowed_at.set(Some(crate::panic::Location::caller()));
|
|
|
|
}
|
|
|
|
|
2022-05-13 17:46:00 +00:00
|
|
|
// SAFETY: `BorrowRefMut` guarantees unique access.
|
|
|
|
let value = unsafe { NonNull::new_unchecked(self.value.get()) };
|
|
|
|
Ok(RefMut { value, borrow: b, marker: PhantomData })
|
Add `debug-refcell` feature to libcore
See https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Attaching.20backtraces.20to.20RefCell/near/226273614
for some background discussion
This PR adds a new off-by-default feature `debug-refcell` to libcore.
When enabled, this feature stores additional debugging information in
`RefCell`. This information is included in the panic message when
`borrow()` or `borrow_mut()` panics, to make it easier to track down the
source of the issue.
Currently, we store the caller location for the earliest active borrow.
This has a number of advantages:
* There is only a constant amount of overhead per `RefCell`
* We don't need any heap memory, so it can easily be implemented in core
* Since we are storing the *earliest* active borrow, we don't need any
extra logic in the `Drop` implementation for `Ref` and `RefMut`
Limitations:
* We only store the caller location, not a full `Backtrace`. Until
we get support for `Backtrace` in libcore, this is the best tha we can
do.
* The captured location is only displayed when `borrow()` or
`borrow_mut()` panics. If a crate calls `try_borrow().unwrap()`
or `try_borrow_mut().unwrap()`, this extra information will be lost.
To make testing easier, I've enabled the `debug-refcell` feature by
default. I'm not sure how to write a test for this feature - we would
need to rebuild core from the test framework, and create a separate
sysroot.
Since this feature will be off-by-default, users will need to use
`xargo` or `cargo -Z build-std` to enable this feature. For users using
a prebuilt standard library, this feature will be disabled with zero
overhead.
I've created a simple test program:
```rust
use std::cell::RefCell;
fn main() {
let _ = std::panic::catch_unwind(|| {
let val = RefCell::new(true);
let _first = val.borrow();
let _second = val.borrow();
let _third = val.borrow_mut();
});
let _ = std::panic::catch_unwind(|| {
let val = RefCell::new(true);
let first = val.borrow_mut();
drop(first);
let _second = val.borrow_mut();
let _thid = val.borrow();
});
}
```
which produces the following output:
```
thread 'main' panicked at 'already borrowed: BorrowMutError { location: Location { file: "refcell_test.rs", line: 6, col: 26 } }', refcell_test.rs:8:26
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread 'main' panicked at 'already mutably borrowed: BorrowError { location: Location { file: "refcell_test.rs", line: 16, col: 27 } }', refcell_test.rs:18:25
```
2021-02-18 02:30:39 +00:00
|
|
|
}
|
|
|
|
None => Err(BorrowMutError {
|
2021-12-14 14:23:34 +00:00
|
|
|
// If a borrow occurred, then we must already have an outstanding borrow,
|
Add `debug-refcell` feature to libcore
See https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Attaching.20backtraces.20to.20RefCell/near/226273614
for some background discussion
This PR adds a new off-by-default feature `debug-refcell` to libcore.
When enabled, this feature stores additional debugging information in
`RefCell`. This information is included in the panic message when
`borrow()` or `borrow_mut()` panics, to make it easier to track down the
source of the issue.
Currently, we store the caller location for the earliest active borrow.
This has a number of advantages:
* There is only a constant amount of overhead per `RefCell`
* We don't need any heap memory, so it can easily be implemented in core
* Since we are storing the *earliest* active borrow, we don't need any
extra logic in the `Drop` implementation for `Ref` and `RefMut`
Limitations:
* We only store the caller location, not a full `Backtrace`. Until
we get support for `Backtrace` in libcore, this is the best tha we can
do.
* The captured location is only displayed when `borrow()` or
`borrow_mut()` panics. If a crate calls `try_borrow().unwrap()`
or `try_borrow_mut().unwrap()`, this extra information will be lost.
To make testing easier, I've enabled the `debug-refcell` feature by
default. I'm not sure how to write a test for this feature - we would
need to rebuild core from the test framework, and create a separate
sysroot.
Since this feature will be off-by-default, users will need to use
`xargo` or `cargo -Z build-std` to enable this feature. For users using
a prebuilt standard library, this feature will be disabled with zero
overhead.
I've created a simple test program:
```rust
use std::cell::RefCell;
fn main() {
let _ = std::panic::catch_unwind(|| {
let val = RefCell::new(true);
let _first = val.borrow();
let _second = val.borrow();
let _third = val.borrow_mut();
});
let _ = std::panic::catch_unwind(|| {
let val = RefCell::new(true);
let first = val.borrow_mut();
drop(first);
let _second = val.borrow_mut();
let _thid = val.borrow();
});
}
```
which produces the following output:
```
thread 'main' panicked at 'already borrowed: BorrowMutError { location: Location { file: "refcell_test.rs", line: 6, col: 26 } }', refcell_test.rs:8:26
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread 'main' panicked at 'already mutably borrowed: BorrowError { location: Location { file: "refcell_test.rs", line: 16, col: 27 } }', refcell_test.rs:18:25
```
2021-02-18 02:30:39 +00:00
|
|
|
// so `borrowed_at` will be `Some`
|
|
|
|
#[cfg(feature = "debug_refcell")]
|
|
|
|
location: self.borrowed_at.get().unwrap(),
|
|
|
|
}),
|
2013-11-22 05:30:34 +00:00
|
|
|
}
|
|
|
|
}
|
2014-10-21 19:59:21 +00:00
|
|
|
|
2016-08-11 21:08:24 +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()
|
|
|
|
}
|
|
|
|
|
2016-05-05 22:39:25 +00:00
|
|
|
/// Returns a mutable reference to the underlying data.
|
|
|
|
///
|
2022-09-03 19:48:17 +00:00
|
|
|
/// Since this method borrows `RefCell` mutably, it is statically guaranteed
|
|
|
|
/// that no borrows to the underlying data exist. The dynamic checks inherent
|
2022-11-25 07:47:59 +00:00
|
|
|
/// in [`borrow_mut`] and most other methods of `RefCell` are therefore
|
2022-09-03 19:48:17 +00:00
|
|
|
/// unnecessary.
|
|
|
|
///
|
|
|
|
/// This method can only be called if `RefCell` can be mutably borrowed,
|
|
|
|
/// which in general is only the case directly after the `RefCell` has
|
|
|
|
/// been created. In these situations, skipping the aforementioned dynamic
|
|
|
|
/// borrowing checks may yield better ergonomics and runtime-performance.
|
|
|
|
///
|
|
|
|
/// In most situations where `RefCell` is used, it can't be borrowed mutably.
|
|
|
|
/// Use [`borrow_mut`] to get mutable access to the underlying data then.
|
2017-03-18 14:33:56 +00:00
|
|
|
///
|
2020-11-30 20:21:15 +00:00
|
|
|
/// [`borrow_mut`]: RefCell::borrow_mut()
|
2017-03-18 14:33:56 +00:00
|
|
|
///
|
2016-07-09 13:01:15 +00:00
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use std::cell::RefCell;
|
|
|
|
///
|
|
|
|
/// let mut c = RefCell::new(5);
|
|
|
|
/// *c.get_mut() += 1;
|
|
|
|
///
|
|
|
|
/// assert_eq!(c, RefCell::new(6));
|
|
|
|
/// ```
|
2016-05-05 22:39:25 +00:00
|
|
|
#[inline]
|
2016-06-28 15:56:56 +00:00
|
|
|
#[stable(feature = "cell_get_mut", since = "1.11.0")]
|
2016-05-05 22:39:25 +00:00
|
|
|
pub fn get_mut(&mut self) -> &mut T {
|
2020-09-19 19:33:40 +00:00
|
|
|
self.value.get_mut()
|
2016-05-05 22:39:25 +00:00
|
|
|
}
|
2019-03-19 11:24:38 +00:00
|
|
|
|
2020-02-27 20:24:14 +00:00
|
|
|
/// Undo the effect of leaked guards on the borrow state of the `RefCell`.
|
|
|
|
///
|
|
|
|
/// This call is similar to [`get_mut`] but more specialized. It borrows `RefCell` mutably to
|
|
|
|
/// ensure no borrows exist and then resets the state tracking shared borrows. This is relevant
|
|
|
|
/// if some `Ref` or `RefMut` borrows have been leaked.
|
|
|
|
///
|
2020-11-30 20:21:15 +00:00
|
|
|
/// [`get_mut`]: RefCell::get_mut()
|
2020-02-27 20:24:14 +00:00
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// #![feature(cell_leak)]
|
|
|
|
/// use std::cell::RefCell;
|
|
|
|
///
|
|
|
|
/// let mut c = RefCell::new(0);
|
|
|
|
/// std::mem::forget(c.borrow_mut());
|
|
|
|
///
|
|
|
|
/// assert!(c.try_borrow().is_err());
|
|
|
|
/// c.undo_leak();
|
|
|
|
/// assert!(c.try_borrow().is_ok());
|
|
|
|
/// ```
|
|
|
|
#[unstable(feature = "cell_leak", issue = "69099")]
|
|
|
|
pub fn undo_leak(&mut self) -> &mut T {
|
|
|
|
*self.borrow.get_mut() = UNUSED;
|
|
|
|
self.get_mut()
|
|
|
|
}
|
|
|
|
|
2019-03-19 11:24:38 +00:00
|
|
|
/// 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());
|
|
|
|
/// }
|
|
|
|
/// ```
|
2019-05-15 09:54:16 +00:00
|
|
|
#[stable(feature = "borrow_state", since = "1.37.0")]
|
2019-03-19 11:24:38 +00:00
|
|
|
#[inline]
|
|
|
|
pub unsafe fn try_borrow_unguarded(&self) -> Result<&T, BorrowError> {
|
|
|
|
if !is_writing(self.borrow.get()) {
|
2020-06-21 22:54:46 +00:00
|
|
|
// SAFETY: We check that nobody is actively writing now, but it is
|
|
|
|
// the caller's responsibility to ensure that nobody writes until
|
|
|
|
// the returned reference is no longer in use.
|
|
|
|
// Also, `self.value.get()` refers to the value owned by `self`
|
|
|
|
// and is thus guaranteed to be valid for the lifetime of `self`.
|
|
|
|
Ok(unsafe { &*self.value.get() })
|
2019-03-19 11:24:38 +00:00
|
|
|
} else {
|
Add `debug-refcell` feature to libcore
See https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Attaching.20backtraces.20to.20RefCell/near/226273614
for some background discussion
This PR adds a new off-by-default feature `debug-refcell` to libcore.
When enabled, this feature stores additional debugging information in
`RefCell`. This information is included in the panic message when
`borrow()` or `borrow_mut()` panics, to make it easier to track down the
source of the issue.
Currently, we store the caller location for the earliest active borrow.
This has a number of advantages:
* There is only a constant amount of overhead per `RefCell`
* We don't need any heap memory, so it can easily be implemented in core
* Since we are storing the *earliest* active borrow, we don't need any
extra logic in the `Drop` implementation for `Ref` and `RefMut`
Limitations:
* We only store the caller location, not a full `Backtrace`. Until
we get support for `Backtrace` in libcore, this is the best tha we can
do.
* The captured location is only displayed when `borrow()` or
`borrow_mut()` panics. If a crate calls `try_borrow().unwrap()`
or `try_borrow_mut().unwrap()`, this extra information will be lost.
To make testing easier, I've enabled the `debug-refcell` feature by
default. I'm not sure how to write a test for this feature - we would
need to rebuild core from the test framework, and create a separate
sysroot.
Since this feature will be off-by-default, users will need to use
`xargo` or `cargo -Z build-std` to enable this feature. For users using
a prebuilt standard library, this feature will be disabled with zero
overhead.
I've created a simple test program:
```rust
use std::cell::RefCell;
fn main() {
let _ = std::panic::catch_unwind(|| {
let val = RefCell::new(true);
let _first = val.borrow();
let _second = val.borrow();
let _third = val.borrow_mut();
});
let _ = std::panic::catch_unwind(|| {
let val = RefCell::new(true);
let first = val.borrow_mut();
drop(first);
let _second = val.borrow_mut();
let _thid = val.borrow();
});
}
```
which produces the following output:
```
thread 'main' panicked at 'already borrowed: BorrowMutError { location: Location { file: "refcell_test.rs", line: 6, col: 26 } }', refcell_test.rs:8:26
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread 'main' panicked at 'already mutably borrowed: BorrowError { location: Location { file: "refcell_test.rs", line: 16, col: 27 } }', refcell_test.rs:18:25
```
2021-02-18 02:30:39 +00:00
|
|
|
Err(BorrowError {
|
2021-12-14 14:23:34 +00:00
|
|
|
// If a borrow occurred, then we must already have an outstanding borrow,
|
Add `debug-refcell` feature to libcore
See https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Attaching.20backtraces.20to.20RefCell/near/226273614
for some background discussion
This PR adds a new off-by-default feature `debug-refcell` to libcore.
When enabled, this feature stores additional debugging information in
`RefCell`. This information is included in the panic message when
`borrow()` or `borrow_mut()` panics, to make it easier to track down the
source of the issue.
Currently, we store the caller location for the earliest active borrow.
This has a number of advantages:
* There is only a constant amount of overhead per `RefCell`
* We don't need any heap memory, so it can easily be implemented in core
* Since we are storing the *earliest* active borrow, we don't need any
extra logic in the `Drop` implementation for `Ref` and `RefMut`
Limitations:
* We only store the caller location, not a full `Backtrace`. Until
we get support for `Backtrace` in libcore, this is the best tha we can
do.
* The captured location is only displayed when `borrow()` or
`borrow_mut()` panics. If a crate calls `try_borrow().unwrap()`
or `try_borrow_mut().unwrap()`, this extra information will be lost.
To make testing easier, I've enabled the `debug-refcell` feature by
default. I'm not sure how to write a test for this feature - we would
need to rebuild core from the test framework, and create a separate
sysroot.
Since this feature will be off-by-default, users will need to use
`xargo` or `cargo -Z build-std` to enable this feature. For users using
a prebuilt standard library, this feature will be disabled with zero
overhead.
I've created a simple test program:
```rust
use std::cell::RefCell;
fn main() {
let _ = std::panic::catch_unwind(|| {
let val = RefCell::new(true);
let _first = val.borrow();
let _second = val.borrow();
let _third = val.borrow_mut();
});
let _ = std::panic::catch_unwind(|| {
let val = RefCell::new(true);
let first = val.borrow_mut();
drop(first);
let _second = val.borrow_mut();
let _thid = val.borrow();
});
}
```
which produces the following output:
```
thread 'main' panicked at 'already borrowed: BorrowMutError { location: Location { file: "refcell_test.rs", line: 6, col: 26 } }', refcell_test.rs:8:26
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread 'main' panicked at 'already mutably borrowed: BorrowError { location: Location { file: "refcell_test.rs", line: 16, col: 27 } }', refcell_test.rs:18:25
```
2021-02-18 02:30:39 +00:00
|
|
|
// so `borrowed_at` will be `Some`
|
|
|
|
#[cfg(feature = "debug_refcell")]
|
|
|
|
location: self.borrowed_at.get().unwrap(),
|
|
|
|
})
|
2019-03-19 11:24:38 +00:00
|
|
|
}
|
|
|
|
}
|
2013-12-11 22:54:27 +00:00
|
|
|
}
|
|
|
|
|
2020-04-21 18:03:50 +00:00
|
|
|
impl<T: Default> RefCell<T> {
|
|
|
|
/// Takes the wrapped value, leaving `Default::default()` in its place.
|
|
|
|
///
|
2020-05-03 10:52:23 +00:00
|
|
|
/// # Panics
|
|
|
|
///
|
|
|
|
/// Panics if the value is currently borrowed.
|
|
|
|
///
|
2020-04-21 18:03:50 +00:00
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use std::cell::RefCell;
|
|
|
|
///
|
|
|
|
/// let c = RefCell::new(5);
|
|
|
|
/// let five = c.take();
|
|
|
|
///
|
|
|
|
/// assert_eq!(five, 5);
|
|
|
|
/// assert_eq!(c.into_inner(), 0);
|
|
|
|
/// ```
|
2020-10-31 18:06:25 +00:00
|
|
|
#[stable(feature = "refcell_take", since = "1.50.0")]
|
2020-04-21 18:03:50 +00:00
|
|
|
pub fn take(&self) -> T {
|
|
|
|
self.replace(Default::default())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-01-24 05:48:20 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2015-04-23 10:53:54 +00:00
|
|
|
unsafe impl<T: ?Sized> Send for RefCell<T> where T: Send {}
|
2014-12-29 18:58:22 +00:00
|
|
|
|
2016-03-01 03:03:23 +00:00
|
|
|
#[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> {
|
2018-02-20 04:52:26 +00:00
|
|
|
/// # Panics
|
|
|
|
///
|
|
|
|
/// Panics if the value is currently mutably borrowed.
|
2015-03-18 23:44:37 +00:00
|
|
|
#[inline]
|
2020-09-22 13:30:09 +00:00
|
|
|
#[track_caller]
|
2013-11-22 05:30:34 +00:00
|
|
|
fn clone(&self) -> RefCell<T> {
|
2014-03-28 17:29:55 +00:00
|
|
|
RefCell::new(self.borrow().clone())
|
2013-11-22 05:30:34 +00:00
|
|
|
}
|
2021-05-11 11:00:34 +00:00
|
|
|
|
|
|
|
/// # Panics
|
|
|
|
///
|
|
|
|
/// Panics if `other` is currently mutably borrowed.
|
|
|
|
#[inline]
|
|
|
|
#[track_caller]
|
|
|
|
fn clone_from(&mut self, other: &Self) {
|
|
|
|
self.get_mut().clone_from(&other.borrow())
|
|
|
|
}
|
2013-11-22 05:30:34 +00:00
|
|
|
}
|
|
|
|
|
2015-01-24 05:48:20 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2019-07-13 15:15:16 +00:00
|
|
|
impl<T: Default> Default for RefCell<T> {
|
2016-09-11 11:30:09 +00:00
|
|
|
/// Creates a `RefCell<T>`, with the `Default` value for T.
|
2015-03-18 23:44:37 +00:00
|
|
|
#[inline]
|
2014-11-14 19:22:42 +00:00
|
|
|
fn default() -> RefCell<T> {
|
|
|
|
RefCell::new(Default::default())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-01-24 05:48:20 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2015-04-23 10:53:54 +00:00
|
|
|
impl<T: ?Sized + PartialEq> PartialEq for RefCell<T> {
|
2018-02-20 04:52:26 +00:00
|
|
|
/// # Panics
|
|
|
|
///
|
2022-11-02 13:38:15 +00:00
|
|
|
/// Panics if the value in either `RefCell` is currently mutably borrowed.
|
2015-03-18 23:44:37 +00:00
|
|
|
#[inline]
|
2013-11-22 05:30:34 +00:00
|
|
|
fn eq(&self, other: &RefCell<T>) -> bool {
|
2014-03-20 22:04:55 +00:00
|
|
|
*self.borrow() == *other.borrow()
|
2013-11-22 05:30:34 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-05-24 08:38:59 +00:00
|
|
|
#[stable(feature = "cell_eq", since = "1.2.0")]
|
|
|
|
impl<T: ?Sized + Eq> Eq for RefCell<T> {}
|
|
|
|
|
2016-05-01 08:26:39 +00:00
|
|
|
#[stable(feature = "cell_ord", since = "1.10.0")]
|
2016-05-01 08:07:47 +00:00
|
|
|
impl<T: ?Sized + PartialOrd> PartialOrd for RefCell<T> {
|
2018-02-20 04:52:26 +00:00
|
|
|
/// # Panics
|
|
|
|
///
|
2022-11-02 13:38:15 +00:00
|
|
|
/// Panics if the value in either `RefCell` is currently mutably borrowed.
|
2016-05-01 08:07:47 +00:00
|
|
|
#[inline]
|
|
|
|
fn partial_cmp(&self, other: &RefCell<T>) -> Option<Ordering> {
|
|
|
|
self.borrow().partial_cmp(&*other.borrow())
|
|
|
|
}
|
|
|
|
|
2018-02-20 04:52:26 +00:00
|
|
|
/// # Panics
|
|
|
|
///
|
2022-11-02 13:38:15 +00:00
|
|
|
/// Panics if the value in either `RefCell` is currently mutably borrowed.
|
2016-05-01 08:07:47 +00:00
|
|
|
#[inline]
|
|
|
|
fn lt(&self, other: &RefCell<T>) -> bool {
|
|
|
|
*self.borrow() < *other.borrow()
|
|
|
|
}
|
|
|
|
|
2018-02-20 04:52:26 +00:00
|
|
|
/// # Panics
|
|
|
|
///
|
2022-11-02 13:38:15 +00:00
|
|
|
/// Panics if the value in either `RefCell` is currently mutably borrowed.
|
2016-05-01 08:07:47 +00:00
|
|
|
#[inline]
|
|
|
|
fn le(&self, other: &RefCell<T>) -> bool {
|
|
|
|
*self.borrow() <= *other.borrow()
|
|
|
|
}
|
|
|
|
|
2018-02-20 04:52:26 +00:00
|
|
|
/// # Panics
|
|
|
|
///
|
2022-11-02 13:38:15 +00:00
|
|
|
/// Panics if the value in either `RefCell` is currently mutably borrowed.
|
2016-05-01 08:07:47 +00:00
|
|
|
#[inline]
|
|
|
|
fn gt(&self, other: &RefCell<T>) -> bool {
|
|
|
|
*self.borrow() > *other.borrow()
|
|
|
|
}
|
|
|
|
|
2018-02-20 04:52:26 +00:00
|
|
|
/// # Panics
|
|
|
|
///
|
2022-11-02 13:38:15 +00:00
|
|
|
/// Panics if the value in either `RefCell` is currently mutably borrowed.
|
2016-05-01 08:07:47 +00:00
|
|
|
#[inline]
|
|
|
|
fn ge(&self, other: &RefCell<T>) -> bool {
|
|
|
|
*self.borrow() >= *other.borrow()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-05-01 08:26:39 +00:00
|
|
|
#[stable(feature = "cell_ord", since = "1.10.0")]
|
2016-05-01 08:07:47 +00:00
|
|
|
impl<T: ?Sized + Ord> Ord for RefCell<T> {
|
2018-02-20 04:52:26 +00:00
|
|
|
/// # Panics
|
|
|
|
///
|
2022-11-02 13:38:15 +00:00
|
|
|
/// Panics if the value in either `RefCell` is currently mutably borrowed.
|
2016-05-01 08:07:47 +00:00
|
|
|
#[inline]
|
|
|
|
fn cmp(&self, other: &RefCell<T>) -> Ordering {
|
|
|
|
self.borrow().cmp(&*other.borrow())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-08-05 19:57:19 +00:00
|
|
|
#[stable(feature = "cell_from", since = "1.12.0")]
|
2021-10-18 10:19:28 +00:00
|
|
|
#[rustc_const_unstable(feature = "const_convert", issue = "88674")]
|
|
|
|
impl<T> const From<T> for RefCell<T> {
|
2021-10-13 15:46:34 +00:00
|
|
|
/// Creates a new `RefCell<T>` containing the given value.
|
2016-08-05 19:57:19 +00:00
|
|
|
fn from(t: T) -> RefCell<T> {
|
|
|
|
RefCell::new(t)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-12-20 07:08:38 +00:00
|
|
|
#[unstable(feature = "coerce_unsized", issue = "18598")]
|
2016-08-12 22:10:34 +00:00
|
|
|
impl<T: CoerceUnsized<U>, U> CoerceUnsized<RefCell<U>> for RefCell<T> {}
|
|
|
|
|
2014-11-29 00:20:14 +00:00
|
|
|
struct BorrowRef<'b> {
|
2016-04-05 09:02:49 +00:00
|
|
|
borrow: &'b Cell<BorrowFlag>,
|
2014-11-29 00:20:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl<'b> BorrowRef<'b> {
|
2015-03-18 23:44:37 +00:00
|
|
|
#[inline]
|
2014-11-29 00:20:14 +00:00
|
|
|
fn new(borrow: &'b Cell<BorrowFlag>) -> Option<BorrowRef<'b>> {
|
2019-07-17 11:25:34 +00:00
|
|
|
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
|
2020-06-02 07:59:11 +00:00
|
|
|
// 2. It was isize::MAX (the max amount of reading borrows) and it overflowed
|
|
|
|
// into isize::MIN (the max amount of writing borrows) so we can't allow
|
2019-07-21 09:49:36 +00:00
|
|
|
// 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
|
2020-06-02 07:59:11 +00:00
|
|
|
// 2. It was > 0 and < isize::MAX, i.e. there were read borrows, and isize
|
2019-07-21 09:49:36 +00:00
|
|
|
// is large enough to represent having one more read borrow
|
2019-07-17 11:25:34 +00:00
|
|
|
borrow.set(b);
|
2018-06-10 05:32:05 +00:00
|
|
|
Some(BorrowRef { borrow })
|
2014-11-29 00:20:14 +00:00
|
|
|
}
|
|
|
|
}
|
2014-08-28 01:46:52 +00:00
|
|
|
}
|
|
|
|
|
2018-09-03 11:50:14 +00:00
|
|
|
impl Drop for BorrowRef<'_> {
|
2015-03-18 23:44:37 +00:00
|
|
|
#[inline]
|
2013-11-22 05:30:34 +00:00
|
|
|
fn drop(&mut self) {
|
2016-04-05 09:02:49 +00:00
|
|
|
let borrow = self.borrow.get();
|
2018-06-27 07:07:18 +00:00
|
|
|
debug_assert!(is_reading(borrow));
|
2016-04-05 09:02:49 +00:00
|
|
|
self.borrow.set(borrow - 1);
|
2013-11-22 05:30:34 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-09-03 11:50:14 +00:00
|
|
|
impl Clone for BorrowRef<'_> {
|
2015-03-18 23:44:37 +00:00
|
|
|
#[inline]
|
2018-09-03 11:50:14 +00:00
|
|
|
fn clone(&self) -> Self {
|
2014-11-29 00:20:14 +00:00
|
|
|
// Since this Ref exists, we know the borrow flag
|
2018-06-27 07:07:18 +00:00
|
|
|
// is a reading borrow.
|
2016-04-05 09:02:49 +00:00
|
|
|
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.
|
2020-06-02 07:59:11 +00:00
|
|
|
assert!(borrow != isize::MAX);
|
2016-04-05 09:02:49 +00:00
|
|
|
self.borrow.set(borrow + 1);
|
|
|
|
BorrowRef { borrow: self.borrow }
|
2014-11-29 00:20:14 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// 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>`.
|
|
|
|
///
|
2020-10-12 20:42:49 +00:00
|
|
|
/// See the [module-level documentation](self) for more.
|
2015-01-24 05:48:20 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2022-01-14 08:50:49 +00:00
|
|
|
#[must_not_suspend = "holding a Ref across suspend points can cause BorrowErrors"]
|
2015-04-23 10:53:54 +00:00
|
|
|
pub struct Ref<'b, T: ?Sized + 'b> {
|
2022-05-13 17:12:32 +00:00
|
|
|
// NB: we use a pointer instead of `&'b T` to avoid `noalias` violations, because a
|
|
|
|
// `Ref` argument doesn't hold immutability for its whole scope, only until it drops.
|
2022-05-17 00:24:53 +00:00
|
|
|
// `NonNull` is also covariant over `T`, just like we would have with `&T`.
|
2022-05-13 17:12:32 +00:00
|
|
|
value: NonNull<T>,
|
2016-04-05 09:02:49 +00:00
|
|
|
borrow: BorrowRef<'b>,
|
2014-11-29 00:20:14 +00:00
|
|
|
}
|
|
|
|
|
2015-01-24 05:48:20 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2018-09-03 11:50:14 +00:00
|
|
|
impl<T: ?Sized> Deref for Ref<'_, T> {
|
2015-01-01 19:53:20 +00:00
|
|
|
type Target = T;
|
|
|
|
|
2014-02-26 21:07:23 +00:00
|
|
|
#[inline]
|
2015-09-03 09:49:08 +00:00
|
|
|
fn deref(&self) -> &T {
|
2022-05-13 17:12:32 +00:00
|
|
|
// SAFETY: the value is accessible as long as we hold our borrow.
|
|
|
|
unsafe { self.value.as_ref() }
|
2014-02-26 21:07:23 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-05-28 20:58:04 +00:00
|
|
|
impl<'b, T: ?Sized> Ref<'b, T> {
|
|
|
|
/// Copies a `Ref`.
|
|
|
|
///
|
|
|
|
/// The `RefCell` is already immutably borrowed, so this cannot fail.
|
|
|
|
///
|
2015-06-09 18:18:03 +00:00
|
|
|
/// 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
|
2015-06-09 18:18:03 +00:00
|
|
|
/// 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")]
|
2021-10-14 22:54:55 +00:00
|
|
|
#[must_use]
|
2015-05-28 20:58:04 +00:00
|
|
|
#[inline]
|
|
|
|
pub fn clone(orig: &Ref<'b, T>) -> Ref<'b, T> {
|
2016-04-05 09:02:49 +00:00
|
|
|
Ref { value: orig.value, borrow: orig.borrow.clone() }
|
2014-05-14 00:29:30 +00:00
|
|
|
}
|
2015-05-28 21:00:52 +00:00
|
|
|
|
2019-02-09 22:16:58 +00:00
|
|
|
/// Makes a new `Ref` for a component of the borrowed data.
|
2015-05-28 21:00:52 +00:00
|
|
|
///
|
|
|
|
/// The `RefCell` is already immutably borrowed, so this cannot fail.
|
|
|
|
///
|
|
|
|
/// This is an associated function that needs to be used as `Ref::map(...)`.
|
2015-06-09 18:18:03 +00:00
|
|
|
/// A method would interfere with methods of the same name on the contents
|
|
|
|
/// of a `RefCell` used through `Deref`.
|
2015-05-28 21:00:52 +00:00
|
|
|
///
|
2017-08-24 15:33:36 +00:00
|
|
|
/// # Examples
|
2015-05-28 21:00:52 +00:00
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// 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)
|
|
|
|
/// ```
|
std: Stabilize APIs for the 1.8 release
This commit is the result of the FCPs ending for the 1.8 release cycle for both
the libs and the lang suteams. The full list of changes are:
Stabilized
* `braced_empty_structs`
* `augmented_assignments`
* `str::encode_utf16` - renamed from `utf16_units`
* `str::EncodeUtf16` - renamed from `Utf16Units`
* `Ref::map`
* `RefMut::map`
* `ptr::drop_in_place`
* `time::Instant`
* `time::SystemTime`
* `{Instant,SystemTime}::now`
* `{Instant,SystemTime}::duration_since` - renamed from `duration_from_earlier`
* `{Instant,SystemTime}::elapsed`
* Various `Add`/`Sub` impls for `Time` and `SystemTime`
* `SystemTimeError`
* `SystemTimeError::duration`
* Various impls for `SystemTimeError`
* `UNIX_EPOCH`
* `ops::{Add,Sub,Mul,Div,Rem,BitAnd,BitOr,BitXor,Shl,Shr}Assign`
Deprecated
* Scoped TLS (the `scoped_thread_local!` macro)
* `Ref::filter_map`
* `RefMut::filter_map`
* `RwLockReadGuard::map`
* `RwLockWriteGuard::map`
* `Condvar::wait_timeout_with`
Closes #27714
Closes #27715
Closes #27746
Closes #27748
Closes #27908
Closes #29866
2016-02-25 23:52:29 +00:00
|
|
|
#[stable(feature = "cell_map", since = "1.8.0")]
|
2015-05-28 21:00:52 +00:00
|
|
|
#[inline]
|
|
|
|
pub fn map<U: ?Sized, F>(orig: Ref<'b, T>, f: F) -> Ref<'b, U>
|
|
|
|
where
|
|
|
|
F: FnOnce(&T) -> &U,
|
|
|
|
{
|
2022-05-13 17:12:32 +00:00
|
|
|
Ref { value: NonNull::from(f(&*orig)), borrow: orig.borrow }
|
2015-05-28 21:00:52 +00:00
|
|
|
}
|
2018-06-10 05:32:05 +00:00
|
|
|
|
2020-12-17 00:46:06 +00:00
|
|
|
/// Makes a new `Ref` for an optional component of the borrowed data. The
|
|
|
|
/// original guard is returned as an `Err(..)` if the closure returns
|
|
|
|
/// `None`.
|
2020-10-27 23:15:36 +00:00
|
|
|
///
|
|
|
|
/// The `RefCell` is already immutably borrowed, so this cannot fail.
|
|
|
|
///
|
|
|
|
/// This is an associated function that needs to be used as
|
2020-12-17 00:46:06 +00:00
|
|
|
/// `Ref::filter_map(...)`. A method would interfere with methods of the same
|
2020-10-27 23:15:36 +00:00
|
|
|
/// name on the contents of a `RefCell` used through `Deref`.
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use std::cell::{RefCell, Ref};
|
|
|
|
///
|
|
|
|
/// let c = RefCell::new(vec![1, 2, 3]);
|
|
|
|
/// let b1: Ref<Vec<u32>> = c.borrow();
|
2020-12-17 00:46:06 +00:00
|
|
|
/// let b2: Result<Ref<u32>, _> = Ref::filter_map(b1, |v| v.get(1));
|
|
|
|
/// assert_eq!(*b2.unwrap(), 2);
|
2020-10-27 23:15:36 +00:00
|
|
|
/// ```
|
2022-05-23 09:04:53 +00:00
|
|
|
#[stable(feature = "cell_filter_map", since = "1.63.0")]
|
2020-10-27 23:15:36 +00:00
|
|
|
#[inline]
|
2020-12-17 00:46:06 +00:00
|
|
|
pub fn filter_map<U: ?Sized, F>(orig: Ref<'b, T>, f: F) -> Result<Ref<'b, U>, Self>
|
2020-10-27 23:15:36 +00:00
|
|
|
where
|
|
|
|
F: FnOnce(&T) -> Option<&U>,
|
|
|
|
{
|
2022-05-13 17:12:32 +00:00
|
|
|
match f(&*orig) {
|
|
|
|
Some(value) => Ok(Ref { value: NonNull::from(value), borrow: orig.borrow }),
|
2020-12-17 00:46:06 +00:00
|
|
|
None => Err(orig),
|
|
|
|
}
|
2020-10-27 23:15:36 +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]);
|
|
|
|
/// ```
|
2019-03-18 19:01:16 +00:00
|
|
|
#[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>)
|
|
|
|
where
|
|
|
|
F: FnOnce(&T) -> (&U, &V),
|
|
|
|
{
|
2022-05-13 17:12:32 +00:00
|
|
|
let (a, b) = f(&*orig);
|
2018-06-10 05:32:05 +00:00
|
|
|
let borrow = orig.borrow.clone();
|
2022-05-13 17:12:32 +00:00
|
|
|
(
|
|
|
|
Ref { value: NonNull::from(a), borrow },
|
|
|
|
Ref { value: NonNull::from(b), borrow: orig.borrow },
|
|
|
|
)
|
2018-06-10 05:32:05 +00:00
|
|
|
}
|
2020-01-29 20:26:16 +00:00
|
|
|
|
|
|
|
/// Convert into a reference to the underlying data.
|
|
|
|
///
|
|
|
|
/// The underlying `RefCell` can never be mutably borrowed from again and will always appear
|
2020-02-12 15:56:09 +00:00
|
|
|
/// already immutably borrowed. It is not a good idea to leak more than a constant number of
|
|
|
|
/// references. The `RefCell` can be immutably borrowed again if only a smaller number of leaks
|
|
|
|
/// have occurred in total.
|
2020-01-29 20:26:16 +00:00
|
|
|
///
|
|
|
|
/// This is an associated function that needs to be used as
|
|
|
|
/// `Ref::leak(...)`. A method would interfere with methods of the
|
|
|
|
/// same name on the contents of a `RefCell` used through `Deref`.
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// #![feature(cell_leak)]
|
|
|
|
/// use std::cell::{RefCell, Ref};
|
|
|
|
/// let cell = RefCell::new(0);
|
|
|
|
///
|
|
|
|
/// let value = Ref::leak(cell.borrow());
|
|
|
|
/// assert_eq!(*value, 0);
|
|
|
|
///
|
|
|
|
/// assert!(cell.try_borrow().is_ok());
|
|
|
|
/// assert!(cell.try_borrow_mut().is_err());
|
|
|
|
/// ```
|
2020-02-12 15:56:09 +00:00
|
|
|
#[unstable(feature = "cell_leak", issue = "69099")]
|
2020-01-29 20:26:16 +00:00
|
|
|
pub fn leak(orig: Ref<'b, T>) -> &'b T {
|
2020-02-27 20:24:14 +00:00
|
|
|
// By forgetting this Ref we ensure that the borrow counter in the RefCell can't go back to
|
|
|
|
// UNUSED within the lifetime `'b`. Resetting the reference tracking state would require a
|
|
|
|
// unique reference to the borrowed RefCell. No further mutable references can be created
|
|
|
|
// from the original cell.
|
2020-01-29 20:26:16 +00:00
|
|
|
mem::forget(orig.borrow);
|
2022-05-13 17:12:32 +00:00
|
|
|
// SAFETY: after forgetting, we can form a reference for the rest of lifetime `'b`.
|
|
|
|
unsafe { orig.value.as_ref() }
|
2020-01-29 20:26:16 +00:00
|
|
|
}
|
2015-05-28 21:00:52 +00:00
|
|
|
}
|
|
|
|
|
2022-12-20 07:08:38 +00:00
|
|
|
#[unstable(feature = "coerce_unsized", issue = "18598")]
|
2016-03-31 14:11:59 +00:00
|
|
|
impl<'b, T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Ref<'b, U>> for Ref<'b, T> {}
|
|
|
|
|
2017-07-10 01:07:29 +00:00
|
|
|
#[stable(feature = "std_guard_impls", since = "1.20.0")]
|
2018-09-03 11:50:14 +00:00
|
|
|
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 {
|
2022-05-20 18:16:30 +00:00
|
|
|
(**self).fmt(f)
|
2017-06-22 10:01:22 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-05-28 21:00:52 +00:00
|
|
|
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
|
2015-06-09 18:18:03 +00:00
|
|
|
/// variant.
|
2015-05-28 21:00:52 +00:00
|
|
|
///
|
|
|
|
/// The `RefCell` is already mutably borrowed, so this cannot fail.
|
|
|
|
///
|
2015-06-09 18:18:03 +00:00
|
|
|
/// 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
|
2015-06-09 18:18:03 +00:00
|
|
|
/// name on the contents of a `RefCell` used through `Deref`.
|
2015-05-28 21:00:52 +00:00
|
|
|
///
|
2017-08-24 15:33:36 +00:00
|
|
|
/// # Examples
|
2015-05-28 21:00:52 +00:00
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// 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'));
|
|
|
|
/// ```
|
std: Stabilize APIs for the 1.8 release
This commit is the result of the FCPs ending for the 1.8 release cycle for both
the libs and the lang suteams. The full list of changes are:
Stabilized
* `braced_empty_structs`
* `augmented_assignments`
* `str::encode_utf16` - renamed from `utf16_units`
* `str::EncodeUtf16` - renamed from `Utf16Units`
* `Ref::map`
* `RefMut::map`
* `ptr::drop_in_place`
* `time::Instant`
* `time::SystemTime`
* `{Instant,SystemTime}::now`
* `{Instant,SystemTime}::duration_since` - renamed from `duration_from_earlier`
* `{Instant,SystemTime}::elapsed`
* Various `Add`/`Sub` impls for `Time` and `SystemTime`
* `SystemTimeError`
* `SystemTimeError::duration`
* Various impls for `SystemTimeError`
* `UNIX_EPOCH`
* `ops::{Add,Sub,Mul,Div,Rem,BitAnd,BitOr,BitXor,Shl,Shr}Assign`
Deprecated
* Scoped TLS (the `scoped_thread_local!` macro)
* `Ref::filter_map`
* `RefMut::filter_map`
* `RwLockReadGuard::map`
* `RwLockWriteGuard::map`
* `Condvar::wait_timeout_with`
Closes #27714
Closes #27715
Closes #27746
Closes #27748
Closes #27908
Closes #29866
2016-02-25 23:52:29 +00:00
|
|
|
#[stable(feature = "cell_map", since = "1.8.0")]
|
2015-05-28 21:00:52 +00:00
|
|
|
#[inline]
|
2022-05-13 17:46:00 +00:00
|
|
|
pub fn map<U: ?Sized, F>(mut orig: RefMut<'b, T>, f: F) -> RefMut<'b, U>
|
2015-05-28 21:00:52 +00:00
|
|
|
where
|
|
|
|
F: FnOnce(&mut T) -> &mut U,
|
|
|
|
{
|
2022-05-13 17:46:00 +00:00
|
|
|
let value = NonNull::from(f(&mut *orig));
|
|
|
|
RefMut { value, borrow: orig.borrow, marker: PhantomData }
|
2015-05-28 21:00:52 +00:00
|
|
|
}
|
2018-06-10 05:32:05 +00:00
|
|
|
|
2020-12-17 00:46:06 +00:00
|
|
|
/// Makes a new `RefMut` for an optional component of the borrowed data. The
|
|
|
|
/// original guard is returned as an `Err(..)` if the closure returns
|
|
|
|
/// `None`.
|
2020-10-27 23:15:36 +00:00
|
|
|
///
|
|
|
|
/// The `RefCell` is already mutably borrowed, so this cannot fail.
|
|
|
|
///
|
|
|
|
/// This is an associated function that needs to be used as
|
2020-12-17 00:46:06 +00:00
|
|
|
/// `RefMut::filter_map(...)`. A method would interfere with methods of the
|
2020-10-27 23:15:36 +00:00
|
|
|
/// same name on the contents of a `RefCell` used through `Deref`.
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use std::cell::{RefCell, RefMut};
|
|
|
|
///
|
|
|
|
/// let c = RefCell::new(vec![1, 2, 3]);
|
|
|
|
///
|
|
|
|
/// {
|
|
|
|
/// let b1: RefMut<Vec<u32>> = c.borrow_mut();
|
2020-12-17 00:46:06 +00:00
|
|
|
/// let mut b2: Result<RefMut<u32>, _> = RefMut::filter_map(b1, |v| v.get_mut(1));
|
2020-10-27 23:15:36 +00:00
|
|
|
///
|
2020-12-17 00:46:06 +00:00
|
|
|
/// if let Ok(mut b2) = b2 {
|
2020-10-27 23:15:36 +00:00
|
|
|
/// *b2 += 2;
|
|
|
|
/// }
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// assert_eq!(*c.borrow(), vec![1, 4, 3]);
|
|
|
|
/// ```
|
2022-05-23 09:04:53 +00:00
|
|
|
#[stable(feature = "cell_filter_map", since = "1.63.0")]
|
2020-10-27 23:15:36 +00:00
|
|
|
#[inline]
|
2022-05-13 17:46:00 +00:00
|
|
|
pub fn filter_map<U: ?Sized, F>(mut orig: RefMut<'b, T>, f: F) -> Result<RefMut<'b, U>, Self>
|
2020-10-27 23:15:36 +00:00
|
|
|
where
|
|
|
|
F: FnOnce(&mut T) -> Option<&mut U>,
|
|
|
|
{
|
2020-12-17 00:46:06 +00:00
|
|
|
// SAFETY: function holds onto an exclusive reference for the duration
|
|
|
|
// of its call through `orig`, and the pointer is only de-referenced
|
|
|
|
// inside of the function call never allowing the exclusive reference to
|
|
|
|
// escape.
|
2022-05-13 17:46:00 +00:00
|
|
|
match f(&mut *orig) {
|
|
|
|
Some(value) => {
|
|
|
|
Ok(RefMut { value: NonNull::from(value), borrow: orig.borrow, marker: PhantomData })
|
2020-12-17 00:46:06 +00:00
|
|
|
}
|
2022-05-13 17:46:00 +00:00
|
|
|
None => Err(orig),
|
2020-12-17 00:46:06 +00:00
|
|
|
}
|
2020-10-27 23:15:36 +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]);
|
|
|
|
/// ```
|
2019-03-18 19:01:16 +00:00
|
|
|
#[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>(
|
2022-05-13 17:46:00 +00:00
|
|
|
mut orig: RefMut<'b, T>,
|
2018-06-10 05:32:05 +00:00
|
|
|
f: F,
|
|
|
|
) -> (RefMut<'b, U>, RefMut<'b, V>)
|
|
|
|
where
|
|
|
|
F: FnOnce(&mut T) -> (&mut U, &mut V),
|
|
|
|
{
|
|
|
|
let borrow = orig.borrow.clone();
|
2022-05-13 17:46:00 +00:00
|
|
|
let (a, b) = f(&mut *orig);
|
|
|
|
(
|
|
|
|
RefMut { value: NonNull::from(a), borrow, marker: PhantomData },
|
|
|
|
RefMut { value: NonNull::from(b), borrow: orig.borrow, marker: PhantomData },
|
|
|
|
)
|
2018-06-10 05:32:05 +00:00
|
|
|
}
|
2020-01-29 20:26:16 +00:00
|
|
|
|
|
|
|
/// Convert into a mutable reference to the underlying data.
|
|
|
|
///
|
|
|
|
/// The underlying `RefCell` can not be borrowed from again and will always appear already
|
|
|
|
/// mutably borrowed, making the returned reference the only to the interior.
|
|
|
|
///
|
|
|
|
/// This is an associated function that needs to be used as
|
|
|
|
/// `RefMut::leak(...)`. A method would interfere with methods of the
|
|
|
|
/// same name on the contents of a `RefCell` used through `Deref`.
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// #![feature(cell_leak)]
|
|
|
|
/// use std::cell::{RefCell, RefMut};
|
|
|
|
/// let cell = RefCell::new(0);
|
|
|
|
///
|
|
|
|
/// let value = RefMut::leak(cell.borrow_mut());
|
|
|
|
/// assert_eq!(*value, 0);
|
|
|
|
/// *value = 1;
|
|
|
|
///
|
|
|
|
/// assert!(cell.try_borrow_mut().is_err());
|
|
|
|
/// ```
|
2020-02-12 15:56:09 +00:00
|
|
|
#[unstable(feature = "cell_leak", issue = "69099")]
|
2022-05-13 17:46:00 +00:00
|
|
|
pub fn leak(mut orig: RefMut<'b, T>) -> &'b mut T {
|
2020-02-27 20:24:14 +00:00
|
|
|
// By forgetting this BorrowRefMut we ensure that the borrow counter in the RefCell can't
|
|
|
|
// go back to UNUSED within the lifetime `'b`. Resetting the reference tracking state would
|
|
|
|
// require a unique reference to the borrowed RefCell. No further references can be created
|
|
|
|
// from the original cell within that lifetime, making the current borrow the only
|
|
|
|
// reference for the remaining lifetime.
|
2020-01-29 20:26:16 +00:00
|
|
|
mem::forget(orig.borrow);
|
2022-05-13 17:46:00 +00:00
|
|
|
// SAFETY: after forgetting, we can form a reference for the rest of lifetime `'b`.
|
|
|
|
unsafe { orig.value.as_mut() }
|
2020-01-29 20:26:16 +00:00
|
|
|
}
|
2014-05-14 00:29:30 +00:00
|
|
|
}
|
|
|
|
|
2014-11-29 00:20:14 +00:00
|
|
|
struct BorrowRefMut<'b> {
|
2016-04-05 09:02:49 +00:00
|
|
|
borrow: &'b Cell<BorrowFlag>,
|
2014-08-28 01:46:52 +00:00
|
|
|
}
|
|
|
|
|
2018-09-03 11:50:14 +00:00
|
|
|
impl Drop for BorrowRefMut<'_> {
|
2015-03-18 23:44:37 +00:00
|
|
|
#[inline]
|
2013-11-22 05:30:34 +00:00
|
|
|
fn drop(&mut self) {
|
2016-04-05 09:02:49 +00:00
|
|
|
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
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-11-29 00:20:14 +00:00
|
|
|
impl<'b> BorrowRefMut<'b> {
|
2015-03-18 23:44:37 +00:00
|
|
|
#[inline]
|
2014-11-29 00:20:14 +00:00
|
|
|
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.
|
2014-11-29 00:20:14 +00:00
|
|
|
match borrow.get() {
|
|
|
|
UNUSED => {
|
2018-06-27 07:07:18 +00:00
|
|
|
borrow.set(UNUSED - 1);
|
2018-08-04 12:58:20 +00:00
|
|
|
Some(BorrowRefMut { borrow })
|
2014-11-29 00:20:14 +00:00
|
|
|
}
|
|
|
|
_ => None,
|
|
|
|
}
|
|
|
|
}
|
2018-06-10 05:32:05 +00:00
|
|
|
|
2019-02-28 22:43:53 +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.
|
2020-06-02 07:59:11 +00:00
|
|
|
assert!(borrow != isize::MIN);
|
2018-06-27 07:07:18 +00:00
|
|
|
self.borrow.set(borrow - 1);
|
2018-06-10 05:32:05 +00:00
|
|
|
BorrowRefMut { borrow: self.borrow }
|
|
|
|
}
|
2014-11-29 00:20:14 +00:00
|
|
|
}
|
|
|
|
|
2015-01-23 20:02:05 +00:00
|
|
|
/// A wrapper type for a mutably borrowed value from a `RefCell<T>`.
|
|
|
|
///
|
2020-10-12 20:42:49 +00:00
|
|
|
/// See the [module-level documentation](self) for more.
|
2015-01-24 05:48:20 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2022-01-14 08:50:49 +00:00
|
|
|
#[must_not_suspend = "holding a RefMut across suspend points can cause BorrowErrors"]
|
2015-04-23 10:53:54 +00:00
|
|
|
pub struct RefMut<'b, T: ?Sized + 'b> {
|
2022-05-13 17:46:00 +00:00
|
|
|
// NB: we use a pointer instead of `&'b mut T` to avoid `noalias` violations, because a
|
|
|
|
// `RefMut` argument doesn't hold exclusivity for its whole scope, only until it drops.
|
|
|
|
value: NonNull<T>,
|
2016-04-05 09:02:49 +00:00
|
|
|
borrow: BorrowRefMut<'b>,
|
2022-05-17 00:24:53 +00:00
|
|
|
// `NonNull` is covariant over `T`, so we need to reintroduce invariance.
|
2022-05-13 17:46:00 +00:00
|
|
|
marker: PhantomData<&'b mut T>,
|
2014-11-29 00:20:14 +00:00
|
|
|
}
|
|
|
|
|
2015-01-24 05:48:20 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2018-09-03 11:50:14 +00:00
|
|
|
impl<T: ?Sized> Deref for RefMut<'_, T> {
|
2015-01-01 19:53:20 +00:00
|
|
|
type Target = T;
|
|
|
|
|
2014-02-26 21:07:23 +00:00
|
|
|
#[inline]
|
2015-09-03 09:49:08 +00:00
|
|
|
fn deref(&self) -> &T {
|
2022-05-13 17:46:00 +00:00
|
|
|
// SAFETY: the value is accessible as long as we hold our borrow.
|
|
|
|
unsafe { self.value.as_ref() }
|
2014-02-26 21:07:23 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-01-24 05:48:20 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2018-09-03 11:50:14 +00:00
|
|
|
impl<T: ?Sized> DerefMut for RefMut<'_, T> {
|
2014-02-26 21:07:23 +00:00
|
|
|
#[inline]
|
2015-09-03 09:49:08 +00:00
|
|
|
fn deref_mut(&mut self) -> &mut T {
|
2022-05-13 17:46:00 +00:00
|
|
|
// SAFETY: the value is accessible as long as we hold our borrow.
|
|
|
|
unsafe { self.value.as_mut() }
|
2014-02-26 21:07:23 +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
|
|
|
|
2022-12-20 07:08:38 +00:00
|
|
|
#[unstable(feature = "coerce_unsized", issue = "18598")]
|
2016-03-31 14:11:59 +00:00
|
|
|
impl<'b, T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<RefMut<'b, U>> for RefMut<'b, T> {}
|
|
|
|
|
2017-07-10 01:07:29 +00:00
|
|
|
#[stable(feature = "std_guard_impls", since = "1.20.0")]
|
2018-09-03 11:50:14 +00:00
|
|
|
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 {
|
2022-05-20 18:16:30 +00:00
|
|
|
(**self).fmt(f)
|
2017-06-22 10:01:22 +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
|
|
|
/// The core primitive for interior mutability in Rust.
|
|
|
|
///
|
2021-02-21 16:24:19 +00:00
|
|
|
/// If you have a reference `&T`, then normally in Rust the compiler performs optimizations based on
|
|
|
|
/// the knowledge that `&T` points to immutable data. Mutating that data, for example through an
|
|
|
|
/// alias or by transmuting an `&T` into an `&mut T`, is considered undefined behavior.
|
|
|
|
/// `UnsafeCell<T>` opts-out of the immutability guarantee for `&T`: a shared reference
|
|
|
|
/// `&UnsafeCell<T>` may point to data that is being mutated. This is called "interior mutability".
|
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
|
|
|
///
|
2021-02-21 16:24:19 +00:00
|
|
|
/// All other types that allow internal mutability, such as `Cell<T>` and `RefCell<T>`, internally
|
|
|
|
/// use `UnsafeCell` to wrap their data.
|
|
|
|
///
|
|
|
|
/// Note that only the immutability guarantee for shared references is affected by `UnsafeCell`. The
|
|
|
|
/// uniqueness guarantee for mutable references is unaffected. There is *no* legal way to obtain
|
|
|
|
/// aliasing `&mut`, not even with `UnsafeCell<T>`.
|
2016-06-28 06:23:37 +00:00
|
|
|
///
|
2020-09-19 19:32:33 +00:00
|
|
|
/// The `UnsafeCell` API itself is technically very simple: [`.get()`] 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.
|
|
|
|
///
|
|
|
|
/// [`.get()`]: `UnsafeCell::get`
|
2018-03-08 21:15:39 +00:00
|
|
|
///
|
|
|
|
/// The precise Rust aliasing rules are somewhat in flux, but the main points are not contentious:
|
|
|
|
///
|
2022-06-22 21:36:30 +00:00
|
|
|
/// - If you create a safe reference with lifetime `'a` (either a `&T` or `&mut T` reference), 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.
|
|
|
|
///
|
|
|
|
/// - For both `&T` without `UnsafeCell<_>` and `&mut T`, you must also not deallocate the data
|
|
|
|
/// until the reference expires. As a special exception, given an `&T`, any part of it that is
|
|
|
|
/// inside an `UnsafeCell<_>` may be deallocated during the lifetime of the reference, after the
|
|
|
|
/// last time the reference is used (dereferenced or reborrowed). Since you cannot deallocate a part
|
2022-12-27 18:17:56 +00:00
|
|
|
/// of what a reference points to, this means the memory an `&T` points to can be deallocated only if
|
2022-06-22 21:36:30 +00:00
|
|
|
/// *every part of it* (including padding) is inside an `UnsafeCell`.
|
|
|
|
///
|
|
|
|
/// However, whenever a `&UnsafeCell<T>` is constructed or dereferenced, it must still point to
|
|
|
|
/// live memory and the compiler is allowed to insert spurious reads if it can prove that this
|
|
|
|
/// memory has not yet been deallocated.
|
2018-03-08 21:15:39 +00:00
|
|
|
///
|
2018-05-19 17:58:16 +00:00
|
|
|
/// - 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
|
2018-03-08 21:15:39 +00:00
|
|
|
/// accesses (or use atomics).
|
2016-06-28 06:23:37 +00:00
|
|
|
///
|
2018-03-08 21:15:39 +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`
|
2018-03-08 21:15:39 +00:00
|
|
|
///
|
2018-05-19 17:58:16 +00:00
|
|
|
/// 2. A `&mut T` reference may be released to safe code provided neither other `&mut T` nor `&T`
|
2018-03-08 21:15:39 +00:00
|
|
|
/// co-exist with it. A `&mut T` must always be unique.
|
2016-06-28 06:23:37 +00:00
|
|
|
///
|
2020-09-19 19:32:33 +00:00
|
|
|
/// Note that whilst mutating the contents of an `&UnsafeCell<T>` (even while other
|
|
|
|
/// `&UnsafeCell<T>` references alias the cell) is
|
|
|
|
/// ok (provided you enforce the above invariants some other way), it is still undefined behavior
|
|
|
|
/// to have multiple `&mut UnsafeCell<T>` aliases. That is, `UnsafeCell` is a wrapper
|
|
|
|
/// designed to have a special interaction with _shared_ accesses (_i.e._, through an
|
|
|
|
/// `&UnsafeCell<_>` reference); there is no magic whatsoever when dealing with _exclusive_
|
|
|
|
/// accesses (_e.g._, through an `&mut UnsafeCell<_>`): neither the cell nor the wrapped value
|
|
|
|
/// may be aliased for the duration of that `&mut` borrow.
|
2020-11-29 20:27:01 +00:00
|
|
|
/// This is showcased by the [`.get_mut()`] accessor, which is a _safe_ getter that yields
|
2020-09-19 19:32:33 +00:00
|
|
|
/// a `&mut T`.
|
|
|
|
///
|
|
|
|
/// [`.get_mut()`]: `UnsafeCell::get_mut`
|
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
|
|
|
///
|
2022-10-27 04:32:36 +00:00
|
|
|
/// # Memory layout
|
|
|
|
///
|
2022-10-12 21:34:13 +00:00
|
|
|
/// `UnsafeCell<T>` has the same in-memory representation as its inner type `T`. A consequence
|
|
|
|
/// of this guarantee is that it is possible to convert between `T` and `UnsafeCell<T>`.
|
|
|
|
/// Special care has to be taken when converting a nested `T` inside of an `Outer<T>` type
|
|
|
|
/// to an `Outer<UnsafeCell<T>>` type: this is not sound when the `Outer<T>` type enables [niche]
|
|
|
|
/// optimizations. For example, the type `Option<NonNull<u8>>` is typically 8 bytes large on
|
|
|
|
/// 64-bit platforms, but the type `Option<UnsafeCell<NonNull<u8>>>` takes up 16 bytes of space.
|
|
|
|
/// Therefore this is not a valid conversion, despite `NonNull<u8>` and `UnsafeCell<NonNull<u8>>>`
|
|
|
|
/// having the same memory layout. This is because `UnsafeCell` disables niche optimizations in
|
|
|
|
/// order to avoid its interior mutability property from spreading from `T` into the `Outer` type,
|
2022-10-20 06:37:47 +00:00
|
|
|
/// thus this can cause distortions in the type size in these cases.
|
|
|
|
///
|
2022-10-24 02:27:37 +00:00
|
|
|
/// Note that the only valid way to obtain a `*mut T` pointer to the contents of a
|
|
|
|
/// _shared_ `UnsafeCell<T>` is through [`.get()`] or [`.raw_get()`]. A `&mut T` reference
|
2022-10-20 06:37:47 +00:00
|
|
|
/// can be obtained by either dereferencing this pointer or by calling [`.get_mut()`]
|
|
|
|
/// on an _exclusive_ `UnsafeCell<T>`. Even though `T` and `UnsafeCell<T>` have the
|
|
|
|
/// same memory layout, the following is not allowed and undefined behavior:
|
|
|
|
///
|
|
|
|
/// ```rust,no_run
|
|
|
|
/// # use std::cell::UnsafeCell;
|
|
|
|
/// unsafe fn not_allowed<T>(ptr: &UnsafeCell<T>) -> &mut T {
|
|
|
|
/// let t = ptr as *const UnsafeCell<T> as *mut T;
|
|
|
|
/// // This is undefined behavior, because the `*mut T` pointer
|
|
|
|
/// // was not obtained through `.get()` nor `.raw_get()`:
|
|
|
|
/// unsafe { &mut *t }
|
|
|
|
/// }
|
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// Instead, do this:
|
2022-09-14 08:10:18 +00:00
|
|
|
///
|
|
|
|
/// ```rust
|
2022-10-20 06:37:47 +00:00
|
|
|
/// # use std::cell::UnsafeCell;
|
|
|
|
/// // Safety: the caller must ensure that there are no references that
|
|
|
|
/// // point to the *contents* of the `UnsafeCell`.
|
|
|
|
/// unsafe fn get_mut<T>(ptr: &UnsafeCell<T>) -> &mut T {
|
|
|
|
/// unsafe { &mut *ptr.get() }
|
|
|
|
/// }
|
|
|
|
/// ```
|
2022-09-14 08:10:18 +00:00
|
|
|
///
|
2022-11-05 03:05:22 +00:00
|
|
|
/// Converting in the other direction from a `&mut T`
|
2022-10-20 06:37:47 +00:00
|
|
|
/// to an `&UnsafeCell<T>` is allowed:
|
2022-10-09 20:32:23 +00:00
|
|
|
///
|
2022-10-20 06:37:47 +00:00
|
|
|
/// ```rust
|
|
|
|
/// # use std::cell::UnsafeCell;
|
|
|
|
/// fn get_shared<T>(ptr: &mut T) -> &UnsafeCell<T> {
|
|
|
|
/// let t = ptr as *mut T as *const UnsafeCell<T>;
|
|
|
|
/// // SAFETY: `T` and `UnsafeCell<T>` have the same memory layout
|
|
|
|
/// unsafe { &*t }
|
2022-10-09 20:32:23 +00:00
|
|
|
/// }
|
2022-09-14 08:10:18 +00:00
|
|
|
/// ```
|
|
|
|
///
|
2022-10-09 20:32:23 +00:00
|
|
|
/// [niche]: https://rust-lang.github.io/unsafe-code-guidelines/glossary.html#niche
|
2022-09-14 08:10:18 +00:00
|
|
|
/// [`.raw_get()`]: `UnsafeCell::raw_get`
|
2022-09-12 09:12:28 +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
|
|
|
///
|
2020-09-19 19:32:33 +00:00
|
|
|
/// Here is an example showcasing how to soundly mutate the contents of an `UnsafeCell<_>` despite
|
|
|
|
/// there being multiple references aliasing the cell:
|
|
|
|
///
|
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;
|
|
|
|
///
|
2020-09-19 19:32:33 +00:00
|
|
|
/// let x: UnsafeCell<i32> = 42.into();
|
|
|
|
/// // Get multiple / concurrent / shared references to the same `x`.
|
|
|
|
/// let (p1, p2): (&UnsafeCell<i32>, &UnsafeCell<i32>) = (&x, &x);
|
|
|
|
///
|
|
|
|
/// unsafe {
|
|
|
|
/// // SAFETY: within this scope there are no other references to `x`'s contents,
|
|
|
|
/// // so ours is effectively unique.
|
|
|
|
/// let p1_exclusive: &mut i32 = &mut *p1.get(); // -- borrow --+
|
|
|
|
/// *p1_exclusive += 27; // |
|
|
|
|
/// } // <---------- cannot go beyond this point -------------------+
|
|
|
|
///
|
|
|
|
/// unsafe {
|
|
|
|
/// // SAFETY: within this scope nobody expects to have exclusive access to `x`'s contents,
|
|
|
|
/// // so we can have multiple shared accesses concurrently.
|
|
|
|
/// let p2_shared: &i32 = &*p2.get();
|
|
|
|
/// assert_eq!(*p2_shared, 42 + 27);
|
|
|
|
/// let p1_shared: &i32 = &*p1.get();
|
|
|
|
/// assert_eq!(*p1_shared, *p2_shared);
|
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
|
|
|
/// }
|
2020-09-19 19:32:33 +00:00
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// The following example showcases the fact that exclusive access to an `UnsafeCell<T>`
|
|
|
|
/// implies exclusive access to its `T`:
|
2015-01-16 07:18:39 +00:00
|
|
|
///
|
2020-09-19 19:32:33 +00:00
|
|
|
/// ```rust
|
|
|
|
/// #![forbid(unsafe_code)] // with exclusive accesses,
|
|
|
|
/// // `UnsafeCell` is a transparent no-op wrapper,
|
|
|
|
/// // so no need for `unsafe` here.
|
|
|
|
/// use std::cell::UnsafeCell;
|
|
|
|
///
|
|
|
|
/// let mut x: UnsafeCell<i32> = 42.into();
|
|
|
|
///
|
|
|
|
/// // Get a compile-time-checked unique reference to `x`.
|
|
|
|
/// let p_unique: &mut UnsafeCell<i32> = &mut x;
|
|
|
|
/// // With an exclusive reference, we can mutate the contents for free.
|
|
|
|
/// *p_unique.get_mut() = 0;
|
|
|
|
/// // Or, equivalently:
|
|
|
|
/// x = UnsafeCell::new(0);
|
|
|
|
///
|
|
|
|
/// // When we own the value, we can extract the contents for free.
|
|
|
|
/// let contents: i32 = x.into_inner();
|
|
|
|
/// assert_eq!(contents, 0);
|
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-05-09 19:50:28 +00:00
|
|
|
#[lang = "unsafe_cell"]
|
2015-01-24 05:48:20 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2018-06-06 11:30:35 +00:00
|
|
|
#[repr(transparent)]
|
2015-04-23 10:53:54 +00:00
|
|
|
pub struct UnsafeCell<T: ?Sized> {
|
2015-08-12 00:27:05 +00:00
|
|
|
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")]
|
2015-04-23 10:53:54 +00:00
|
|
|
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> {
|
2015-04-13 14:21:32 +00:00
|
|
|
/// 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.
|
|
|
|
///
|
2022-11-05 11:25:58 +00:00
|
|
|
/// All access to the inner value through `&UnsafeCell<T>` requires `unsafe` code.
|
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")]
|
2021-04-04 18:55:13 +00:00
|
|
|
#[inline(always)]
|
2015-05-27 08:18:36 +00:00
|
|
|
pub const fn new(value: T) -> UnsafeCell<T> {
|
2018-08-04 12:58:20 +00:00
|
|
|
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
|
|
|
}
|
|
|
|
|
2022-12-12 09:16:18 +00:00
|
|
|
/// Unwraps the value, consuming the cell.
|
2015-04-23 10:53:54 +00:00
|
|
|
///
|
2015-01-23 20:02:05 +00:00
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use std::cell::UnsafeCell;
|
|
|
|
///
|
|
|
|
/// let uc = UnsafeCell::new(5);
|
|
|
|
///
|
2018-01-05 01:11:20 +00:00
|
|
|
/// let five = uc.into_inner();
|
2015-01-23 20:02:05 +00:00
|
|
|
/// ```
|
2021-04-04 18:55:13 +00:00
|
|
|
#[inline(always)]
|
2015-01-24 05:48:20 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2020-11-04 10:58:41 +00:00
|
|
|
#[rustc_const_unstable(feature = "const_cell_into_inner", issue = "78729")]
|
2020-11-04 10:41:57 +00:00
|
|
|
pub const fn into_inner(self) -> T {
|
2015-05-30 09:15:19 +00:00
|
|
|
self.value
|
|
|
|
}
|
2015-04-23 10:53:54 +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
|
|
|
|
2015-04-23 10:53:54 +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.
|
2018-02-14 07:19:01 +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
|
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);
|
|
|
|
///
|
2015-04-23 10:53:54 +00:00
|
|
|
/// let five = uc.get();
|
2015-01-23 20:02:05 +00:00
|
|
|
/// ```
|
2021-04-04 18:55:13 +00:00
|
|
|
#[inline(always)]
|
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 {
|
2018-11-17 09:20:28 +00:00
|
|
|
// We can just cast the pointer from `UnsafeCell<T>` to `T` because of
|
2022-10-28 23:48:00 +00:00
|
|
|
// #[repr(transparent)]. This exploits std's special status, there is
|
2019-11-13 08:07:52 +00:00
|
|
|
// 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
|
2015-04-23 10:53:54 +00:00
|
|
|
}
|
2019-11-09 11:34:29 +00:00
|
|
|
|
2020-09-19 19:32:33 +00:00
|
|
|
/// Returns a mutable reference to the underlying data.
|
|
|
|
///
|
|
|
|
/// This call borrows the `UnsafeCell` mutably (at compile-time) which
|
|
|
|
/// guarantees that we possess the only reference.
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use std::cell::UnsafeCell;
|
|
|
|
///
|
|
|
|
/// let mut c = UnsafeCell::new(5);
|
|
|
|
/// *c.get_mut() += 1;
|
|
|
|
///
|
|
|
|
/// assert_eq!(*c.get_mut(), 6);
|
|
|
|
/// ```
|
2021-04-04 18:55:13 +00:00
|
|
|
#[inline(always)]
|
2020-11-28 00:30:26 +00:00
|
|
|
#[stable(feature = "unsafe_cell_get_mut", since = "1.50.0")]
|
2021-09-10 21:07:14 +00:00
|
|
|
#[rustc_const_unstable(feature = "const_unsafecell_get_mut", issue = "88836")]
|
2021-09-07 13:41:15 +00:00
|
|
|
pub const fn get_mut(&mut self) -> &mut T {
|
2020-11-04 13:54:22 +00:00
|
|
|
&mut self.value
|
2020-09-19 19:32:33 +00:00
|
|
|
}
|
|
|
|
|
2019-11-09 11:34:29 +00:00
|
|
|
/// Gets a mutable pointer to the wrapped value.
|
2021-08-31 21:44:13 +00:00
|
|
|
/// The difference from [`get`] is that this function accepts a raw pointer,
|
2019-11-13 08:11:09 +00:00
|
|
|
/// 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
|
2019-11-13 08:05:57 +00:00
|
|
|
/// or mutable aliases going on when casting to `&T`.
|
2019-11-09 11:34:29 +00:00
|
|
|
///
|
2020-11-30 20:21:15 +00:00
|
|
|
/// [`get`]: UnsafeCell::get()
|
2019-11-13 08:11:09 +00:00
|
|
|
///
|
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
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// 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);
|
|
|
|
/// ```
|
2021-04-04 18:55:13 +00:00
|
|
|
#[inline(always)]
|
2021-08-31 21:44:13 +00:00
|
|
|
#[stable(feature = "unsafe_cell_raw_get", since = "1.56.0")]
|
2021-11-18 02:08:16 +00:00
|
|
|
#[rustc_const_stable(feature = "unsafe_cell_raw_get", since = "1.56.0")]
|
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
|
2022-10-28 23:48:00 +00:00
|
|
|
// #[repr(transparent)]. This exploits std's special status, there is
|
2019-11-13 08:07:52 +00:00
|
|
|
// 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
|
|
|
}
|
2016-04-15 15:53:43 +00:00
|
|
|
|
2017-05-20 07:38:39 +00:00
|
|
|
#[stable(feature = "unsafe_cell_default", since = "1.10.0")]
|
2016-04-15 15:53:43 +00:00
|
|
|
impl<T: Default> Default for UnsafeCell<T> {
|
2016-09-11 11:30:09 +00:00
|
|
|
/// Creates an `UnsafeCell`, with the `Default` value for T.
|
2016-04-15 15:53:43 +00:00
|
|
|
fn default() -> UnsafeCell<T> {
|
|
|
|
UnsafeCell::new(Default::default())
|
|
|
|
}
|
|
|
|
}
|
2016-08-05 19:57:19 +00:00
|
|
|
|
|
|
|
#[stable(feature = "cell_from", since = "1.12.0")]
|
2021-10-18 10:19:28 +00:00
|
|
|
#[rustc_const_unstable(feature = "const_convert", issue = "88674")]
|
|
|
|
impl<T> const From<T> for UnsafeCell<T> {
|
2021-10-13 15:46:34 +00:00
|
|
|
/// Creates a new `UnsafeCell<T>` containing the given value.
|
2016-08-05 19:57:19 +00:00
|
|
|
fn from(t: T) -> UnsafeCell<T> {
|
|
|
|
UnsafeCell::new(t)
|
|
|
|
}
|
|
|
|
}
|
2016-08-12 22:10:34 +00:00
|
|
|
|
2022-12-20 07:08:38 +00:00
|
|
|
#[unstable(feature = "coerce_unsized", issue = "18598")]
|
2016-08-12 22:10:34 +00:00
|
|
|
impl<T: CoerceUnsized<U>, U> CoerceUnsized<UnsafeCell<U>> for UnsafeCell<T> {}
|
|
|
|
|
2022-05-24 21:56:19 +00:00
|
|
|
// Allow types that wrap `UnsafeCell` to also implement `DispatchFromDyn`
|
|
|
|
// and become object safe method receivers.
|
|
|
|
// Note that currently `UnsafeCell` itself cannot be a method receiver
|
|
|
|
// because it does not implement Deref.
|
|
|
|
// In other words:
|
|
|
|
// `self: UnsafeCell<&Self>` won't work
|
|
|
|
// `self: UnsafeCellWrapper<Self>` becomes possible
|
|
|
|
#[unstable(feature = "dispatch_from_dyn", issue = "none")]
|
|
|
|
impl<T: DispatchFromDyn<U>, U> DispatchFromDyn<UnsafeCell<U>> for UnsafeCell<T> {}
|
|
|
|
|
2022-03-29 17:30:55 +00:00
|
|
|
/// [`UnsafeCell`], but [`Sync`].
|
|
|
|
///
|
|
|
|
/// This is just an `UnsafeCell`, except it implements `Sync`
|
|
|
|
/// if `T` implements `Sync`.
|
|
|
|
///
|
|
|
|
/// `UnsafeCell` doesn't implement `Sync`, to prevent accidental mis-use.
|
|
|
|
/// You can use `SyncUnsafeCell` instead of `UnsafeCell` to allow it to be
|
|
|
|
/// shared between threads, if that's intentional.
|
|
|
|
/// Providing proper synchronization is still the task of the user,
|
|
|
|
/// making this type just as unsafe to use.
|
|
|
|
///
|
|
|
|
/// See [`UnsafeCell`] for details.
|
2022-03-29 17:54:00 +00:00
|
|
|
#[unstable(feature = "sync_unsafe_cell", issue = "95439")]
|
2022-03-29 17:30:55 +00:00
|
|
|
#[repr(transparent)]
|
|
|
|
pub struct SyncUnsafeCell<T: ?Sized> {
|
|
|
|
value: UnsafeCell<T>,
|
|
|
|
}
|
|
|
|
|
2022-03-29 17:54:00 +00:00
|
|
|
#[unstable(feature = "sync_unsafe_cell", issue = "95439")]
|
2022-03-29 17:30:55 +00:00
|
|
|
unsafe impl<T: ?Sized + Sync> Sync for SyncUnsafeCell<T> {}
|
|
|
|
|
2022-03-29 17:54:00 +00:00
|
|
|
#[unstable(feature = "sync_unsafe_cell", issue = "95439")]
|
2022-03-29 17:30:55 +00:00
|
|
|
impl<T> SyncUnsafeCell<T> {
|
|
|
|
/// Constructs a new instance of `SyncUnsafeCell` which will wrap the specified value.
|
|
|
|
#[inline]
|
|
|
|
pub const fn new(value: T) -> Self {
|
|
|
|
Self { value: UnsafeCell { value } }
|
|
|
|
}
|
|
|
|
|
2022-12-12 09:16:18 +00:00
|
|
|
/// Unwraps the value, consuming the cell.
|
2022-03-29 17:30:55 +00:00
|
|
|
#[inline]
|
|
|
|
pub const fn into_inner(self) -> T {
|
|
|
|
self.value.into_inner()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-03-29 17:54:00 +00:00
|
|
|
#[unstable(feature = "sync_unsafe_cell", issue = "95439")]
|
2022-03-29 17:30:55 +00:00
|
|
|
impl<T: ?Sized> SyncUnsafeCell<T> {
|
|
|
|
/// Gets a mutable pointer to the wrapped value.
|
|
|
|
///
|
|
|
|
/// 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
|
|
|
|
/// or mutable aliases going on when casting to `&T`
|
|
|
|
#[inline]
|
|
|
|
pub const fn get(&self) -> *mut T {
|
|
|
|
self.value.get()
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns a mutable reference to the underlying data.
|
|
|
|
///
|
|
|
|
/// This call borrows the `SyncUnsafeCell` mutably (at compile-time) which
|
|
|
|
/// guarantees that we possess the only reference.
|
|
|
|
#[inline]
|
|
|
|
pub const fn get_mut(&mut self) -> &mut T {
|
|
|
|
self.value.get_mut()
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Gets a mutable pointer to the wrapped value.
|
|
|
|
///
|
|
|
|
/// See [`UnsafeCell::get`] for details.
|
|
|
|
#[inline]
|
|
|
|
pub const fn raw_get(this: *const Self) -> *mut T {
|
|
|
|
// We can just cast the pointer from `SyncUnsafeCell<T>` to `T` because
|
|
|
|
// of #[repr(transparent)] on both SyncUnsafeCell and UnsafeCell.
|
|
|
|
// See UnsafeCell::raw_get.
|
|
|
|
this as *const T as *mut T
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-03-29 17:54:00 +00:00
|
|
|
#[unstable(feature = "sync_unsafe_cell", issue = "95439")]
|
2022-03-29 17:30:55 +00:00
|
|
|
impl<T: Default> Default for SyncUnsafeCell<T> {
|
|
|
|
/// Creates an `SyncUnsafeCell`, with the `Default` value for T.
|
|
|
|
fn default() -> SyncUnsafeCell<T> {
|
|
|
|
SyncUnsafeCell::new(Default::default())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-03-29 17:54:00 +00:00
|
|
|
#[unstable(feature = "sync_unsafe_cell", issue = "95439")]
|
2022-03-29 17:30:55 +00:00
|
|
|
#[rustc_const_unstable(feature = "const_convert", issue = "88674")]
|
|
|
|
impl<T> const From<T> for SyncUnsafeCell<T> {
|
|
|
|
/// Creates a new `SyncUnsafeCell<T>` containing the given value.
|
|
|
|
fn from(t: T) -> SyncUnsafeCell<T> {
|
|
|
|
SyncUnsafeCell::new(t)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-12-20 07:08:38 +00:00
|
|
|
#[unstable(feature = "coerce_unsized", issue = "18598")]
|
2022-03-29 17:54:00 +00:00
|
|
|
//#[unstable(feature = "sync_unsafe_cell", issue = "95439")]
|
2022-03-29 17:30:55 +00:00
|
|
|
impl<T: CoerceUnsized<U>, U> CoerceUnsized<SyncUnsafeCell<U>> for SyncUnsafeCell<T> {}
|
|
|
|
|
2022-05-24 21:56:19 +00:00
|
|
|
// Allow types that wrap `SyncUnsafeCell` to also implement `DispatchFromDyn`
|
|
|
|
// and become object safe method receivers.
|
|
|
|
// Note that currently `SyncUnsafeCell` itself cannot be a method receiver
|
|
|
|
// because it does not implement Deref.
|
|
|
|
// In other words:
|
|
|
|
// `self: SyncUnsafeCell<&Self>` won't work
|
|
|
|
// `self: SyncUnsafeCellWrapper<Self>` becomes possible
|
|
|
|
#[unstable(feature = "dispatch_from_dyn", issue = "none")]
|
|
|
|
//#[unstable(feature = "sync_unsafe_cell", issue = "95439")]
|
|
|
|
impl<T: DispatchFromDyn<U>, U> DispatchFromDyn<SyncUnsafeCell<U>> for SyncUnsafeCell<T> {}
|
|
|
|
|
2016-08-12 22:10:34 +00:00
|
|
|
#[allow(unused)]
|
2022-03-29 17:30:55 +00:00
|
|
|
fn assert_coerce_unsized(
|
|
|
|
a: UnsafeCell<&i32>,
|
|
|
|
b: SyncUnsafeCell<&i32>,
|
|
|
|
c: Cell<&i32>,
|
|
|
|
d: RefCell<&i32>,
|
|
|
|
) {
|
2018-07-10 18:39:28 +00:00
|
|
|
let _: UnsafeCell<&dyn Send> = a;
|
2022-03-29 17:30:55 +00:00
|
|
|
let _: SyncUnsafeCell<&dyn Send> = b;
|
|
|
|
let _: Cell<&dyn Send> = c;
|
|
|
|
let _: RefCell<&dyn Send> = d;
|
2016-08-12 22:10:34 +00:00
|
|
|
}
|