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