]> git.lizzy.rs Git - rust.git/blob - src/libcore/cell.rs
change #![feature(const_fn)] to specific gates
[rust.git] / src / libcore / cell.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Shareable mutable containers.
12 //!
13 //! Values of the `Cell<T>` and `RefCell<T>` types may be mutated through shared references (i.e.
14 //! the common `&T` type), whereas most Rust types can only be mutated through unique (`&mut T`)
15 //! references. We say that `Cell<T>` and `RefCell<T>` provide 'interior mutability', in contrast
16 //! with typical Rust types that exhibit 'inherited mutability'.
17 //!
18 //! Cell types come in two flavors: `Cell<T>` and `RefCell<T>`. `Cell<T>` implements interior
19 //! mutability by moving values in and out of the `Cell<T>`. To use references instead of values,
20 //! one must use the `RefCell<T>` type, acquiring a write lock before mutating. `Cell<T>` provides
21 //! methods to retrieve and change the current interior value:
22 //!
23 //!  - For types that implement `Copy`, the `get` method retrieves the current interior value.
24 //!  - For types that implement `Default`, the `take` method replaces the current interior value
25 //!    with `Default::default()` and returns the replaced value.
26 //!  - For all types, the `replace` method replaces the current interior value and returns the
27 //!    replaced value and the `into_inner` method consumes the `Cell<T>` and returns the interior
28 //!    value. Additionally, the `set` method replaces the interior value, dropping the replaced
29 //!    value.
30 //!
31 //! `RefCell<T>` uses Rust's lifetimes to implement 'dynamic borrowing', a process whereby one can
32 //! claim temporary, exclusive, mutable access to the inner value. Borrows for `RefCell<T>`s are
33 //! tracked 'at runtime', unlike Rust's native reference types which are entirely tracked
34 //! statically, at compile time. Because `RefCell<T>` borrows are dynamic it is possible to attempt
35 //! to borrow a value that is already mutably borrowed; when this happens it results in thread
36 //! panic.
37 //!
38 //! # When to choose interior mutability
39 //!
40 //! The more common inherited mutability, where one must have unique access to mutate a value, is
41 //! one of the key language elements that enables Rust to reason strongly about pointer aliasing,
42 //! statically preventing crash bugs. Because of that, inherited mutability is preferred, and
43 //! interior mutability is something of a last resort. Since cell types enable mutation where it
44 //! would otherwise be disallowed though, there are occasions when interior mutability might be
45 //! appropriate, or even *must* be used, e.g.
46 //!
47 //! * Introducing mutability 'inside' of something immutable
48 //! * Implementation details of logically-immutable methods.
49 //! * Mutating implementations of `Clone`.
50 //!
51 //! ## Introducing mutability 'inside' of something immutable
52 //!
53 //! Many shared smart pointer types, including `Rc<T>` and `Arc<T>`, provide containers that can be
54 //! cloned and shared between multiple parties. Because the contained values may be
55 //! multiply-aliased, they can only be borrowed with `&`, not `&mut`. Without cells it would be
56 //! impossible to mutate data inside of these smart pointers at all.
57 //!
58 //! It's very common then to put a `RefCell<T>` inside shared pointer types to reintroduce
59 //! mutability:
60 //!
61 //! ```
62 //! use std::collections::HashMap;
63 //! use std::cell::RefCell;
64 //! use std::rc::Rc;
65 //!
66 //! fn main() {
67 //!     let shared_map: Rc<RefCell<_>> = Rc::new(RefCell::new(HashMap::new()));
68 //!     shared_map.borrow_mut().insert("africa", 92388);
69 //!     shared_map.borrow_mut().insert("kyoto", 11837);
70 //!     shared_map.borrow_mut().insert("piccadilly", 11826);
71 //!     shared_map.borrow_mut().insert("marbles", 38);
72 //! }
73 //! ```
74 //!
75 //! Note that this example uses `Rc<T>` and not `Arc<T>`. `RefCell<T>`s are for single-threaded
76 //! scenarios. Consider using `RwLock<T>` or `Mutex<T>` if you need shared mutability in a
77 //! multi-threaded situation.
78 //!
79 //! ## Implementation details of logically-immutable methods
80 //!
81 //! Occasionally it may be desirable not to expose in an API that there is mutation happening
82 //! "under the hood". This may be because logically the operation is immutable, but e.g. caching
83 //! forces the implementation to perform mutation; or because you must employ mutation to implement
84 //! a trait method that was originally defined to take `&self`.
85 //!
86 //! ```
87 //! # #![allow(dead_code)]
88 //! use std::cell::RefCell;
89 //!
90 //! struct Graph {
91 //!     edges: Vec<(i32, i32)>,
92 //!     span_tree_cache: RefCell<Option<Vec<(i32, i32)>>>
93 //! }
94 //!
95 //! impl Graph {
96 //!     fn minimum_spanning_tree(&self) -> Vec<(i32, i32)> {
97 //!         // Create a new scope to contain the lifetime of the
98 //!         // dynamic borrow
99 //!         {
100 //!             // Take a reference to the inside of cache cell
101 //!             let mut cache = self.span_tree_cache.borrow_mut();
102 //!             if cache.is_some() {
103 //!                 return cache.as_ref().unwrap().clone();
104 //!             }
105 //!
106 //!             let span_tree = self.calc_span_tree();
107 //!             *cache = Some(span_tree);
108 //!         }
109 //!
110 //!         // Recursive call to return the just-cached value.
111 //!         // Note that if we had not let the previous borrow
112 //!         // of the cache fall out of scope then the subsequent
113 //!         // recursive borrow would cause a dynamic thread panic.
114 //!         // This is the major hazard of using `RefCell`.
115 //!         self.minimum_spanning_tree()
116 //!     }
117 //! #   fn calc_span_tree(&self) -> Vec<(i32, i32)> { vec![] }
118 //! }
119 //! ```
120 //!
121 //! ## Mutating implementations of `Clone`
122 //!
123 //! This is simply a special - but common - case of the previous: hiding mutability for operations
124 //! that appear to be immutable. The `clone` method is expected to not change the source value, and
125 //! is declared to take `&self`, not `&mut self`. Therefore any mutation that happens in the
126 //! `clone` method must use cell types. For example, `Rc<T>` maintains its reference counts within a
127 //! `Cell<T>`.
128 //!
129 //! ```
130 //! #![feature(core_intrinsics)]
131 //! #![feature(shared)]
132 //! use std::cell::Cell;
133 //! use std::ptr::Shared;
134 //! use std::intrinsics::abort;
135 //!
136 //! struct Rc<T: ?Sized> {
137 //!     ptr: Shared<RcBox<T>>
138 //! }
139 //!
140 //! struct RcBox<T: ?Sized> {
141 //!     strong: Cell<usize>,
142 //!     refcount: Cell<usize>,
143 //!     value: T,
144 //! }
145 //!
146 //! impl<T: ?Sized> Clone for Rc<T> {
147 //!     fn clone(&self) -> Rc<T> {
148 //!         self.inc_strong();
149 //!         Rc { ptr: self.ptr }
150 //!     }
151 //! }
152 //!
153 //! trait RcBoxPtr<T: ?Sized> {
154 //!
155 //!     fn inner(&self) -> &RcBox<T>;
156 //!
157 //!     fn strong(&self) -> usize {
158 //!         self.inner().strong.get()
159 //!     }
160 //!
161 //!     fn inc_strong(&self) {
162 //!         self.inner()
163 //!             .strong
164 //!             .set(self.strong()
165 //!                      .checked_add(1)
166 //!                      .unwrap_or_else(|| unsafe { abort() }));
167 //!     }
168 //! }
169 //!
170 //! impl<T: ?Sized> RcBoxPtr<T> for Rc<T> {
171 //!    fn inner(&self) -> &RcBox<T> {
172 //!        unsafe {
173 //!            self.ptr.as_ref()
174 //!        }
175 //!    }
176 //! }
177 //! ```
178 //!
179
180 #![stable(feature = "rust1", since = "1.0.0")]
181
182 use cmp::Ordering;
183 use fmt::{self, Debug, Display};
184 use marker::Unsize;
185 use mem;
186 use ops::{Deref, DerefMut, CoerceUnsized};
187 use ptr;
188
189 /// A mutable memory location.
190 ///
191 /// # Examples
192 ///
193 /// Here you can see how using `Cell<T>` allows to use mutable field inside
194 /// immutable struct (which is also called 'interior mutability').
195 ///
196 /// ```
197 /// use std::cell::Cell;
198 ///
199 /// struct SomeStruct {
200 ///     regular_field: u8,
201 ///     special_field: Cell<u8>,
202 /// }
203 ///
204 /// let my_struct = SomeStruct {
205 ///     regular_field: 0,
206 ///     special_field: Cell::new(1),
207 /// };
208 ///
209 /// let new_value = 100;
210 ///
211 /// // ERROR, because my_struct is immutable
212 /// // my_struct.regular_field = new_value;
213 ///
214 /// // WORKS, although `my_struct` is immutable, field `special_field` is mutable because it is Cell
215 /// my_struct.special_field.set(new_value);
216 /// assert_eq!(my_struct.special_field.get(), new_value);
217 /// ```
218 ///
219 /// See the [module-level documentation](index.html) for more.
220 #[stable(feature = "rust1", since = "1.0.0")]
221 pub struct Cell<T> {
222     value: UnsafeCell<T>,
223 }
224
225 impl<T:Copy> Cell<T> {
226     /// Returns a copy of the contained value.
227     ///
228     /// # Examples
229     ///
230     /// ```
231     /// use std::cell::Cell;
232     ///
233     /// let c = Cell::new(5);
234     ///
235     /// let five = c.get();
236     /// ```
237     #[inline]
238     #[stable(feature = "rust1", since = "1.0.0")]
239     pub fn get(&self) -> T {
240         unsafe{ *self.value.get() }
241     }
242 }
243
244 #[stable(feature = "rust1", since = "1.0.0")]
245 unsafe impl<T> Send for Cell<T> where T: Send {}
246
247 #[stable(feature = "rust1", since = "1.0.0")]
248 impl<T> !Sync for Cell<T> {}
249
250 #[stable(feature = "rust1", since = "1.0.0")]
251 impl<T:Copy> Clone for Cell<T> {
252     #[inline]
253     fn clone(&self) -> Cell<T> {
254         Cell::new(self.get())
255     }
256 }
257
258 #[stable(feature = "rust1", since = "1.0.0")]
259 impl<T:Default> Default for Cell<T> {
260     /// Creates a `Cell<T>`, with the `Default` value for T.
261     #[inline]
262     fn default() -> Cell<T> {
263         Cell::new(Default::default())
264     }
265 }
266
267 #[stable(feature = "rust1", since = "1.0.0")]
268 impl<T:PartialEq + Copy> PartialEq for Cell<T> {
269     #[inline]
270     fn eq(&self, other: &Cell<T>) -> bool {
271         self.get() == other.get()
272     }
273 }
274
275 #[stable(feature = "cell_eq", since = "1.2.0")]
276 impl<T:Eq + Copy> Eq for Cell<T> {}
277
278 #[stable(feature = "cell_ord", since = "1.10.0")]
279 impl<T:PartialOrd + Copy> PartialOrd for Cell<T> {
280     #[inline]
281     fn partial_cmp(&self, other: &Cell<T>) -> Option<Ordering> {
282         self.get().partial_cmp(&other.get())
283     }
284
285     #[inline]
286     fn lt(&self, other: &Cell<T>) -> bool {
287         self.get() < other.get()
288     }
289
290     #[inline]
291     fn le(&self, other: &Cell<T>) -> bool {
292         self.get() <= other.get()
293     }
294
295     #[inline]
296     fn gt(&self, other: &Cell<T>) -> bool {
297         self.get() > other.get()
298     }
299
300     #[inline]
301     fn ge(&self, other: &Cell<T>) -> bool {
302         self.get() >= other.get()
303     }
304 }
305
306 #[stable(feature = "cell_ord", since = "1.10.0")]
307 impl<T:Ord + Copy> Ord for Cell<T> {
308     #[inline]
309     fn cmp(&self, other: &Cell<T>) -> Ordering {
310         self.get().cmp(&other.get())
311     }
312 }
313
314 #[stable(feature = "cell_from", since = "1.12.0")]
315 impl<T> From<T> for Cell<T> {
316     fn from(t: T) -> Cell<T> {
317         Cell::new(t)
318     }
319 }
320
321 impl<T> Cell<T> {
322     /// Creates a new `Cell` containing the given value.
323     ///
324     /// # Examples
325     ///
326     /// ```
327     /// use std::cell::Cell;
328     ///
329     /// let c = Cell::new(5);
330     /// ```
331     #[stable(feature = "rust1", since = "1.0.0")]
332     #[cfg_attr(not(stage0), rustc_const_unstable(feature = "const_cell_new"))]
333     #[inline]
334     pub const fn new(value: T) -> Cell<T> {
335         Cell {
336             value: UnsafeCell::new(value),
337         }
338     }
339
340     /// Returns a raw pointer to the underlying data in this cell.
341     ///
342     /// # Examples
343     ///
344     /// ```
345     /// use std::cell::Cell;
346     ///
347     /// let c = Cell::new(5);
348     ///
349     /// let ptr = c.as_ptr();
350     /// ```
351     #[inline]
352     #[stable(feature = "cell_as_ptr", since = "1.12.0")]
353     pub fn as_ptr(&self) -> *mut T {
354         self.value.get()
355     }
356
357     /// Returns a mutable reference to the underlying data.
358     ///
359     /// This call borrows `Cell` mutably (at compile-time) which guarantees
360     /// that we possess the only reference.
361     ///
362     /// # Examples
363     ///
364     /// ```
365     /// use std::cell::Cell;
366     ///
367     /// let mut c = Cell::new(5);
368     /// *c.get_mut() += 1;
369     ///
370     /// assert_eq!(c.get(), 6);
371     /// ```
372     #[inline]
373     #[stable(feature = "cell_get_mut", since = "1.11.0")]
374     pub fn get_mut(&mut self) -> &mut T {
375         unsafe {
376             &mut *self.value.get()
377         }
378     }
379
380     /// Sets the contained value.
381     ///
382     /// # Examples
383     ///
384     /// ```
385     /// use std::cell::Cell;
386     ///
387     /// let c = Cell::new(5);
388     ///
389     /// c.set(10);
390     /// ```
391     #[inline]
392     #[stable(feature = "rust1", since = "1.0.0")]
393     pub fn set(&self, val: T) {
394         let old = self.replace(val);
395         drop(old);
396     }
397
398     /// Swaps the values of two Cells.
399     /// Difference with `std::mem::swap` is that this function doesn't require `&mut` reference.
400     ///
401     /// # Examples
402     ///
403     /// ```
404     /// use std::cell::Cell;
405     ///
406     /// let c1 = Cell::new(5i32);
407     /// let c2 = Cell::new(10i32);
408     /// c1.swap(&c2);
409     /// assert_eq!(10, c1.get());
410     /// assert_eq!(5, c2.get());
411     /// ```
412     #[inline]
413     #[stable(feature = "move_cell", since = "1.17.0")]
414     pub fn swap(&self, other: &Self) {
415         if ptr::eq(self, other) {
416             return;
417         }
418         unsafe {
419             ptr::swap(self.value.get(), other.value.get());
420         }
421     }
422
423     /// Replaces the contained value, and returns it.
424     ///
425     /// # Examples
426     ///
427     /// ```
428     /// use std::cell::Cell;
429     ///
430     /// let cell = Cell::new(5);
431     /// assert_eq!(cell.get(), 5);
432     /// assert_eq!(cell.replace(10), 5);
433     /// assert_eq!(cell.get(), 10);
434     /// ```
435     #[stable(feature = "move_cell", since = "1.17.0")]
436     pub fn replace(&self, val: T) -> T {
437         mem::replace(unsafe { &mut *self.value.get() }, val)
438     }
439
440     /// Unwraps the value.
441     ///
442     /// # Examples
443     ///
444     /// ```
445     /// use std::cell::Cell;
446     ///
447     /// let c = Cell::new(5);
448     /// let five = c.into_inner();
449     ///
450     /// assert_eq!(five, 5);
451     /// ```
452     #[stable(feature = "move_cell", since = "1.17.0")]
453     pub fn into_inner(self) -> T {
454         unsafe { self.value.into_inner() }
455     }
456 }
457
458 impl<T: Default> Cell<T> {
459     /// Takes the value of the cell, leaving `Default::default()` in its place.
460     ///
461     /// # Examples
462     ///
463     /// ```
464     /// use std::cell::Cell;
465     ///
466     /// let c = Cell::new(5);
467     /// let five = c.take();
468     ///
469     /// assert_eq!(five, 5);
470     /// assert_eq!(c.into_inner(), 0);
471     /// ```
472     #[stable(feature = "move_cell", since = "1.17.0")]
473     pub fn take(&self) -> T {
474         self.replace(Default::default())
475     }
476 }
477
478 #[unstable(feature = "coerce_unsized", issue = "27732")]
479 impl<T: CoerceUnsized<U>, U> CoerceUnsized<Cell<U>> for Cell<T> {}
480
481 /// A mutable memory location with dynamically checked borrow rules
482 ///
483 /// See the [module-level documentation](index.html) for more.
484 #[stable(feature = "rust1", since = "1.0.0")]
485 pub struct RefCell<T: ?Sized> {
486     borrow: Cell<BorrowFlag>,
487     value: UnsafeCell<T>,
488 }
489
490 /// An error returned by [`RefCell::try_borrow`](struct.RefCell.html#method.try_borrow).
491 #[stable(feature = "try_borrow", since = "1.13.0")]
492 pub struct BorrowError {
493     _private: (),
494 }
495
496 #[stable(feature = "try_borrow", since = "1.13.0")]
497 impl Debug for BorrowError {
498     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
499         f.debug_struct("BorrowError").finish()
500     }
501 }
502
503 #[stable(feature = "try_borrow", since = "1.13.0")]
504 impl Display for BorrowError {
505     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
506         Display::fmt("already mutably borrowed", f)
507     }
508 }
509
510 /// An error returned by [`RefCell::try_borrow_mut`](struct.RefCell.html#method.try_borrow_mut).
511 #[stable(feature = "try_borrow", since = "1.13.0")]
512 pub struct BorrowMutError {
513     _private: (),
514 }
515
516 #[stable(feature = "try_borrow", since = "1.13.0")]
517 impl Debug for BorrowMutError {
518     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
519         f.debug_struct("BorrowMutError").finish()
520     }
521 }
522
523 #[stable(feature = "try_borrow", since = "1.13.0")]
524 impl Display for BorrowMutError {
525     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
526         Display::fmt("already borrowed", f)
527     }
528 }
529
530 // Values [1, MAX-1] represent the number of `Ref` active
531 // (will not outgrow its range since `usize` is the size of the address space)
532 type BorrowFlag = usize;
533 const UNUSED: BorrowFlag = 0;
534 const WRITING: BorrowFlag = !0;
535
536 impl<T> RefCell<T> {
537     /// Creates a new `RefCell` containing `value`.
538     ///
539     /// # Examples
540     ///
541     /// ```
542     /// use std::cell::RefCell;
543     ///
544     /// let c = RefCell::new(5);
545     /// ```
546     #[stable(feature = "rust1", since = "1.0.0")]
547     #[cfg_attr(not(stage0), rustc_const_unstable(feature = "const_refcell_new"))]
548     #[inline]
549     pub const fn new(value: T) -> RefCell<T> {
550         RefCell {
551             value: UnsafeCell::new(value),
552             borrow: Cell::new(UNUSED),
553         }
554     }
555
556     /// Consumes the `RefCell`, returning the wrapped value.
557     ///
558     /// # Examples
559     ///
560     /// ```
561     /// use std::cell::RefCell;
562     ///
563     /// let c = RefCell::new(5);
564     ///
565     /// let five = c.into_inner();
566     /// ```
567     #[stable(feature = "rust1", since = "1.0.0")]
568     #[inline]
569     pub fn into_inner(self) -> T {
570         // Since this function takes `self` (the `RefCell`) by value, the
571         // compiler statically verifies that it is not currently borrowed.
572         // Therefore the following assertion is just a `debug_assert!`.
573         debug_assert!(self.borrow.get() == UNUSED);
574         unsafe { self.value.into_inner() }
575     }
576
577     /// Replaces the wrapped value with a new one, returning the old value,
578     /// without deinitializing either one.
579     ///
580     /// This function corresponds to [`std::mem::replace`](../mem/fn.replace.html).
581     ///
582     /// # Examples
583     ///
584     /// ```
585     /// #![feature(refcell_replace_swap)]
586     /// use std::cell::RefCell;
587     /// let c = RefCell::new(5);
588     /// let u = c.replace(6);
589     /// assert_eq!(u, 5);
590     /// assert_eq!(c, RefCell::new(6));
591     /// ```
592     ///
593     /// # Panics
594     ///
595     /// This function will panic if the `RefCell` has any outstanding borrows,
596     /// whether or not they are full mutable borrows.
597     #[inline]
598     #[unstable(feature = "refcell_replace_swap", issue="43570")]
599     pub fn replace(&self, t: T) -> T {
600         mem::replace(&mut *self.borrow_mut(), t)
601     }
602
603     /// Swaps the wrapped value of `self` with the wrapped value of `other`,
604     /// without deinitializing either one.
605     ///
606     /// This function corresponds to [`std::mem::swap`](../mem/fn.swap.html).
607     ///
608     /// # Examples
609     ///
610     /// ```
611     /// #![feature(refcell_replace_swap)]
612     /// use std::cell::RefCell;
613     /// let c = RefCell::new(5);
614     /// let d = RefCell::new(6);
615     /// c.swap(&d);
616     /// assert_eq!(c, RefCell::new(6));
617     /// assert_eq!(d, RefCell::new(5));
618     /// ```
619     ///
620     /// # Panics
621     ///
622     /// This function will panic if either `RefCell` has any outstanding borrows,
623     /// whether or not they are full mutable borrows.
624     #[inline]
625     #[unstable(feature = "refcell_replace_swap", issue="43570")]
626     pub fn swap(&self, other: &Self) {
627         mem::swap(&mut *self.borrow_mut(), &mut *other.borrow_mut())
628     }
629 }
630
631 impl<T: ?Sized> RefCell<T> {
632     /// Immutably borrows the wrapped value.
633     ///
634     /// The borrow lasts until the returned `Ref` exits scope. Multiple
635     /// immutable borrows can be taken out at the same time.
636     ///
637     /// # Panics
638     ///
639     /// Panics if the value is currently mutably borrowed. For a non-panicking variant, use
640     /// [`try_borrow`](#method.try_borrow).
641     ///
642     /// # Examples
643     ///
644     /// ```
645     /// use std::cell::RefCell;
646     ///
647     /// let c = RefCell::new(5);
648     ///
649     /// let borrowed_five = c.borrow();
650     /// let borrowed_five2 = c.borrow();
651     /// ```
652     ///
653     /// An example of panic:
654     ///
655     /// ```
656     /// use std::cell::RefCell;
657     /// use std::thread;
658     ///
659     /// let result = thread::spawn(move || {
660     ///    let c = RefCell::new(5);
661     ///    let m = c.borrow_mut();
662     ///
663     ///    let b = c.borrow(); // this causes a panic
664     /// }).join();
665     ///
666     /// assert!(result.is_err());
667     /// ```
668     #[stable(feature = "rust1", since = "1.0.0")]
669     #[inline]
670     pub fn borrow(&self) -> Ref<T> {
671         self.try_borrow().expect("already mutably borrowed")
672     }
673
674     /// Immutably borrows the wrapped value, returning an error if the value is currently mutably
675     /// borrowed.
676     ///
677     /// The borrow lasts until the returned `Ref` exits scope. Multiple immutable borrows can be
678     /// taken out at the same time.
679     ///
680     /// This is the non-panicking variant of [`borrow`](#method.borrow).
681     ///
682     /// # Examples
683     ///
684     /// ```
685     /// use std::cell::RefCell;
686     ///
687     /// let c = RefCell::new(5);
688     ///
689     /// {
690     ///     let m = c.borrow_mut();
691     ///     assert!(c.try_borrow().is_err());
692     /// }
693     ///
694     /// {
695     ///     let m = c.borrow();
696     ///     assert!(c.try_borrow().is_ok());
697     /// }
698     /// ```
699     #[stable(feature = "try_borrow", since = "1.13.0")]
700     #[inline]
701     pub fn try_borrow(&self) -> Result<Ref<T>, BorrowError> {
702         match BorrowRef::new(&self.borrow) {
703             Some(b) => Ok(Ref {
704                 value: unsafe { &*self.value.get() },
705                 borrow: b,
706             }),
707             None => Err(BorrowError { _private: () }),
708         }
709     }
710
711     /// Mutably borrows the wrapped value.
712     ///
713     /// The borrow lasts until the returned `RefMut` exits scope. The value
714     /// cannot be borrowed while this borrow is active.
715     ///
716     /// # Panics
717     ///
718     /// Panics if the value is currently borrowed. For a non-panicking variant, use
719     /// [`try_borrow_mut`](#method.try_borrow_mut).
720     ///
721     /// # Examples
722     ///
723     /// ```
724     /// use std::cell::RefCell;
725     ///
726     /// let c = RefCell::new(5);
727     ///
728     /// *c.borrow_mut() = 7;
729     ///
730     /// assert_eq!(*c.borrow(), 7);
731     /// ```
732     ///
733     /// An example of panic:
734     ///
735     /// ```
736     /// use std::cell::RefCell;
737     /// use std::thread;
738     ///
739     /// let result = thread::spawn(move || {
740     ///    let c = RefCell::new(5);
741     ///    let m = c.borrow();
742     ///
743     ///    let b = c.borrow_mut(); // this causes a panic
744     /// }).join();
745     ///
746     /// assert!(result.is_err());
747     /// ```
748     #[stable(feature = "rust1", since = "1.0.0")]
749     #[inline]
750     pub fn borrow_mut(&self) -> RefMut<T> {
751         self.try_borrow_mut().expect("already borrowed")
752     }
753
754     /// Mutably borrows the wrapped value, returning an error if the value is currently borrowed.
755     ///
756     /// The borrow lasts until the returned `RefMut` exits scope. The value cannot be borrowed
757     /// while this borrow is active.
758     ///
759     /// This is the non-panicking variant of [`borrow_mut`](#method.borrow_mut).
760     ///
761     /// # Examples
762     ///
763     /// ```
764     /// use std::cell::RefCell;
765     ///
766     /// let c = RefCell::new(5);
767     ///
768     /// {
769     ///     let m = c.borrow();
770     ///     assert!(c.try_borrow_mut().is_err());
771     /// }
772     ///
773     /// assert!(c.try_borrow_mut().is_ok());
774     /// ```
775     #[stable(feature = "try_borrow", since = "1.13.0")]
776     #[inline]
777     pub fn try_borrow_mut(&self) -> Result<RefMut<T>, BorrowMutError> {
778         match BorrowRefMut::new(&self.borrow) {
779             Some(b) => Ok(RefMut {
780                 value: unsafe { &mut *self.value.get() },
781                 borrow: b,
782             }),
783             None => Err(BorrowMutError { _private: () }),
784         }
785     }
786
787     /// Returns a raw pointer to the underlying data in this cell.
788     ///
789     /// # Examples
790     ///
791     /// ```
792     /// use std::cell::RefCell;
793     ///
794     /// let c = RefCell::new(5);
795     ///
796     /// let ptr = c.as_ptr();
797     /// ```
798     #[inline]
799     #[stable(feature = "cell_as_ptr", since = "1.12.0")]
800     pub fn as_ptr(&self) -> *mut T {
801         self.value.get()
802     }
803
804     /// Returns a mutable reference to the underlying data.
805     ///
806     /// This call borrows `RefCell` mutably (at compile-time) so there is no
807     /// need for dynamic checks.
808     ///
809     /// However be cautious: this method expects `self` to be mutable, which is
810     /// generally not the case when using a `RefCell`. Take a look at the
811     /// [`borrow_mut`] method instead if `self` isn't mutable.
812     ///
813     /// Also, please be aware that this method is only for special circumstances and is usually
814     /// not what you want. In case of doubt, use [`borrow_mut`] instead.
815     ///
816     /// [`borrow_mut`]: #method.borrow_mut
817     ///
818     /// # Examples
819     ///
820     /// ```
821     /// use std::cell::RefCell;
822     ///
823     /// let mut c = RefCell::new(5);
824     /// *c.get_mut() += 1;
825     ///
826     /// assert_eq!(c, RefCell::new(6));
827     /// ```
828     #[inline]
829     #[stable(feature = "cell_get_mut", since = "1.11.0")]
830     pub fn get_mut(&mut self) -> &mut T {
831         unsafe {
832             &mut *self.value.get()
833         }
834     }
835 }
836
837 #[stable(feature = "rust1", since = "1.0.0")]
838 unsafe impl<T: ?Sized> Send for RefCell<T> where T: Send {}
839
840 #[stable(feature = "rust1", since = "1.0.0")]
841 impl<T: ?Sized> !Sync for RefCell<T> {}
842
843 #[stable(feature = "rust1", since = "1.0.0")]
844 impl<T: Clone> Clone for RefCell<T> {
845     #[inline]
846     fn clone(&self) -> RefCell<T> {
847         RefCell::new(self.borrow().clone())
848     }
849 }
850
851 #[stable(feature = "rust1", since = "1.0.0")]
852 impl<T:Default> Default for RefCell<T> {
853     /// Creates a `RefCell<T>`, with the `Default` value for T.
854     #[inline]
855     fn default() -> RefCell<T> {
856         RefCell::new(Default::default())
857     }
858 }
859
860 #[stable(feature = "rust1", since = "1.0.0")]
861 impl<T: ?Sized + PartialEq> PartialEq for RefCell<T> {
862     #[inline]
863     fn eq(&self, other: &RefCell<T>) -> bool {
864         *self.borrow() == *other.borrow()
865     }
866 }
867
868 #[stable(feature = "cell_eq", since = "1.2.0")]
869 impl<T: ?Sized + Eq> Eq for RefCell<T> {}
870
871 #[stable(feature = "cell_ord", since = "1.10.0")]
872 impl<T: ?Sized + PartialOrd> PartialOrd for RefCell<T> {
873     #[inline]
874     fn partial_cmp(&self, other: &RefCell<T>) -> Option<Ordering> {
875         self.borrow().partial_cmp(&*other.borrow())
876     }
877
878     #[inline]
879     fn lt(&self, other: &RefCell<T>) -> bool {
880         *self.borrow() < *other.borrow()
881     }
882
883     #[inline]
884     fn le(&self, other: &RefCell<T>) -> bool {
885         *self.borrow() <= *other.borrow()
886     }
887
888     #[inline]
889     fn gt(&self, other: &RefCell<T>) -> bool {
890         *self.borrow() > *other.borrow()
891     }
892
893     #[inline]
894     fn ge(&self, other: &RefCell<T>) -> bool {
895         *self.borrow() >= *other.borrow()
896     }
897 }
898
899 #[stable(feature = "cell_ord", since = "1.10.0")]
900 impl<T: ?Sized + Ord> Ord for RefCell<T> {
901     #[inline]
902     fn cmp(&self, other: &RefCell<T>) -> Ordering {
903         self.borrow().cmp(&*other.borrow())
904     }
905 }
906
907 #[stable(feature = "cell_from", since = "1.12.0")]
908 impl<T> From<T> for RefCell<T> {
909     fn from(t: T) -> RefCell<T> {
910         RefCell::new(t)
911     }
912 }
913
914 #[unstable(feature = "coerce_unsized", issue = "27732")]
915 impl<T: CoerceUnsized<U>, U> CoerceUnsized<RefCell<U>> for RefCell<T> {}
916
917 struct BorrowRef<'b> {
918     borrow: &'b Cell<BorrowFlag>,
919 }
920
921 impl<'b> BorrowRef<'b> {
922     #[inline]
923     fn new(borrow: &'b Cell<BorrowFlag>) -> Option<BorrowRef<'b>> {
924         match borrow.get() {
925             WRITING => None,
926             b => {
927                 borrow.set(b + 1);
928                 Some(BorrowRef { borrow: borrow })
929             },
930         }
931     }
932 }
933
934 impl<'b> Drop for BorrowRef<'b> {
935     #[inline]
936     fn drop(&mut self) {
937         let borrow = self.borrow.get();
938         debug_assert!(borrow != WRITING && borrow != UNUSED);
939         self.borrow.set(borrow - 1);
940     }
941 }
942
943 impl<'b> Clone for BorrowRef<'b> {
944     #[inline]
945     fn clone(&self) -> BorrowRef<'b> {
946         // Since this Ref exists, we know the borrow flag
947         // is not set to WRITING.
948         let borrow = self.borrow.get();
949         debug_assert!(borrow != UNUSED);
950         // Prevent the borrow counter from overflowing.
951         assert!(borrow != WRITING);
952         self.borrow.set(borrow + 1);
953         BorrowRef { borrow: self.borrow }
954     }
955 }
956
957 /// Wraps a borrowed reference to a value in a `RefCell` box.
958 /// A wrapper type for an immutably borrowed value from a `RefCell<T>`.
959 ///
960 /// See the [module-level documentation](index.html) for more.
961 #[stable(feature = "rust1", since = "1.0.0")]
962 pub struct Ref<'b, T: ?Sized + 'b> {
963     value: &'b T,
964     borrow: BorrowRef<'b>,
965 }
966
967 #[stable(feature = "rust1", since = "1.0.0")]
968 impl<'b, T: ?Sized> Deref for Ref<'b, T> {
969     type Target = T;
970
971     #[inline]
972     fn deref(&self) -> &T {
973         self.value
974     }
975 }
976
977 impl<'b, T: ?Sized> Ref<'b, T> {
978     /// Copies a `Ref`.
979     ///
980     /// The `RefCell` is already immutably borrowed, so this cannot fail.
981     ///
982     /// This is an associated function that needs to be used as
983     /// `Ref::clone(...)`.  A `Clone` implementation or a method would interfere
984     /// with the widespread use of `r.borrow().clone()` to clone the contents of
985     /// a `RefCell`.
986     #[stable(feature = "cell_extras", since = "1.15.0")]
987     #[inline]
988     pub fn clone(orig: &Ref<'b, T>) -> Ref<'b, T> {
989         Ref {
990             value: orig.value,
991             borrow: orig.borrow.clone(),
992         }
993     }
994
995     /// Make a new `Ref` for a component of the borrowed data.
996     ///
997     /// The `RefCell` is already immutably borrowed, so this cannot fail.
998     ///
999     /// This is an associated function that needs to be used as `Ref::map(...)`.
1000     /// A method would interfere with methods of the same name on the contents
1001     /// of a `RefCell` used through `Deref`.
1002     ///
1003     /// # Examples
1004     ///
1005     /// ```
1006     /// use std::cell::{RefCell, Ref};
1007     ///
1008     /// let c = RefCell::new((5, 'b'));
1009     /// let b1: Ref<(u32, char)> = c.borrow();
1010     /// let b2: Ref<u32> = Ref::map(b1, |t| &t.0);
1011     /// assert_eq!(*b2, 5)
1012     /// ```
1013     #[stable(feature = "cell_map", since = "1.8.0")]
1014     #[inline]
1015     pub fn map<U: ?Sized, F>(orig: Ref<'b, T>, f: F) -> Ref<'b, U>
1016         where F: FnOnce(&T) -> &U
1017     {
1018         Ref {
1019             value: f(orig.value),
1020             borrow: orig.borrow,
1021         }
1022     }
1023 }
1024
1025 #[unstable(feature = "coerce_unsized", issue = "27732")]
1026 impl<'b, T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Ref<'b, U>> for Ref<'b, T> {}
1027
1028 #[stable(feature = "std_guard_impls", since = "1.20.0")]
1029 impl<'a, T: ?Sized + fmt::Display> fmt::Display for Ref<'a, T> {
1030     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1031         self.value.fmt(f)
1032     }
1033 }
1034
1035 impl<'b, T: ?Sized> RefMut<'b, T> {
1036     /// Make a new `RefMut` for a component of the borrowed data, e.g. an enum
1037     /// variant.
1038     ///
1039     /// The `RefCell` is already mutably borrowed, so this cannot fail.
1040     ///
1041     /// This is an associated function that needs to be used as
1042     /// `RefMut::map(...)`.  A method would interfere with methods of the same
1043     /// name on the contents of a `RefCell` used through `Deref`.
1044     ///
1045     /// # Examples
1046     ///
1047     /// ```
1048     /// use std::cell::{RefCell, RefMut};
1049     ///
1050     /// let c = RefCell::new((5, 'b'));
1051     /// {
1052     ///     let b1: RefMut<(u32, char)> = c.borrow_mut();
1053     ///     let mut b2: RefMut<u32> = RefMut::map(b1, |t| &mut t.0);
1054     ///     assert_eq!(*b2, 5);
1055     ///     *b2 = 42;
1056     /// }
1057     /// assert_eq!(*c.borrow(), (42, 'b'));
1058     /// ```
1059     #[stable(feature = "cell_map", since = "1.8.0")]
1060     #[inline]
1061     pub fn map<U: ?Sized, F>(orig: RefMut<'b, T>, f: F) -> RefMut<'b, U>
1062         where F: FnOnce(&mut T) -> &mut U
1063     {
1064         RefMut {
1065             value: f(orig.value),
1066             borrow: orig.borrow,
1067         }
1068     }
1069 }
1070
1071 struct BorrowRefMut<'b> {
1072     borrow: &'b Cell<BorrowFlag>,
1073 }
1074
1075 impl<'b> Drop for BorrowRefMut<'b> {
1076     #[inline]
1077     fn drop(&mut self) {
1078         let borrow = self.borrow.get();
1079         debug_assert!(borrow == WRITING);
1080         self.borrow.set(UNUSED);
1081     }
1082 }
1083
1084 impl<'b> BorrowRefMut<'b> {
1085     #[inline]
1086     fn new(borrow: &'b Cell<BorrowFlag>) -> Option<BorrowRefMut<'b>> {
1087         match borrow.get() {
1088             UNUSED => {
1089                 borrow.set(WRITING);
1090                 Some(BorrowRefMut { borrow: borrow })
1091             },
1092             _ => None,
1093         }
1094     }
1095 }
1096
1097 /// A wrapper type for a mutably borrowed value from a `RefCell<T>`.
1098 ///
1099 /// See the [module-level documentation](index.html) for more.
1100 #[stable(feature = "rust1", since = "1.0.0")]
1101 pub struct RefMut<'b, T: ?Sized + 'b> {
1102     value: &'b mut T,
1103     borrow: BorrowRefMut<'b>,
1104 }
1105
1106 #[stable(feature = "rust1", since = "1.0.0")]
1107 impl<'b, T: ?Sized> Deref for RefMut<'b, T> {
1108     type Target = T;
1109
1110     #[inline]
1111     fn deref(&self) -> &T {
1112         self.value
1113     }
1114 }
1115
1116 #[stable(feature = "rust1", since = "1.0.0")]
1117 impl<'b, T: ?Sized> DerefMut for RefMut<'b, T> {
1118     #[inline]
1119     fn deref_mut(&mut self) -> &mut T {
1120         self.value
1121     }
1122 }
1123
1124 #[unstable(feature = "coerce_unsized", issue = "27732")]
1125 impl<'b, T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<RefMut<'b, U>> for RefMut<'b, T> {}
1126
1127 #[stable(feature = "std_guard_impls", since = "1.20.0")]
1128 impl<'a, T: ?Sized + fmt::Display> fmt::Display for RefMut<'a, T> {
1129     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1130         self.value.fmt(f)
1131     }
1132 }
1133
1134 /// The core primitive for interior mutability in Rust.
1135 ///
1136 /// `UnsafeCell<T>` is a type that wraps some `T` and indicates unsafe interior operations on the
1137 /// wrapped type. Types with an `UnsafeCell<T>` field are considered to have an 'unsafe interior'.
1138 /// The `UnsafeCell<T>` type is the only legal way to obtain aliasable data that is considered
1139 /// mutable. In general, transmuting an `&T` type into an `&mut T` is considered undefined behavior.
1140 ///
1141 /// The compiler makes optimizations based on the knowledge that `&T` is not mutably aliased or
1142 /// mutated, and that `&mut T` is unique. When building abstractions like `Cell`, `RefCell`,
1143 /// `Mutex`, etc, you need to turn these optimizations off. `UnsafeCell` is the only legal way
1144 /// to do this. When `UnsafeCell<T>` is immutably aliased, it is still safe to obtain a mutable
1145 /// reference to its interior and/or to mutate it. However, it is up to the abstraction designer
1146 /// to ensure that no two mutable references obtained this way are active at the same time, and
1147 /// that there are no active mutable references or mutations when an immutable reference is obtained
1148 /// from the cell. This is often done via runtime checks.
1149 ///
1150 /// Note that while mutating or mutably aliasing the contents of an `& UnsafeCell<T>` is
1151 /// okay (provided you enforce the invariants some other way); it is still undefined behavior
1152 /// to have multiple `&mut UnsafeCell<T>` aliases.
1153 ///
1154 ///
1155 /// Types like `Cell<T>` and `RefCell<T>` use this type to wrap their internal data.
1156 ///
1157 /// # Examples
1158 ///
1159 /// ```
1160 /// use std::cell::UnsafeCell;
1161 /// use std::marker::Sync;
1162 ///
1163 /// # #[allow(dead_code)]
1164 /// struct NotThreadSafe<T> {
1165 ///     value: UnsafeCell<T>,
1166 /// }
1167 ///
1168 /// unsafe impl<T> Sync for NotThreadSafe<T> {}
1169 /// ```
1170 #[lang = "unsafe_cell"]
1171 #[stable(feature = "rust1", since = "1.0.0")]
1172 pub struct UnsafeCell<T: ?Sized> {
1173     value: T,
1174 }
1175
1176 #[stable(feature = "rust1", since = "1.0.0")]
1177 impl<T: ?Sized> !Sync for UnsafeCell<T> {}
1178
1179 impl<T> UnsafeCell<T> {
1180     /// Constructs a new instance of `UnsafeCell` which will wrap the specified
1181     /// value.
1182     ///
1183     /// All access to the inner value through methods is `unsafe`.
1184     ///
1185     /// # Examples
1186     ///
1187     /// ```
1188     /// use std::cell::UnsafeCell;
1189     ///
1190     /// let uc = UnsafeCell::new(5);
1191     /// ```
1192     #[stable(feature = "rust1", since = "1.0.0")]
1193     #[cfg_attr(not(stage0), rustc_const_unstable(feature = "const_unsafe_cell_new"))]
1194     #[inline]
1195     pub const fn new(value: T) -> UnsafeCell<T> {
1196         UnsafeCell { value: value }
1197     }
1198
1199     /// Unwraps the value.
1200     ///
1201     /// # Safety
1202     ///
1203     /// This function is unsafe because this thread or another thread may currently be
1204     /// inspecting the inner value.
1205     ///
1206     /// # Examples
1207     ///
1208     /// ```
1209     /// use std::cell::UnsafeCell;
1210     ///
1211     /// let uc = UnsafeCell::new(5);
1212     ///
1213     /// let five = unsafe { uc.into_inner() };
1214     /// ```
1215     #[inline]
1216     #[stable(feature = "rust1", since = "1.0.0")]
1217     pub unsafe fn into_inner(self) -> T {
1218         self.value
1219     }
1220 }
1221
1222 impl<T: ?Sized> UnsafeCell<T> {
1223     /// Gets a mutable pointer to the wrapped value.
1224     ///
1225     /// This can be cast to a pointer of any kind.
1226     /// Ensure that the access is unique when casting to
1227     /// `&mut T`, and ensure that there are no mutations or mutable
1228     /// aliases going on when casting to `&T`
1229     ///
1230     /// # Examples
1231     ///
1232     /// ```
1233     /// use std::cell::UnsafeCell;
1234     ///
1235     /// let uc = UnsafeCell::new(5);
1236     ///
1237     /// let five = uc.get();
1238     /// ```
1239     #[inline]
1240     #[stable(feature = "rust1", since = "1.0.0")]
1241     pub fn get(&self) -> *mut T {
1242         &self.value as *const T as *mut T
1243     }
1244 }
1245
1246 #[stable(feature = "unsafe_cell_default", since = "1.10.0")]
1247 impl<T: Default> Default for UnsafeCell<T> {
1248     /// Creates an `UnsafeCell`, with the `Default` value for T.
1249     fn default() -> UnsafeCell<T> {
1250         UnsafeCell::new(Default::default())
1251     }
1252 }
1253
1254 #[stable(feature = "cell_from", since = "1.12.0")]
1255 impl<T> From<T> for UnsafeCell<T> {
1256     fn from(t: T) -> UnsafeCell<T> {
1257         UnsafeCell::new(t)
1258     }
1259 }
1260
1261 #[unstable(feature = "coerce_unsized", issue = "27732")]
1262 impl<T: CoerceUnsized<U>, U> CoerceUnsized<UnsafeCell<U>> for UnsafeCell<T> {}
1263
1264 #[allow(unused)]
1265 fn assert_coerce_unsized(a: UnsafeCell<&i32>, b: Cell<&i32>, c: RefCell<&i32>) {
1266     let _: UnsafeCell<&Send> = a;
1267     let _: Cell<&Send> = b;
1268     let _: RefCell<&Send> = c;
1269 }