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