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