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