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, once set, its value cannot be updated 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")]
338const impl<T: [const] Default> 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")]
395const impl<T> 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 #[ferrocene::prevalidated]
677 pub const fn take(&self) -> T
678 where
679 T: [const] Default,
680 {
681 self.replace(Default::default())
682 }
683}
684
685#[unstable(feature = "coerce_unsized", issue = "18598")]
686impl<T: CoerceUnsized<U>, U> CoerceUnsized<Cell<U>> for Cell<T> {}
687
688// Allow types that wrap `Cell` to also implement `DispatchFromDyn`
689// and become dyn-compatible method receivers.
690// Note that currently `Cell` itself cannot be a method receiver
691// because it does not implement Deref.
692// In other words:
693// `self: Cell<&Self>` won't work
694// `self: CellWrapper<Self>` becomes possible
695#[unstable(feature = "dispatch_from_dyn", issue = "none")]
696impl<T: DispatchFromDyn<U>, U> DispatchFromDyn<Cell<U>> for Cell<T> {}
697
698#[stable(feature = "more_conversion_trait_impls", since = "1.95.0")]
699impl<T, const N: usize> AsRef<[Cell<T>; N]> for Cell<[T; N]> {
700 #[inline]
701 fn as_ref(&self) -> &[Cell<T>; N] {
702 self.as_array_of_cells()
703 }
704}
705
706#[stable(feature = "more_conversion_trait_impls", since = "1.95.0")]
707impl<T, const N: usize> AsRef<[Cell<T>]> for Cell<[T; N]> {
708 #[inline]
709 fn as_ref(&self) -> &[Cell<T>] {
710 &*self.as_array_of_cells()
711 }
712}
713
714#[stable(feature = "more_conversion_trait_impls", since = "1.95.0")]
715impl<T> AsRef<[Cell<T>]> for Cell<[T]> {
716 #[inline]
717 fn as_ref(&self) -> &[Cell<T>] {
718 self.as_slice_of_cells()
719 }
720}
721
722impl<T> Cell<[T]> {
723 /// Returns a `&[Cell<T>]` from a `&Cell<[T]>`
724 ///
725 /// # Examples
726 ///
727 /// ```
728 /// use std::cell::Cell;
729 ///
730 /// let slice: &mut [i32] = &mut [1, 2, 3];
731 /// let cell_slice: &Cell<[i32]> = Cell::from_mut(slice);
732 /// let slice_cell: &[Cell<i32>] = cell_slice.as_slice_of_cells();
733 ///
734 /// assert_eq!(slice_cell.len(), 3);
735 /// ```
736 #[stable(feature = "as_cell", since = "1.37.0")]
737 #[rustc_const_stable(feature = "const_cell", since = "1.88.0")]
738 pub const fn as_slice_of_cells(&self) -> &[Cell<T>] {
739 // SAFETY: `Cell<T>` has the same memory layout as `T`.
740 unsafe { &*(self as *const Cell<[T]> as *const [Cell<T>]) }
741 }
742}
743
744impl<T, const N: usize> Cell<[T; N]> {
745 /// Returns a `&[Cell<T>; N]` from a `&Cell<[T; N]>`
746 ///
747 /// # Examples
748 ///
749 /// ```
750 /// use std::cell::Cell;
751 ///
752 /// let mut array: [i32; 3] = [1, 2, 3];
753 /// let cell_array: &Cell<[i32; 3]> = Cell::from_mut(&mut array);
754 /// let array_cell: &[Cell<i32>; 3] = cell_array.as_array_of_cells();
755 /// ```
756 #[stable(feature = "as_array_of_cells", since = "1.91.0")]
757 #[rustc_const_stable(feature = "as_array_of_cells", since = "1.91.0")]
758 pub const fn as_array_of_cells(&self) -> &[Cell<T>; N] {
759 // SAFETY: `Cell<T>` has the same memory layout as `T`.
760 unsafe { &*(self as *const Cell<[T; N]> as *const [Cell<T>; N]) }
761 }
762}
763
764/// Types for which cloning `Cell<Self>` is sound.
765///
766/// # Safety
767///
768/// Implementing this trait for a type is sound if and only if the following code is sound for T =
769/// that type.
770///
771/// ```
772/// #![feature(cell_get_cloned)]
773/// # use std::cell::{CloneFromCell, Cell};
774/// fn clone_from_cell<T: CloneFromCell>(cell: &Cell<T>) -> T {
775/// unsafe { T::clone(&*cell.as_ptr()) }
776/// }
777/// ```
778///
779/// Importantly, you can't just implement `CloneFromCell` for any arbitrary `Copy` type, e.g. the
780/// following is unsound:
781///
782/// ```rust
783/// # use std::cell::Cell;
784///
785/// #[derive(Copy, Debug)]
786/// pub struct Bad<'a>(Option<&'a Cell<Bad<'a>>>, u8);
787///
788/// impl Clone for Bad<'_> {
789/// fn clone(&self) -> Self {
790/// let a: &u8 = &self.1;
791/// // when self.0 points to self, we write to self.1 while we have a live `&u8` pointing to
792/// // it -- this is UB
793/// self.0.unwrap().set(Self(None, 1));
794/// dbg!((a, self));
795/// Self(None, 0)
796/// }
797/// }
798///
799/// // this is not sound
800/// // unsafe impl CloneFromCell for Bad<'_> {}
801/// ```
802#[unstable(feature = "cell_get_cloned", issue = "145329")]
803// Allow potential overlapping implementations in user code
804#[marker]
805pub unsafe trait CloneFromCell: Clone {}
806
807// `CloneFromCell` can be implemented for types that don't have indirection and which don't access
808// `Cell`s in their `Clone` implementation. A commonly-used subset is covered here.
809#[unstable(feature = "cell_get_cloned", issue = "145329")]
810unsafe impl<T: CloneFromCell, const N: usize> CloneFromCell for [T; N] {}
811#[unstable(feature = "cell_get_cloned", issue = "145329")]
812unsafe impl<T: CloneFromCell> CloneFromCell for Option<T> {}
813#[unstable(feature = "cell_get_cloned", issue = "145329")]
814unsafe impl<T: CloneFromCell, E: CloneFromCell> CloneFromCell for Result<T, E> {}
815#[unstable(feature = "cell_get_cloned", issue = "145329")]
816unsafe impl<T: ?Sized> CloneFromCell for PhantomData<T> {}
817#[unstable(feature = "cell_get_cloned", issue = "145329")]
818unsafe impl<T: CloneFromCell> CloneFromCell for ManuallyDrop<T> {}
819#[unstable(feature = "cell_get_cloned", issue = "145329")]
820unsafe impl<T: CloneFromCell> CloneFromCell for ops::Range<T> {}
821#[unstable(feature = "cell_get_cloned", issue = "145329")]
822unsafe impl<T: CloneFromCell> CloneFromCell for range::Range<T> {}
823
824#[unstable(feature = "cell_get_cloned", issue = "145329")]
825impl<T: CloneFromCell> Cell<T> {
826 /// Get a clone of the `Cell` that contains a copy of the original value.
827 ///
828 /// This allows a cheaply `Clone`-able type like an `Rc` to be stored in a `Cell`, exposing the
829 /// cheaper `clone()` method.
830 ///
831 /// # Examples
832 ///
833 /// ```
834 /// #![feature(cell_get_cloned)]
835 ///
836 /// use core::cell::Cell;
837 /// use std::rc::Rc;
838 ///
839 /// let rc = Rc::new(1usize);
840 /// let c1 = Cell::new(rc);
841 /// let c2 = c1.get_cloned();
842 /// assert_eq!(*c2.into_inner(), 1);
843 /// ```
844 pub fn get_cloned(&self) -> Self {
845 // SAFETY: T is CloneFromCell, which guarantees that this is sound.
846 Cell::new(T::clone(unsafe { &*self.as_ptr() }))
847 }
848}
849
850/// A mutable memory location with dynamically checked borrow rules
851///
852/// See the [module-level documentation](self) for more.
853#[rustc_diagnostic_item = "RefCell"]
854#[stable(feature = "rust1", since = "1.0.0")]
855#[ferrocene::prevalidated]
856pub struct RefCell<T: ?Sized> {
857 borrow: Cell<BorrowCounter>,
858 // Stores the location of the earliest currently active borrow.
859 // This gets updated whenever we go from having zero borrows
860 // to having a single borrow. When a borrow occurs, this gets included
861 // in the generated `BorrowError`/`BorrowMutError`
862 #[cfg(feature = "debug_refcell")]
863 borrowed_at: Cell<Option<&'static crate::panic::Location<'static>>>,
864 value: UnsafeCell<T>,
865}
866
867/// An error returned by [`RefCell::try_borrow`].
868#[stable(feature = "try_borrow", since = "1.13.0")]
869#[non_exhaustive]
870#[derive(Debug)]
871#[ferrocene::prevalidated]
872pub struct BorrowError {
873 #[cfg(feature = "debug_refcell")]
874 location: &'static crate::panic::Location<'static>,
875}
876
877#[stable(feature = "try_borrow", since = "1.13.0")]
878impl Display for BorrowError {
879 #[ferrocene::prevalidated]
880 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
881 #[cfg(feature = "debug_refcell")]
882 let res = write!(
883 f,
884 "RefCell already mutably borrowed; a previous borrow was at {}",
885 self.location
886 );
887
888 #[cfg(not(feature = "debug_refcell"))]
889 let res = Display::fmt("RefCell already mutably borrowed", f);
890
891 res
892 }
893}
894
895/// An error returned by [`RefCell::try_borrow_mut`].
896#[stable(feature = "try_borrow", since = "1.13.0")]
897#[non_exhaustive]
898#[derive(Debug)]
899#[ferrocene::prevalidated]
900pub struct BorrowMutError {
901 #[cfg(feature = "debug_refcell")]
902 location: &'static crate::panic::Location<'static>,
903}
904
905#[stable(feature = "try_borrow", since = "1.13.0")]
906impl Display for BorrowMutError {
907 #[ferrocene::prevalidated]
908 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
909 #[cfg(feature = "debug_refcell")]
910 let res = write!(f, "RefCell already borrowed; a previous borrow was at {}", self.location);
911
912 #[cfg(not(feature = "debug_refcell"))]
913 let res = Display::fmt("RefCell already borrowed", f);
914
915 res
916 }
917}
918
919// This ensures the panicking code is outlined from `borrow_mut` for `RefCell`.
920#[cfg_attr(not(panic = "immediate-abort"), inline(never))]
921#[track_caller]
922#[cold]
923#[ferrocene::prevalidated]
924const fn panic_already_borrowed(err: BorrowMutError) -> ! {
925 const_panic!(
926 "RefCell already borrowed",
927 "{err}",
928 err: BorrowMutError = err,
929 )
930}
931
932// This ensures the panicking code is outlined from `borrow` for `RefCell`.
933#[cfg_attr(not(panic = "immediate-abort"), inline(never))]
934#[track_caller]
935#[cold]
936#[ferrocene::prevalidated]
937const fn panic_already_mutably_borrowed(err: BorrowError) -> ! {
938 const_panic!(
939 "RefCell already mutably borrowed",
940 "{err}",
941 err: BorrowError = err,
942 )
943}
944
945// Positive values represent the number of `Ref` active. Negative values
946// represent the number of `RefMut` active. Multiple `RefMut`s can only be
947// active at a time if they refer to distinct, nonoverlapping components of a
948// `RefCell` (e.g., different ranges of a slice).
949//
950// `Ref` and `RefMut` are both two words in size, and so there will likely never
951// be enough `Ref`s or `RefMut`s in existence to overflow half of the `usize`
952// range. Thus, a `BorrowCounter` will probably never overflow or underflow.
953// However, this is not a guarantee, as a pathological program could repeatedly
954// create and then mem::forget `Ref`s or `RefMut`s. Thus, all code must
955// explicitly check for overflow and underflow in order to avoid unsafety, or at
956// least behave correctly in the event that overflow or underflow happens (e.g.,
957// see BorrowRef::new).
958type BorrowCounter = isize;
959const UNUSED: BorrowCounter = 0;
960
961#[inline(always)]
962#[ferrocene::prevalidated]
963const fn is_writing(x: BorrowCounter) -> bool {
964 x < UNUSED
965}
966
967#[inline(always)]
968#[ferrocene::prevalidated]
969const fn is_reading(x: BorrowCounter) -> bool {
970 x > UNUSED
971}
972
973impl<T> RefCell<T> {
974 /// Creates a new `RefCell` containing `value`.
975 ///
976 /// # Examples
977 ///
978 /// ```
979 /// use std::cell::RefCell;
980 ///
981 /// let c = RefCell::new(5);
982 /// ```
983 #[stable(feature = "rust1", since = "1.0.0")]
984 #[rustc_const_stable(feature = "const_refcell_new", since = "1.24.0")]
985 #[inline]
986 #[ferrocene::prevalidated]
987 pub const fn new(value: T) -> RefCell<T> {
988 RefCell {
989 value: UnsafeCell::new(value),
990 borrow: Cell::new(UNUSED),
991 #[cfg(feature = "debug_refcell")]
992 borrowed_at: Cell::new(None),
993 }
994 }
995
996 /// Consumes the `RefCell`, returning the wrapped value.
997 ///
998 /// # Examples
999 ///
1000 /// ```
1001 /// use std::cell::RefCell;
1002 ///
1003 /// let c = RefCell::new(5);
1004 ///
1005 /// let five = c.into_inner();
1006 /// ```
1007 #[stable(feature = "rust1", since = "1.0.0")]
1008 #[rustc_const_stable(feature = "const_cell_into_inner", since = "1.83.0")]
1009 #[rustc_allow_const_fn_unstable(const_precise_live_drops)]
1010 #[inline]
1011 pub const fn into_inner(self) -> T {
1012 // Since this function takes `self` (the `RefCell`) by value, the
1013 // compiler statically verifies that it is not currently borrowed.
1014 self.value.into_inner()
1015 }
1016
1017 /// Replaces the wrapped value with a new one, returning the old value,
1018 /// without deinitializing either one.
1019 ///
1020 /// This function corresponds to [`std::mem::replace`](../mem/fn.replace.html).
1021 ///
1022 /// # Panics
1023 ///
1024 /// Panics if the value is currently borrowed.
1025 ///
1026 /// # Examples
1027 ///
1028 /// ```
1029 /// use std::cell::RefCell;
1030 /// let cell = RefCell::new(5);
1031 /// let old_value = cell.replace(6);
1032 /// assert_eq!(old_value, 5);
1033 /// assert_eq!(cell, RefCell::new(6));
1034 /// ```
1035 #[inline]
1036 #[stable(feature = "refcell_replace", since = "1.24.0")]
1037 #[track_caller]
1038 #[rustc_confusables("swap")]
1039 #[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
1040 #[rustc_should_not_be_called_on_const_items]
1041 #[ferrocene::prevalidated]
1042 pub const fn replace(&self, t: T) -> T {
1043 mem::replace(&mut self.borrow_mut(), t)
1044 }
1045
1046 /// Replaces the wrapped value with a new one computed from `f`, returning
1047 /// the old value, without deinitializing either one.
1048 ///
1049 /// # Panics
1050 ///
1051 /// Panics if the value is currently borrowed.
1052 ///
1053 /// # Examples
1054 ///
1055 /// ```
1056 /// use std::cell::RefCell;
1057 /// let cell = RefCell::new(5);
1058 /// let old_value = cell.replace_with(|&mut old| old + 1);
1059 /// assert_eq!(old_value, 5);
1060 /// assert_eq!(cell, RefCell::new(6));
1061 /// ```
1062 #[inline]
1063 #[stable(feature = "refcell_replace_swap", since = "1.35.0")]
1064 #[track_caller]
1065 #[rustc_should_not_be_called_on_const_items]
1066 #[ferrocene::prevalidated]
1067 pub fn replace_with<F: FnOnce(&mut T) -> T>(&self, f: F) -> T {
1068 let mut_borrow = &mut *self.borrow_mut();
1069 let replacement = f(mut_borrow);
1070 mem::replace(mut_borrow, replacement)
1071 }
1072
1073 /// Swaps the wrapped value of `self` with the wrapped value of `other`,
1074 /// without deinitializing either one.
1075 ///
1076 /// This function corresponds to [`std::mem::swap`](../mem/fn.swap.html).
1077 ///
1078 /// # Panics
1079 ///
1080 /// Panics if the value in either `RefCell` is currently borrowed, or
1081 /// if `self` and `other` point to the same `RefCell`.
1082 ///
1083 /// # Examples
1084 ///
1085 /// ```
1086 /// use std::cell::RefCell;
1087 /// let c = RefCell::new(5);
1088 /// let d = RefCell::new(6);
1089 /// c.swap(&d);
1090 /// assert_eq!(c, RefCell::new(6));
1091 /// assert_eq!(d, RefCell::new(5));
1092 /// ```
1093 #[inline]
1094 #[stable(feature = "refcell_swap", since = "1.24.0")]
1095 #[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
1096 #[rustc_should_not_be_called_on_const_items]
1097 pub const fn swap(&self, other: &Self) {
1098 mem::swap(&mut *self.borrow_mut(), &mut *other.borrow_mut())
1099 }
1100}
1101
1102impl<T: ?Sized> RefCell<T> {
1103 /// Immutably borrows the wrapped value.
1104 ///
1105 /// The borrow lasts until the returned `Ref` exits scope. Multiple
1106 /// immutable borrows can be taken out at the same time.
1107 ///
1108 /// # Panics
1109 ///
1110 /// Panics if the value is currently mutably borrowed. For a non-panicking variant, use
1111 /// [`try_borrow`](#method.try_borrow).
1112 ///
1113 /// # Examples
1114 ///
1115 /// ```
1116 /// use std::cell::RefCell;
1117 ///
1118 /// let c = RefCell::new(5);
1119 ///
1120 /// let borrowed_five = c.borrow();
1121 /// let borrowed_five2 = c.borrow();
1122 /// ```
1123 ///
1124 /// An example of panic:
1125 ///
1126 /// ```should_panic
1127 /// use std::cell::RefCell;
1128 ///
1129 /// let c = RefCell::new(5);
1130 ///
1131 /// let m = c.borrow_mut();
1132 /// let b = c.borrow(); // this causes a panic
1133 /// ```
1134 #[stable(feature = "rust1", since = "1.0.0")]
1135 #[inline]
1136 #[track_caller]
1137 #[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
1138 #[rustc_should_not_be_called_on_const_items]
1139 #[ferrocene::prevalidated]
1140 pub const fn borrow(&self) -> Ref<'_, T> {
1141 match self.try_borrow() {
1142 Ok(b) => b,
1143 Err(err) => panic_already_mutably_borrowed(err),
1144 }
1145 }
1146
1147 /// Immutably borrows the wrapped value, returning an error if the value is currently mutably
1148 /// borrowed.
1149 ///
1150 /// The borrow lasts until the returned `Ref` exits scope. Multiple immutable borrows can be
1151 /// taken out at the same time.
1152 ///
1153 /// This is the non-panicking variant of [`borrow`](#method.borrow).
1154 ///
1155 /// # Examples
1156 ///
1157 /// ```
1158 /// use std::cell::RefCell;
1159 ///
1160 /// let c = RefCell::new(5);
1161 ///
1162 /// {
1163 /// let m = c.borrow_mut();
1164 /// assert!(c.try_borrow().is_err());
1165 /// }
1166 ///
1167 /// {
1168 /// let m = c.borrow();
1169 /// assert!(c.try_borrow().is_ok());
1170 /// }
1171 /// ```
1172 #[stable(feature = "try_borrow", since = "1.13.0")]
1173 #[inline]
1174 #[cfg_attr(feature = "debug_refcell", track_caller)]
1175 #[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
1176 #[rustc_should_not_be_called_on_const_items]
1177 #[ferrocene::prevalidated]
1178 pub const fn try_borrow(&self) -> Result<Ref<'_, T>, BorrowError> {
1179 match BorrowRef::new(&self.borrow) {
1180 Some(b) => {
1181 #[cfg(feature = "debug_refcell")]
1182 {
1183 // `borrowed_at` is always the *first* active borrow
1184 if b.borrow.get() == 1 {
1185 self.borrowed_at.replace(Some(crate::panic::Location::caller()));
1186 }
1187 }
1188
1189 // SAFETY: `BorrowRef` ensures that there is only immutable access
1190 // to the value while borrowed.
1191 let value = unsafe { NonNull::new_unchecked(self.value.get()) };
1192 Ok(Ref { value, borrow: b })
1193 }
1194 None => Err(BorrowError {
1195 // If a borrow occurred, then we must already have an outstanding borrow,
1196 // so `borrowed_at` will be `Some`
1197 #[cfg(feature = "debug_refcell")]
1198 location: self.borrowed_at.get().unwrap(),
1199 }),
1200 }
1201 }
1202
1203 /// Mutably borrows the wrapped value.
1204 ///
1205 /// The borrow lasts until the returned `RefMut` or all `RefMut`s derived
1206 /// from it exit scope. The value cannot be borrowed while this borrow is
1207 /// active.
1208 ///
1209 /// # Panics
1210 ///
1211 /// Panics if the value is currently borrowed. For a non-panicking variant, use
1212 /// [`try_borrow_mut`](#method.try_borrow_mut).
1213 ///
1214 /// # Examples
1215 ///
1216 /// ```
1217 /// use std::cell::RefCell;
1218 ///
1219 /// let c = RefCell::new("hello".to_owned());
1220 ///
1221 /// *c.borrow_mut() = "bonjour".to_owned();
1222 ///
1223 /// assert_eq!(&*c.borrow(), "bonjour");
1224 /// ```
1225 ///
1226 /// An example of panic:
1227 ///
1228 /// ```should_panic
1229 /// use std::cell::RefCell;
1230 ///
1231 /// let c = RefCell::new(5);
1232 /// let m = c.borrow();
1233 ///
1234 /// let b = c.borrow_mut(); // this causes a panic
1235 /// ```
1236 #[stable(feature = "rust1", since = "1.0.0")]
1237 #[inline]
1238 #[track_caller]
1239 #[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
1240 #[rustc_should_not_be_called_on_const_items]
1241 #[ferrocene::prevalidated]
1242 pub const fn borrow_mut(&self) -> RefMut<'_, T> {
1243 match self.try_borrow_mut() {
1244 Ok(b) => b,
1245 Err(err) => panic_already_borrowed(err),
1246 }
1247 }
1248
1249 /// Mutably borrows the wrapped value, returning an error if the value is currently borrowed.
1250 ///
1251 /// The borrow lasts until the returned `RefMut` or all `RefMut`s derived
1252 /// from it exit scope. The value cannot be borrowed while this borrow is
1253 /// active.
1254 ///
1255 /// This is the non-panicking variant of [`borrow_mut`](#method.borrow_mut).
1256 ///
1257 /// # Examples
1258 ///
1259 /// ```
1260 /// use std::cell::RefCell;
1261 ///
1262 /// let c = RefCell::new(5);
1263 ///
1264 /// {
1265 /// let m = c.borrow();
1266 /// assert!(c.try_borrow_mut().is_err());
1267 /// }
1268 ///
1269 /// assert!(c.try_borrow_mut().is_ok());
1270 /// ```
1271 #[stable(feature = "try_borrow", since = "1.13.0")]
1272 #[inline]
1273 #[cfg_attr(feature = "debug_refcell", track_caller)]
1274 #[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
1275 #[rustc_should_not_be_called_on_const_items]
1276 #[ferrocene::prevalidated]
1277 pub const fn try_borrow_mut(&self) -> Result<RefMut<'_, T>, BorrowMutError> {
1278 match BorrowRefMut::new(&self.borrow) {
1279 Some(b) => {
1280 #[cfg(feature = "debug_refcell")]
1281 {
1282 self.borrowed_at.replace(Some(crate::panic::Location::caller()));
1283 }
1284
1285 // SAFETY: `BorrowRefMut` guarantees unique access.
1286 let value = unsafe { NonNull::new_unchecked(self.value.get()) };
1287 Ok(RefMut { value, borrow: b, marker: PhantomData })
1288 }
1289 None => Err(BorrowMutError {
1290 // If a borrow occurred, then we must already have an outstanding borrow,
1291 // so `borrowed_at` will be `Some`
1292 #[cfg(feature = "debug_refcell")]
1293 location: self.borrowed_at.get().unwrap(),
1294 }),
1295 }
1296 }
1297
1298 /// Returns a raw pointer to the underlying data in this cell.
1299 ///
1300 /// # Examples
1301 ///
1302 /// ```
1303 /// use std::cell::RefCell;
1304 ///
1305 /// let c = RefCell::new(5);
1306 ///
1307 /// let ptr = c.as_ptr();
1308 /// ```
1309 #[inline]
1310 #[stable(feature = "cell_as_ptr", since = "1.12.0")]
1311 #[rustc_as_ptr]
1312 #[rustc_never_returns_null_ptr]
1313 #[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
1314 pub const fn as_ptr(&self) -> *mut T {
1315 self.value.get()
1316 }
1317
1318 /// Returns a mutable reference to the underlying data.
1319 ///
1320 /// Since this method borrows `RefCell` mutably, it is statically guaranteed
1321 /// that no borrows to the underlying data exist. The dynamic checks inherent
1322 /// in [`borrow_mut`] and most other methods of `RefCell` are therefore
1323 /// unnecessary. Note that this method does not reset the borrowing state if borrows were previously leaked
1324 /// (e.g., via [`forget()`] on a [`Ref`] or [`RefMut`]). For that purpose,
1325 /// consider using the unstable [`undo_leak`] method.
1326 ///
1327 /// This method can only be called if `RefCell` can be mutably borrowed,
1328 /// which in general is only the case directly after the `RefCell` has
1329 /// been created. In these situations, skipping the aforementioned dynamic
1330 /// borrowing checks may yield better ergonomics and runtime-performance.
1331 ///
1332 /// In most situations where `RefCell` is used, it can't be borrowed mutably.
1333 /// Use [`borrow_mut`] to get mutable access to the underlying data then.
1334 ///
1335 /// [`borrow_mut`]: RefCell::borrow_mut()
1336 /// [`forget()`]: mem::forget
1337 /// [`undo_leak`]: RefCell::undo_leak()
1338 ///
1339 /// # Examples
1340 ///
1341 /// ```
1342 /// use std::cell::RefCell;
1343 ///
1344 /// let mut c = RefCell::new(5);
1345 /// *c.get_mut() += 1;
1346 ///
1347 /// assert_eq!(c, RefCell::new(6));
1348 /// ```
1349 #[inline]
1350 #[stable(feature = "cell_get_mut", since = "1.11.0")]
1351 #[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
1352 pub const fn get_mut(&mut self) -> &mut T {
1353 self.value.get_mut()
1354 }
1355
1356 /// Undo the effect of leaked guards on the borrow state of the `RefCell`.
1357 ///
1358 /// This call is similar to [`get_mut`] but more specialized. It borrows `RefCell` mutably to
1359 /// ensure no borrows exist and then resets the state tracking shared borrows. This is relevant
1360 /// if some `Ref` or `RefMut` borrows have been leaked.
1361 ///
1362 /// [`get_mut`]: RefCell::get_mut()
1363 ///
1364 /// # Examples
1365 ///
1366 /// ```
1367 /// #![feature(cell_leak)]
1368 /// use std::cell::RefCell;
1369 ///
1370 /// let mut c = RefCell::new(0);
1371 /// std::mem::forget(c.borrow_mut());
1372 ///
1373 /// assert!(c.try_borrow().is_err());
1374 /// c.undo_leak();
1375 /// assert!(c.try_borrow().is_ok());
1376 /// ```
1377 #[unstable(feature = "cell_leak", issue = "69099")]
1378 #[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
1379 pub const fn undo_leak(&mut self) -> &mut T {
1380 *self.borrow.get_mut() = UNUSED;
1381 self.get_mut()
1382 }
1383
1384 /// Immutably borrows the wrapped value, returning an error if the value is
1385 /// currently mutably borrowed.
1386 ///
1387 /// # Safety
1388 ///
1389 /// Unlike `RefCell::borrow`, this method is unsafe because it does not
1390 /// return a `Ref`, thus leaving the borrow flag untouched. Mutably
1391 /// borrowing the `RefCell` while the reference returned by this method
1392 /// is alive is undefined behavior.
1393 ///
1394 /// # Examples
1395 ///
1396 /// ```
1397 /// use std::cell::RefCell;
1398 ///
1399 /// let c = RefCell::new(5);
1400 ///
1401 /// {
1402 /// let m = c.borrow_mut();
1403 /// assert!(unsafe { c.try_borrow_unguarded() }.is_err());
1404 /// }
1405 ///
1406 /// {
1407 /// let m = c.borrow();
1408 /// assert!(unsafe { c.try_borrow_unguarded() }.is_ok());
1409 /// }
1410 /// ```
1411 #[stable(feature = "borrow_state", since = "1.37.0")]
1412 #[inline]
1413 #[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
1414 pub const unsafe fn try_borrow_unguarded(&self) -> Result<&T, BorrowError> {
1415 if !is_writing(self.borrow.get()) {
1416 // SAFETY: We check that nobody is actively writing now, but it is
1417 // the caller's responsibility to ensure that nobody writes until
1418 // the returned reference is no longer in use.
1419 // Also, `self.value.get()` refers to the value owned by `self`
1420 // and is thus guaranteed to be valid for the lifetime of `self`.
1421 Ok(unsafe { &*self.value.get() })
1422 } else {
1423 Err(BorrowError {
1424 // If a borrow occurred, then we must already have an outstanding borrow,
1425 // so `borrowed_at` will be `Some`
1426 #[cfg(feature = "debug_refcell")]
1427 location: self.borrowed_at.get().unwrap(),
1428 })
1429 }
1430 }
1431}
1432
1433impl<T: Default> RefCell<T> {
1434 /// Takes the wrapped value, leaving `Default::default()` in its place.
1435 ///
1436 /// # Panics
1437 ///
1438 /// Panics if the value is currently borrowed.
1439 ///
1440 /// # Examples
1441 ///
1442 /// ```
1443 /// use std::cell::RefCell;
1444 ///
1445 /// let c = RefCell::new(5);
1446 /// let five = c.take();
1447 ///
1448 /// assert_eq!(five, 5);
1449 /// assert_eq!(c.into_inner(), 0);
1450 /// ```
1451 #[stable(feature = "refcell_take", since = "1.50.0")]
1452 #[ferrocene::prevalidated]
1453 pub fn take(&self) -> T {
1454 self.replace(Default::default())
1455 }
1456}
1457
1458#[stable(feature = "rust1", since = "1.0.0")]
1459unsafe impl<T: ?Sized> Send for RefCell<T> where T: Send {}
1460
1461#[stable(feature = "rust1", since = "1.0.0")]
1462impl<T: ?Sized> !Sync for RefCell<T> {}
1463
1464#[stable(feature = "rust1", since = "1.0.0")]
1465impl<T: Clone> Clone for RefCell<T> {
1466 /// # Panics
1467 ///
1468 /// Panics if the value is currently mutably borrowed.
1469 #[inline]
1470 #[track_caller]
1471 fn clone(&self) -> RefCell<T> {
1472 RefCell::new(self.borrow().clone())
1473 }
1474
1475 /// # Panics
1476 ///
1477 /// Panics if `source` is currently mutably borrowed.
1478 #[inline]
1479 #[track_caller]
1480 fn clone_from(&mut self, source: &Self) {
1481 self.get_mut().clone_from(&source.borrow())
1482 }
1483}
1484
1485#[stable(feature = "rust1", since = "1.0.0")]
1486#[rustc_const_unstable(feature = "const_default", issue = "143894")]
1487const impl<T: [const] Default> Default for RefCell<T> {
1488 /// Creates a `RefCell<T>`, with the `Default` value for T.
1489 #[inline]
1490 fn default() -> RefCell<T> {
1491 RefCell::new(Default::default())
1492 }
1493}
1494
1495#[stable(feature = "rust1", since = "1.0.0")]
1496impl<T: ?Sized + PartialEq> PartialEq for RefCell<T> {
1497 /// # Panics
1498 ///
1499 /// Panics if the value in either `RefCell` is currently mutably borrowed.
1500 #[inline]
1501 fn eq(&self, other: &RefCell<T>) -> bool {
1502 *self.borrow() == *other.borrow()
1503 }
1504}
1505
1506#[stable(feature = "cell_eq", since = "1.2.0")]
1507impl<T: ?Sized + Eq> Eq for RefCell<T> {}
1508
1509#[stable(feature = "cell_ord", since = "1.10.0")]
1510impl<T: ?Sized + PartialOrd> PartialOrd for RefCell<T> {
1511 /// # Panics
1512 ///
1513 /// Panics if the value in either `RefCell` is currently mutably borrowed.
1514 #[inline]
1515 fn partial_cmp(&self, other: &RefCell<T>) -> Option<Ordering> {
1516 self.borrow().partial_cmp(&*other.borrow())
1517 }
1518
1519 /// # Panics
1520 ///
1521 /// Panics if the value in either `RefCell` is currently mutably borrowed.
1522 #[inline]
1523 fn lt(&self, other: &RefCell<T>) -> bool {
1524 *self.borrow() < *other.borrow()
1525 }
1526
1527 /// # Panics
1528 ///
1529 /// Panics if the value in either `RefCell` is currently mutably borrowed.
1530 #[inline]
1531 fn le(&self, other: &RefCell<T>) -> bool {
1532 *self.borrow() <= *other.borrow()
1533 }
1534
1535 /// # Panics
1536 ///
1537 /// Panics if the value in either `RefCell` is currently mutably borrowed.
1538 #[inline]
1539 fn gt(&self, other: &RefCell<T>) -> bool {
1540 *self.borrow() > *other.borrow()
1541 }
1542
1543 /// # Panics
1544 ///
1545 /// Panics if the value in either `RefCell` is currently mutably borrowed.
1546 #[inline]
1547 fn ge(&self, other: &RefCell<T>) -> bool {
1548 *self.borrow() >= *other.borrow()
1549 }
1550}
1551
1552#[stable(feature = "cell_ord", since = "1.10.0")]
1553impl<T: ?Sized + Ord> Ord for RefCell<T> {
1554 /// # Panics
1555 ///
1556 /// Panics if the value in either `RefCell` is currently mutably borrowed.
1557 #[inline]
1558 fn cmp(&self, other: &RefCell<T>) -> Ordering {
1559 self.borrow().cmp(&*other.borrow())
1560 }
1561}
1562
1563#[stable(feature = "cell_from", since = "1.12.0")]
1564#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
1565const impl<T> From<T> for RefCell<T> {
1566 /// Creates a new `RefCell<T>` containing the given value.
1567 fn from(t: T) -> RefCell<T> {
1568 RefCell::new(t)
1569 }
1570}
1571
1572#[unstable(feature = "coerce_unsized", issue = "18598")]
1573impl<T: CoerceUnsized<U>, U> CoerceUnsized<RefCell<U>> for RefCell<T> {}
1574
1575#[ferrocene::prevalidated]
1576struct BorrowRef<'b> {
1577 borrow: &'b Cell<BorrowCounter>,
1578}
1579
1580impl<'b> BorrowRef<'b> {
1581 #[inline]
1582 #[ferrocene::prevalidated]
1583 const fn new(borrow: &'b Cell<BorrowCounter>) -> Option<BorrowRef<'b>> {
1584 let b = borrow.get().wrapping_add(1);
1585 if !is_reading(b) {
1586 // Incrementing borrow can result in a non-reading value (<= 0) in these cases:
1587 // 1. It was < 0, i.e. there are writing borrows, so we can't allow a read borrow
1588 // due to Rust's reference aliasing rules
1589 // 2. It was isize::MAX (the max amount of reading borrows) and it overflowed
1590 // into isize::MIN (the max amount of writing borrows) so we can't allow
1591 // an additional read borrow because isize can't represent so many read borrows
1592 // (this can only happen if you mem::forget more than a small constant amount of
1593 // `Ref`s, which is not good practice)
1594 None
1595 } else {
1596 // Incrementing borrow can result in a reading value (> 0) in these cases:
1597 // 1. It was = 0, i.e. it wasn't borrowed, and we are taking the first read borrow
1598 // 2. It was > 0 and < isize::MAX, i.e. there were read borrows, and isize
1599 // is large enough to represent having one more read borrow
1600 borrow.replace(b);
1601 Some(BorrowRef { borrow })
1602 }
1603 }
1604}
1605
1606#[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
1607const impl Drop for BorrowRef<'_> {
1608 #[inline]
1609 #[ferrocene::prevalidated]
1610 fn drop(&mut self) {
1611 let borrow = self.borrow.get();
1612 debug_assert!(is_reading(borrow));
1613 self.borrow.replace(borrow - 1);
1614 }
1615}
1616
1617#[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
1618const impl Clone for BorrowRef<'_> {
1619 #[inline]
1620 fn clone(&self) -> Self {
1621 // Since this Ref exists, we know the borrow flag
1622 // is a reading borrow.
1623 let borrow = self.borrow.get();
1624 debug_assert!(is_reading(borrow));
1625 // Prevent the borrow counter from overflowing into
1626 // a writing borrow.
1627 assert!(borrow != BorrowCounter::MAX);
1628 self.borrow.replace(borrow + 1);
1629 BorrowRef { borrow: self.borrow }
1630 }
1631}
1632
1633/// Wraps a borrowed reference to a value in a `RefCell` box.
1634/// A wrapper type for an immutably borrowed value from a `RefCell<T>`.
1635///
1636/// See the [module-level documentation](self) for more.
1637#[stable(feature = "rust1", since = "1.0.0")]
1638#[must_not_suspend = "holding a Ref across suspend points can cause BorrowErrors"]
1639#[rustc_diagnostic_item = "RefCellRef"]
1640#[ferrocene::prevalidated]
1641pub struct Ref<'b, T: ?Sized + 'b> {
1642 // NB: we use a pointer instead of `&'b T` to avoid `noalias` violations, because a
1643 // `Ref` argument doesn't hold immutability for its whole scope, only until it drops.
1644 // `NonNull` is also covariant over `T`, just like we would have with `&T`.
1645 value: NonNull<T>,
1646 borrow: BorrowRef<'b>,
1647}
1648
1649#[stable(feature = "rust1", since = "1.0.0")]
1650#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
1651const impl<T: ?Sized> Deref for Ref<'_, T> {
1652 type Target = T;
1653
1654 #[inline]
1655 #[ferrocene::prevalidated]
1656 fn deref(&self) -> &T {
1657 // SAFETY: the value is accessible as long as we hold our borrow.
1658 unsafe { self.value.as_ref() }
1659 }
1660}
1661
1662#[unstable(feature = "deref_pure_trait", issue = "87121")]
1663unsafe impl<T: ?Sized> DerefPure for Ref<'_, T> {}
1664
1665impl<'b, T: ?Sized> Ref<'b, T> {
1666 /// Copies a `Ref`.
1667 ///
1668 /// The `RefCell` is already immutably borrowed, so this cannot fail.
1669 ///
1670 /// This is an associated function that needs to be used as
1671 /// `Ref::clone(...)`. A `Clone` implementation or a method would interfere
1672 /// with the widespread use of `r.borrow().clone()` to clone the contents of
1673 /// a `RefCell`.
1674 #[stable(feature = "cell_extras", since = "1.15.0")]
1675 #[must_use]
1676 #[inline]
1677 #[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
1678 pub const fn clone(orig: &Ref<'b, T>) -> Ref<'b, T> {
1679 Ref { value: orig.value, borrow: orig.borrow.clone() }
1680 }
1681
1682 /// Makes a new `Ref` for a component of the borrowed data.
1683 ///
1684 /// The `RefCell` is already immutably borrowed, so this cannot fail.
1685 ///
1686 /// This is an associated function that needs to be used as `Ref::map(...)`.
1687 /// A method would interfere with methods of the same name on the contents
1688 /// of a `RefCell` used through `Deref`.
1689 ///
1690 /// # Examples
1691 ///
1692 /// ```
1693 /// use std::cell::{RefCell, Ref};
1694 ///
1695 /// let c = RefCell::new((5, 'b'));
1696 /// let b1: Ref<'_, (u32, char)> = c.borrow();
1697 /// let b2: Ref<'_, u32> = Ref::map(b1, |t| &t.0);
1698 /// assert_eq!(*b2, 5)
1699 /// ```
1700 #[stable(feature = "cell_map", since = "1.8.0")]
1701 #[inline]
1702 pub fn map<U: ?Sized, F>(orig: Ref<'b, T>, f: F) -> Ref<'b, U>
1703 where
1704 F: FnOnce(&T) -> &U,
1705 {
1706 Ref { value: NonNull::from(f(&*orig)), borrow: orig.borrow }
1707 }
1708
1709 /// Makes a new `Ref` for an optional component of the borrowed data. The
1710 /// original guard is returned as an `Err(..)` if the closure returns
1711 /// `None`.
1712 ///
1713 /// The `RefCell` is already immutably borrowed, so this cannot fail.
1714 ///
1715 /// This is an associated function that needs to be used as
1716 /// `Ref::filter_map(...)`. A method would interfere with methods of the same
1717 /// name on the contents of a `RefCell` used through `Deref`.
1718 ///
1719 /// # Examples
1720 ///
1721 /// ```
1722 /// use std::cell::{RefCell, Ref};
1723 ///
1724 /// let c = RefCell::new(vec![1, 2, 3]);
1725 /// let b1: Ref<'_, Vec<u32>> = c.borrow();
1726 /// let b2: Result<Ref<'_, u32>, _> = Ref::filter_map(b1, |v| v.get(1));
1727 /// assert_eq!(*b2.unwrap(), 2);
1728 /// ```
1729 #[stable(feature = "cell_filter_map", since = "1.63.0")]
1730 #[inline]
1731 pub fn filter_map<U: ?Sized, F>(orig: Ref<'b, T>, f: F) -> Result<Ref<'b, U>, Self>
1732 where
1733 F: FnOnce(&T) -> Option<&U>,
1734 {
1735 match f(&*orig) {
1736 Some(value) => Ok(Ref { value: NonNull::from(value), borrow: orig.borrow }),
1737 None => Err(orig),
1738 }
1739 }
1740
1741 /// Tries to makes a new `Ref` for a component of the borrowed data.
1742 /// On failure, the original guard is returned alongside with the error
1743 /// returned by the closure.
1744 ///
1745 /// The `RefCell` is already immutably borrowed, so this cannot fail.
1746 ///
1747 /// This is an associated function that needs to be used as
1748 /// `Ref::try_map(...)`. A method would interfere with methods of the same
1749 /// name on the contents of a `RefCell` used through `Deref`.
1750 ///
1751 /// # Examples
1752 ///
1753 /// ```
1754 /// #![feature(refcell_try_map)]
1755 /// use std::cell::{RefCell, Ref};
1756 /// use std::str::{from_utf8, Utf8Error};
1757 ///
1758 /// let c = RefCell::new(vec![0xF0, 0x9F, 0xA6 ,0x80]);
1759 /// let b1: Ref<'_, Vec<u8>> = c.borrow();
1760 /// let b2: Result<Ref<'_, str>, _> = Ref::try_map(b1, |v| from_utf8(v));
1761 /// assert_eq!(&*b2.unwrap(), "🦀");
1762 ///
1763 /// let c = RefCell::new(vec![0xF0, 0x9F, 0xA6]);
1764 /// let b1: Ref<'_, Vec<u8>> = c.borrow();
1765 /// let b2: Result<_, (Ref<'_, Vec<u8>>, Utf8Error)> = Ref::try_map(b1, |v| from_utf8(v));
1766 /// let (b3, e) = b2.unwrap_err();
1767 /// assert_eq!(*b3, vec![0xF0, 0x9F, 0xA6]);
1768 /// assert_eq!(e.valid_up_to(), 0);
1769 /// ```
1770 #[unstable(feature = "refcell_try_map", issue = "143801")]
1771 #[inline]
1772 pub fn try_map<U: ?Sized, E>(
1773 orig: Ref<'b, T>,
1774 f: impl FnOnce(&T) -> Result<&U, E>,
1775 ) -> Result<Ref<'b, U>, (Self, E)> {
1776 match f(&*orig) {
1777 Ok(value) => Ok(Ref { value: NonNull::from(value), borrow: orig.borrow }),
1778 Err(e) => Err((orig, e)),
1779 }
1780 }
1781
1782 /// Splits a `Ref` into multiple `Ref`s for different components of the
1783 /// borrowed data.
1784 ///
1785 /// The `RefCell` is already immutably borrowed, so this cannot fail.
1786 ///
1787 /// This is an associated function that needs to be used as
1788 /// `Ref::map_split(...)`. A method would interfere with methods of the same
1789 /// name on the contents of a `RefCell` used through `Deref`.
1790 ///
1791 /// # Examples
1792 ///
1793 /// ```
1794 /// use std::cell::{Ref, RefCell};
1795 ///
1796 /// let cell = RefCell::new([1, 2, 3, 4]);
1797 /// let borrow = cell.borrow();
1798 /// let (begin, end) = Ref::map_split(borrow, |slice| slice.split_at(2));
1799 /// assert_eq!(*begin, [1, 2]);
1800 /// assert_eq!(*end, [3, 4]);
1801 /// ```
1802 #[stable(feature = "refcell_map_split", since = "1.35.0")]
1803 #[inline]
1804 pub fn map_split<U: ?Sized, V: ?Sized, F>(orig: Ref<'b, T>, f: F) -> (Ref<'b, U>, Ref<'b, V>)
1805 where
1806 F: FnOnce(&T) -> (&U, &V),
1807 {
1808 let (a, b) = f(&*orig);
1809 let borrow = orig.borrow.clone();
1810 (
1811 Ref { value: NonNull::from(a), borrow },
1812 Ref { value: NonNull::from(b), borrow: orig.borrow },
1813 )
1814 }
1815
1816 /// Converts into a reference to the underlying data.
1817 ///
1818 /// The underlying `RefCell` can never be mutably borrowed from again and will always appear
1819 /// already immutably borrowed. It is not a good idea to leak more than a constant number of
1820 /// references. The `RefCell` can be immutably borrowed again if only a smaller number of leaks
1821 /// have occurred in total.
1822 ///
1823 /// This is an associated function that needs to be used as
1824 /// `Ref::leak(...)`. A method would interfere with methods of the
1825 /// same name on the contents of a `RefCell` used through `Deref`.
1826 ///
1827 /// # Examples
1828 ///
1829 /// ```
1830 /// #![feature(cell_leak)]
1831 /// use std::cell::{RefCell, Ref};
1832 /// let cell = RefCell::new(0);
1833 ///
1834 /// let value = Ref::leak(cell.borrow());
1835 /// assert_eq!(*value, 0);
1836 ///
1837 /// assert!(cell.try_borrow().is_ok());
1838 /// assert!(cell.try_borrow_mut().is_err());
1839 /// ```
1840 #[unstable(feature = "cell_leak", issue = "69099")]
1841 #[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
1842 pub const fn leak(orig: Ref<'b, T>) -> &'b T {
1843 // By forgetting this Ref we ensure that the borrow counter in the RefCell can't go back to
1844 // UNUSED within the lifetime `'b`. Resetting the reference tracking state would require a
1845 // unique reference to the borrowed RefCell. No further mutable references can be created
1846 // from the original cell.
1847 mem::forget(orig.borrow);
1848 // SAFETY: after forgetting, we can form a reference for the rest of lifetime `'b`.
1849 unsafe { orig.value.as_ref() }
1850 }
1851}
1852
1853#[unstable(feature = "coerce_unsized", issue = "18598")]
1854impl<'b, T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Ref<'b, U>> for Ref<'b, T> {}
1855
1856#[stable(feature = "std_guard_impls", since = "1.20.0")]
1857impl<T: ?Sized + fmt::Display> fmt::Display for Ref<'_, T> {
1858 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1859 (**self).fmt(f)
1860 }
1861}
1862
1863impl<'b, T: ?Sized> RefMut<'b, T> {
1864 /// Makes a new `RefMut` for a component of the borrowed data, e.g., an enum
1865 /// variant.
1866 ///
1867 /// The `RefCell` is already mutably borrowed, so this cannot fail.
1868 ///
1869 /// This is an associated function that needs to be used as
1870 /// `RefMut::map(...)`. A method would interfere with methods of the same
1871 /// name on the contents of a `RefCell` used through `Deref`.
1872 ///
1873 /// # Examples
1874 ///
1875 /// ```
1876 /// use std::cell::{RefCell, RefMut};
1877 ///
1878 /// let c = RefCell::new((5, 'b'));
1879 /// {
1880 /// let b1: RefMut<'_, (u32, char)> = c.borrow_mut();
1881 /// let mut b2: RefMut<'_, u32> = RefMut::map(b1, |t| &mut t.0);
1882 /// assert_eq!(*b2, 5);
1883 /// *b2 = 42;
1884 /// }
1885 /// assert_eq!(*c.borrow(), (42, 'b'));
1886 /// ```
1887 #[stable(feature = "cell_map", since = "1.8.0")]
1888 #[inline]
1889 pub fn map<U: ?Sized, F>(mut orig: RefMut<'b, T>, f: F) -> RefMut<'b, U>
1890 where
1891 F: FnOnce(&mut T) -> &mut U,
1892 {
1893 let value = NonNull::from(f(&mut *orig));
1894 RefMut { value, borrow: orig.borrow, marker: PhantomData }
1895 }
1896
1897 /// Makes a new `RefMut` for an optional component of the borrowed data. The
1898 /// original guard is returned as an `Err(..)` if the closure returns
1899 /// `None`.
1900 ///
1901 /// The `RefCell` is already mutably borrowed, so this cannot fail.
1902 ///
1903 /// This is an associated function that needs to be used as
1904 /// `RefMut::filter_map(...)`. A method would interfere with methods of the
1905 /// same name on the contents of a `RefCell` used through `Deref`.
1906 ///
1907 /// # Examples
1908 ///
1909 /// ```
1910 /// use std::cell::{RefCell, RefMut};
1911 ///
1912 /// let c = RefCell::new(vec![1, 2, 3]);
1913 ///
1914 /// {
1915 /// let b1: RefMut<'_, Vec<u32>> = c.borrow_mut();
1916 /// let mut b2: Result<RefMut<'_, u32>, _> = RefMut::filter_map(b1, |v| v.get_mut(1));
1917 ///
1918 /// if let Ok(mut b2) = b2 {
1919 /// *b2 += 2;
1920 /// }
1921 /// }
1922 ///
1923 /// assert_eq!(*c.borrow(), vec![1, 4, 3]);
1924 /// ```
1925 #[stable(feature = "cell_filter_map", since = "1.63.0")]
1926 #[inline]
1927 pub fn filter_map<U: ?Sized, F>(mut orig: RefMut<'b, T>, f: F) -> Result<RefMut<'b, U>, Self>
1928 where
1929 F: FnOnce(&mut T) -> Option<&mut U>,
1930 {
1931 // SAFETY: function holds onto an exclusive reference for the duration
1932 // of its call through `orig`, and the pointer is only de-referenced
1933 // inside of the function call never allowing the exclusive reference to
1934 // escape.
1935 match f(&mut *orig) {
1936 Some(value) => {
1937 Ok(RefMut { value: NonNull::from(value), borrow: orig.borrow, marker: PhantomData })
1938 }
1939 None => Err(orig),
1940 }
1941 }
1942
1943 /// Tries to makes a new `RefMut` for a component of the borrowed data.
1944 /// On failure, the original guard is returned alongside with the error
1945 /// returned by the closure.
1946 ///
1947 /// The `RefCell` is already mutably borrowed, so this cannot fail.
1948 ///
1949 /// This is an associated function that needs to be used as
1950 /// `RefMut::try_map(...)`. A method would interfere with methods of the same
1951 /// name on the contents of a `RefCell` used through `Deref`.
1952 ///
1953 /// # Examples
1954 ///
1955 /// ```
1956 /// #![feature(refcell_try_map)]
1957 /// use std::cell::{RefCell, RefMut};
1958 /// use std::str::{from_utf8_mut, Utf8Error};
1959 ///
1960 /// let c = RefCell::new(vec![0x68, 0x65, 0x6C, 0x6C, 0x6F]);
1961 /// {
1962 /// let b1: RefMut<'_, Vec<u8>> = c.borrow_mut();
1963 /// let b2: Result<RefMut<'_, str>, _> = RefMut::try_map(b1, |v| from_utf8_mut(v));
1964 /// let mut b2 = b2.unwrap();
1965 /// assert_eq!(&*b2, "hello");
1966 /// b2.make_ascii_uppercase();
1967 /// }
1968 /// assert_eq!(*c.borrow(), "HELLO".as_bytes());
1969 ///
1970 /// let c = RefCell::new(vec![0xFF]);
1971 /// let b1: RefMut<'_, Vec<u8>> = c.borrow_mut();
1972 /// let b2: Result<_, (RefMut<'_, Vec<u8>>, Utf8Error)> = RefMut::try_map(b1, |v| from_utf8_mut(v));
1973 /// let (b3, e) = b2.unwrap_err();
1974 /// assert_eq!(*b3, vec![0xFF]);
1975 /// assert_eq!(e.valid_up_to(), 0);
1976 /// ```
1977 #[unstable(feature = "refcell_try_map", issue = "143801")]
1978 #[inline]
1979 pub fn try_map<U: ?Sized, E>(
1980 mut orig: RefMut<'b, T>,
1981 f: impl FnOnce(&mut T) -> Result<&mut U, E>,
1982 ) -> Result<RefMut<'b, U>, (Self, E)> {
1983 // SAFETY: function holds onto an exclusive reference for the duration
1984 // of its call through `orig`, and the pointer is only de-referenced
1985 // inside of the function call never allowing the exclusive reference to
1986 // escape.
1987 match f(&mut *orig) {
1988 Ok(value) => {
1989 Ok(RefMut { value: NonNull::from(value), borrow: orig.borrow, marker: PhantomData })
1990 }
1991 Err(e) => Err((orig, e)),
1992 }
1993 }
1994
1995 /// Splits a `RefMut` into multiple `RefMut`s for different components of the
1996 /// borrowed data.
1997 ///
1998 /// The underlying `RefCell` will remain mutably borrowed until both
1999 /// returned `RefMut`s go out of scope.
2000 ///
2001 /// The `RefCell` is already mutably borrowed, so this cannot fail.
2002 ///
2003 /// This is an associated function that needs to be used as
2004 /// `RefMut::map_split(...)`. A method would interfere with methods of the
2005 /// same name on the contents of a `RefCell` used through `Deref`.
2006 ///
2007 /// # Examples
2008 ///
2009 /// ```
2010 /// use std::cell::{RefCell, RefMut};
2011 ///
2012 /// let cell = RefCell::new([1, 2, 3, 4]);
2013 /// let borrow = cell.borrow_mut();
2014 /// let (mut begin, mut end) = RefMut::map_split(borrow, |slice| slice.split_at_mut(2));
2015 /// assert_eq!(*begin, [1, 2]);
2016 /// assert_eq!(*end, [3, 4]);
2017 /// begin.copy_from_slice(&[4, 3]);
2018 /// end.copy_from_slice(&[2, 1]);
2019 /// ```
2020 #[stable(feature = "refcell_map_split", since = "1.35.0")]
2021 #[inline]
2022 pub fn map_split<U: ?Sized, V: ?Sized, F>(
2023 mut orig: RefMut<'b, T>,
2024 f: F,
2025 ) -> (RefMut<'b, U>, RefMut<'b, V>)
2026 where
2027 F: FnOnce(&mut T) -> (&mut U, &mut V),
2028 {
2029 let borrow = orig.borrow.clone();
2030 let (a, b) = f(&mut *orig);
2031 (
2032 RefMut { value: NonNull::from(a), borrow, marker: PhantomData },
2033 RefMut { value: NonNull::from(b), borrow: orig.borrow, marker: PhantomData },
2034 )
2035 }
2036
2037 /// Converts into a mutable reference to the underlying data.
2038 ///
2039 /// The underlying `RefCell` can not be borrowed from again and will always appear already
2040 /// mutably borrowed, making the returned reference the only to the interior.
2041 ///
2042 /// This is an associated function that needs to be used as
2043 /// `RefMut::leak(...)`. A method would interfere with methods of the
2044 /// same name on the contents of a `RefCell` used through `Deref`.
2045 ///
2046 /// # Examples
2047 ///
2048 /// ```
2049 /// #![feature(cell_leak)]
2050 /// use std::cell::{RefCell, RefMut};
2051 /// let cell = RefCell::new(0);
2052 ///
2053 /// let value = RefMut::leak(cell.borrow_mut());
2054 /// assert_eq!(*value, 0);
2055 /// *value = 1;
2056 ///
2057 /// assert!(cell.try_borrow_mut().is_err());
2058 /// ```
2059 #[unstable(feature = "cell_leak", issue = "69099")]
2060 #[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
2061 pub const fn leak(mut orig: RefMut<'b, T>) -> &'b mut T {
2062 // By forgetting this BorrowRefMut we ensure that the borrow counter in the RefCell can't
2063 // go back to UNUSED within the lifetime `'b`. Resetting the reference tracking state would
2064 // require a unique reference to the borrowed RefCell. No further references can be created
2065 // from the original cell within that lifetime, making the current borrow the only
2066 // reference for the remaining lifetime.
2067 mem::forget(orig.borrow);
2068 // SAFETY: after forgetting, we can form a reference for the rest of lifetime `'b`.
2069 unsafe { orig.value.as_mut() }
2070 }
2071}
2072
2073#[ferrocene::prevalidated]
2074struct BorrowRefMut<'b> {
2075 borrow: &'b Cell<BorrowCounter>,
2076}
2077
2078#[rustc_const_unstable(feature = "const_ref_cell", issue = "137844")]
2079const impl Drop for BorrowRefMut<'_> {
2080 #[inline]
2081 #[ferrocene::prevalidated]
2082 fn drop(&mut self) {
2083 let borrow = self.borrow.get();
2084 debug_assert!(is_writing(borrow));
2085 self.borrow.replace(borrow + 1);
2086 }
2087}
2088
2089impl<'b> BorrowRefMut<'b> {
2090 #[inline]
2091 #[ferrocene::prevalidated]
2092 const fn new(borrow: &'b Cell<BorrowCounter>) -> Option<BorrowRefMut<'b>> {
2093 // NOTE: Unlike BorrowRefMut::clone, new is called to create the initial
2094 // mutable reference, and so there must currently be no existing
2095 // references. Thus, while clone increments the mutable refcount, here
2096 // we explicitly only allow going from UNUSED to UNUSED - 1.
2097 match borrow.get() {
2098 UNUSED => {
2099 borrow.replace(UNUSED - 1);
2100 Some(BorrowRefMut { borrow })
2101 }
2102 _ => None,
2103 }
2104 }
2105
2106 // Clones a `BorrowRefMut`.
2107 //
2108 // This is only valid if each `BorrowRefMut` is used to track a mutable
2109 // reference to a distinct, nonoverlapping range of the original object.
2110 // This isn't in a Clone impl so that code doesn't call this implicitly.
2111 #[inline]
2112 fn clone(&self) -> BorrowRefMut<'b> {
2113 let borrow = self.borrow.get();
2114 debug_assert!(is_writing(borrow));
2115 // Prevent the borrow counter from underflowing.
2116 assert!(borrow != BorrowCounter::MIN);
2117 self.borrow.set(borrow - 1);
2118 BorrowRefMut { borrow: self.borrow }
2119 }
2120}
2121
2122/// A wrapper type for a mutably borrowed value from a `RefCell<T>`.
2123///
2124/// See the [module-level documentation](self) for more.
2125#[stable(feature = "rust1", since = "1.0.0")]
2126#[must_not_suspend = "holding a RefMut across suspend points can cause BorrowErrors"]
2127#[rustc_diagnostic_item = "RefCellRefMut"]
2128#[ferrocene::prevalidated]
2129pub struct RefMut<'b, T: ?Sized + 'b> {
2130 // NB: we use a pointer instead of `&'b mut T` to avoid `noalias` violations, because a
2131 // `RefMut` argument doesn't hold exclusivity for its whole scope, only until it drops.
2132 value: NonNull<T>,
2133 borrow: BorrowRefMut<'b>,
2134 // `NonNull` is covariant over `T`, so we need to reintroduce invariance.
2135 marker: PhantomData<&'b mut T>,
2136}
2137
2138#[stable(feature = "rust1", since = "1.0.0")]
2139#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
2140const impl<T: ?Sized> Deref for RefMut<'_, T> {
2141 type Target = T;
2142
2143 #[inline]
2144 #[ferrocene::prevalidated]
2145 fn deref(&self) -> &T {
2146 // SAFETY: the value is accessible as long as we hold our borrow.
2147 unsafe { self.value.as_ref() }
2148 }
2149}
2150
2151#[stable(feature = "rust1", since = "1.0.0")]
2152#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
2153const impl<T: ?Sized> DerefMut for RefMut<'_, T> {
2154 #[inline]
2155 #[ferrocene::prevalidated]
2156 fn deref_mut(&mut self) -> &mut T {
2157 // SAFETY: the value is accessible as long as we hold our borrow.
2158 unsafe { self.value.as_mut() }
2159 }
2160}
2161
2162#[unstable(feature = "deref_pure_trait", issue = "87121")]
2163unsafe impl<T: ?Sized> DerefPure for RefMut<'_, T> {}
2164
2165#[unstable(feature = "coerce_unsized", issue = "18598")]
2166impl<'b, T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<RefMut<'b, U>> for RefMut<'b, T> {}
2167
2168#[stable(feature = "std_guard_impls", since = "1.20.0")]
2169impl<T: ?Sized + fmt::Display> fmt::Display for RefMut<'_, T> {
2170 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2171 (**self).fmt(f)
2172 }
2173}
2174
2175/// The core primitive for interior mutability in Rust.
2176///
2177/// If you have a reference `&T`, then normally in Rust the compiler performs optimizations based on
2178/// the knowledge that `&T` points to immutable data. Mutating that data, for example through an
2179/// alias or by transmuting a `&T` into a `&mut T`, is considered undefined behavior.
2180/// `UnsafeCell<T>` opts-out of the immutability guarantee for `&T`: a shared reference
2181/// `&UnsafeCell<T>` may point to data that is being mutated. This is called "interior mutability".
2182///
2183/// All other types that allow internal mutability, such as [`Cell<T>`] and [`RefCell<T>`], internally
2184/// use `UnsafeCell` to wrap their data.
2185///
2186/// Note that only the immutability guarantee for shared references is affected by `UnsafeCell`. The
2187/// uniqueness guarantee for mutable references is unaffected. There is *no* legal way to obtain
2188/// aliasing `&mut`, not even with `UnsafeCell<T>`.
2189///
2190/// `UnsafeCell` does nothing to avoid data races; they are still undefined behavior. If multiple
2191/// threads have access to the same `UnsafeCell`, they must follow the usual rules of the
2192/// [concurrent memory model]: conflicting non-synchronized accesses must be done via the APIs in
2193/// [`core::sync::atomic`].
2194///
2195/// The `UnsafeCell` API itself is technically very simple: [`.get()`] gives you a raw pointer
2196/// `*mut T` to its contents. It is up to _you_ as the abstraction designer to use that raw pointer
2197/// correctly.
2198///
2199/// [`.get()`]: `UnsafeCell::get`
2200/// [concurrent memory model]: ../sync/atomic/index.html#memory-model-for-atomic-accesses
2201///
2202/// # Aliasing rules
2203///
2204/// The precise Rust aliasing rules are somewhat in flux, but the main points are not contentious:
2205///
2206/// - If you create a safe reference with lifetime `'a` (either a `&T` or `&mut T` reference), then
2207/// you must not access the data in any way that contradicts that reference for the remainder of
2208/// `'a`. For example, this means that if you take the `*mut T` from an `UnsafeCell<T>` and cast it
2209/// to a `&T`, then the data in `T` must remain immutable (modulo any `UnsafeCell` data found
2210/// within `T`, of course) until that reference's lifetime expires. Similarly, if you create a
2211/// `&mut T` reference, then you must not access the data within the
2212/// `UnsafeCell` until that reference expires.
2213///
2214/// - For both `&T` without `UnsafeCell<_>` and `&mut T`, you must also not deallocate the data
2215/// until the reference expires. As a special exception, given a `&T`, any part of it that is
2216/// inside an `UnsafeCell<_>` may be deallocated during the lifetime of the reference, after the
2217/// last time the reference is used (dereferenced or reborrowed). Since you cannot deallocate a part
2218/// of what a reference points to, this means the memory a `&T` points to can be deallocated only if
2219/// *every part of it* (including padding) is inside an `UnsafeCell`.
2220///
2221/// However, whenever a `&UnsafeCell<T>` is constructed or dereferenced, it must still point to
2222/// live memory and the compiler is allowed to insert spurious reads if it can prove that this
2223/// memory has not yet been deallocated.
2224///
2225/// To assist with proper design, the following scenarios are explicitly declared legal
2226/// for single-threaded code:
2227///
2228/// 1. A `&T` reference can be released to safe code and there it can co-exist with other `&T`
2229/// references, but not with a `&mut T`
2230///
2231/// 2. A `&mut T` reference may be released to safe code provided neither other `&mut T` nor `&T`
2232/// co-exist with it. A `&mut T` must always be unique.
2233///
2234/// Note that whilst mutating the contents of a `&UnsafeCell<T>` (even while other
2235/// `&UnsafeCell<T>` references alias the cell) is
2236/// ok (provided you enforce the above invariants some other way), it is still undefined behavior
2237/// to have multiple `&mut UnsafeCell<T>` aliases. That is, `UnsafeCell` is a wrapper
2238/// designed to have a special interaction with _shared_ accesses (_i.e._, through an
2239/// `&UnsafeCell<_>` reference); there is no magic whatsoever when dealing with _exclusive_
2240/// accesses (_e.g._, through a `&mut UnsafeCell<_>`): neither the cell nor the wrapped value
2241/// may be aliased for the duration of that `&mut` borrow.
2242/// This is showcased by the [`.get_mut()`] accessor, which is a _safe_ getter that yields
2243/// a `&mut T`.
2244///
2245/// [`.get_mut()`]: `UnsafeCell::get_mut`
2246///
2247/// # Memory layout
2248///
2249/// `UnsafeCell<T>` has the same in-memory representation as its inner type `T`. A consequence
2250/// of this guarantee is that it is possible to convert between `T` and `UnsafeCell<T>`.
2251/// Special care has to be taken when converting a nested `T` inside of an `Outer<T>` type
2252/// to an `Outer<UnsafeCell<T>>` type: this is not sound when the `Outer<T>` type enables [niche]
2253/// optimizations. For example, the type `Option<NonNull<u8>>` is typically 8 bytes large on
2254/// 64-bit platforms, but the type `Option<UnsafeCell<NonNull<u8>>>` takes up 16 bytes of space.
2255/// Therefore this is not a valid conversion, despite `NonNull<u8>` and `UnsafeCell<NonNull<u8>>>`
2256/// having the same memory layout. This is because `UnsafeCell` disables niche optimizations in
2257/// order to avoid its interior mutability property from spreading from `T` into the `Outer` type,
2258/// thus this can cause distortions in the type size in these cases.
2259///
2260/// Note that the only valid way to obtain a `*mut T` pointer to the contents of a
2261/// _shared_ `UnsafeCell<T>` is through [`.get()`] or [`.raw_get()`]. A `&T` or `&mut T` reference
2262/// can then be obtained from that pointer, as long as the aliasing rules outlined above are obeyed.
2263/// Even though `T` and `UnsafeCell<T>` have the
2264/// same memory layout, the following is not allowed and undefined behavior:
2265///
2266/// ```rust,compile_fail
2267/// # use std::cell::UnsafeCell;
2268/// unsafe fn not_allowed<T>(ptr: &UnsafeCell<T>) -> &mut T {
2269/// let t = ptr as *const UnsafeCell<T> as *mut T;
2270/// // This is undefined behavior, because the `*mut T` pointer
2271/// // was not obtained through `.get()` nor `.raw_get()`:
2272/// unsafe { &mut *t }
2273/// }
2274/// ```
2275///
2276/// Instead, do this:
2277///
2278/// ```rust
2279/// # use std::cell::UnsafeCell;
2280/// // Safety: the caller must ensure that there are no references that
2281/// // point to the *contents* of the `UnsafeCell`.
2282/// unsafe fn get_mut<T>(ptr: &UnsafeCell<T>) -> &mut T {
2283/// unsafe { &mut *ptr.get() }
2284/// }
2285/// ```
2286///
2287/// Converting in the other direction from a `&mut T`
2288/// to an `&UnsafeCell<T>` is allowed:
2289///
2290/// ```rust
2291/// # use std::cell::UnsafeCell;
2292/// fn get_shared<T>(ptr: &mut T) -> &UnsafeCell<T> {
2293/// let t = ptr as *mut T as *const UnsafeCell<T>;
2294/// // SAFETY: `T` and `UnsafeCell<T>` have the same memory layout
2295/// unsafe { &*t }
2296/// }
2297/// ```
2298///
2299/// [niche]: https://rust-lang.github.io/unsafe-code-guidelines/glossary.html#niche
2300/// [`.raw_get()`]: `UnsafeCell::raw_get`
2301///
2302/// # Examples
2303///
2304/// Here is an example showcasing how to soundly mutate the contents of an `UnsafeCell<_>` despite
2305/// there being multiple references aliasing the cell:
2306///
2307/// ```
2308/// use std::cell::UnsafeCell;
2309///
2310/// let x: UnsafeCell<i32> = 42.into();
2311/// // Get multiple / concurrent / shared references to the same `x`.
2312/// let (p1, p2): (&UnsafeCell<i32>, &UnsafeCell<i32>) = (&x, &x);
2313///
2314/// unsafe {
2315/// // SAFETY: within this scope there are no other references to `x`'s contents,
2316/// // so ours is effectively unique.
2317/// let p1_exclusive: &mut i32 = &mut *p1.get(); // -- borrow --+
2318/// *p1_exclusive += 27; // |
2319/// } // <---------- cannot go beyond this point -------------------+
2320///
2321/// unsafe {
2322/// // SAFETY: within this scope nobody expects to have exclusive access to `x`'s contents,
2323/// // so we can have multiple shared accesses concurrently.
2324/// let p2_shared: &i32 = &*p2.get();
2325/// assert_eq!(*p2_shared, 42 + 27);
2326/// let p1_shared: &i32 = &*p1.get();
2327/// assert_eq!(*p1_shared, *p2_shared);
2328/// }
2329/// ```
2330///
2331/// The following example showcases the fact that exclusive access to an `UnsafeCell<T>`
2332/// implies exclusive access to its `T`:
2333///
2334/// ```rust
2335/// #![forbid(unsafe_code)]
2336/// // with exclusive accesses, `UnsafeCell` is a transparent no-op wrapper, so no need for
2337/// // `unsafe` here.
2338/// use std::cell::UnsafeCell;
2339///
2340/// let mut x: UnsafeCell<i32> = 42.into();
2341///
2342/// // Get a compile-time-checked unique reference to `x`.
2343/// let p_unique: &mut UnsafeCell<i32> = &mut x;
2344/// // With an exclusive reference, we can mutate the contents for free.
2345/// *p_unique.get_mut() = 0;
2346/// // Or, equivalently:
2347/// x = UnsafeCell::new(0);
2348///
2349/// // When we own the value, we can extract the contents for free.
2350/// let contents: i32 = x.into_inner();
2351/// assert_eq!(contents, 0);
2352/// ```
2353#[lang = "unsafe_cell"]
2354#[stable(feature = "rust1", since = "1.0.0")]
2355#[repr(transparent)]
2356#[rustc_pub_transparent]
2357#[ferrocene::prevalidated]
2358pub struct UnsafeCell<T: ?Sized> {
2359 value: T,
2360}
2361
2362#[stable(feature = "rust1", since = "1.0.0")]
2363impl<T: ?Sized> !Sync for UnsafeCell<T> {}
2364
2365impl<T> UnsafeCell<T> {
2366 /// Constructs a new instance of `UnsafeCell` which will wrap the specified
2367 /// value.
2368 ///
2369 /// All access to the inner value through `&UnsafeCell<T>` requires `unsafe` code.
2370 ///
2371 /// # Examples
2372 ///
2373 /// ```
2374 /// use std::cell::UnsafeCell;
2375 ///
2376 /// let uc = UnsafeCell::new(5);
2377 /// ```
2378 #[stable(feature = "rust1", since = "1.0.0")]
2379 #[rustc_const_stable(feature = "const_unsafe_cell_new", since = "1.32.0")]
2380 #[inline(always)]
2381 #[ferrocene::prevalidated]
2382 pub const fn new(value: T) -> UnsafeCell<T> {
2383 UnsafeCell { value }
2384 }
2385
2386 /// Unwraps the value, consuming the cell.
2387 ///
2388 /// # Examples
2389 ///
2390 /// ```
2391 /// use std::cell::UnsafeCell;
2392 ///
2393 /// let uc = UnsafeCell::new(5);
2394 ///
2395 /// let five = uc.into_inner();
2396 /// ```
2397 #[inline(always)]
2398 #[stable(feature = "rust1", since = "1.0.0")]
2399 #[rustc_const_stable(feature = "const_cell_into_inner", since = "1.83.0")]
2400 #[rustc_allow_const_fn_unstable(const_precise_live_drops)]
2401 #[ferrocene::prevalidated]
2402 pub const fn into_inner(self) -> T {
2403 self.value
2404 }
2405
2406 /// Replace the value in this `UnsafeCell` and return the old value.
2407 ///
2408 /// # Safety
2409 ///
2410 /// The caller must take care to avoid aliasing and data races.
2411 ///
2412 /// - It is Undefined Behavior to allow calls to race with
2413 /// any other access to the wrapped value.
2414 /// - It is Undefined Behavior to call this while any other
2415 /// reference(s) to the wrapped value are alive.
2416 ///
2417 /// # Examples
2418 ///
2419 /// ```
2420 /// #![feature(unsafe_cell_access)]
2421 /// use std::cell::UnsafeCell;
2422 ///
2423 /// let uc = UnsafeCell::new(5);
2424 ///
2425 /// let old = unsafe { uc.replace(10) };
2426 /// assert_eq!(old, 5);
2427 /// ```
2428 #[inline]
2429 #[unstable(feature = "unsafe_cell_access", issue = "136327")]
2430 #[rustc_should_not_be_called_on_const_items]
2431 pub const unsafe fn replace(&self, value: T) -> T {
2432 // SAFETY: pointer comes from `&self` so naturally satisfies invariants.
2433 unsafe { ptr::replace(self.get(), value) }
2434 }
2435}
2436
2437impl<T: ?Sized> UnsafeCell<T> {
2438 /// Converts from `&mut T` to `&mut UnsafeCell<T>`.
2439 ///
2440 /// # Examples
2441 ///
2442 /// ```
2443 /// use std::cell::UnsafeCell;
2444 ///
2445 /// let mut val = 42;
2446 /// let uc = UnsafeCell::from_mut(&mut val);
2447 ///
2448 /// *uc.get_mut() -= 1;
2449 /// assert_eq!(*uc.get_mut(), 41);
2450 /// ```
2451 #[inline(always)]
2452 #[stable(feature = "unsafe_cell_from_mut", since = "1.84.0")]
2453 #[rustc_const_stable(feature = "unsafe_cell_from_mut", since = "1.84.0")]
2454 pub const fn from_mut(value: &mut T) -> &mut UnsafeCell<T> {
2455 // SAFETY: `UnsafeCell<T>` has the same memory layout as `T` due to #[repr(transparent)].
2456 unsafe { &mut *(value as *mut T as *mut UnsafeCell<T>) }
2457 }
2458
2459 /// Gets a mutable pointer to the wrapped value.
2460 ///
2461 /// This can be cast to a pointer of any kind. When creating (shared or mutable) references, you
2462 /// must uphold the aliasing rules; see [the type-level docs][UnsafeCell#aliasing-rules] for
2463 /// more discussion and caveats.
2464 ///
2465 /// # Examples
2466 ///
2467 /// ```
2468 /// use std::cell::UnsafeCell;
2469 ///
2470 /// let uc = UnsafeCell::new(5);
2471 ///
2472 /// let five = uc.get();
2473 /// ```
2474 #[inline(always)]
2475 #[stable(feature = "rust1", since = "1.0.0")]
2476 #[rustc_const_stable(feature = "const_unsafecell_get", since = "1.32.0")]
2477 #[rustc_as_ptr]
2478 #[rustc_never_returns_null_ptr]
2479 #[rustc_should_not_be_called_on_const_items]
2480 #[ferrocene::prevalidated]
2481 pub const fn get(&self) -> *mut T {
2482 // We can just cast the pointer from `UnsafeCell<T>` to `T` because of
2483 // #[repr(transparent)]. This exploits std's special status, there is
2484 // no guarantee for user code that this will work in future versions of the compiler!
2485 self as *const UnsafeCell<T> as *const T as *mut T
2486 }
2487
2488 /// Returns a mutable reference to the underlying data.
2489 ///
2490 /// This call borrows the `UnsafeCell` mutably (at compile-time) which
2491 /// guarantees that we possess the only reference.
2492 ///
2493 /// # Examples
2494 ///
2495 /// ```
2496 /// use std::cell::UnsafeCell;
2497 ///
2498 /// let mut c = UnsafeCell::new(5);
2499 /// *c.get_mut() += 1;
2500 ///
2501 /// assert_eq!(*c.get_mut(), 6);
2502 /// ```
2503 #[inline(always)]
2504 #[stable(feature = "unsafe_cell_get_mut", since = "1.50.0")]
2505 #[rustc_const_stable(feature = "const_unsafecell_get_mut", since = "1.83.0")]
2506 #[ferrocene::prevalidated]
2507 pub const fn get_mut(&mut self) -> &mut T {
2508 &mut self.value
2509 }
2510
2511 /// Gets a mutable pointer to the wrapped value.
2512 /// The difference from [`get`] is that this function accepts a raw pointer,
2513 /// which is useful to avoid the creation of temporary references.
2514 ///
2515 /// This can be cast to a pointer of any kind. When creating (shared or mutable) references, you
2516 /// must uphold the aliasing rules; see [the type-level docs][UnsafeCell#aliasing-rules] for
2517 /// more discussion and caveats.
2518 ///
2519 /// [`get`]: UnsafeCell::get()
2520 ///
2521 /// # Examples
2522 ///
2523 /// Gradual initialization of an `UnsafeCell` requires `raw_get`, as
2524 /// calling `get` would require creating a reference to uninitialized data:
2525 ///
2526 /// ```
2527 /// use std::cell::UnsafeCell;
2528 /// use std::mem::MaybeUninit;
2529 ///
2530 /// let m = MaybeUninit::<UnsafeCell<i32>>::uninit();
2531 /// unsafe { UnsafeCell::raw_get(m.as_ptr()).write(5); }
2532 /// // avoid below which references to uninitialized data
2533 /// // unsafe { UnsafeCell::get(&*m.as_ptr()).write(5); }
2534 /// let uc = unsafe { m.assume_init() };
2535 ///
2536 /// assert_eq!(uc.into_inner(), 5);
2537 /// ```
2538 #[inline(always)]
2539 #[stable(feature = "unsafe_cell_raw_get", since = "1.56.0")]
2540 #[rustc_const_stable(feature = "unsafe_cell_raw_get", since = "1.56.0")]
2541 #[rustc_diagnostic_item = "unsafe_cell_raw_get"]
2542 #[ferrocene::prevalidated]
2543 pub const fn raw_get(this: *const Self) -> *mut T {
2544 // We can just cast the pointer from `UnsafeCell<T>` to `T` because of
2545 // #[repr(transparent)]. This exploits std's special status, there is
2546 // no guarantee for user code that this will work in future versions of the compiler!
2547 this as *const T as *mut T
2548 }
2549
2550 /// Get a shared reference to the value within the `UnsafeCell`.
2551 ///
2552 /// # Safety
2553 ///
2554 /// - It is Undefined Behavior to call this while any mutable
2555 /// reference to the wrapped value is alive.
2556 /// - Mutating the wrapped value while the returned
2557 /// reference is alive is Undefined Behavior.
2558 ///
2559 /// # Examples
2560 ///
2561 /// ```
2562 /// #![feature(unsafe_cell_access)]
2563 /// use std::cell::UnsafeCell;
2564 ///
2565 /// let uc = UnsafeCell::new(5);
2566 ///
2567 /// let val = unsafe { uc.as_ref_unchecked() };
2568 /// assert_eq!(val, &5);
2569 /// ```
2570 #[inline]
2571 #[unstable(feature = "unsafe_cell_access", issue = "136327")]
2572 #[rustc_should_not_be_called_on_const_items]
2573 pub const unsafe fn as_ref_unchecked(&self) -> &T {
2574 // SAFETY: pointer comes from `&self` so naturally satisfies ptr-to-ref invariants.
2575 unsafe { self.get().as_ref_unchecked() }
2576 }
2577
2578 /// Get an exclusive reference to the value within the `UnsafeCell`.
2579 ///
2580 /// # Safety
2581 ///
2582 /// - It is Undefined Behavior to call this while any other
2583 /// reference(s) to the wrapped value are alive.
2584 /// - Mutating the wrapped value through other means while the
2585 /// returned reference is alive is Undefined Behavior.
2586 ///
2587 /// # Examples
2588 ///
2589 /// ```
2590 /// #![feature(unsafe_cell_access)]
2591 /// use std::cell::UnsafeCell;
2592 ///
2593 /// let uc = UnsafeCell::new(5);
2594 ///
2595 /// unsafe { *uc.as_mut_unchecked() += 1; }
2596 /// assert_eq!(uc.into_inner(), 6);
2597 /// ```
2598 #[inline]
2599 #[unstable(feature = "unsafe_cell_access", issue = "136327")]
2600 #[allow(clippy::mut_from_ref)]
2601 #[rustc_should_not_be_called_on_const_items]
2602 pub const unsafe fn as_mut_unchecked(&self) -> &mut T {
2603 // SAFETY: pointer comes from `&self` so naturally satisfies ptr-to-ref invariants.
2604 unsafe { self.get().as_mut_unchecked() }
2605 }
2606}
2607
2608#[stable(feature = "unsafe_cell_default", since = "1.10.0")]
2609#[rustc_const_unstable(feature = "const_default", issue = "143894")]
2610const impl<T: [const] Default> Default for UnsafeCell<T> {
2611 /// Creates an `UnsafeCell`, with the `Default` value for T.
2612 fn default() -> UnsafeCell<T> {
2613 UnsafeCell::new(Default::default())
2614 }
2615}
2616
2617#[stable(feature = "cell_from", since = "1.12.0")]
2618#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
2619const impl<T> From<T> for UnsafeCell<T> {
2620 /// Creates a new `UnsafeCell<T>` containing the given value.
2621 fn from(t: T) -> UnsafeCell<T> {
2622 UnsafeCell::new(t)
2623 }
2624}
2625
2626#[unstable(feature = "coerce_unsized", issue = "18598")]
2627impl<T: CoerceUnsized<U>, U> CoerceUnsized<UnsafeCell<U>> for UnsafeCell<T> {}
2628
2629// Allow types that wrap `UnsafeCell` to also implement `DispatchFromDyn`
2630// and become dyn-compatible method receivers.
2631// Note that currently `UnsafeCell` itself cannot be a method receiver
2632// because it does not implement Deref.
2633// In other words:
2634// `self: UnsafeCell<&Self>` won't work
2635// `self: UnsafeCellWrapper<Self>` becomes possible
2636#[unstable(feature = "dispatch_from_dyn", issue = "none")]
2637impl<T: DispatchFromDyn<U>, U> DispatchFromDyn<UnsafeCell<U>> for UnsafeCell<T> {}
2638
2639/// [`UnsafeCell`], but [`Sync`].
2640///
2641/// This is just an `UnsafeCell`, except it implements `Sync`
2642/// if `T` implements `Sync`.
2643///
2644/// `UnsafeCell` doesn't implement `Sync`, to prevent accidental mis-use.
2645/// You can use `SyncUnsafeCell` instead of `UnsafeCell` to allow it to be
2646/// shared between threads, if that's intentional.
2647/// Providing proper synchronization is still the task of the user,
2648/// making this type just as unsafe to use.
2649///
2650/// See [`UnsafeCell`] for details.
2651#[unstable(feature = "sync_unsafe_cell", issue = "95439")]
2652#[repr(transparent)]
2653#[rustc_diagnostic_item = "SyncUnsafeCell"]
2654#[rustc_pub_transparent]
2655#[ferrocene::prevalidated]
2656pub struct SyncUnsafeCell<T: ?Sized> {
2657 value: UnsafeCell<T>,
2658}
2659
2660#[unstable(feature = "sync_unsafe_cell", issue = "95439")]
2661unsafe impl<T: ?Sized + Sync> Sync for SyncUnsafeCell<T> {}
2662
2663#[unstable(feature = "sync_unsafe_cell", issue = "95439")]
2664impl<T> SyncUnsafeCell<T> {
2665 /// Constructs a new instance of `SyncUnsafeCell` which will wrap the specified value.
2666 #[inline]
2667 pub const fn new(value: T) -> Self {
2668 Self { value: UnsafeCell { value } }
2669 }
2670
2671 /// Unwraps the value, consuming the cell.
2672 #[inline]
2673 #[rustc_const_unstable(feature = "sync_unsafe_cell", issue = "95439")]
2674 pub const fn into_inner(self) -> T {
2675 self.value.into_inner()
2676 }
2677}
2678
2679#[unstable(feature = "sync_unsafe_cell", issue = "95439")]
2680impl<T: ?Sized> SyncUnsafeCell<T> {
2681 /// Gets a mutable pointer to the wrapped value.
2682 ///
2683 /// This can be cast to a pointer of any kind.
2684 /// Ensure that the access is unique (no active references, mutable or not)
2685 /// when casting to `&mut T`, and ensure that there are no mutations
2686 /// or mutable aliases going on when casting to `&T`
2687 #[inline]
2688 #[rustc_as_ptr]
2689 #[rustc_never_returns_null_ptr]
2690 #[rustc_should_not_be_called_on_const_items]
2691 pub const fn get(&self) -> *mut T {
2692 self.value.get()
2693 }
2694
2695 /// Returns a mutable reference to the underlying data.
2696 ///
2697 /// This call borrows the `SyncUnsafeCell` mutably (at compile-time) which
2698 /// guarantees that we possess the only reference.
2699 #[inline]
2700 pub const fn get_mut(&mut self) -> &mut T {
2701 self.value.get_mut()
2702 }
2703
2704 /// Gets a mutable pointer to the wrapped value.
2705 ///
2706 /// See [`UnsafeCell::get`] for details.
2707 #[inline]
2708 pub const fn raw_get(this: *const Self) -> *mut T {
2709 // We can just cast the pointer from `SyncUnsafeCell<T>` to `T` because
2710 // of #[repr(transparent)] on both SyncUnsafeCell and UnsafeCell.
2711 // See UnsafeCell::raw_get.
2712 this as *const T as *mut T
2713 }
2714}
2715
2716#[unstable(feature = "sync_unsafe_cell", issue = "95439")]
2717#[rustc_const_unstable(feature = "const_default", issue = "143894")]
2718const impl<T: [const] Default> Default for SyncUnsafeCell<T> {
2719 /// Creates an `SyncUnsafeCell`, with the `Default` value for T.
2720 fn default() -> SyncUnsafeCell<T> {
2721 SyncUnsafeCell::new(Default::default())
2722 }
2723}
2724
2725#[unstable(feature = "sync_unsafe_cell", issue = "95439")]
2726#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
2727const impl<T> From<T> for SyncUnsafeCell<T> {
2728 /// Creates a new `SyncUnsafeCell<T>` containing the given value.
2729 fn from(t: T) -> SyncUnsafeCell<T> {
2730 SyncUnsafeCell::new(t)
2731 }
2732}
2733
2734#[unstable(feature = "coerce_unsized", issue = "18598")]
2735//#[unstable(feature = "sync_unsafe_cell", issue = "95439")]
2736impl<T: CoerceUnsized<U>, U> CoerceUnsized<SyncUnsafeCell<U>> for SyncUnsafeCell<T> {}
2737
2738// Allow types that wrap `SyncUnsafeCell` to also implement `DispatchFromDyn`
2739// and become dyn-compatible method receivers.
2740// Note that currently `SyncUnsafeCell` itself cannot be a method receiver
2741// because it does not implement Deref.
2742// In other words:
2743// `self: SyncUnsafeCell<&Self>` won't work
2744// `self: SyncUnsafeCellWrapper<Self>` becomes possible
2745#[unstable(feature = "dispatch_from_dyn", issue = "none")]
2746//#[unstable(feature = "sync_unsafe_cell", issue = "95439")]
2747impl<T: DispatchFromDyn<U>, U> DispatchFromDyn<SyncUnsafeCell<U>> for SyncUnsafeCell<T> {}
2748
2749#[allow(unused)]
2750fn assert_coerce_unsized(
2751 a: UnsafeCell<&i32>,
2752 b: SyncUnsafeCell<&i32>,
2753 c: Cell<&i32>,
2754 d: RefCell<&i32>,
2755) {
2756 let _: UnsafeCell<&dyn Send> = a;
2757 let _: SyncUnsafeCell<&dyn Send> = b;
2758 let _: Cell<&dyn Send> = c;
2759 let _: RefCell<&dyn Send> = d;
2760}
2761
2762#[unstable(feature = "pin_coerce_unsized_trait", issue = "150112")]
2763unsafe impl<'b, T: ?Sized> PinCoerceUnsized for Ref<'b, T> {}
2764
2765#[unstable(feature = "pin_coerce_unsized_trait", issue = "150112")]
2766unsafe impl<'b, T: ?Sized> PinCoerceUnsized for RefMut<'b, T> {}