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