core/cell.rs
1//! Shareable mutable containers.
2//!
3//! Rust memory safety is based on this rule: Given an object `T`, it is only possible to
4//! have one of the following:
5//!
6//! - Several immutable references (`&T`) to the object (also known as **aliasing**).
7//! - One mutable reference (`&mut T`) to the object (also known as **mutability**).
8//!
9//! This is enforced by the Rust compiler. However, there are situations where this rule is not
10//! flexible enough. Sometimes it is required to have multiple references to an object and yet
11//! mutate it.
12//!
13//! Shareable mutable containers exist to permit mutability in a controlled manner, even in the
14//! presence of aliasing. [`Cell<T>`], [`RefCell<T>`], and [`OnceCell<T>`] allow doing this in
15//! a single-threaded way—they do not implement [`Sync`]. (If you need to do aliasing and
16//! mutation among multiple threads, [`Mutex<T>`], [`RwLock<T>`], [`OnceLock<T>`] or [`atomic`]
17//! types are the correct data structures to do so).
18//!
19//! Values of the `Cell<T>`, `RefCell<T>`, and `OnceCell<T>` types may be mutated through shared
20//! references (i.e. the common `&T` type), whereas most Rust types can only be mutated through
21//! unique (`&mut T`) references. We say these cell types provide 'interior mutability'
22//! (mutable via `&T`), in contrast with typical Rust types that exhibit 'inherited mutability'
23//! (mutable only via `&mut T`).
24//!
25//! Cell types come in four flavors: `Cell<T>`, `RefCell<T>`, `OnceCell<T>`, and `LazyCell<T>`.
26//! Each provides a different way of providing safe interior mutability.
27//!
28//! ## `Cell<T>`
29//!
30//! [`Cell<T>`] implements interior mutability by moving values in and out of the cell. That is, an
31//! `&mut T` to the inner value can never be obtained, and the value itself cannot be directly
32//! obtained without replacing it with something else. Both of these rules ensure that there is
33//! never more than one reference pointing to the inner value. This type provides the following
34//! methods:
35//!
36//! - For types that implement [`Copy`], the [`get`](Cell::get) method retrieves the current
37//! interior value by duplicating it.
38//! - For types that implement [`Default`], the [`take`](Cell::take) method replaces the current
39//! interior value with [`Default::default()`] and returns the replaced value.
40//! - All types have:
41//! - [`replace`](Cell::replace): replaces the current interior value and returns the replaced
42//! value.
43//! - [`into_inner`](Cell::into_inner): this method consumes the `Cell<T>` and returns the
44//! interior value.
45//! - [`set`](Cell::set): this method replaces the interior value, dropping the replaced value.
46//!
47//! `Cell<T>` is typically used for more simple types where copying or moving values isn't too
48//! resource intensive (e.g. numbers), and should usually be preferred over other cell types when
49//! possible. For larger and non-copy types, `RefCell` provides some advantages.
50//!
51//! ## `RefCell<T>`
52//!
53//! [`RefCell<T>`] uses Rust's lifetimes to implement "dynamic borrowing", a process whereby one can
54//! claim temporary, exclusive, mutable access to the inner value. Borrows for `RefCell<T>`s are
55//! tracked at _runtime_, unlike Rust's native reference types which are entirely tracked
56//! statically, at compile time.
57//!
58//! An immutable reference to a `RefCell`'s inner value (`&T`) can be obtained with
59//! [`borrow`](`RefCell::borrow`), and a mutable borrow (`&mut T`) can be obtained with
60//! [`borrow_mut`](`RefCell::borrow_mut`). When these functions are called, they first verify that
61//! Rust's borrow rules will be satisfied: any number of immutable borrows are allowed or a
62//! single mutable borrow is allowed, but never both. If a borrow is attempted that would violate
63//! these rules, the thread will panic.
64//!
65//! The corresponding [`Sync`] version of `RefCell<T>` is [`RwLock<T>`].
66//!
67//! ## `OnceCell<T>`
68//!
69//! [`OnceCell<T>`] is somewhat of a hybrid of `Cell` and `RefCell` that works for values that
70//! typically only need to be set once. This means that a reference `&T` can be obtained without
71//! moving or copying the inner value (unlike `Cell`) but also without runtime checks (unlike
72//! `RefCell`). However, its value can also not be updated once set unless you have a mutable
73//! reference to the `OnceCell`.
74//!
75//! `OnceCell` provides the following methods:
76//!
77//! - [`get`](OnceCell::get): obtain a reference to the inner value
78//! - [`set`](OnceCell::set): set the inner value if it is unset (returns a `Result`)
79//! - [`get_or_init`](OnceCell::get_or_init): return the inner value, initializing it if needed
80//! - [`get_mut`](OnceCell::get_mut): provide a mutable reference to the inner value, only available
81//! if you have a mutable reference to the cell itself.
82//!
83//! The corresponding [`Sync`] version of `OnceCell<T>` is [`OnceLock<T>`].
84//!
85//! ## `LazyCell<T, F>`
86//!
87//! A common pattern with OnceCell is, for a given OnceCell, to use the same function on every
88//! call to [`OnceCell::get_or_init`] with that cell. This is what is offered by [`LazyCell`],
89//! which pairs cells of `T` with functions of `F`, and always calls `F` before it yields `&T`.
90//! This happens implicitly by simply attempting to dereference the LazyCell to get its contents,
91//! so its use is much more transparent with a place which has been initialized by a constant.
92//!
93//! More complicated patterns that don't fit this description can be built on `OnceCell<T>` instead.
94//!
95//! `LazyCell` works by providing an implementation of `impl Deref` that calls the function,
96//! so you can just use it by dereference (e.g. `*lazy_cell` or `lazy_cell.deref()`).
97//!
98//! The corresponding [`Sync`] version of `LazyCell<T, F>` is [`LazyLock<T, F>`].
99//!
100//! # When to choose interior mutability
101//!
102//! The more common inherited mutability, where one must have unique access to mutate a value, is
103//! one of the key language elements that enables Rust to reason strongly about pointer aliasing,
104//! statically preventing crash bugs. Because of that, inherited mutability is preferred, and
105//! interior mutability is something of a last resort. Since cell types enable mutation where it
106//! would otherwise be disallowed though, there are occasions when interior mutability might be
107//! appropriate, or even *must* be used, e.g.
108//!
109//! * Introducing mutability 'inside' of something immutable
110//! * Implementation details of logically-immutable methods.
111//! * Mutating implementations of [`Clone`].
112//!
113//! ## Introducing mutability 'inside' of something immutable
114//!
115//! Many shared smart pointer types, including [`Rc<T>`] and [`Arc<T>`], provide containers that can
116//! be cloned and shared between multiple parties. Because the contained values may be
117//! multiply-aliased, they can only be borrowed with `&`, not `&mut`. Without cells it would be
118//! impossible to mutate data inside of these smart pointers at all.
119//!
120//! It's very common then to put a `RefCell<T>` inside shared pointer types to reintroduce
121//! mutability:
122//!
123//! ```
124//! use std::cell::{RefCell, RefMut};
125//! use std::collections::HashMap;
126//! use std::rc::Rc;
127//!
128//! fn main() {
129//! let shared_map: Rc<RefCell<_>> = Rc::new(RefCell::new(HashMap::new()));
130//! // Create a new block to limit the scope of the dynamic borrow
131//! {
132//! let mut map: RefMut<'_, _> = shared_map.borrow_mut();
133//! map.insert("africa", 92388);
134//! map.insert("kyoto", 11837);
135//! map.insert("piccadilly", 11826);
136//! map.insert("marbles", 38);
137//! }
138//!
139//! // Note that if we had not let the previous borrow of the cache fall out
140//! // of scope then the subsequent borrow would cause a dynamic thread panic.
141//! // This is the major hazard of using `RefCell`.
142//! let total: i32 = shared_map.borrow().values().sum();
143//! println!("{total}");
144//! }
145//! ```
146//!
147//! Note that this example uses `Rc<T>` and not `Arc<T>`. `RefCell<T>`s are for single-threaded
148//! scenarios. Consider using [`RwLock<T>`] or [`Mutex<T>`] if you need shared mutability in a
149//! multi-threaded situation.
150//!
151//! ## Implementation details of logically-immutable methods
152//!
153//! Occasionally it may be desirable not to expose in an API that there is mutation happening
154//! "under the hood". This may be because logically the operation is immutable, but e.g., caching
155//! forces the implementation to perform mutation; or because you must employ mutation to implement
156//! a trait method that was originally defined to take `&self`.
157//!
158//! ```
159//! # #![allow(dead_code)]
160//! use std::cell::OnceCell;
161//!
162//! struct Graph {
163//! edges: Vec<(i32, i32)>,
164//! span_tree_cache: OnceCell<Vec<(i32, i32)>>
165//! }
166//!
167//! impl Graph {
168//! fn minimum_spanning_tree(&self) -> Vec<(i32, i32)> {
169//! self.span_tree_cache
170//! .get_or_init(|| self.calc_span_tree())
171//! .clone()
172//! }
173//!
174//! fn calc_span_tree(&self) -> Vec<(i32, i32)> {
175//! // Expensive computation goes here
176//! vec![]
177//! }
178//! }
179//! ```
180//!
181//! ## Mutating implementations of `Clone`
182//!
183//! This is simply a special - but common - case of the previous: hiding mutability for operations
184//! that appear to be immutable. The [`clone`](Clone::clone) method is expected to not change the
185//! source value, and is declared to take `&self`, not `&mut self`. Therefore, any mutation that
186//! happens in the `clone` method must use cell types. For example, [`Rc<T>`] maintains its
187//! reference counts within a `Cell<T>`.
188//!
189//! ```
190//! use std::cell::Cell;
191//! use std::ptr::NonNull;
192//! use std::process::abort;
193//! use std::marker::PhantomData;
194//!
195//! struct Rc<T: ?Sized> {
196//! ptr: NonNull<RcInner<T>>,
197//! phantom: PhantomData<RcInner<T>>,
198//! }
199//!
200//! struct RcInner<T: ?Sized> {
201//! strong: Cell<usize>,
202//! refcount: Cell<usize>,
203//! value: T,
204//! }
205//!
206//! impl<T: ?Sized> Clone for Rc<T> {
207//! fn clone(&self) -> Rc<T> {
208//! self.inc_strong();
209//! Rc {
210//! ptr: self.ptr,
211//! phantom: PhantomData,
212//! }
213//! }
214//! }
215//!
216//! trait RcInnerPtr<T: ?Sized> {
217//!
218//! fn inner(&self) -> &RcInner<T>;
219//!
220//! fn strong(&self) -> usize {
221//! self.inner().strong.get()
222//! }
223//!
224//! fn inc_strong(&self) {
225//! self.inner()
226//! .strong
227//! .set(self.strong()
228//! .checked_add(1)
229//! .unwrap_or_else(|| abort() ));
230//! }
231//! }
232//!
233//! impl<T: ?Sized> RcInnerPtr<T> for Rc<T> {
234//! fn inner(&self) -> &RcInner<T> {
235//! unsafe {
236//! self.ptr.as_ref()
237//! }
238//! }
239//! }
240//! ```
241//!
242//! [`Arc<T>`]: ../../std/sync/struct.Arc.html
243//! [`Rc<T>`]: ../../std/rc/struct.Rc.html
244//! [`RwLock<T>`]: ../../std/sync/struct.RwLock.html
245//! [`Mutex<T>`]: ../../std/sync/struct.Mutex.html
246//! [`OnceLock<T>`]: ../../std/sync/struct.OnceLock.html
247//! [`LazyLock<T, F>`]: ../../std/sync/struct.LazyLock.html
248//! [`Sync`]: ../../std/marker/trait.Sync.html
249//! [`atomic`]: crate::sync::atomic
250
251#![stable(feature = "rust1", since = "1.0.0")]
252
253#[cfg(not(feature = "ferrocene_certified"))]
254use crate::cmp::Ordering;
255#[cfg(not(feature = "ferrocene_certified"))]
256use crate::fmt::{self, Debug, Display};
257#[cfg(not(feature = "ferrocene_certified"))]
258use crate::marker::{Destruct, PhantomData, Unsize};
259#[cfg(not(feature = "ferrocene_certified"))]
260use crate::mem::{self, ManuallyDrop};
261#[cfg(not(feature = "ferrocene_certified"))]
262use crate::ops::{self, CoerceUnsized, Deref, DerefMut, DerefPure, DispatchFromDyn};
263#[cfg(not(feature = "ferrocene_certified"))]
264use crate::panic::const_panic;
265#[cfg(not(feature = "ferrocene_certified"))]
266use crate::pin::PinCoerceUnsized;
267#[cfg(not(feature = "ferrocene_certified"))]
268use crate::ptr::{self, NonNull};
269#[cfg(not(feature = "ferrocene_certified"))]
270use crate::range;
271
272#[cfg(not(feature = "ferrocene_certified"))]
273mod lazy;
274#[cfg(not(feature = "ferrocene_certified"))]
275mod once;
276
277#[stable(feature = "lazy_cell", since = "1.80.0")]
278#[cfg(not(feature = "ferrocene_certified"))]
279pub use lazy::LazyCell;
280#[stable(feature = "once_cell", since = "1.70.0")]
281#[cfg(not(feature = "ferrocene_certified"))]
282pub use once::OnceCell;
283
284/// A mutable memory location.
285///
286/// # Memory layout
287///
288/// `Cell<T>` has the same [memory layout and caveats as
289/// `UnsafeCell<T>`](UnsafeCell#memory-layout). In particular, this means that
290/// `Cell<T>` has the same in-memory representation as its inner type `T`.
291///
292/// # Examples
293///
294/// In this example, you can see that `Cell<T>` enables mutation inside an
295/// immutable struct. In other words, it enables "interior mutability".
296///
297/// ```
298/// use std::cell::Cell;
299///
300/// struct SomeStruct {
301/// regular_field: u8,
302/// special_field: Cell<u8>,
303/// }
304///
305/// let my_struct = SomeStruct {
306/// regular_field: 0,
307/// special_field: Cell::new(1),
308/// };
309///
310/// let new_value = 100;
311///
312/// // ERROR: `my_struct` is immutable
313/// // my_struct.regular_field = new_value;
314///
315/// // WORKS: although `my_struct` is immutable, `special_field` is a `Cell`,
316/// // which can always be mutated
317/// my_struct.special_field.set(new_value);
318/// assert_eq!(my_struct.special_field.get(), new_value);
319/// ```
320///
321/// See the [module-level documentation](self) for more.
322#[rustc_diagnostic_item = "Cell"]
323#[stable(feature = "rust1", since = "1.0.0")]
324#[repr(transparent)]
325#[rustc_pub_transparent]
326#[cfg(not(feature = "ferrocene_certified"))]
327pub struct Cell<T: ?Sized> {
328 value: UnsafeCell<T>,
329}
330
331#[stable(feature = "rust1", since = "1.0.0")]
332#[cfg(not(feature = "ferrocene_certified"))]
333unsafe impl<T: ?Sized> Send for Cell<T> where T: Send {}
334
335// Note that this negative impl isn't strictly necessary for correctness,
336// as `Cell` wraps `UnsafeCell`, which is itself `!Sync`.
337// However, given how important `Cell`'s `!Sync`-ness is,
338// having an explicit negative impl is nice for documentation purposes
339// and results in nicer error messages.
340#[stable(feature = "rust1", since = "1.0.0")]
341#[cfg(not(feature = "ferrocene_certified"))]
342impl<T: ?Sized> !Sync for Cell<T> {}
343
344#[stable(feature = "rust1", since = "1.0.0")]
345#[cfg(not(feature = "ferrocene_certified"))]
346impl<T: Copy> Clone for Cell<T> {
347 #[inline]
348 fn clone(&self) -> Cell<T> {
349 Cell::new(self.get())
350 }
351}
352
353#[stable(feature = "rust1", since = "1.0.0")]
354#[rustc_const_unstable(feature = "const_default", issue = "143894")]
355#[cfg(not(feature = "ferrocene_certified"))]
356impl<T: [const] Default> const Default for Cell<T> {
357 /// Creates a `Cell<T>`, with the `Default` value for T.
358 #[inline]
359 fn default() -> Cell<T> {
360 Cell::new(Default::default())
361 }
362}
363
364#[stable(feature = "rust1", since = "1.0.0")]
365#[cfg(not(feature = "ferrocene_certified"))]
366impl<T: PartialEq + Copy> PartialEq for Cell<T> {
367 #[inline]
368 fn eq(&self, other: &Cell<T>) -> bool {
369 self.get() == other.get()
370 }
371}
372
373#[stable(feature = "cell_eq", since = "1.2.0")]
374#[cfg(not(feature = "ferrocene_certified"))]
375impl<T: Eq + Copy> Eq for Cell<T> {}
376
377#[stable(feature = "cell_ord", since = "1.10.0")]
378#[cfg(not(feature = "ferrocene_certified"))]
379impl<T: PartialOrd + Copy> PartialOrd for Cell<T> {
380 #[inline]
381 fn partial_cmp(&self, other: &Cell<T>) -> Option<Ordering> {
382 self.get().partial_cmp(&other.get())
383 }
384
385 #[inline]
386 fn lt(&self, other: &Cell<T>) -> bool {
387 self.get() < other.get()
388 }
389
390 #[inline]
391 fn le(&self, other: &Cell<T>) -> bool {
392 self.get() <= other.get()
393 }
394
395 #[inline]
396 fn gt(&self, other: &Cell<T>) -> bool {
397 self.get() > other.get()
398 }
399
400 #[inline]
401 fn ge(&self, other: &Cell<T>) -> bool {
402 self.get() >= other.get()
403 }
404}
405
406#[stable(feature = "cell_ord", since = "1.10.0")]
407#[cfg(not(feature = "ferrocene_certified"))]
408impl<T: Ord + Copy> Ord for Cell<T> {
409 #[inline]
410 fn cmp(&self, other: &Cell<T>) -> Ordering {
411 self.get().cmp(&other.get())
412 }
413}
414
415#[stable(feature = "cell_from", since = "1.12.0")]
416#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
417#[cfg(not(feature = "ferrocene_certified"))]
418impl<T> const From<T> for Cell<T> {
419 /// Creates a new `Cell<T>` containing the given value.
420 fn from(t: T) -> Cell<T> {
421 Cell::new(t)
422 }
423}
424
425#[cfg(not(feature = "ferrocene_certified"))]
426impl<T> Cell<T> {
427 /// Creates a new `Cell` containing the given value.
428 ///
429 /// # Examples
430 ///
431 /// ```
432 /// use std::cell::Cell;
433 ///
434 /// let c = Cell::new(5);
435 /// ```
436 #[stable(feature = "rust1", since = "1.0.0")]
437 #[rustc_const_stable(feature = "const_cell_new", since = "1.24.0")]
438 #[inline]
439 pub const fn new(value: T) -> Cell<T> {
440 Cell { value: UnsafeCell::new(value) }
441 }
442
443 /// Sets the contained value.
444 ///
445 /// # Examples
446 ///
447 /// ```
448 /// use std::cell::Cell;
449 ///
450 /// let c = Cell::new(5);
451 ///
452 /// c.set(10);
453 /// ```
454 #[inline]
455 #[stable(feature = "rust1", since = "1.0.0")]
456 #[rustc_const_unstable(feature = "const_cell_traits", issue = "147787")]
457 pub const fn set(&self, val: T)
458 where
459 T: [const] Destruct,
460 {
461 self.replace(val);
462 }
463
464 /// Swaps the values of two `Cell`s.
465 ///
466 /// The difference with `std::mem::swap` is that this function doesn't
467 /// require a `&mut` reference.
468 ///
469 /// # Panics
470 ///
471 /// This function will panic if `self` and `other` are different `Cell`s that partially overlap.
472 /// (Using just standard library methods, it is impossible to create such partially overlapping `Cell`s.
473 /// However, unsafe code is allowed to e.g. create two `&Cell<[i32; 2]>` that partially overlap.)
474 ///
475 /// # Examples
476 ///
477 /// ```
478 /// use std::cell::Cell;
479 ///
480 /// let c1 = Cell::new(5i32);
481 /// let c2 = Cell::new(10i32);
482 /// c1.swap(&c2);
483 /// assert_eq!(10, c1.get());
484 /// assert_eq!(5, c2.get());
485 /// ```
486 #[inline]
487 #[stable(feature = "move_cell", since = "1.17.0")]
488 pub fn swap(&self, other: &Self) {
489 // This function documents that it *will* panic, and intrinsics::is_nonoverlapping doesn't
490 // do the check in const, so trying to use it here would be inviting unnecessary fragility.
491 fn is_nonoverlapping<T>(src: *const T, dst: *const T) -> bool {
492 let src_usize = src.addr();
493 let dst_usize = dst.addr();
494 let diff = src_usize.abs_diff(dst_usize);
495 diff >= size_of::<T>()
496 }
497
498 if ptr::eq(self, other) {
499 // Swapping wouldn't change anything.
500 return;
501 }
502 if !is_nonoverlapping(self, other) {
503 // See <https://github.com/rust-lang/rust/issues/80778> for why we need to stop here.
504 panic!("`Cell::swap` on overlapping non-identical `Cell`s");
505 }
506 // SAFETY: This can be risky if called from separate threads, but `Cell`
507 // is `!Sync` so this won't happen. This also won't invalidate any
508 // pointers since `Cell` makes sure nothing else will be pointing into
509 // either of these `Cell`s. We also excluded shenanigans like partially overlapping `Cell`s,
510 // so `swap` will just properly copy two full values of type `T` back and forth.
511 unsafe {
512 mem::swap(&mut *self.value.get(), &mut *other.value.get());
513 }
514 }
515
516 /// Replaces the contained value with `val`, and returns the old contained value.
517 ///
518 /// # Examples
519 ///
520 /// ```
521 /// use std::cell::Cell;
522 ///
523 /// let cell = Cell::new(5);
524 /// assert_eq!(cell.get(), 5);
525 /// assert_eq!(cell.replace(10), 5);
526 /// assert_eq!(cell.get(), 10);
527 /// ```
528 #[inline]
529 #[stable(feature = "move_cell", since = "1.17.0")]
530 #[rustc_const_stable(feature = "const_cell", since = "1.88.0")]
531 #[rustc_confusables("swap")]
532 pub const fn replace(&self, val: T) -> T {
533 // SAFETY: This can cause data races if called from a separate thread,
534 // but `Cell` is `!Sync` so this won't happen.
535 mem::replace(unsafe { &mut *self.value.get() }, val)
536 }
537
538 /// Unwraps the value, consuming the cell.
539 ///
540 /// # Examples
541 ///
542 /// ```
543 /// use std::cell::Cell;
544 ///
545 /// let c = Cell::new(5);
546 /// let five = c.into_inner();
547 ///
548 /// assert_eq!(five, 5);
549 /// ```
550 #[stable(feature = "move_cell", since = "1.17.0")]
551 #[rustc_const_stable(feature = "const_cell_into_inner", since = "1.83.0")]
552 #[rustc_allow_const_fn_unstable(const_precise_live_drops)]
553 pub const fn into_inner(self) -> T {
554 self.value.into_inner()
555 }
556}
557
558#[cfg(not(feature = "ferrocene_certified"))]
559impl<T: Copy> Cell<T> {
560 /// Returns a copy of the contained value.
561 ///
562 /// # Examples
563 ///
564 /// ```
565 /// use std::cell::Cell;
566 ///
567 /// let c = Cell::new(5);
568 ///
569 /// let five = c.get();
570 /// ```
571 #[inline]
572 #[stable(feature = "rust1", since = "1.0.0")]
573 #[rustc_const_stable(feature = "const_cell", since = "1.88.0")]
574 pub const fn get(&self) -> T {
575 // SAFETY: This can cause data races if called from a separate thread,
576 // but `Cell` is `!Sync` so this won't happen.
577 unsafe { *self.value.get() }
578 }
579
580 /// Updates the contained value using a function.
581 ///
582 /// # Examples
583 ///
584 /// ```
585 /// use std::cell::Cell;
586 ///
587 /// let c = Cell::new(5);
588 /// c.update(|x| x + 1);
589 /// assert_eq!(c.get(), 6);
590 /// ```
591 #[inline]
592 #[stable(feature = "cell_update", since = "1.88.0")]
593 #[rustc_const_unstable(feature = "const_cell_traits", issue = "147787")]
594 pub const fn update(&self, f: impl [const] FnOnce(T) -> T)
595 where
596 // FIXME(const-hack): `Copy` should imply `const Destruct`
597 T: [const] Destruct,
598 {
599 let old = self.get();
600 self.set(f(old));
601 }
602}
603
604#[cfg(not(feature = "ferrocene_certified"))]
605impl<T: ?Sized> Cell<T> {
606 /// Returns a raw pointer to the underlying data in this cell.
607 ///
608 /// # Examples
609 ///
610 /// ```
611 /// use std::cell::Cell;
612 ///
613 /// let c = Cell::new(5);
614 ///
615 /// let ptr = c.as_ptr();
616 /// ```
617 #[inline]
618 #[stable(feature = "cell_as_ptr", since = "1.12.0")]
619 #[rustc_const_stable(feature = "const_cell_as_ptr", since = "1.32.0")]
620 #[rustc_as_ptr]
621 #[rustc_never_returns_null_ptr]
622 pub const fn as_ptr(&self) -> *mut T {
623 self.value.get()
624 }
625
626 /// Returns a mutable reference to the underlying data.
627 ///
628 /// This call borrows `Cell` mutably (at compile-time) which guarantees
629 /// that we possess the only reference.
630 ///
631 /// However be cautious: this method expects `self` to be mutable, which is
632 /// generally not the case when using a `Cell`. If you require interior
633 /// mutability by reference, consider using `RefCell` which provides
634 /// run-time checked mutable borrows through its [`borrow_mut`] method.
635 ///
636 /// [`borrow_mut`]: RefCell::borrow_mut()
637 ///
638 /// # Examples
639 ///
640 /// ```
641 /// use std::cell::Cell;
642 ///
643 /// let mut c = Cell::new(5);
644 /// *c.get_mut() += 1;
645 ///
646 /// assert_eq!(c.get(), 6);
647 /// ```
648 #[inline]
649 #[stable(feature = "cell_get_mut", since = "1.11.0")]
650 #[rustc_const_stable(feature = "const_cell", since = "1.88.0")]
651 pub const fn get_mut(&mut self) -> &mut T {
652 self.value.get_mut()
653 }
654
655 /// Returns a `&Cell<T>` from a `&mut T`
656 ///
657 /// # Examples
658 ///
659 /// ```
660 /// use std::cell::Cell;
661 ///
662 /// let slice: &mut [i32] = &mut [1, 2, 3];
663 /// let cell_slice: &Cell<[i32]> = Cell::from_mut(slice);
664 /// let slice_cell: &[Cell<i32>] = cell_slice.as_slice_of_cells();
665 ///
666 /// assert_eq!(slice_cell.len(), 3);
667 /// ```
668 #[inline]
669 #[stable(feature = "as_cell", since = "1.37.0")]
670 #[rustc_const_stable(feature = "const_cell", since = "1.88.0")]
671 pub const fn from_mut(t: &mut T) -> &Cell<T> {
672 // SAFETY: `&mut` ensures unique access.
673 unsafe { &*(t as *mut T as *const Cell<T>) }
674 }
675}
676
677#[cfg(not(feature = "ferrocene_certified"))]
678impl<T: Default> Cell<T> {
679 /// Takes the value of the cell, leaving `Default::default()` in its place.
680 ///
681 /// # Examples
682 ///
683 /// ```
684 /// use std::cell::Cell;
685 ///
686 /// let c = Cell::new(5);
687 /// let five = c.take();
688 ///
689 /// assert_eq!(five, 5);
690 /// assert_eq!(c.into_inner(), 0);
691 /// ```
692 #[stable(feature = "move_cell", since = "1.17.0")]
693 #[rustc_const_unstable(feature = "const_cell_traits", issue = "147787")]
694 pub const fn take(&self) -> T
695 where
696 T: [const] Default,
697 {
698 self.replace(Default::default())
699 }
700}
701
702#[unstable(feature = "coerce_unsized", issue = "18598")]
703#[cfg(not(feature = "ferrocene_certified"))]
704impl<T: CoerceUnsized<U>, U> CoerceUnsized<Cell<U>> for Cell<T> {}
705
706// Allow types that wrap `Cell` to also implement `DispatchFromDyn`
707// and become dyn-compatible method receivers.
708// Note that currently `Cell` itself cannot be a method receiver
709// because it does not implement Deref.
710// In other words:
711// `self: Cell<&Self>` won't work
712// `self: CellWrapper<Self>` becomes possible
713#[unstable(feature = "dispatch_from_dyn", issue = "none")]
714#[cfg(not(feature = "ferrocene_certified"))]
715impl<T: DispatchFromDyn<U>, U> DispatchFromDyn<Cell<U>> for Cell<T> {}
716
717#[cfg(not(feature = "ferrocene_certified"))]
718impl<T> Cell<[T]> {
719 /// Returns a `&[Cell<T>]` from a `&Cell<[T]>`
720 ///
721 /// # Examples
722 ///
723 /// ```
724 /// use std::cell::Cell;
725 ///
726 /// let slice: &mut [i32] = &mut [1, 2, 3];
727 /// let cell_slice: &Cell<[i32]> = Cell::from_mut(slice);
728 /// let slice_cell: &[Cell<i32>] = cell_slice.as_slice_of_cells();
729 ///
730 /// assert_eq!(slice_cell.len(), 3);
731 /// ```
732 #[stable(feature = "as_cell", since = "1.37.0")]
733 #[rustc_const_stable(feature = "const_cell", since = "1.88.0")]
734 pub const fn as_slice_of_cells(&self) -> &[Cell<T>] {
735 // SAFETY: `Cell<T>` has the same memory layout as `T`.
736 unsafe { &*(self as *const Cell<[T]> as *const [Cell<T>]) }
737 }
738}
739
740#[cfg(not(feature = "ferrocene_certified"))]
741impl<T, const N: usize> Cell<[T; N]> {
742 /// Returns a `&[Cell<T>; N]` from a `&Cell<[T; N]>`
743 ///
744 /// # Examples
745 ///
746 /// ```
747 /// use std::cell::Cell;
748 ///
749 /// let mut array: [i32; 3] = [1, 2, 3];
750 /// let cell_array: &Cell<[i32; 3]> = Cell::from_mut(&mut array);
751 /// let array_cell: &[Cell<i32>; 3] = cell_array.as_array_of_cells();
752 /// ```
753 #[stable(feature = "as_array_of_cells", since = "1.91.0")]
754 #[rustc_const_stable(feature = "as_array_of_cells", since = "1.91.0")]
755 pub const fn as_array_of_cells(&self) -> &[Cell<T>; N] {
756 // SAFETY: `Cell<T>` has the same memory layout as `T`.
757 unsafe { &*(self as *const Cell<[T; N]> as *const [Cell<T>; N]) }
758 }
759}
760
761/// Types for which cloning `Cell<Self>` is sound.
762///
763/// # Safety
764///
765/// Implementing this trait for a type is sound if and only if the following code is sound for T =
766/// that type.
767///
768/// ```
769/// #![feature(cell_get_cloned)]
770/// # use std::cell::{CloneFromCell, Cell};
771/// fn clone_from_cell<T: CloneFromCell>(cell: &Cell<T>) -> T {
772/// unsafe { T::clone(&*cell.as_ptr()) }
773/// }
774/// ```
775///
776/// Importantly, you can't just implement `CloneFromCell` for any arbitrary `Copy` type, e.g. the
777/// following is unsound:
778///
779/// ```rust
780/// #![feature(cell_get_cloned)]
781/// # use std::cell::Cell;
782///
783/// #[derive(Copy, Debug)]
784/// pub struct Bad<'a>(Option<&'a Cell<Bad<'a>>>, u8);
785///
786/// impl Clone for Bad<'_> {
787/// fn clone(&self) -> Self {
788/// let a: &u8 = &self.1;
789/// // when self.0 points to self, we write to self.1 while we have a live `&u8` pointing to
790/// // it -- this is UB
791/// self.0.unwrap().set(Self(None, 1));
792/// dbg!((a, self));
793/// Self(None, 0)
794/// }
795/// }
796///
797/// // this is not sound
798/// // unsafe impl CloneFromCell for Bad<'_> {}
799/// ```
800#[unstable(feature = "cell_get_cloned", issue = "145329")]
801// Allow potential overlapping implementations in user code
802#[marker]
803#[cfg(not(feature = "ferrocene_certified"))]
804pub unsafe trait CloneFromCell: Clone {}
805
806// `CloneFromCell` can be implemented for types that don't have indirection and which don't access
807// `Cell`s in their `Clone` implementation. A commonly-used subset is covered here.
808#[unstable(feature = "cell_get_cloned", issue = "145329")]
809#[cfg(not(feature = "ferrocene_certified"))]
810unsafe impl<T: CloneFromCell, const N: usize> CloneFromCell for [T; N] {}
811#[unstable(feature = "cell_get_cloned", issue = "145329")]
812#[cfg(not(feature = "ferrocene_certified"))]
813unsafe impl<T: CloneFromCell> CloneFromCell for Option<T> {}
814#[unstable(feature = "cell_get_cloned", issue = "145329")]
815#[cfg(not(feature = "ferrocene_certified"))]
816unsafe impl<T: CloneFromCell, E: CloneFromCell> CloneFromCell for Result<T, E> {}
817#[unstable(feature = "cell_get_cloned", issue = "145329")]
818#[cfg(not(feature = "ferrocene_certified"))]
819unsafe impl<T: ?Sized> CloneFromCell for PhantomData<T> {}
820#[unstable(feature = "cell_get_cloned", issue = "145329")]
821#[cfg(not(feature = "ferrocene_certified"))]
822unsafe impl<T: CloneFromCell> CloneFromCell for ManuallyDrop<T> {}
823#[unstable(feature = "cell_get_cloned", issue = "145329")]
824#[cfg(not(feature = "ferrocene_certified"))]
825unsafe impl<T: CloneFromCell> CloneFromCell for ops::Range<T> {}
826#[unstable(feature = "cell_get_cloned", issue = "145329")]
827#[cfg(not(feature = "ferrocene_certified"))]
828unsafe impl<T: CloneFromCell> CloneFromCell for range::Range<T> {}
829
830#[unstable(feature = "cell_get_cloned", issue = "145329")]
831#[cfg(not(feature = "ferrocene_certified"))]
832impl<T: CloneFromCell> Cell<T> {
833 /// Get a clone of the `Cell` that contains a copy of the original value.
834 ///
835 /// This allows a cheaply `Clone`-able type like an `Rc` to be stored in a `Cell`, exposing the
836 /// cheaper `clone()` method.
837 ///
838 /// # Examples
839 ///
840 /// ```
841 /// #![feature(cell_get_cloned)]
842 ///
843 /// use core::cell::Cell;
844 /// use std::rc::Rc;
845 ///
846 /// let rc = Rc::new(1usize);
847 /// let c1 = Cell::new(rc);
848 /// let c2 = c1.get_cloned();
849 /// assert_eq!(*c2.into_inner(), 1);
850 /// ```
851 pub fn get_cloned(&self) -> Self {
852 // SAFETY: T is CloneFromCell, which guarantees that this is sound.
853 Cell::new(T::clone(unsafe { &*self.as_ptr() }))
854 }
855}
856
857/// A mutable memory location with dynamically checked borrow rules
858///
859/// See the [module-level documentation](self) for more.
860#[rustc_diagnostic_item = "RefCell"]
861#[stable(feature = "rust1", since = "1.0.0")]
862#[cfg(not(feature = "ferrocene_certified"))]
863pub struct RefCell<T: ?Sized> {
864 borrow: Cell<BorrowCounter>,
865 // Stores the location of the earliest currently active borrow.
866 // This gets updated whenever we go from having zero borrows
867 // to having a single borrow. When a borrow occurs, this gets included
868 // in the generated `BorrowError`/`BorrowMutError`
869 #[cfg(feature = "debug_refcell")]
870 borrowed_at: Cell<Option<&'static crate::panic::Location<'static>>>,
871 value: UnsafeCell<T>,
872}
873
874/// An error returned by [`RefCell::try_borrow`].
875#[stable(feature = "try_borrow", since = "1.13.0")]
876#[non_exhaustive]
877#[derive(Debug)]
878#[cfg(not(feature = "ferrocene_certified"))]
879pub struct BorrowError {
880 #[cfg(feature = "debug_refcell")]
881 location: &'static crate::panic::Location<'static>,
882}
883
884#[stable(feature = "try_borrow", since = "1.13.0")]
885#[cfg(not(feature = "ferrocene_certified"))]
886impl Display for BorrowError {
887 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
888 #[cfg(feature = "debug_refcell")]
889 let res = write!(
890 f,
891 "RefCell already mutably borrowed; a previous borrow was at {}",
892 self.location
893 );
894
895 #[cfg(not(feature = "debug_refcell"))]
896 let res = Display::fmt("RefCell already mutably borrowed", f);
897
898 res
899 }
900}
901
902/// An error returned by [`RefCell::try_borrow_mut`].
903#[stable(feature = "try_borrow", since = "1.13.0")]
904#[non_exhaustive]
905#[derive(Debug)]
906#[cfg(not(feature = "ferrocene_certified"))]
907pub struct BorrowMutError {
908 #[cfg(feature = "debug_refcell")]
909 location: &'static crate::panic::Location<'static>,
910}
911
912#[stable(feature = "try_borrow", since = "1.13.0")]
913#[cfg(not(feature = "ferrocene_certified"))]
914impl Display for BorrowMutError {
915 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
916 #[cfg(feature = "debug_refcell")]
917 let res = write!(f, "RefCell already borrowed; a previous borrow was at {}", self.location);
918
919 #[cfg(not(feature = "debug_refcell"))]
920 let res = Display::fmt("RefCell already borrowed", f);
921
922 res
923 }
924}
925
926// This ensures the panicking code is outlined from `borrow_mut` for `RefCell`.
927#[cfg_attr(not(panic = "immediate-abort"), inline(never))]
928#[track_caller]
929#[cold]
930#[cfg(not(feature = "ferrocene_certified"))]
931const fn panic_already_borrowed(err: BorrowMutError) -> ! {
932 const_panic!(
933 "RefCell already borrowed",
934 "{err}",
935 err: BorrowMutError = err,
936 )
937}
938
939// This ensures the panicking code is outlined from `borrow` for `RefCell`.
940#[cfg_attr(not(panic = "immediate-abort"), inline(never))]
941#[track_caller]
942#[cold]
943#[cfg(not(feature = "ferrocene_certified"))]
944const fn panic_already_mutably_borrowed(err: BorrowError) -> ! {
945 const_panic!(
946 "RefCell already mutably borrowed",
947 "{err}",
948 err: BorrowError = err,
949 )
950}
951
952// Positive values represent the number of `Ref` active. Negative values
953// represent the number of `RefMut` active. Multiple `RefMut`s can only be
954// active at a time if they refer to distinct, nonoverlapping components of a
955// `RefCell` (e.g., different ranges of a slice).
956//
957// `Ref` and `RefMut` are both two words in size, and so there will likely never
958// be enough `Ref`s or `RefMut`s in existence to overflow half of the `usize`
959// range. Thus, a `BorrowCounter` will probably never overflow or underflow.
960// However, this is not a guarantee, as a pathological program could repeatedly
961// create and then mem::forget `Ref`s or `RefMut`s. Thus, all code must
962// explicitly check for overflow and underflow in order to avoid unsafety, or at
963// least behave correctly in the event that overflow or underflow happens (e.g.,
964// see BorrowRef::new).
965#[cfg(not(feature = "ferrocene_certified"))]
966type BorrowCounter = isize;
967#[cfg(not(feature = "ferrocene_certified"))]
968const UNUSED: BorrowCounter = 0;
969
970#[inline(always)]
971#[cfg(not(feature = "ferrocene_certified"))]
972const fn is_writing(x: BorrowCounter) -> bool {
973 x < UNUSED
974}
975
976#[inline(always)]
977#[cfg(not(feature = "ferrocene_certified"))]
978const fn is_reading(x: BorrowCounter) -> bool {
979 x > UNUSED
980}
981
982#[cfg(not(feature = "ferrocene_certified"))]
983impl<T> RefCell<T> {
984 /// Creates a new `RefCell` containing `value`.
985 ///
986 /// # Examples
987 ///
988 /// ```
989 /// use std::cell::RefCell;
990 ///
991 /// let c = RefCell::new(5);
992 /// ```
993 #[stable(feature = "rust1", since = "1.0.0")]
994 #[rustc_const_stable(feature = "const_refcell_new", since = "1.24.0")]
995 #[inline]
996 pub const fn new(value: T) -> RefCell<T> {
997 RefCell {
998 value: UnsafeCell::new(value),
999 borrow: Cell::new(UNUSED),
1000 #[cfg(feature = "debug_refcell")]
1001 borrowed_at: Cell::new(None),
1002 }
1003 }
1004
1005 /// Consumes the `RefCell`, returning the wrapped value.
1006 ///
1007 /// # Examples
1008 ///
1009 /// ```
1010 /// use std::cell::RefCell;
1011 ///
1012 /// let c = RefCell::new(5);
1013 ///
1014 /// let five = c.into_inner();
1015 /// ```
1016 #[stable(feature = "rust1", since = "1.0.0")]
1017 #[rustc_const_stable(feature = "const_cell_into_inner", since = "1.83.0")]
1018 #[rustc_allow_const_fn_unstable(const_precise_live_drops)]
1019 #[inline]
1020 pub const fn into_inner(self) -> T {
1021 // Since this function takes `self` (the `RefCell`) by value, the
1022 // compiler statically verifies that it is not currently borrowed.
1023 self.value.into_inner()
1024 }
1025
1026 /// Replaces the wrapped value with a new one, returning the old value,
1027 /// without deinitializing either one.
1028 ///
1029 /// This function corresponds to [`std::mem::replace`](../mem/fn.replace.html).
1030 ///
1031 /// # Panics
1032 ///
1033 /// Panics if the value is currently borrowed.
1034 ///
1035 /// # Examples
1036 ///
1037 /// ```
1038 /// use std::cell::RefCell;
1039 /// let cell = RefCell::new(5);
1040 /// let old_value = cell.replace(6);
1041 /// assert_eq!(old_value, 5);
1042 /// assert_eq!(cell, RefCell::new(6));
1043 /// ```
1044 #[inline]
1045 #[stable(feature = "refcell_replace", since = "1.24.0")]
1046 #[track_caller]
1047 #[rustc_confusables("swap")]
1048 #[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
1049 pub const fn replace(&self, t: T) -> T {
1050 mem::replace(&mut self.borrow_mut(), t)
1051 }
1052
1053 /// Replaces the wrapped value with a new one computed from `f`, returning
1054 /// the old value, without deinitializing either one.
1055 ///
1056 /// # Panics
1057 ///
1058 /// Panics if the value is currently borrowed.
1059 ///
1060 /// # Examples
1061 ///
1062 /// ```
1063 /// use std::cell::RefCell;
1064 /// let cell = RefCell::new(5);
1065 /// let old_value = cell.replace_with(|&mut old| old + 1);
1066 /// assert_eq!(old_value, 5);
1067 /// assert_eq!(cell, RefCell::new(6));
1068 /// ```
1069 #[inline]
1070 #[stable(feature = "refcell_replace_swap", since = "1.35.0")]
1071 #[track_caller]
1072 pub fn replace_with<F: FnOnce(&mut T) -> T>(&self, f: F) -> T {
1073 let mut_borrow = &mut *self.borrow_mut();
1074 let replacement = f(mut_borrow);
1075 mem::replace(mut_borrow, replacement)
1076 }
1077
1078 /// Swaps the wrapped value of `self` with the wrapped value of `other`,
1079 /// without deinitializing either one.
1080 ///
1081 /// This function corresponds to [`std::mem::swap`](../mem/fn.swap.html).
1082 ///
1083 /// # Panics
1084 ///
1085 /// Panics if the value in either `RefCell` is currently borrowed, or
1086 /// if `self` and `other` point to the same `RefCell`.
1087 ///
1088 /// # Examples
1089 ///
1090 /// ```
1091 /// use std::cell::RefCell;
1092 /// let c = RefCell::new(5);
1093 /// let d = RefCell::new(6);
1094 /// c.swap(&d);
1095 /// assert_eq!(c, RefCell::new(6));
1096 /// assert_eq!(d, RefCell::new(5));
1097 /// ```
1098 #[inline]
1099 #[stable(feature = "refcell_swap", since = "1.24.0")]
1100 #[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
1101 pub const fn swap(&self, other: &Self) {
1102 mem::swap(&mut *self.borrow_mut(), &mut *other.borrow_mut())
1103 }
1104}
1105
1106#[cfg(not(feature = "ferrocene_certified"))]
1107impl<T: ?Sized> RefCell<T> {
1108 /// Immutably borrows the wrapped value.
1109 ///
1110 /// The borrow lasts until the returned `Ref` exits scope. Multiple
1111 /// immutable borrows can be taken out at the same time.
1112 ///
1113 /// # Panics
1114 ///
1115 /// Panics if the value is currently mutably borrowed. For a non-panicking variant, use
1116 /// [`try_borrow`](#method.try_borrow).
1117 ///
1118 /// # Examples
1119 ///
1120 /// ```
1121 /// use std::cell::RefCell;
1122 ///
1123 /// let c = RefCell::new(5);
1124 ///
1125 /// let borrowed_five = c.borrow();
1126 /// let borrowed_five2 = c.borrow();
1127 /// ```
1128 ///
1129 /// An example of panic:
1130 ///
1131 /// ```should_panic
1132 /// use std::cell::RefCell;
1133 ///
1134 /// let c = RefCell::new(5);
1135 ///
1136 /// let m = c.borrow_mut();
1137 /// let b = c.borrow(); // this causes a panic
1138 /// ```
1139 #[stable(feature = "rust1", since = "1.0.0")]
1140 #[inline]
1141 #[track_caller]
1142 #[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
1143 pub const fn borrow(&self) -> Ref<'_, T> {
1144 match self.try_borrow() {
1145 Ok(b) => b,
1146 Err(err) => panic_already_mutably_borrowed(err),
1147 }
1148 }
1149
1150 /// Immutably borrows the wrapped value, returning an error if the value is currently mutably
1151 /// borrowed.
1152 ///
1153 /// The borrow lasts until the returned `Ref` exits scope. Multiple immutable borrows can be
1154 /// taken out at the same time.
1155 ///
1156 /// This is the non-panicking variant of [`borrow`](#method.borrow).
1157 ///
1158 /// # Examples
1159 ///
1160 /// ```
1161 /// use std::cell::RefCell;
1162 ///
1163 /// let c = RefCell::new(5);
1164 ///
1165 /// {
1166 /// let m = c.borrow_mut();
1167 /// assert!(c.try_borrow().is_err());
1168 /// }
1169 ///
1170 /// {
1171 /// let m = c.borrow();
1172 /// assert!(c.try_borrow().is_ok());
1173 /// }
1174 /// ```
1175 #[stable(feature = "try_borrow", since = "1.13.0")]
1176 #[inline]
1177 #[cfg_attr(feature = "debug_refcell", track_caller)]
1178 #[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
1179 pub const fn try_borrow(&self) -> Result<Ref<'_, T>, BorrowError> {
1180 match BorrowRef::new(&self.borrow) {
1181 Some(b) => {
1182 #[cfg(feature = "debug_refcell")]
1183 {
1184 // `borrowed_at` is always the *first* active borrow
1185 if b.borrow.get() == 1 {
1186 self.borrowed_at.replace(Some(crate::panic::Location::caller()));
1187 }
1188 }
1189
1190 // SAFETY: `BorrowRef` ensures that there is only immutable access
1191 // to the value while borrowed.
1192 let value = unsafe { NonNull::new_unchecked(self.value.get()) };
1193 Ok(Ref { value, borrow: b })
1194 }
1195 None => Err(BorrowError {
1196 // If a borrow occurred, then we must already have an outstanding borrow,
1197 // so `borrowed_at` will be `Some`
1198 #[cfg(feature = "debug_refcell")]
1199 location: self.borrowed_at.get().unwrap(),
1200 }),
1201 }
1202 }
1203
1204 /// Mutably borrows the wrapped value.
1205 ///
1206 /// The borrow lasts until the returned `RefMut` or all `RefMut`s derived
1207 /// from it exit scope. The value cannot be borrowed while this borrow is
1208 /// active.
1209 ///
1210 /// # Panics
1211 ///
1212 /// Panics if the value is currently borrowed. For a non-panicking variant, use
1213 /// [`try_borrow_mut`](#method.try_borrow_mut).
1214 ///
1215 /// # Examples
1216 ///
1217 /// ```
1218 /// use std::cell::RefCell;
1219 ///
1220 /// let c = RefCell::new("hello".to_owned());
1221 ///
1222 /// *c.borrow_mut() = "bonjour".to_owned();
1223 ///
1224 /// assert_eq!(&*c.borrow(), "bonjour");
1225 /// ```
1226 ///
1227 /// An example of panic:
1228 ///
1229 /// ```should_panic
1230 /// use std::cell::RefCell;
1231 ///
1232 /// let c = RefCell::new(5);
1233 /// let m = c.borrow();
1234 ///
1235 /// let b = c.borrow_mut(); // this causes a panic
1236 /// ```
1237 #[stable(feature = "rust1", since = "1.0.0")]
1238 #[inline]
1239 #[track_caller]
1240 #[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
1241 pub const fn borrow_mut(&self) -> RefMut<'_, T> {
1242 match self.try_borrow_mut() {
1243 Ok(b) => b,
1244 Err(err) => panic_already_borrowed(err),
1245 }
1246 }
1247
1248 /// Mutably borrows the wrapped value, returning an error if the value is currently borrowed.
1249 ///
1250 /// The borrow lasts until the returned `RefMut` or all `RefMut`s derived
1251 /// from it exit scope. The value cannot be borrowed while this borrow is
1252 /// active.
1253 ///
1254 /// This is the non-panicking variant of [`borrow_mut`](#method.borrow_mut).
1255 ///
1256 /// # Examples
1257 ///
1258 /// ```
1259 /// use std::cell::RefCell;
1260 ///
1261 /// let c = RefCell::new(5);
1262 ///
1263 /// {
1264 /// let m = c.borrow();
1265 /// assert!(c.try_borrow_mut().is_err());
1266 /// }
1267 ///
1268 /// assert!(c.try_borrow_mut().is_ok());
1269 /// ```
1270 #[stable(feature = "try_borrow", since = "1.13.0")]
1271 #[inline]
1272 #[cfg_attr(feature = "debug_refcell", track_caller)]
1273 #[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
1274 pub const fn try_borrow_mut(&self) -> Result<RefMut<'_, T>, BorrowMutError> {
1275 match BorrowRefMut::new(&self.borrow) {
1276 Some(b) => {
1277 #[cfg(feature = "debug_refcell")]
1278 {
1279 self.borrowed_at.replace(Some(crate::panic::Location::caller()));
1280 }
1281
1282 // SAFETY: `BorrowRefMut` guarantees unique access.
1283 let value = unsafe { NonNull::new_unchecked(self.value.get()) };
1284 Ok(RefMut { value, borrow: b, marker: PhantomData })
1285 }
1286 None => Err(BorrowMutError {
1287 // If a borrow occurred, then we must already have an outstanding borrow,
1288 // so `borrowed_at` will be `Some`
1289 #[cfg(feature = "debug_refcell")]
1290 location: self.borrowed_at.get().unwrap(),
1291 }),
1292 }
1293 }
1294
1295 /// Returns a raw pointer to the underlying data in this cell.
1296 ///
1297 /// # Examples
1298 ///
1299 /// ```
1300 /// use std::cell::RefCell;
1301 ///
1302 /// let c = RefCell::new(5);
1303 ///
1304 /// let ptr = c.as_ptr();
1305 /// ```
1306 #[inline]
1307 #[stable(feature = "cell_as_ptr", since = "1.12.0")]
1308 #[rustc_as_ptr]
1309 #[rustc_never_returns_null_ptr]
1310 #[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
1311 pub const fn as_ptr(&self) -> *mut T {
1312 self.value.get()
1313 }
1314
1315 /// Returns a mutable reference to the underlying data.
1316 ///
1317 /// Since this method borrows `RefCell` mutably, it is statically guaranteed
1318 /// that no borrows to the underlying data exist. The dynamic checks inherent
1319 /// in [`borrow_mut`] and most other methods of `RefCell` are therefore
1320 /// unnecessary. Note that this method does not reset the borrowing state if borrows were previously leaked
1321 /// (e.g., via [`forget()`] on a [`Ref`] or [`RefMut`]). For that purpose,
1322 /// consider using the unstable [`undo_leak`] method.
1323 ///
1324 /// This method can only be called if `RefCell` can be mutably borrowed,
1325 /// which in general is only the case directly after the `RefCell` has
1326 /// been created. In these situations, skipping the aforementioned dynamic
1327 /// borrowing checks may yield better ergonomics and runtime-performance.
1328 ///
1329 /// In most situations where `RefCell` is used, it can't be borrowed mutably.
1330 /// Use [`borrow_mut`] to get mutable access to the underlying data then.
1331 ///
1332 /// [`borrow_mut`]: RefCell::borrow_mut()
1333 /// [`forget()`]: mem::forget
1334 /// [`undo_leak`]: RefCell::undo_leak()
1335 ///
1336 /// # Examples
1337 ///
1338 /// ```
1339 /// use std::cell::RefCell;
1340 ///
1341 /// let mut c = RefCell::new(5);
1342 /// *c.get_mut() += 1;
1343 ///
1344 /// assert_eq!(c, RefCell::new(6));
1345 /// ```
1346 #[inline]
1347 #[stable(feature = "cell_get_mut", since = "1.11.0")]
1348 #[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
1349 pub const fn get_mut(&mut self) -> &mut T {
1350 self.value.get_mut()
1351 }
1352
1353 /// Undo the effect of leaked guards on the borrow state of the `RefCell`.
1354 ///
1355 /// This call is similar to [`get_mut`] but more specialized. It borrows `RefCell` mutably to
1356 /// ensure no borrows exist and then resets the state tracking shared borrows. This is relevant
1357 /// if some `Ref` or `RefMut` borrows have been leaked.
1358 ///
1359 /// [`get_mut`]: RefCell::get_mut()
1360 ///
1361 /// # Examples
1362 ///
1363 /// ```
1364 /// #![feature(cell_leak)]
1365 /// use std::cell::RefCell;
1366 ///
1367 /// let mut c = RefCell::new(0);
1368 /// std::mem::forget(c.borrow_mut());
1369 ///
1370 /// assert!(c.try_borrow().is_err());
1371 /// c.undo_leak();
1372 /// assert!(c.try_borrow().is_ok());
1373 /// ```
1374 #[unstable(feature = "cell_leak", issue = "69099")]
1375 #[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
1376 pub const fn undo_leak(&mut self) -> &mut T {
1377 *self.borrow.get_mut() = UNUSED;
1378 self.get_mut()
1379 }
1380
1381 /// Immutably borrows the wrapped value, returning an error if the value is
1382 /// currently mutably borrowed.
1383 ///
1384 /// # Safety
1385 ///
1386 /// Unlike `RefCell::borrow`, this method is unsafe because it does not
1387 /// return a `Ref`, thus leaving the borrow flag untouched. Mutably
1388 /// borrowing the `RefCell` while the reference returned by this method
1389 /// is alive is undefined behavior.
1390 ///
1391 /// # Examples
1392 ///
1393 /// ```
1394 /// use std::cell::RefCell;
1395 ///
1396 /// let c = RefCell::new(5);
1397 ///
1398 /// {
1399 /// let m = c.borrow_mut();
1400 /// assert!(unsafe { c.try_borrow_unguarded() }.is_err());
1401 /// }
1402 ///
1403 /// {
1404 /// let m = c.borrow();
1405 /// assert!(unsafe { c.try_borrow_unguarded() }.is_ok());
1406 /// }
1407 /// ```
1408 #[stable(feature = "borrow_state", since = "1.37.0")]
1409 #[inline]
1410 #[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
1411 pub const unsafe fn try_borrow_unguarded(&self) -> Result<&T, BorrowError> {
1412 if !is_writing(self.borrow.get()) {
1413 // SAFETY: We check that nobody is actively writing now, but it is
1414 // the caller's responsibility to ensure that nobody writes until
1415 // the returned reference is no longer in use.
1416 // Also, `self.value.get()` refers to the value owned by `self`
1417 // and is thus guaranteed to be valid for the lifetime of `self`.
1418 Ok(unsafe { &*self.value.get() })
1419 } else {
1420 Err(BorrowError {
1421 // If a borrow occurred, then we must already have an outstanding borrow,
1422 // so `borrowed_at` will be `Some`
1423 #[cfg(feature = "debug_refcell")]
1424 location: self.borrowed_at.get().unwrap(),
1425 })
1426 }
1427 }
1428}
1429
1430#[cfg(not(feature = "ferrocene_certified"))]
1431impl<T: Default> RefCell<T> {
1432 /// Takes the wrapped value, leaving `Default::default()` in its place.
1433 ///
1434 /// # Panics
1435 ///
1436 /// Panics if the value is currently borrowed.
1437 ///
1438 /// # Examples
1439 ///
1440 /// ```
1441 /// use std::cell::RefCell;
1442 ///
1443 /// let c = RefCell::new(5);
1444 /// let five = c.take();
1445 ///
1446 /// assert_eq!(five, 5);
1447 /// assert_eq!(c.into_inner(), 0);
1448 /// ```
1449 #[stable(feature = "refcell_take", since = "1.50.0")]
1450 pub fn take(&self) -> T {
1451 self.replace(Default::default())
1452 }
1453}
1454
1455#[stable(feature = "rust1", since = "1.0.0")]
1456#[cfg(not(feature = "ferrocene_certified"))]
1457unsafe impl<T: ?Sized> Send for RefCell<T> where T: Send {}
1458
1459#[stable(feature = "rust1", since = "1.0.0")]
1460#[cfg(not(feature = "ferrocene_certified"))]
1461impl<T: ?Sized> !Sync for RefCell<T> {}
1462
1463#[stable(feature = "rust1", since = "1.0.0")]
1464#[cfg(not(feature = "ferrocene_certified"))]
1465impl<T: Clone> Clone for RefCell<T> {
1466 /// # Panics
1467 ///
1468 /// Panics if the value is currently mutably borrowed.
1469 #[inline]
1470 #[track_caller]
1471 fn clone(&self) -> RefCell<T> {
1472 RefCell::new(self.borrow().clone())
1473 }
1474
1475 /// # Panics
1476 ///
1477 /// Panics if `source` is currently mutably borrowed.
1478 #[inline]
1479 #[track_caller]
1480 fn clone_from(&mut self, source: &Self) {
1481 self.get_mut().clone_from(&source.borrow())
1482 }
1483}
1484
1485#[stable(feature = "rust1", since = "1.0.0")]
1486#[rustc_const_unstable(feature = "const_default", issue = "143894")]
1487#[cfg(not(feature = "ferrocene_certified"))]
1488impl<T: [const] Default> const Default for RefCell<T> {
1489 /// Creates a `RefCell<T>`, with the `Default` value for T.
1490 #[inline]
1491 fn default() -> RefCell<T> {
1492 RefCell::new(Default::default())
1493 }
1494}
1495
1496#[stable(feature = "rust1", since = "1.0.0")]
1497#[cfg(not(feature = "ferrocene_certified"))]
1498impl<T: ?Sized + PartialEq> PartialEq for RefCell<T> {
1499 /// # Panics
1500 ///
1501 /// Panics if the value in either `RefCell` is currently mutably borrowed.
1502 #[inline]
1503 fn eq(&self, other: &RefCell<T>) -> bool {
1504 *self.borrow() == *other.borrow()
1505 }
1506}
1507
1508#[stable(feature = "cell_eq", since = "1.2.0")]
1509#[cfg(not(feature = "ferrocene_certified"))]
1510impl<T: ?Sized + Eq> Eq for RefCell<T> {}
1511
1512#[stable(feature = "cell_ord", since = "1.10.0")]
1513#[cfg(not(feature = "ferrocene_certified"))]
1514impl<T: ?Sized + PartialOrd> PartialOrd for RefCell<T> {
1515 /// # Panics
1516 ///
1517 /// Panics if the value in either `RefCell` is currently mutably borrowed.
1518 #[inline]
1519 fn partial_cmp(&self, other: &RefCell<T>) -> Option<Ordering> {
1520 self.borrow().partial_cmp(&*other.borrow())
1521 }
1522
1523 /// # Panics
1524 ///
1525 /// Panics if the value in either `RefCell` is currently mutably borrowed.
1526 #[inline]
1527 fn lt(&self, other: &RefCell<T>) -> bool {
1528 *self.borrow() < *other.borrow()
1529 }
1530
1531 /// # Panics
1532 ///
1533 /// Panics if the value in either `RefCell` is currently mutably borrowed.
1534 #[inline]
1535 fn le(&self, other: &RefCell<T>) -> bool {
1536 *self.borrow() <= *other.borrow()
1537 }
1538
1539 /// # Panics
1540 ///
1541 /// Panics if the value in either `RefCell` is currently mutably borrowed.
1542 #[inline]
1543 fn gt(&self, other: &RefCell<T>) -> bool {
1544 *self.borrow() > *other.borrow()
1545 }
1546
1547 /// # Panics
1548 ///
1549 /// Panics if the value in either `RefCell` is currently mutably borrowed.
1550 #[inline]
1551 fn ge(&self, other: &RefCell<T>) -> bool {
1552 *self.borrow() >= *other.borrow()
1553 }
1554}
1555
1556#[stable(feature = "cell_ord", since = "1.10.0")]
1557#[cfg(not(feature = "ferrocene_certified"))]
1558impl<T: ?Sized + Ord> Ord for RefCell<T> {
1559 /// # Panics
1560 ///
1561 /// Panics if the value in either `RefCell` is currently mutably borrowed.
1562 #[inline]
1563 fn cmp(&self, other: &RefCell<T>) -> Ordering {
1564 self.borrow().cmp(&*other.borrow())
1565 }
1566}
1567
1568#[stable(feature = "cell_from", since = "1.12.0")]
1569#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
1570#[cfg(not(feature = "ferrocene_certified"))]
1571impl<T> const From<T> for RefCell<T> {
1572 /// Creates a new `RefCell<T>` containing the given value.
1573 fn from(t: T) -> RefCell<T> {
1574 RefCell::new(t)
1575 }
1576}
1577
1578#[unstable(feature = "coerce_unsized", issue = "18598")]
1579#[cfg(not(feature = "ferrocene_certified"))]
1580impl<T: CoerceUnsized<U>, U> CoerceUnsized<RefCell<U>> for RefCell<T> {}
1581
1582#[cfg(not(feature = "ferrocene_certified"))]
1583struct BorrowRef<'b> {
1584 borrow: &'b Cell<BorrowCounter>,
1585}
1586
1587#[cfg(not(feature = "ferrocene_certified"))]
1588impl<'b> BorrowRef<'b> {
1589 #[inline]
1590 const fn new(borrow: &'b Cell<BorrowCounter>) -> Option<BorrowRef<'b>> {
1591 let b = borrow.get().wrapping_add(1);
1592 if !is_reading(b) {
1593 // Incrementing borrow can result in a non-reading value (<= 0) in these cases:
1594 // 1. It was < 0, i.e. there are writing borrows, so we can't allow a read borrow
1595 // due to Rust's reference aliasing rules
1596 // 2. It was isize::MAX (the max amount of reading borrows) and it overflowed
1597 // into isize::MIN (the max amount of writing borrows) so we can't allow
1598 // an additional read borrow because isize can't represent so many read borrows
1599 // (this can only happen if you mem::forget more than a small constant amount of
1600 // `Ref`s, which is not good practice)
1601 None
1602 } else {
1603 // Incrementing borrow can result in a reading value (> 0) in these cases:
1604 // 1. It was = 0, i.e. it wasn't borrowed, and we are taking the first read borrow
1605 // 2. It was > 0 and < isize::MAX, i.e. there were read borrows, and isize
1606 // is large enough to represent having one more read borrow
1607 borrow.replace(b);
1608 Some(BorrowRef { borrow })
1609 }
1610 }
1611}
1612
1613#[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
1614#[cfg(not(feature = "ferrocene_certified"))]
1615impl const Drop for BorrowRef<'_> {
1616 #[inline]
1617 fn drop(&mut self) {
1618 let borrow = self.borrow.get();
1619 debug_assert!(is_reading(borrow));
1620 self.borrow.replace(borrow - 1);
1621 }
1622}
1623
1624#[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
1625#[cfg(not(feature = "ferrocene_certified"))]
1626impl const Clone for BorrowRef<'_> {
1627 #[inline]
1628 fn clone(&self) -> Self {
1629 // Since this Ref exists, we know the borrow flag
1630 // is a reading borrow.
1631 let borrow = self.borrow.get();
1632 debug_assert!(is_reading(borrow));
1633 // Prevent the borrow counter from overflowing into
1634 // a writing borrow.
1635 assert!(borrow != BorrowCounter::MAX);
1636 self.borrow.replace(borrow + 1);
1637 BorrowRef { borrow: self.borrow }
1638 }
1639}
1640
1641/// Wraps a borrowed reference to a value in a `RefCell` box.
1642/// A wrapper type for an immutably borrowed value from a `RefCell<T>`.
1643///
1644/// See the [module-level documentation](self) for more.
1645#[stable(feature = "rust1", since = "1.0.0")]
1646#[must_not_suspend = "holding a Ref across suspend points can cause BorrowErrors"]
1647#[rustc_diagnostic_item = "RefCellRef"]
1648#[cfg(not(feature = "ferrocene_certified"))]
1649pub struct Ref<'b, T: ?Sized + 'b> {
1650 // NB: we use a pointer instead of `&'b T` to avoid `noalias` violations, because a
1651 // `Ref` argument doesn't hold immutability for its whole scope, only until it drops.
1652 // `NonNull` is also covariant over `T`, just like we would have with `&T`.
1653 value: NonNull<T>,
1654 borrow: BorrowRef<'b>,
1655}
1656
1657#[stable(feature = "rust1", since = "1.0.0")]
1658#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
1659#[cfg(not(feature = "ferrocene_certified"))]
1660impl<T: ?Sized> const Deref for Ref<'_, T> {
1661 type Target = T;
1662
1663 #[inline]
1664 fn deref(&self) -> &T {
1665 // SAFETY: the value is accessible as long as we hold our borrow.
1666 unsafe { self.value.as_ref() }
1667 }
1668}
1669
1670#[unstable(feature = "deref_pure_trait", issue = "87121")]
1671#[cfg(not(feature = "ferrocene_certified"))]
1672unsafe impl<T: ?Sized> DerefPure for Ref<'_, T> {}
1673
1674#[cfg(not(feature = "ferrocene_certified"))]
1675impl<'b, T: ?Sized> Ref<'b, T> {
1676 /// Copies a `Ref`.
1677 ///
1678 /// The `RefCell` is already immutably borrowed, so this cannot fail.
1679 ///
1680 /// This is an associated function that needs to be used as
1681 /// `Ref::clone(...)`. A `Clone` implementation or a method would interfere
1682 /// with the widespread use of `r.borrow().clone()` to clone the contents of
1683 /// a `RefCell`.
1684 #[stable(feature = "cell_extras", since = "1.15.0")]
1685 #[must_use]
1686 #[inline]
1687 #[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
1688 pub const fn clone(orig: &Ref<'b, T>) -> Ref<'b, T> {
1689 Ref { value: orig.value, borrow: orig.borrow.clone() }
1690 }
1691
1692 /// Makes a new `Ref` for a component of the borrowed data.
1693 ///
1694 /// The `RefCell` is already immutably borrowed, so this cannot fail.
1695 ///
1696 /// This is an associated function that needs to be used as `Ref::map(...)`.
1697 /// A method would interfere with methods of the same name on the contents
1698 /// of a `RefCell` used through `Deref`.
1699 ///
1700 /// # Examples
1701 ///
1702 /// ```
1703 /// use std::cell::{RefCell, Ref};
1704 ///
1705 /// let c = RefCell::new((5, 'b'));
1706 /// let b1: Ref<'_, (u32, char)> = c.borrow();
1707 /// let b2: Ref<'_, u32> = Ref::map(b1, |t| &t.0);
1708 /// assert_eq!(*b2, 5)
1709 /// ```
1710 #[stable(feature = "cell_map", since = "1.8.0")]
1711 #[inline]
1712 pub fn map<U: ?Sized, F>(orig: Ref<'b, T>, f: F) -> Ref<'b, U>
1713 where
1714 F: FnOnce(&T) -> &U,
1715 {
1716 Ref { value: NonNull::from(f(&*orig)), borrow: orig.borrow }
1717 }
1718
1719 /// Makes a new `Ref` for an optional component of the borrowed data. The
1720 /// original guard is returned as an `Err(..)` if the closure returns
1721 /// `None`.
1722 ///
1723 /// The `RefCell` is already immutably borrowed, so this cannot fail.
1724 ///
1725 /// This is an associated function that needs to be used as
1726 /// `Ref::filter_map(...)`. A method would interfere with methods of the same
1727 /// name on the contents of a `RefCell` used through `Deref`.
1728 ///
1729 /// # Examples
1730 ///
1731 /// ```
1732 /// use std::cell::{RefCell, Ref};
1733 ///
1734 /// let c = RefCell::new(vec![1, 2, 3]);
1735 /// let b1: Ref<'_, Vec<u32>> = c.borrow();
1736 /// let b2: Result<Ref<'_, u32>, _> = Ref::filter_map(b1, |v| v.get(1));
1737 /// assert_eq!(*b2.unwrap(), 2);
1738 /// ```
1739 #[stable(feature = "cell_filter_map", since = "1.63.0")]
1740 #[inline]
1741 pub fn filter_map<U: ?Sized, F>(orig: Ref<'b, T>, f: F) -> Result<Ref<'b, U>, Self>
1742 where
1743 F: FnOnce(&T) -> Option<&U>,
1744 {
1745 match f(&*orig) {
1746 Some(value) => Ok(Ref { value: NonNull::from(value), borrow: orig.borrow }),
1747 None => Err(orig),
1748 }
1749 }
1750
1751 /// Tries to makes a new `Ref` for a component of the borrowed data.
1752 /// On failure, the original guard is returned alongside with the error
1753 /// returned by the closure.
1754 ///
1755 /// The `RefCell` is already immutably borrowed, so this cannot fail.
1756 ///
1757 /// This is an associated function that needs to be used as
1758 /// `Ref::try_map(...)`. A method would interfere with methods of the same
1759 /// name on the contents of a `RefCell` used through `Deref`.
1760 ///
1761 /// # Examples
1762 ///
1763 /// ```
1764 /// #![feature(refcell_try_map)]
1765 /// use std::cell::{RefCell, Ref};
1766 /// use std::str::{from_utf8, Utf8Error};
1767 ///
1768 /// let c = RefCell::new(vec![0xF0, 0x9F, 0xA6 ,0x80]);
1769 /// let b1: Ref<'_, Vec<u8>> = c.borrow();
1770 /// let b2: Result<Ref<'_, str>, _> = Ref::try_map(b1, |v| from_utf8(v));
1771 /// assert_eq!(&*b2.unwrap(), "🦀");
1772 ///
1773 /// let c = RefCell::new(vec![0xF0, 0x9F, 0xA6]);
1774 /// let b1: Ref<'_, Vec<u8>> = c.borrow();
1775 /// let b2: Result<_, (Ref<'_, Vec<u8>>, Utf8Error)> = Ref::try_map(b1, |v| from_utf8(v));
1776 /// let (b3, e) = b2.unwrap_err();
1777 /// assert_eq!(*b3, vec![0xF0, 0x9F, 0xA6]);
1778 /// assert_eq!(e.valid_up_to(), 0);
1779 /// ```
1780 #[unstable(feature = "refcell_try_map", issue = "143801")]
1781 #[inline]
1782 pub fn try_map<U: ?Sized, E>(
1783 orig: Ref<'b, T>,
1784 f: impl FnOnce(&T) -> Result<&U, E>,
1785 ) -> Result<Ref<'b, U>, (Self, E)> {
1786 match f(&*orig) {
1787 Ok(value) => Ok(Ref { value: NonNull::from(value), borrow: orig.borrow }),
1788 Err(e) => Err((orig, e)),
1789 }
1790 }
1791
1792 /// Splits a `Ref` into multiple `Ref`s for different components of the
1793 /// borrowed data.
1794 ///
1795 /// The `RefCell` is already immutably borrowed, so this cannot fail.
1796 ///
1797 /// This is an associated function that needs to be used as
1798 /// `Ref::map_split(...)`. A method would interfere with methods of the same
1799 /// name on the contents of a `RefCell` used through `Deref`.
1800 ///
1801 /// # Examples
1802 ///
1803 /// ```
1804 /// use std::cell::{Ref, RefCell};
1805 ///
1806 /// let cell = RefCell::new([1, 2, 3, 4]);
1807 /// let borrow = cell.borrow();
1808 /// let (begin, end) = Ref::map_split(borrow, |slice| slice.split_at(2));
1809 /// assert_eq!(*begin, [1, 2]);
1810 /// assert_eq!(*end, [3, 4]);
1811 /// ```
1812 #[stable(feature = "refcell_map_split", since = "1.35.0")]
1813 #[inline]
1814 pub fn map_split<U: ?Sized, V: ?Sized, F>(orig: Ref<'b, T>, f: F) -> (Ref<'b, U>, Ref<'b, V>)
1815 where
1816 F: FnOnce(&T) -> (&U, &V),
1817 {
1818 let (a, b) = f(&*orig);
1819 let borrow = orig.borrow.clone();
1820 (
1821 Ref { value: NonNull::from(a), borrow },
1822 Ref { value: NonNull::from(b), borrow: orig.borrow },
1823 )
1824 }
1825
1826 /// Converts into a reference to the underlying data.
1827 ///
1828 /// The underlying `RefCell` can never be mutably borrowed from again and will always appear
1829 /// already immutably borrowed. It is not a good idea to leak more than a constant number of
1830 /// references. The `RefCell` can be immutably borrowed again if only a smaller number of leaks
1831 /// have occurred in total.
1832 ///
1833 /// This is an associated function that needs to be used as
1834 /// `Ref::leak(...)`. A method would interfere with methods of the
1835 /// same name on the contents of a `RefCell` used through `Deref`.
1836 ///
1837 /// # Examples
1838 ///
1839 /// ```
1840 /// #![feature(cell_leak)]
1841 /// use std::cell::{RefCell, Ref};
1842 /// let cell = RefCell::new(0);
1843 ///
1844 /// let value = Ref::leak(cell.borrow());
1845 /// assert_eq!(*value, 0);
1846 ///
1847 /// assert!(cell.try_borrow().is_ok());
1848 /// assert!(cell.try_borrow_mut().is_err());
1849 /// ```
1850 #[unstable(feature = "cell_leak", issue = "69099")]
1851 #[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
1852 pub const fn leak(orig: Ref<'b, T>) -> &'b T {
1853 // By forgetting this Ref we ensure that the borrow counter in the RefCell can't go back to
1854 // UNUSED within the lifetime `'b`. Resetting the reference tracking state would require a
1855 // unique reference to the borrowed RefCell. No further mutable references can be created
1856 // from the original cell.
1857 mem::forget(orig.borrow);
1858 // SAFETY: after forgetting, we can form a reference for the rest of lifetime `'b`.
1859 unsafe { orig.value.as_ref() }
1860 }
1861}
1862
1863#[unstable(feature = "coerce_unsized", issue = "18598")]
1864#[cfg(not(feature = "ferrocene_certified"))]
1865impl<'b, T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Ref<'b, U>> for Ref<'b, T> {}
1866
1867#[stable(feature = "std_guard_impls", since = "1.20.0")]
1868#[cfg(not(feature = "ferrocene_certified"))]
1869impl<T: ?Sized + fmt::Display> fmt::Display for Ref<'_, T> {
1870 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1871 (**self).fmt(f)
1872 }
1873}
1874
1875#[cfg(not(feature = "ferrocene_certified"))]
1876impl<'b, T: ?Sized> RefMut<'b, T> {
1877 /// Makes a new `RefMut` for a component of the borrowed data, e.g., an enum
1878 /// variant.
1879 ///
1880 /// The `RefCell` is already mutably borrowed, so this cannot fail.
1881 ///
1882 /// This is an associated function that needs to be used as
1883 /// `RefMut::map(...)`. A method would interfere with methods of the same
1884 /// name on the contents of a `RefCell` used through `Deref`.
1885 ///
1886 /// # Examples
1887 ///
1888 /// ```
1889 /// use std::cell::{RefCell, RefMut};
1890 ///
1891 /// let c = RefCell::new((5, 'b'));
1892 /// {
1893 /// let b1: RefMut<'_, (u32, char)> = c.borrow_mut();
1894 /// let mut b2: RefMut<'_, u32> = RefMut::map(b1, |t| &mut t.0);
1895 /// assert_eq!(*b2, 5);
1896 /// *b2 = 42;
1897 /// }
1898 /// assert_eq!(*c.borrow(), (42, 'b'));
1899 /// ```
1900 #[stable(feature = "cell_map", since = "1.8.0")]
1901 #[inline]
1902 pub fn map<U: ?Sized, F>(mut orig: RefMut<'b, T>, f: F) -> RefMut<'b, U>
1903 where
1904 F: FnOnce(&mut T) -> &mut U,
1905 {
1906 let value = NonNull::from(f(&mut *orig));
1907 RefMut { value, borrow: orig.borrow, marker: PhantomData }
1908 }
1909
1910 /// Makes a new `RefMut` for an optional component of the borrowed data. The
1911 /// original guard is returned as an `Err(..)` if the closure returns
1912 /// `None`.
1913 ///
1914 /// The `RefCell` is already mutably borrowed, so this cannot fail.
1915 ///
1916 /// This is an associated function that needs to be used as
1917 /// `RefMut::filter_map(...)`. A method would interfere with methods of the
1918 /// same name on the contents of a `RefCell` used through `Deref`.
1919 ///
1920 /// # Examples
1921 ///
1922 /// ```
1923 /// use std::cell::{RefCell, RefMut};
1924 ///
1925 /// let c = RefCell::new(vec![1, 2, 3]);
1926 ///
1927 /// {
1928 /// let b1: RefMut<'_, Vec<u32>> = c.borrow_mut();
1929 /// let mut b2: Result<RefMut<'_, u32>, _> = RefMut::filter_map(b1, |v| v.get_mut(1));
1930 ///
1931 /// if let Ok(mut b2) = b2 {
1932 /// *b2 += 2;
1933 /// }
1934 /// }
1935 ///
1936 /// assert_eq!(*c.borrow(), vec![1, 4, 3]);
1937 /// ```
1938 #[stable(feature = "cell_filter_map", since = "1.63.0")]
1939 #[inline]
1940 pub fn filter_map<U: ?Sized, F>(mut orig: RefMut<'b, T>, f: F) -> Result<RefMut<'b, U>, Self>
1941 where
1942 F: FnOnce(&mut T) -> Option<&mut U>,
1943 {
1944 // SAFETY: function holds onto an exclusive reference for the duration
1945 // of its call through `orig`, and the pointer is only de-referenced
1946 // inside of the function call never allowing the exclusive reference to
1947 // escape.
1948 match f(&mut *orig) {
1949 Some(value) => {
1950 Ok(RefMut { value: NonNull::from(value), borrow: orig.borrow, marker: PhantomData })
1951 }
1952 None => Err(orig),
1953 }
1954 }
1955
1956 /// Tries to makes a new `RefMut` for a component of the borrowed data.
1957 /// On failure, the original guard is returned alongside with the error
1958 /// returned by the closure.
1959 ///
1960 /// The `RefCell` is already mutably borrowed, so this cannot fail.
1961 ///
1962 /// This is an associated function that needs to be used as
1963 /// `RefMut::try_map(...)`. A method would interfere with methods of the same
1964 /// name on the contents of a `RefCell` used through `Deref`.
1965 ///
1966 /// # Examples
1967 ///
1968 /// ```
1969 /// #![feature(refcell_try_map)]
1970 /// use std::cell::{RefCell, RefMut};
1971 /// use std::str::{from_utf8_mut, Utf8Error};
1972 ///
1973 /// let c = RefCell::new(vec![0x68, 0x65, 0x6C, 0x6C, 0x6F]);
1974 /// {
1975 /// let b1: RefMut<'_, Vec<u8>> = c.borrow_mut();
1976 /// let b2: Result<RefMut<'_, str>, _> = RefMut::try_map(b1, |v| from_utf8_mut(v));
1977 /// let mut b2 = b2.unwrap();
1978 /// assert_eq!(&*b2, "hello");
1979 /// b2.make_ascii_uppercase();
1980 /// }
1981 /// assert_eq!(*c.borrow(), "HELLO".as_bytes());
1982 ///
1983 /// let c = RefCell::new(vec![0xFF]);
1984 /// let b1: RefMut<'_, Vec<u8>> = c.borrow_mut();
1985 /// let b2: Result<_, (RefMut<'_, Vec<u8>>, Utf8Error)> = RefMut::try_map(b1, |v| from_utf8_mut(v));
1986 /// let (b3, e) = b2.unwrap_err();
1987 /// assert_eq!(*b3, vec![0xFF]);
1988 /// assert_eq!(e.valid_up_to(), 0);
1989 /// ```
1990 #[unstable(feature = "refcell_try_map", issue = "143801")]
1991 #[inline]
1992 pub fn try_map<U: ?Sized, E>(
1993 mut orig: RefMut<'b, T>,
1994 f: impl FnOnce(&mut T) -> Result<&mut U, E>,
1995 ) -> Result<RefMut<'b, U>, (Self, E)> {
1996 // SAFETY: function holds onto an exclusive reference for the duration
1997 // of its call through `orig`, and the pointer is only de-referenced
1998 // inside of the function call never allowing the exclusive reference to
1999 // escape.
2000 match f(&mut *orig) {
2001 Ok(value) => {
2002 Ok(RefMut { value: NonNull::from(value), borrow: orig.borrow, marker: PhantomData })
2003 }
2004 Err(e) => Err((orig, e)),
2005 }
2006 }
2007
2008 /// Splits a `RefMut` into multiple `RefMut`s for different components of the
2009 /// borrowed data.
2010 ///
2011 /// The underlying `RefCell` will remain mutably borrowed until both
2012 /// returned `RefMut`s go out of scope.
2013 ///
2014 /// The `RefCell` is already mutably borrowed, so this cannot fail.
2015 ///
2016 /// This is an associated function that needs to be used as
2017 /// `RefMut::map_split(...)`. A method would interfere with methods of the
2018 /// same name on the contents of a `RefCell` used through `Deref`.
2019 ///
2020 /// # Examples
2021 ///
2022 /// ```
2023 /// use std::cell::{RefCell, RefMut};
2024 ///
2025 /// let cell = RefCell::new([1, 2, 3, 4]);
2026 /// let borrow = cell.borrow_mut();
2027 /// let (mut begin, mut end) = RefMut::map_split(borrow, |slice| slice.split_at_mut(2));
2028 /// assert_eq!(*begin, [1, 2]);
2029 /// assert_eq!(*end, [3, 4]);
2030 /// begin.copy_from_slice(&[4, 3]);
2031 /// end.copy_from_slice(&[2, 1]);
2032 /// ```
2033 #[stable(feature = "refcell_map_split", since = "1.35.0")]
2034 #[inline]
2035 pub fn map_split<U: ?Sized, V: ?Sized, F>(
2036 mut orig: RefMut<'b, T>,
2037 f: F,
2038 ) -> (RefMut<'b, U>, RefMut<'b, V>)
2039 where
2040 F: FnOnce(&mut T) -> (&mut U, &mut V),
2041 {
2042 let borrow = orig.borrow.clone();
2043 let (a, b) = f(&mut *orig);
2044 (
2045 RefMut { value: NonNull::from(a), borrow, marker: PhantomData },
2046 RefMut { value: NonNull::from(b), borrow: orig.borrow, marker: PhantomData },
2047 )
2048 }
2049
2050 /// Converts into a mutable reference to the underlying data.
2051 ///
2052 /// The underlying `RefCell` can not be borrowed from again and will always appear already
2053 /// mutably borrowed, making the returned reference the only to the interior.
2054 ///
2055 /// This is an associated function that needs to be used as
2056 /// `RefMut::leak(...)`. A method would interfere with methods of the
2057 /// same name on the contents of a `RefCell` used through `Deref`.
2058 ///
2059 /// # Examples
2060 ///
2061 /// ```
2062 /// #![feature(cell_leak)]
2063 /// use std::cell::{RefCell, RefMut};
2064 /// let cell = RefCell::new(0);
2065 ///
2066 /// let value = RefMut::leak(cell.borrow_mut());
2067 /// assert_eq!(*value, 0);
2068 /// *value = 1;
2069 ///
2070 /// assert!(cell.try_borrow_mut().is_err());
2071 /// ```
2072 #[unstable(feature = "cell_leak", issue = "69099")]
2073 #[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
2074 pub const fn leak(mut orig: RefMut<'b, T>) -> &'b mut T {
2075 // By forgetting this BorrowRefMut we ensure that the borrow counter in the RefCell can't
2076 // go back to UNUSED within the lifetime `'b`. Resetting the reference tracking state would
2077 // require a unique reference to the borrowed RefCell. No further references can be created
2078 // from the original cell within that lifetime, making the current borrow the only
2079 // reference for the remaining lifetime.
2080 mem::forget(orig.borrow);
2081 // SAFETY: after forgetting, we can form a reference for the rest of lifetime `'b`.
2082 unsafe { orig.value.as_mut() }
2083 }
2084}
2085
2086#[cfg(not(feature = "ferrocene_certified"))]
2087struct BorrowRefMut<'b> {
2088 borrow: &'b Cell<BorrowCounter>,
2089}
2090
2091#[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
2092#[cfg(not(feature = "ferrocene_certified"))]
2093impl const Drop for BorrowRefMut<'_> {
2094 #[inline]
2095 fn drop(&mut self) {
2096 let borrow = self.borrow.get();
2097 debug_assert!(is_writing(borrow));
2098 self.borrow.replace(borrow + 1);
2099 }
2100}
2101
2102#[cfg(not(feature = "ferrocene_certified"))]
2103impl<'b> BorrowRefMut<'b> {
2104 #[inline]
2105 const fn new(borrow: &'b Cell<BorrowCounter>) -> Option<BorrowRefMut<'b>> {
2106 // NOTE: Unlike BorrowRefMut::clone, new is called to create the initial
2107 // mutable reference, and so there must currently be no existing
2108 // references. Thus, while clone increments the mutable refcount, here
2109 // we explicitly only allow going from UNUSED to UNUSED - 1.
2110 match borrow.get() {
2111 UNUSED => {
2112 borrow.replace(UNUSED - 1);
2113 Some(BorrowRefMut { borrow })
2114 }
2115 _ => None,
2116 }
2117 }
2118
2119 // Clones a `BorrowRefMut`.
2120 //
2121 // This is only valid if each `BorrowRefMut` is used to track a mutable
2122 // reference to a distinct, nonoverlapping range of the original object.
2123 // This isn't in a Clone impl so that code doesn't call this implicitly.
2124 #[inline]
2125 fn clone(&self) -> BorrowRefMut<'b> {
2126 let borrow = self.borrow.get();
2127 debug_assert!(is_writing(borrow));
2128 // Prevent the borrow counter from underflowing.
2129 assert!(borrow != BorrowCounter::MIN);
2130 self.borrow.set(borrow - 1);
2131 BorrowRefMut { borrow: self.borrow }
2132 }
2133}
2134
2135/// A wrapper type for a mutably borrowed value from a `RefCell<T>`.
2136///
2137/// See the [module-level documentation](self) for more.
2138#[stable(feature = "rust1", since = "1.0.0")]
2139#[must_not_suspend = "holding a RefMut across suspend points can cause BorrowErrors"]
2140#[rustc_diagnostic_item = "RefCellRefMut"]
2141#[cfg(not(feature = "ferrocene_certified"))]
2142pub struct RefMut<'b, T: ?Sized + 'b> {
2143 // NB: we use a pointer instead of `&'b mut T` to avoid `noalias` violations, because a
2144 // `RefMut` argument doesn't hold exclusivity for its whole scope, only until it drops.
2145 value: NonNull<T>,
2146 borrow: BorrowRefMut<'b>,
2147 // `NonNull` is covariant over `T`, so we need to reintroduce invariance.
2148 marker: PhantomData<&'b mut T>,
2149}
2150
2151#[stable(feature = "rust1", since = "1.0.0")]
2152#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
2153#[cfg(not(feature = "ferrocene_certified"))]
2154impl<T: ?Sized> const Deref for RefMut<'_, T> {
2155 type Target = T;
2156
2157 #[inline]
2158 fn deref(&self) -> &T {
2159 // SAFETY: the value is accessible as long as we hold our borrow.
2160 unsafe { self.value.as_ref() }
2161 }
2162}
2163
2164#[stable(feature = "rust1", since = "1.0.0")]
2165#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
2166#[cfg(not(feature = "ferrocene_certified"))]
2167impl<T: ?Sized> const DerefMut for RefMut<'_, T> {
2168 #[inline]
2169 fn deref_mut(&mut self) -> &mut T {
2170 // SAFETY: the value is accessible as long as we hold our borrow.
2171 unsafe { self.value.as_mut() }
2172 }
2173}
2174
2175#[unstable(feature = "deref_pure_trait", issue = "87121")]
2176#[cfg(not(feature = "ferrocene_certified"))]
2177unsafe impl<T: ?Sized> DerefPure for RefMut<'_, T> {}
2178
2179#[unstable(feature = "coerce_unsized", issue = "18598")]
2180#[cfg(not(feature = "ferrocene_certified"))]
2181impl<'b, T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<RefMut<'b, U>> for RefMut<'b, T> {}
2182
2183#[stable(feature = "std_guard_impls", since = "1.20.0")]
2184#[cfg(not(feature = "ferrocene_certified"))]
2185impl<T: ?Sized + fmt::Display> fmt::Display for RefMut<'_, T> {
2186 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2187 (**self).fmt(f)
2188 }
2189}
2190
2191/// The core primitive for interior mutability in Rust.
2192///
2193/// If you have a reference `&T`, then normally in Rust the compiler performs optimizations based on
2194/// the knowledge that `&T` points to immutable data. Mutating that data, for example through an
2195/// alias or by transmuting a `&T` into a `&mut T`, is considered undefined behavior.
2196/// `UnsafeCell<T>` opts-out of the immutability guarantee for `&T`: a shared reference
2197/// `&UnsafeCell<T>` may point to data that is being mutated. This is called "interior mutability".
2198///
2199/// All other types that allow internal mutability, such as [`Cell<T>`] and [`RefCell<T>`], internally
2200/// use `UnsafeCell` to wrap their data.
2201///
2202/// Note that only the immutability guarantee for shared references is affected by `UnsafeCell`. The
2203/// uniqueness guarantee for mutable references is unaffected. There is *no* legal way to obtain
2204/// aliasing `&mut`, not even with `UnsafeCell<T>`.
2205///
2206/// `UnsafeCell` does nothing to avoid data races; they are still undefined behavior. If multiple
2207/// threads have access to the same `UnsafeCell`, they must follow the usual rules of the
2208/// [concurrent memory model]: conflicting non-synchronized accesses must be done via the APIs in
2209/// [`core::sync::atomic`].
2210///
2211/// The `UnsafeCell` API itself is technically very simple: [`.get()`] gives you a raw pointer
2212/// `*mut T` to its contents. It is up to _you_ as the abstraction designer to use that raw pointer
2213/// correctly.
2214///
2215/// [`.get()`]: `UnsafeCell::get`
2216/// [concurrent memory model]: ../sync/atomic/index.html#memory-model-for-atomic-accesses
2217///
2218/// # Aliasing rules
2219///
2220/// The precise Rust aliasing rules are somewhat in flux, but the main points are not contentious:
2221///
2222/// - If you create a safe reference with lifetime `'a` (either a `&T` or `&mut T` reference), then
2223/// you must not access the data in any way that contradicts that reference for the remainder of
2224/// `'a`. For example, this means that if you take the `*mut T` from an `UnsafeCell<T>` and cast it
2225/// to an `&T`, then the data in `T` must remain immutable (modulo any `UnsafeCell` data found
2226/// within `T`, of course) until that reference's lifetime expires. Similarly, if you create a
2227/// `&mut T` reference that is released to safe code, then you must not access the data within the
2228/// `UnsafeCell` until that reference expires.
2229///
2230/// - For both `&T` without `UnsafeCell<_>` and `&mut T`, you must also not deallocate the data
2231/// until the reference expires. As a special exception, given an `&T`, any part of it that is
2232/// inside an `UnsafeCell<_>` may be deallocated during the lifetime of the reference, after the
2233/// last time the reference is used (dereferenced or reborrowed). Since you cannot deallocate a part
2234/// of what a reference points to, this means the memory an `&T` points to can be deallocated only if
2235/// *every part of it* (including padding) is inside an `UnsafeCell`.
2236///
2237/// However, whenever a `&UnsafeCell<T>` is constructed or dereferenced, it must still point to
2238/// live memory and the compiler is allowed to insert spurious reads if it can prove that this
2239/// memory has not yet been deallocated.
2240///
2241/// To assist with proper design, the following scenarios are explicitly declared legal
2242/// for single-threaded code:
2243///
2244/// 1. A `&T` reference can be released to safe code and there it can co-exist with other `&T`
2245/// references, but not with a `&mut T`
2246///
2247/// 2. A `&mut T` reference may be released to safe code provided neither other `&mut T` nor `&T`
2248/// co-exist with it. A `&mut T` must always be unique.
2249///
2250/// Note that whilst mutating the contents of an `&UnsafeCell<T>` (even while other
2251/// `&UnsafeCell<T>` references alias the cell) is
2252/// ok (provided you enforce the above invariants some other way), it is still undefined behavior
2253/// to have multiple `&mut UnsafeCell<T>` aliases. That is, `UnsafeCell` is a wrapper
2254/// designed to have a special interaction with _shared_ accesses (_i.e._, through an
2255/// `&UnsafeCell<_>` reference); there is no magic whatsoever when dealing with _exclusive_
2256/// accesses (_e.g._, through a `&mut UnsafeCell<_>`): neither the cell nor the wrapped value
2257/// may be aliased for the duration of that `&mut` borrow.
2258/// This is showcased by the [`.get_mut()`] accessor, which is a _safe_ getter that yields
2259/// a `&mut T`.
2260///
2261/// [`.get_mut()`]: `UnsafeCell::get_mut`
2262///
2263/// # Memory layout
2264///
2265/// `UnsafeCell<T>` has the same in-memory representation as its inner type `T`. A consequence
2266/// of this guarantee is that it is possible to convert between `T` and `UnsafeCell<T>`.
2267/// Special care has to be taken when converting a nested `T` inside of an `Outer<T>` type
2268/// to an `Outer<UnsafeCell<T>>` type: this is not sound when the `Outer<T>` type enables [niche]
2269/// optimizations. For example, the type `Option<NonNull<u8>>` is typically 8 bytes large on
2270/// 64-bit platforms, but the type `Option<UnsafeCell<NonNull<u8>>>` takes up 16 bytes of space.
2271/// Therefore this is not a valid conversion, despite `NonNull<u8>` and `UnsafeCell<NonNull<u8>>>`
2272/// having the same memory layout. This is because `UnsafeCell` disables niche optimizations in
2273/// order to avoid its interior mutability property from spreading from `T` into the `Outer` type,
2274/// thus this can cause distortions in the type size in these cases.
2275///
2276/// Note that the only valid way to obtain a `*mut T` pointer to the contents of a
2277/// _shared_ `UnsafeCell<T>` is through [`.get()`] or [`.raw_get()`]. A `&mut T` reference
2278/// can be obtained by either dereferencing this pointer or by calling [`.get_mut()`]
2279/// on an _exclusive_ `UnsafeCell<T>`. Even though `T` and `UnsafeCell<T>` have the
2280/// same memory layout, the following is not allowed and undefined behavior:
2281///
2282/// ```rust,compile_fail
2283/// # use std::cell::UnsafeCell;
2284/// unsafe fn not_allowed<T>(ptr: &UnsafeCell<T>) -> &mut T {
2285/// let t = ptr as *const UnsafeCell<T> as *mut T;
2286/// // This is undefined behavior, because the `*mut T` pointer
2287/// // was not obtained through `.get()` nor `.raw_get()`:
2288/// unsafe { &mut *t }
2289/// }
2290/// ```
2291///
2292/// Instead, do this:
2293///
2294/// ```rust
2295/// # use std::cell::UnsafeCell;
2296/// // Safety: the caller must ensure that there are no references that
2297/// // point to the *contents* of the `UnsafeCell`.
2298/// unsafe fn get_mut<T>(ptr: &UnsafeCell<T>) -> &mut T {
2299/// unsafe { &mut *ptr.get() }
2300/// }
2301/// ```
2302///
2303/// Converting in the other direction from a `&mut T`
2304/// to an `&UnsafeCell<T>` is allowed:
2305///
2306/// ```rust
2307/// # use std::cell::UnsafeCell;
2308/// fn get_shared<T>(ptr: &mut T) -> &UnsafeCell<T> {
2309/// let t = ptr as *mut T as *const UnsafeCell<T>;
2310/// // SAFETY: `T` and `UnsafeCell<T>` have the same memory layout
2311/// unsafe { &*t }
2312/// }
2313/// ```
2314///
2315/// [niche]: https://rust-lang.github.io/unsafe-code-guidelines/glossary.html#niche
2316/// [`.raw_get()`]: `UnsafeCell::raw_get`
2317///
2318/// # Examples
2319///
2320/// Here is an example showcasing how to soundly mutate the contents of an `UnsafeCell<_>` despite
2321/// there being multiple references aliasing the cell:
2322///
2323/// ```
2324/// use std::cell::UnsafeCell;
2325///
2326/// let x: UnsafeCell<i32> = 42.into();
2327/// // Get multiple / concurrent / shared references to the same `x`.
2328/// let (p1, p2): (&UnsafeCell<i32>, &UnsafeCell<i32>) = (&x, &x);
2329///
2330/// unsafe {
2331/// // SAFETY: within this scope there are no other references to `x`'s contents,
2332/// // so ours is effectively unique.
2333/// let p1_exclusive: &mut i32 = &mut *p1.get(); // -- borrow --+
2334/// *p1_exclusive += 27; // |
2335/// } // <---------- cannot go beyond this point -------------------+
2336///
2337/// unsafe {
2338/// // SAFETY: within this scope nobody expects to have exclusive access to `x`'s contents,
2339/// // so we can have multiple shared accesses concurrently.
2340/// let p2_shared: &i32 = &*p2.get();
2341/// assert_eq!(*p2_shared, 42 + 27);
2342/// let p1_shared: &i32 = &*p1.get();
2343/// assert_eq!(*p1_shared, *p2_shared);
2344/// }
2345/// ```
2346///
2347/// The following example showcases the fact that exclusive access to an `UnsafeCell<T>`
2348/// implies exclusive access to its `T`:
2349///
2350/// ```rust
2351/// #![forbid(unsafe_code)]
2352/// // with exclusive accesses, `UnsafeCell` is a transparent no-op wrapper, so no need for
2353/// // `unsafe` here.
2354/// use std::cell::UnsafeCell;
2355///
2356/// let mut x: UnsafeCell<i32> = 42.into();
2357///
2358/// // Get a compile-time-checked unique reference to `x`.
2359/// let p_unique: &mut UnsafeCell<i32> = &mut x;
2360/// // With an exclusive reference, we can mutate the contents for free.
2361/// *p_unique.get_mut() = 0;
2362/// // Or, equivalently:
2363/// x = UnsafeCell::new(0);
2364///
2365/// // When we own the value, we can extract the contents for free.
2366/// let contents: i32 = x.into_inner();
2367/// assert_eq!(contents, 0);
2368/// ```
2369#[lang = "unsafe_cell"]
2370#[stable(feature = "rust1", since = "1.0.0")]
2371#[repr(transparent)]
2372#[rustc_pub_transparent]
2373pub struct UnsafeCell<T: ?Sized> {
2374 value: T,
2375}
2376
2377#[stable(feature = "rust1", since = "1.0.0")]
2378#[cfg(not(feature = "ferrocene_certified"))]
2379impl<T: ?Sized> !Sync for UnsafeCell<T> {}
2380
2381impl<T> UnsafeCell<T> {
2382 /// Constructs a new instance of `UnsafeCell` which will wrap the specified
2383 /// value.
2384 ///
2385 /// All access to the inner value through `&UnsafeCell<T>` requires `unsafe` code.
2386 ///
2387 /// # Examples
2388 ///
2389 /// ```
2390 /// use std::cell::UnsafeCell;
2391 ///
2392 /// let uc = UnsafeCell::new(5);
2393 /// ```
2394 #[stable(feature = "rust1", since = "1.0.0")]
2395 #[rustc_const_stable(feature = "const_unsafe_cell_new", since = "1.32.0")]
2396 #[inline(always)]
2397 pub const fn new(value: T) -> UnsafeCell<T> {
2398 UnsafeCell { value }
2399 }
2400
2401 /// Unwraps the value, consuming the cell.
2402 ///
2403 /// # Examples
2404 ///
2405 /// ```
2406 /// use std::cell::UnsafeCell;
2407 ///
2408 /// let uc = UnsafeCell::new(5);
2409 ///
2410 /// let five = uc.into_inner();
2411 /// ```
2412 #[inline(always)]
2413 #[stable(feature = "rust1", since = "1.0.0")]
2414 #[rustc_const_stable(feature = "const_cell_into_inner", since = "1.83.0")]
2415 #[rustc_allow_const_fn_unstable(const_precise_live_drops)]
2416 pub const fn into_inner(self) -> T {
2417 self.value
2418 }
2419
2420 /// Replace the value in this `UnsafeCell` and return the old value.
2421 ///
2422 /// # Safety
2423 ///
2424 /// The caller must take care to avoid aliasing and data races.
2425 ///
2426 /// - It is Undefined Behavior to allow calls to race with
2427 /// any other access to the wrapped value.
2428 /// - It is Undefined Behavior to call this while any other
2429 /// reference(s) to the wrapped value are alive.
2430 ///
2431 /// # Examples
2432 ///
2433 /// ```
2434 /// #![feature(unsafe_cell_access)]
2435 /// use std::cell::UnsafeCell;
2436 ///
2437 /// let uc = UnsafeCell::new(5);
2438 ///
2439 /// let old = unsafe { uc.replace(10) };
2440 /// assert_eq!(old, 5);
2441 /// ```
2442 #[inline]
2443 #[unstable(feature = "unsafe_cell_access", issue = "136327")]
2444 #[cfg(not(feature = "ferrocene_certified"))]
2445 pub const unsafe fn replace(&self, value: T) -> T {
2446 // SAFETY: pointer comes from `&self` so naturally satisfies invariants.
2447 unsafe { ptr::replace(self.get(), value) }
2448 }
2449}
2450
2451impl<T: ?Sized> UnsafeCell<T> {
2452 /// Converts from `&mut T` to `&mut UnsafeCell<T>`.
2453 ///
2454 /// # Examples
2455 ///
2456 /// ```
2457 /// use std::cell::UnsafeCell;
2458 ///
2459 /// let mut val = 42;
2460 /// let uc = UnsafeCell::from_mut(&mut val);
2461 ///
2462 /// *uc.get_mut() -= 1;
2463 /// assert_eq!(*uc.get_mut(), 41);
2464 /// ```
2465 #[inline(always)]
2466 #[stable(feature = "unsafe_cell_from_mut", since = "1.84.0")]
2467 #[rustc_const_stable(feature = "unsafe_cell_from_mut", since = "1.84.0")]
2468 #[cfg(not(feature = "ferrocene_certified"))]
2469 pub const fn from_mut(value: &mut T) -> &mut UnsafeCell<T> {
2470 // SAFETY: `UnsafeCell<T>` has the same memory layout as `T` due to #[repr(transparent)].
2471 unsafe { &mut *(value as *mut T as *mut UnsafeCell<T>) }
2472 }
2473
2474 /// Gets a mutable pointer to the wrapped value.
2475 ///
2476 /// This can be cast to a pointer of any kind. When creating references, you must uphold the
2477 /// aliasing rules; see [the type-level docs][UnsafeCell#aliasing-rules] for more discussion and
2478 /// caveats.
2479 ///
2480 /// # Examples
2481 ///
2482 /// ```
2483 /// use std::cell::UnsafeCell;
2484 ///
2485 /// let uc = UnsafeCell::new(5);
2486 ///
2487 /// let five = uc.get();
2488 /// ```
2489 #[inline(always)]
2490 #[stable(feature = "rust1", since = "1.0.0")]
2491 #[rustc_const_stable(feature = "const_unsafecell_get", since = "1.32.0")]
2492 #[rustc_as_ptr]
2493 #[rustc_never_returns_null_ptr]
2494 pub const fn get(&self) -> *mut T {
2495 // We can just cast the pointer from `UnsafeCell<T>` to `T` because of
2496 // #[repr(transparent)]. This exploits std's special status, there is
2497 // no guarantee for user code that this will work in future versions of the compiler!
2498 self as *const UnsafeCell<T> as *const T as *mut T
2499 }
2500
2501 /// Returns a mutable reference to the underlying data.
2502 ///
2503 /// This call borrows the `UnsafeCell` mutably (at compile-time) which
2504 /// guarantees that we possess the only reference.
2505 ///
2506 /// # Examples
2507 ///
2508 /// ```
2509 /// use std::cell::UnsafeCell;
2510 ///
2511 /// let mut c = UnsafeCell::new(5);
2512 /// *c.get_mut() += 1;
2513 ///
2514 /// assert_eq!(*c.get_mut(), 6);
2515 /// ```
2516 #[inline(always)]
2517 #[stable(feature = "unsafe_cell_get_mut", since = "1.50.0")]
2518 #[rustc_const_stable(feature = "const_unsafecell_get_mut", since = "1.83.0")]
2519 pub const fn get_mut(&mut self) -> &mut T {
2520 &mut self.value
2521 }
2522
2523 /// Gets a mutable pointer to the wrapped value.
2524 /// The difference from [`get`] is that this function accepts a raw pointer,
2525 /// which is useful to avoid the creation of temporary references.
2526 ///
2527 /// This can be cast to a pointer of any kind. When creating references, you must uphold the
2528 /// aliasing rules; see [the type-level docs][UnsafeCell#aliasing-rules] for more discussion and
2529 /// caveats.
2530 ///
2531 /// [`get`]: UnsafeCell::get()
2532 ///
2533 /// # Examples
2534 ///
2535 /// Gradual initialization of an `UnsafeCell` requires `raw_get`, as
2536 /// calling `get` would require creating a reference to uninitialized data:
2537 ///
2538 /// ```
2539 /// use std::cell::UnsafeCell;
2540 /// use std::mem::MaybeUninit;
2541 ///
2542 /// let m = MaybeUninit::<UnsafeCell<i32>>::uninit();
2543 /// unsafe { UnsafeCell::raw_get(m.as_ptr()).write(5); }
2544 /// // avoid below which references to uninitialized data
2545 /// // unsafe { UnsafeCell::get(&*m.as_ptr()).write(5); }
2546 /// let uc = unsafe { m.assume_init() };
2547 ///
2548 /// assert_eq!(uc.into_inner(), 5);
2549 /// ```
2550 #[inline(always)]
2551 #[stable(feature = "unsafe_cell_raw_get", since = "1.56.0")]
2552 #[rustc_const_stable(feature = "unsafe_cell_raw_get", since = "1.56.0")]
2553 #[rustc_diagnostic_item = "unsafe_cell_raw_get"]
2554 #[cfg(not(feature = "ferrocene_certified"))]
2555 pub const fn raw_get(this: *const Self) -> *mut T {
2556 // We can just cast the pointer from `UnsafeCell<T>` to `T` because of
2557 // #[repr(transparent)]. This exploits std's special status, there is
2558 // no guarantee for user code that this will work in future versions of the compiler!
2559 this as *const T as *mut T
2560 }
2561
2562 /// Get a shared reference to the value within the `UnsafeCell`.
2563 ///
2564 /// # Safety
2565 ///
2566 /// - It is Undefined Behavior to call this while any mutable
2567 /// reference to the wrapped value is alive.
2568 /// - Mutating the wrapped value while the returned
2569 /// reference is alive is Undefined Behavior.
2570 ///
2571 /// # Examples
2572 ///
2573 /// ```
2574 /// #![feature(unsafe_cell_access)]
2575 /// use std::cell::UnsafeCell;
2576 ///
2577 /// let uc = UnsafeCell::new(5);
2578 ///
2579 /// let val = unsafe { uc.as_ref_unchecked() };
2580 /// assert_eq!(val, &5);
2581 /// ```
2582 #[inline]
2583 #[unstable(feature = "unsafe_cell_access", issue = "136327")]
2584 #[cfg(not(feature = "ferrocene_certified"))]
2585 pub const unsafe fn as_ref_unchecked(&self) -> &T {
2586 // SAFETY: pointer comes from `&self` so naturally satisfies ptr-to-ref invariants.
2587 unsafe { self.get().as_ref_unchecked() }
2588 }
2589
2590 /// Get an exclusive reference to the value within the `UnsafeCell`.
2591 ///
2592 /// # Safety
2593 ///
2594 /// - It is Undefined Behavior to call this while any other
2595 /// reference(s) to the wrapped value are alive.
2596 /// - Mutating the wrapped value through other means while the
2597 /// returned reference is alive is Undefined Behavior.
2598 ///
2599 /// # Examples
2600 ///
2601 /// ```
2602 /// #![feature(unsafe_cell_access)]
2603 /// use std::cell::UnsafeCell;
2604 ///
2605 /// let uc = UnsafeCell::new(5);
2606 ///
2607 /// unsafe { *uc.as_mut_unchecked() += 1; }
2608 /// assert_eq!(uc.into_inner(), 6);
2609 /// ```
2610 #[inline]
2611 #[unstable(feature = "unsafe_cell_access", issue = "136327")]
2612 #[allow(clippy::mut_from_ref)]
2613 #[cfg(not(feature = "ferrocene_certified"))]
2614 pub const unsafe fn as_mut_unchecked(&self) -> &mut T {
2615 // SAFETY: pointer comes from `&self` so naturally satisfies ptr-to-ref invariants.
2616 unsafe { self.get().as_mut_unchecked() }
2617 }
2618}
2619
2620#[stable(feature = "unsafe_cell_default", since = "1.10.0")]
2621#[rustc_const_unstable(feature = "const_default", issue = "143894")]
2622#[cfg(not(feature = "ferrocene_certified"))]
2623impl<T: [const] Default> const Default for UnsafeCell<T> {
2624 /// Creates an `UnsafeCell`, with the `Default` value for T.
2625 fn default() -> UnsafeCell<T> {
2626 UnsafeCell::new(Default::default())
2627 }
2628}
2629
2630#[stable(feature = "cell_from", since = "1.12.0")]
2631#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
2632#[cfg(not(feature = "ferrocene_certified"))]
2633impl<T> const From<T> for UnsafeCell<T> {
2634 /// Creates a new `UnsafeCell<T>` containing the given value.
2635 fn from(t: T) -> UnsafeCell<T> {
2636 UnsafeCell::new(t)
2637 }
2638}
2639
2640#[unstable(feature = "coerce_unsized", issue = "18598")]
2641#[cfg(not(feature = "ferrocene_certified"))]
2642impl<T: CoerceUnsized<U>, U> CoerceUnsized<UnsafeCell<U>> for UnsafeCell<T> {}
2643
2644// Allow types that wrap `UnsafeCell` to also implement `DispatchFromDyn`
2645// and become dyn-compatible method receivers.
2646// Note that currently `UnsafeCell` itself cannot be a method receiver
2647// because it does not implement Deref.
2648// In other words:
2649// `self: UnsafeCell<&Self>` won't work
2650// `self: UnsafeCellWrapper<Self>` becomes possible
2651#[unstable(feature = "dispatch_from_dyn", issue = "none")]
2652#[cfg(not(feature = "ferrocene_certified"))]
2653impl<T: DispatchFromDyn<U>, U> DispatchFromDyn<UnsafeCell<U>> for UnsafeCell<T> {}
2654
2655/// [`UnsafeCell`], but [`Sync`].
2656///
2657/// This is just an `UnsafeCell`, except it implements `Sync`
2658/// if `T` implements `Sync`.
2659///
2660/// `UnsafeCell` doesn't implement `Sync`, to prevent accidental mis-use.
2661/// You can use `SyncUnsafeCell` instead of `UnsafeCell` to allow it to be
2662/// shared between threads, if that's intentional.
2663/// Providing proper synchronization is still the task of the user,
2664/// making this type just as unsafe to use.
2665///
2666/// See [`UnsafeCell`] for details.
2667#[unstable(feature = "sync_unsafe_cell", issue = "95439")]
2668#[repr(transparent)]
2669#[rustc_diagnostic_item = "SyncUnsafeCell"]
2670#[rustc_pub_transparent]
2671#[cfg(not(feature = "ferrocene_certified"))]
2672pub struct SyncUnsafeCell<T: ?Sized> {
2673 value: UnsafeCell<T>,
2674}
2675
2676#[unstable(feature = "sync_unsafe_cell", issue = "95439")]
2677#[cfg(not(feature = "ferrocene_certified"))]
2678unsafe impl<T: ?Sized + Sync> Sync for SyncUnsafeCell<T> {}
2679
2680#[unstable(feature = "sync_unsafe_cell", issue = "95439")]
2681#[cfg(not(feature = "ferrocene_certified"))]
2682impl<T> SyncUnsafeCell<T> {
2683 /// Constructs a new instance of `SyncUnsafeCell` which will wrap the specified value.
2684 #[inline]
2685 pub const fn new(value: T) -> Self {
2686 Self { value: UnsafeCell { value } }
2687 }
2688
2689 /// Unwraps the value, consuming the cell.
2690 #[inline]
2691 #[rustc_const_unstable(feature = "sync_unsafe_cell", issue = "95439")]
2692 pub const fn into_inner(self) -> T {
2693 self.value.into_inner()
2694 }
2695}
2696
2697#[unstable(feature = "sync_unsafe_cell", issue = "95439")]
2698#[cfg(not(feature = "ferrocene_certified"))]
2699impl<T: ?Sized> SyncUnsafeCell<T> {
2700 /// Gets a mutable pointer to the wrapped value.
2701 ///
2702 /// This can be cast to a pointer of any kind.
2703 /// Ensure that the access is unique (no active references, mutable or not)
2704 /// when casting to `&mut T`, and ensure that there are no mutations
2705 /// or mutable aliases going on when casting to `&T`
2706 #[inline]
2707 #[rustc_as_ptr]
2708 #[rustc_never_returns_null_ptr]
2709 pub const fn get(&self) -> *mut T {
2710 self.value.get()
2711 }
2712
2713 /// Returns a mutable reference to the underlying data.
2714 ///
2715 /// This call borrows the `SyncUnsafeCell` mutably (at compile-time) which
2716 /// guarantees that we possess the only reference.
2717 #[inline]
2718 pub const fn get_mut(&mut self) -> &mut T {
2719 self.value.get_mut()
2720 }
2721
2722 /// Gets a mutable pointer to the wrapped value.
2723 ///
2724 /// See [`UnsafeCell::get`] for details.
2725 #[inline]
2726 pub const fn raw_get(this: *const Self) -> *mut T {
2727 // We can just cast the pointer from `SyncUnsafeCell<T>` to `T` because
2728 // of #[repr(transparent)] on both SyncUnsafeCell and UnsafeCell.
2729 // See UnsafeCell::raw_get.
2730 this as *const T as *mut T
2731 }
2732}
2733
2734#[unstable(feature = "sync_unsafe_cell", issue = "95439")]
2735#[rustc_const_unstable(feature = "const_default", issue = "143894")]
2736#[cfg(not(feature = "ferrocene_certified"))]
2737impl<T: [const] Default> const Default for SyncUnsafeCell<T> {
2738 /// Creates an `SyncUnsafeCell`, with the `Default` value for T.
2739 fn default() -> SyncUnsafeCell<T> {
2740 SyncUnsafeCell::new(Default::default())
2741 }
2742}
2743
2744#[unstable(feature = "sync_unsafe_cell", issue = "95439")]
2745#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
2746#[cfg(not(feature = "ferrocene_certified"))]
2747impl<T> const From<T> for SyncUnsafeCell<T> {
2748 /// Creates a new `SyncUnsafeCell<T>` containing the given value.
2749 fn from(t: T) -> SyncUnsafeCell<T> {
2750 SyncUnsafeCell::new(t)
2751 }
2752}
2753
2754#[unstable(feature = "coerce_unsized", issue = "18598")]
2755//#[unstable(feature = "sync_unsafe_cell", issue = "95439")]
2756#[cfg(not(feature = "ferrocene_certified"))]
2757impl<T: CoerceUnsized<U>, U> CoerceUnsized<SyncUnsafeCell<U>> for SyncUnsafeCell<T> {}
2758
2759// Allow types that wrap `SyncUnsafeCell` to also implement `DispatchFromDyn`
2760// and become dyn-compatible method receivers.
2761// Note that currently `SyncUnsafeCell` itself cannot be a method receiver
2762// because it does not implement Deref.
2763// In other words:
2764// `self: SyncUnsafeCell<&Self>` won't work
2765// `self: SyncUnsafeCellWrapper<Self>` becomes possible
2766#[unstable(feature = "dispatch_from_dyn", issue = "none")]
2767//#[unstable(feature = "sync_unsafe_cell", issue = "95439")]
2768#[cfg(not(feature = "ferrocene_certified"))]
2769impl<T: DispatchFromDyn<U>, U> DispatchFromDyn<SyncUnsafeCell<U>> for SyncUnsafeCell<T> {}
2770
2771#[allow(unused)]
2772#[cfg(not(feature = "ferrocene_certified"))]
2773fn assert_coerce_unsized(
2774 a: UnsafeCell<&i32>,
2775 b: SyncUnsafeCell<&i32>,
2776 c: Cell<&i32>,
2777 d: RefCell<&i32>,
2778) {
2779 let _: UnsafeCell<&dyn Send> = a;
2780 let _: SyncUnsafeCell<&dyn Send> = b;
2781 let _: Cell<&dyn Send> = c;
2782 let _: RefCell<&dyn Send> = d;
2783}
2784
2785#[unstable(feature = "pin_coerce_unsized_trait", issue = "123430")]
2786#[cfg(not(feature = "ferrocene_certified"))]
2787unsafe impl<T: ?Sized> PinCoerceUnsized for UnsafeCell<T> {}
2788
2789#[unstable(feature = "pin_coerce_unsized_trait", issue = "123430")]
2790#[cfg(not(feature = "ferrocene_certified"))]
2791unsafe impl<T: ?Sized> PinCoerceUnsized for SyncUnsafeCell<T> {}
2792
2793#[unstable(feature = "pin_coerce_unsized_trait", issue = "123430")]
2794#[cfg(not(feature = "ferrocene_certified"))]
2795unsafe impl<T: ?Sized> PinCoerceUnsized for Cell<T> {}
2796
2797#[unstable(feature = "pin_coerce_unsized_trait", issue = "123430")]
2798#[cfg(not(feature = "ferrocene_certified"))]
2799unsafe impl<T: ?Sized> PinCoerceUnsized for RefCell<T> {}
2800
2801#[unstable(feature = "pin_coerce_unsized_trait", issue = "123430")]
2802#[cfg(not(feature = "ferrocene_certified"))]
2803unsafe impl<'b, T: ?Sized> PinCoerceUnsized for Ref<'b, T> {}
2804
2805#[unstable(feature = "pin_coerce_unsized_trait", issue = "123430")]
2806#[cfg(not(feature = "ferrocene_certified"))]
2807unsafe impl<'b, T: ?Sized> PinCoerceUnsized for RefMut<'b, T> {}