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