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