]> git.lizzy.rs Git - rust.git/blob - src/libcore/cell.rs
Auto merge of #41433 - estebank:constructor, r=michaelwoerister
[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 //! use std::intrinsics::assume;
136 //!
137 //! struct Rc<T: ?Sized> {
138 //!     ptr: Shared<RcBox<T>>
139 //! }
140 //!
141 //! struct RcBox<T: ?Sized> {
142 //!     strong: Cell<usize>,
143 //!     refcount: Cell<usize>,
144 //!     value: T,
145 //! }
146 //!
147 //! impl<T: ?Sized> Clone for Rc<T> {
148 //!     fn clone(&self) -> Rc<T> {
149 //!         self.inc_strong();
150 //!         Rc { ptr: self.ptr }
151 //!     }
152 //! }
153 //!
154 //! trait RcBoxPtr<T: ?Sized> {
155 //!
156 //!     fn inner(&self) -> &RcBox<T>;
157 //!
158 //!     fn strong(&self) -> usize {
159 //!         self.inner().strong.get()
160 //!     }
161 //!
162 //!     fn inc_strong(&self) {
163 //!         self.inner()
164 //!             .strong
165 //!             .set(self.strong()
166 //!                      .checked_add(1)
167 //!                      .unwrap_or_else(|| unsafe { abort() }));
168 //!     }
169 //! }
170 //!
171 //! impl<T: ?Sized> RcBoxPtr<T> for Rc<T> {
172 //!    fn inner(&self) -> &RcBox<T> {
173 //!        unsafe {
174 //!            assume(!(*(&self.ptr as *const _ as *const *const ())).is_null());
175 //!            &(**self.ptr)
176 //!        }
177 //!    }
178 //! }
179 //! ```
180 //!
181
182 #![stable(feature = "rust1", since = "1.0.0")]
183
184 use cmp::Ordering;
185 use fmt::{self, Debug, Display};
186 use marker::Unsize;
187 use mem;
188 use ops::{Deref, DerefMut, CoerceUnsized};
189 use ptr;
190
191 /// A mutable memory location.
192 ///
193 /// See the [module-level documentation](index.html) for more.
194 #[stable(feature = "rust1", since = "1.0.0")]
195 pub struct Cell<T> {
196     value: UnsafeCell<T>,
197 }
198
199 impl<T:Copy> Cell<T> {
200     /// Returns a copy of the contained value.
201     ///
202     /// # Examples
203     ///
204     /// ```
205     /// use std::cell::Cell;
206     ///
207     /// let c = Cell::new(5);
208     ///
209     /// let five = c.get();
210     /// ```
211     #[inline]
212     #[stable(feature = "rust1", since = "1.0.0")]
213     pub fn get(&self) -> T {
214         unsafe{ *self.value.get() }
215     }
216 }
217
218 #[stable(feature = "rust1", since = "1.0.0")]
219 unsafe impl<T> Send for Cell<T> where T: Send {}
220
221 #[stable(feature = "rust1", since = "1.0.0")]
222 impl<T> !Sync for Cell<T> {}
223
224 #[stable(feature = "rust1", since = "1.0.0")]
225 impl<T:Copy> Clone for Cell<T> {
226     #[inline]
227     fn clone(&self) -> Cell<T> {
228         Cell::new(self.get())
229     }
230 }
231
232 #[stable(feature = "rust1", since = "1.0.0")]
233 impl<T:Default> Default for Cell<T> {
234     /// Creates a `Cell<T>`, with the `Default` value for T.
235     #[inline]
236     fn default() -> Cell<T> {
237         Cell::new(Default::default())
238     }
239 }
240
241 #[stable(feature = "rust1", since = "1.0.0")]
242 impl<T:PartialEq + Copy> PartialEq for Cell<T> {
243     #[inline]
244     fn eq(&self, other: &Cell<T>) -> bool {
245         self.get() == other.get()
246     }
247 }
248
249 #[stable(feature = "cell_eq", since = "1.2.0")]
250 impl<T:Eq + Copy> Eq for Cell<T> {}
251
252 #[stable(feature = "cell_ord", since = "1.10.0")]
253 impl<T:PartialOrd + Copy> PartialOrd for Cell<T> {
254     #[inline]
255     fn partial_cmp(&self, other: &Cell<T>) -> Option<Ordering> {
256         self.get().partial_cmp(&other.get())
257     }
258
259     #[inline]
260     fn lt(&self, other: &Cell<T>) -> bool {
261         self.get() < other.get()
262     }
263
264     #[inline]
265     fn le(&self, other: &Cell<T>) -> bool {
266         self.get() <= other.get()
267     }
268
269     #[inline]
270     fn gt(&self, other: &Cell<T>) -> bool {
271         self.get() > other.get()
272     }
273
274     #[inline]
275     fn ge(&self, other: &Cell<T>) -> bool {
276         self.get() >= other.get()
277     }
278 }
279
280 #[stable(feature = "cell_ord", since = "1.10.0")]
281 impl<T:Ord + Copy> Ord for Cell<T> {
282     #[inline]
283     fn cmp(&self, other: &Cell<T>) -> Ordering {
284         self.get().cmp(&other.get())
285     }
286 }
287
288 #[stable(feature = "cell_from", since = "1.12.0")]
289 impl<T> From<T> for Cell<T> {
290     fn from(t: T) -> Cell<T> {
291         Cell::new(t)
292     }
293 }
294
295 impl<T> Cell<T> {
296     /// Creates a new `Cell` containing the given value.
297     ///
298     /// # Examples
299     ///
300     /// ```
301     /// use std::cell::Cell;
302     ///
303     /// let c = Cell::new(5);
304     /// ```
305     #[stable(feature = "rust1", since = "1.0.0")]
306     #[inline]
307     pub const fn new(value: T) -> Cell<T> {
308         Cell {
309             value: UnsafeCell::new(value),
310         }
311     }
312
313     /// Returns a raw pointer to the underlying data in this cell.
314     ///
315     /// # Examples
316     ///
317     /// ```
318     /// use std::cell::Cell;
319     ///
320     /// let c = Cell::new(5);
321     ///
322     /// let ptr = c.as_ptr();
323     /// ```
324     #[inline]
325     #[stable(feature = "cell_as_ptr", since = "1.12.0")]
326     pub fn as_ptr(&self) -> *mut T {
327         self.value.get()
328     }
329
330     /// Returns a mutable reference to the underlying data.
331     ///
332     /// This call borrows `Cell` mutably (at compile-time) which guarantees
333     /// that we possess the only reference.
334     ///
335     /// # Examples
336     ///
337     /// ```
338     /// use std::cell::Cell;
339     ///
340     /// let mut c = Cell::new(5);
341     /// *c.get_mut() += 1;
342     ///
343     /// assert_eq!(c.get(), 6);
344     /// ```
345     #[inline]
346     #[stable(feature = "cell_get_mut", since = "1.11.0")]
347     pub fn get_mut(&mut self) -> &mut T {
348         unsafe {
349             &mut *self.value.get()
350         }
351     }
352
353     /// Sets the contained value.
354     ///
355     /// # Examples
356     ///
357     /// ```
358     /// use std::cell::Cell;
359     ///
360     /// let c = Cell::new(5);
361     ///
362     /// c.set(10);
363     /// ```
364     #[inline]
365     #[stable(feature = "rust1", since = "1.0.0")]
366     pub fn set(&self, val: T) {
367         let old = self.replace(val);
368         drop(old);
369     }
370
371     /// Swaps the values of two Cells.
372     /// Difference with `std::mem::swap` is that this function doesn't require `&mut` reference.
373     ///
374     /// # Examples
375     ///
376     /// ```
377     /// use std::cell::Cell;
378     ///
379     /// let c1 = Cell::new(5i32);
380     /// let c2 = Cell::new(10i32);
381     /// c1.swap(&c2);
382     /// assert_eq!(10, c1.get());
383     /// assert_eq!(5, c2.get());
384     /// ```
385     #[inline]
386     #[stable(feature = "move_cell", since = "1.17.0")]
387     pub fn swap(&self, other: &Self) {
388         if ptr::eq(self, other) {
389             return;
390         }
391         unsafe {
392             ptr::swap(self.value.get(), other.value.get());
393         }
394     }
395
396     /// Replaces the contained value.
397     ///
398     /// # Examples
399     ///
400     /// ```
401     /// use std::cell::Cell;
402     ///
403     /// let c = Cell::new(5);
404     /// let old = c.replace(10);
405     ///
406     /// assert_eq!(5, old);
407     /// ```
408     #[stable(feature = "move_cell", since = "1.17.0")]
409     pub fn replace(&self, val: T) -> T {
410         mem::replace(unsafe { &mut *self.value.get() }, val)
411     }
412
413     /// Unwraps the value.
414     ///
415     /// # Examples
416     ///
417     /// ```
418     /// use std::cell::Cell;
419     ///
420     /// let c = Cell::new(5);
421     /// let five = c.into_inner();
422     ///
423     /// assert_eq!(five, 5);
424     /// ```
425     #[stable(feature = "move_cell", since = "1.17.0")]
426     pub fn into_inner(self) -> T {
427         unsafe { self.value.into_inner() }
428     }
429 }
430
431 impl<T: Default> Cell<T> {
432     /// Takes the value of the cell, leaving `Default::default()` in its place.
433     ///
434     /// # Examples
435     ///
436     /// ```
437     /// use std::cell::Cell;
438     ///
439     /// let c = Cell::new(5);
440     /// let five = c.take();
441     ///
442     /// assert_eq!(five, 5);
443     /// assert_eq!(c.into_inner(), 0);
444     /// ```
445     #[stable(feature = "move_cell", since = "1.17.0")]
446     pub fn take(&self) -> T {
447         self.replace(Default::default())
448     }
449 }
450
451 #[unstable(feature = "coerce_unsized", issue = "27732")]
452 impl<T: CoerceUnsized<U>, U> CoerceUnsized<Cell<U>> for Cell<T> {}
453
454 /// A mutable memory location with dynamically checked borrow rules
455 ///
456 /// See the [module-level documentation](index.html) for more.
457 #[stable(feature = "rust1", since = "1.0.0")]
458 pub struct RefCell<T: ?Sized> {
459     borrow: Cell<BorrowFlag>,
460     value: UnsafeCell<T>,
461 }
462
463 /// An error returned by [`RefCell::try_borrow`](struct.RefCell.html#method.try_borrow).
464 #[stable(feature = "try_borrow", since = "1.13.0")]
465 pub struct BorrowError {
466     _private: (),
467 }
468
469 #[stable(feature = "try_borrow", since = "1.13.0")]
470 impl Debug for BorrowError {
471     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
472         f.debug_struct("BorrowError").finish()
473     }
474 }
475
476 #[stable(feature = "try_borrow", since = "1.13.0")]
477 impl Display for BorrowError {
478     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
479         Display::fmt("already mutably borrowed", f)
480     }
481 }
482
483 /// An error returned by [`RefCell::try_borrow_mut`](struct.RefCell.html#method.try_borrow_mut).
484 #[stable(feature = "try_borrow", since = "1.13.0")]
485 pub struct BorrowMutError {
486     _private: (),
487 }
488
489 #[stable(feature = "try_borrow", since = "1.13.0")]
490 impl Debug for BorrowMutError {
491     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
492         f.debug_struct("BorrowMutError").finish()
493     }
494 }
495
496 #[stable(feature = "try_borrow", since = "1.13.0")]
497 impl Display for BorrowMutError {
498     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
499         Display::fmt("already borrowed", f)
500     }
501 }
502
503 // Values [1, MAX-1] represent the number of `Ref` active
504 // (will not outgrow its range since `usize` is the size of the address space)
505 type BorrowFlag = usize;
506 const UNUSED: BorrowFlag = 0;
507 const WRITING: BorrowFlag = !0;
508
509 impl<T> RefCell<T> {
510     /// Creates a new `RefCell` containing `value`.
511     ///
512     /// # Examples
513     ///
514     /// ```
515     /// use std::cell::RefCell;
516     ///
517     /// let c = RefCell::new(5);
518     /// ```
519     #[stable(feature = "rust1", since = "1.0.0")]
520     #[inline]
521     pub const fn new(value: T) -> RefCell<T> {
522         RefCell {
523             value: UnsafeCell::new(value),
524             borrow: Cell::new(UNUSED),
525         }
526     }
527
528     /// Consumes the `RefCell`, returning the wrapped value.
529     ///
530     /// # Examples
531     ///
532     /// ```
533     /// use std::cell::RefCell;
534     ///
535     /// let c = RefCell::new(5);
536     ///
537     /// let five = c.into_inner();
538     /// ```
539     #[stable(feature = "rust1", since = "1.0.0")]
540     #[inline]
541     pub fn into_inner(self) -> T {
542         // Since this function takes `self` (the `RefCell`) by value, the
543         // compiler statically verifies that it is not currently borrowed.
544         // Therefore the following assertion is just a `debug_assert!`.
545         debug_assert!(self.borrow.get() == UNUSED);
546         unsafe { self.value.into_inner() }
547     }
548 }
549
550 impl<T: ?Sized> RefCell<T> {
551     /// Immutably borrows the wrapped value.
552     ///
553     /// The borrow lasts until the returned `Ref` exits scope. Multiple
554     /// immutable borrows can be taken out at the same time.
555     ///
556     /// # Panics
557     ///
558     /// Panics if the value is currently mutably borrowed. For a non-panicking variant, use
559     /// [`try_borrow`](#method.try_borrow).
560     ///
561     /// # Examples
562     ///
563     /// ```
564     /// use std::cell::RefCell;
565     ///
566     /// let c = RefCell::new(5);
567     ///
568     /// let borrowed_five = c.borrow();
569     /// let borrowed_five2 = c.borrow();
570     /// ```
571     ///
572     /// An example of panic:
573     ///
574     /// ```
575     /// use std::cell::RefCell;
576     /// use std::thread;
577     ///
578     /// let result = thread::spawn(move || {
579     ///    let c = RefCell::new(5);
580     ///    let m = c.borrow_mut();
581     ///
582     ///    let b = c.borrow(); // this causes a panic
583     /// }).join();
584     ///
585     /// assert!(result.is_err());
586     /// ```
587     #[stable(feature = "rust1", since = "1.0.0")]
588     #[inline]
589     pub fn borrow(&self) -> Ref<T> {
590         self.try_borrow().expect("already mutably borrowed")
591     }
592
593     /// Immutably borrows the wrapped value, returning an error if the value is currently mutably
594     /// borrowed.
595     ///
596     /// The borrow lasts until the returned `Ref` exits scope. Multiple immutable borrows can be
597     /// taken out at the same time.
598     ///
599     /// This is the non-panicking variant of [`borrow`](#method.borrow).
600     ///
601     /// # Examples
602     ///
603     /// ```
604     /// use std::cell::RefCell;
605     ///
606     /// let c = RefCell::new(5);
607     ///
608     /// {
609     ///     let m = c.borrow_mut();
610     ///     assert!(c.try_borrow().is_err());
611     /// }
612     ///
613     /// {
614     ///     let m = c.borrow();
615     ///     assert!(c.try_borrow().is_ok());
616     /// }
617     /// ```
618     #[stable(feature = "try_borrow", since = "1.13.0")]
619     #[inline]
620     pub fn try_borrow(&self) -> Result<Ref<T>, BorrowError> {
621         match BorrowRef::new(&self.borrow) {
622             Some(b) => Ok(Ref {
623                 value: unsafe { &*self.value.get() },
624                 borrow: b,
625             }),
626             None => Err(BorrowError { _private: () }),
627         }
628     }
629
630     /// Mutably borrows the wrapped value.
631     ///
632     /// The borrow lasts until the returned `RefMut` exits scope. The value
633     /// cannot be borrowed while this borrow is active.
634     ///
635     /// # Panics
636     ///
637     /// Panics if the value is currently borrowed. For a non-panicking variant, use
638     /// [`try_borrow_mut`](#method.try_borrow_mut).
639     ///
640     /// # Examples
641     ///
642     /// ```
643     /// use std::cell::RefCell;
644     ///
645     /// let c = RefCell::new(5);
646     ///
647     /// *c.borrow_mut() = 7;
648     ///
649     /// assert_eq!(*c.borrow(), 7);
650     /// ```
651     ///
652     /// An example of panic:
653     ///
654     /// ```
655     /// use std::cell::RefCell;
656     /// use std::thread;
657     ///
658     /// let result = thread::spawn(move || {
659     ///    let c = RefCell::new(5);
660     ///    let m = c.borrow();
661     ///
662     ///    let b = c.borrow_mut(); // this causes a panic
663     /// }).join();
664     ///
665     /// assert!(result.is_err());
666     /// ```
667     #[stable(feature = "rust1", since = "1.0.0")]
668     #[inline]
669     pub fn borrow_mut(&self) -> RefMut<T> {
670         self.try_borrow_mut().expect("already borrowed")
671     }
672
673     /// Mutably borrows the wrapped value, returning an error if the value is currently borrowed.
674     ///
675     /// The borrow lasts until the returned `RefMut` exits scope. The value cannot be borrowed
676     /// while this borrow is active.
677     ///
678     /// This is the non-panicking variant of [`borrow_mut`](#method.borrow_mut).
679     ///
680     /// # Examples
681     ///
682     /// ```
683     /// use std::cell::RefCell;
684     ///
685     /// let c = RefCell::new(5);
686     ///
687     /// {
688     ///     let m = c.borrow();
689     ///     assert!(c.try_borrow_mut().is_err());
690     /// }
691     ///
692     /// assert!(c.try_borrow_mut().is_ok());
693     /// ```
694     #[stable(feature = "try_borrow", since = "1.13.0")]
695     #[inline]
696     pub fn try_borrow_mut(&self) -> Result<RefMut<T>, BorrowMutError> {
697         match BorrowRefMut::new(&self.borrow) {
698             Some(b) => Ok(RefMut {
699                 value: unsafe { &mut *self.value.get() },
700                 borrow: b,
701             }),
702             None => Err(BorrowMutError { _private: () }),
703         }
704     }
705
706     /// Returns a raw pointer to the underlying data in this cell.
707     ///
708     /// # Examples
709     ///
710     /// ```
711     /// use std::cell::RefCell;
712     ///
713     /// let c = RefCell::new(5);
714     ///
715     /// let ptr = c.as_ptr();
716     /// ```
717     #[inline]
718     #[stable(feature = "cell_as_ptr", since = "1.12.0")]
719     pub fn as_ptr(&self) -> *mut T {
720         self.value.get()
721     }
722
723     /// Returns a mutable reference to the underlying data.
724     ///
725     /// This call borrows `RefCell` mutably (at compile-time) so there is no
726     /// need for dynamic checks.
727     ///
728     /// However be cautious: this method expects `self` to be mutable, which is
729     /// generally not the case when using a `RefCell`. Take a look at the
730     /// [`borrow_mut`] method instead if `self` isn't mutable.
731     ///
732     /// Also, please be aware that this method is only for special circumstances and is usually
733     /// not you want. In case of doubt, use [`borrow_mut`] instead.
734     ///
735     /// [`borrow_mut`]: #method.borrow_mut
736     ///
737     /// # Examples
738     ///
739     /// ```
740     /// use std::cell::RefCell;
741     ///
742     /// let mut c = RefCell::new(5);
743     /// *c.get_mut() += 1;
744     ///
745     /// assert_eq!(c, RefCell::new(6));
746     /// ```
747     #[inline]
748     #[stable(feature = "cell_get_mut", since = "1.11.0")]
749     pub fn get_mut(&mut self) -> &mut T {
750         unsafe {
751             &mut *self.value.get()
752         }
753     }
754 }
755
756 #[stable(feature = "rust1", since = "1.0.0")]
757 unsafe impl<T: ?Sized> Send for RefCell<T> where T: Send {}
758
759 #[stable(feature = "rust1", since = "1.0.0")]
760 impl<T: ?Sized> !Sync for RefCell<T> {}
761
762 #[stable(feature = "rust1", since = "1.0.0")]
763 impl<T: Clone> Clone for RefCell<T> {
764     #[inline]
765     fn clone(&self) -> RefCell<T> {
766         RefCell::new(self.borrow().clone())
767     }
768 }
769
770 #[stable(feature = "rust1", since = "1.0.0")]
771 impl<T:Default> Default for RefCell<T> {
772     /// Creates a `RefCell<T>`, with the `Default` value for T.
773     #[inline]
774     fn default() -> RefCell<T> {
775         RefCell::new(Default::default())
776     }
777 }
778
779 #[stable(feature = "rust1", since = "1.0.0")]
780 impl<T: ?Sized + PartialEq> PartialEq for RefCell<T> {
781     #[inline]
782     fn eq(&self, other: &RefCell<T>) -> bool {
783         *self.borrow() == *other.borrow()
784     }
785 }
786
787 #[stable(feature = "cell_eq", since = "1.2.0")]
788 impl<T: ?Sized + Eq> Eq for RefCell<T> {}
789
790 #[stable(feature = "cell_ord", since = "1.10.0")]
791 impl<T: ?Sized + PartialOrd> PartialOrd for RefCell<T> {
792     #[inline]
793     fn partial_cmp(&self, other: &RefCell<T>) -> Option<Ordering> {
794         self.borrow().partial_cmp(&*other.borrow())
795     }
796
797     #[inline]
798     fn lt(&self, other: &RefCell<T>) -> bool {
799         *self.borrow() < *other.borrow()
800     }
801
802     #[inline]
803     fn le(&self, other: &RefCell<T>) -> bool {
804         *self.borrow() <= *other.borrow()
805     }
806
807     #[inline]
808     fn gt(&self, other: &RefCell<T>) -> bool {
809         *self.borrow() > *other.borrow()
810     }
811
812     #[inline]
813     fn ge(&self, other: &RefCell<T>) -> bool {
814         *self.borrow() >= *other.borrow()
815     }
816 }
817
818 #[stable(feature = "cell_ord", since = "1.10.0")]
819 impl<T: ?Sized + Ord> Ord for RefCell<T> {
820     #[inline]
821     fn cmp(&self, other: &RefCell<T>) -> Ordering {
822         self.borrow().cmp(&*other.borrow())
823     }
824 }
825
826 #[stable(feature = "cell_from", since = "1.12.0")]
827 impl<T> From<T> for RefCell<T> {
828     fn from(t: T) -> RefCell<T> {
829         RefCell::new(t)
830     }
831 }
832
833 #[unstable(feature = "coerce_unsized", issue = "27732")]
834 impl<T: CoerceUnsized<U>, U> CoerceUnsized<RefCell<U>> for RefCell<T> {}
835
836 struct BorrowRef<'b> {
837     borrow: &'b Cell<BorrowFlag>,
838 }
839
840 impl<'b> BorrowRef<'b> {
841     #[inline]
842     fn new(borrow: &'b Cell<BorrowFlag>) -> Option<BorrowRef<'b>> {
843         match borrow.get() {
844             WRITING => None,
845             b => {
846                 borrow.set(b + 1);
847                 Some(BorrowRef { borrow: borrow })
848             },
849         }
850     }
851 }
852
853 impl<'b> Drop for BorrowRef<'b> {
854     #[inline]
855     fn drop(&mut self) {
856         let borrow = self.borrow.get();
857         debug_assert!(borrow != WRITING && borrow != UNUSED);
858         self.borrow.set(borrow - 1);
859     }
860 }
861
862 impl<'b> Clone for BorrowRef<'b> {
863     #[inline]
864     fn clone(&self) -> BorrowRef<'b> {
865         // Since this Ref exists, we know the borrow flag
866         // is not set to WRITING.
867         let borrow = self.borrow.get();
868         debug_assert!(borrow != UNUSED);
869         // Prevent the borrow counter from overflowing.
870         assert!(borrow != WRITING);
871         self.borrow.set(borrow + 1);
872         BorrowRef { borrow: self.borrow }
873     }
874 }
875
876 /// Wraps a borrowed reference to a value in a `RefCell` box.
877 /// A wrapper type for an immutably borrowed value from a `RefCell<T>`.
878 ///
879 /// See the [module-level documentation](index.html) for more.
880 #[stable(feature = "rust1", since = "1.0.0")]
881 pub struct Ref<'b, T: ?Sized + 'b> {
882     value: &'b T,
883     borrow: BorrowRef<'b>,
884 }
885
886 #[stable(feature = "rust1", since = "1.0.0")]
887 impl<'b, T: ?Sized> Deref for Ref<'b, T> {
888     type Target = T;
889
890     #[inline]
891     fn deref(&self) -> &T {
892         self.value
893     }
894 }
895
896 impl<'b, T: ?Sized> Ref<'b, T> {
897     /// Copies a `Ref`.
898     ///
899     /// The `RefCell` is already immutably borrowed, so this cannot fail.
900     ///
901     /// This is an associated function that needs to be used as
902     /// `Ref::clone(...)`.  A `Clone` implementation or a method would interfere
903     /// with the widespread use of `r.borrow().clone()` to clone the contents of
904     /// a `RefCell`.
905     #[stable(feature = "cell_extras", since = "1.15.0")]
906     #[inline]
907     pub fn clone(orig: &Ref<'b, T>) -> Ref<'b, T> {
908         Ref {
909             value: orig.value,
910             borrow: orig.borrow.clone(),
911         }
912     }
913
914     /// Make a new `Ref` for a component of the borrowed data.
915     ///
916     /// The `RefCell` is already immutably borrowed, so this cannot fail.
917     ///
918     /// This is an associated function that needs to be used as `Ref::map(...)`.
919     /// A method would interfere with methods of the same name on the contents
920     /// of a `RefCell` used through `Deref`.
921     ///
922     /// # Example
923     ///
924     /// ```
925     /// use std::cell::{RefCell, Ref};
926     ///
927     /// let c = RefCell::new((5, 'b'));
928     /// let b1: Ref<(u32, char)> = c.borrow();
929     /// let b2: Ref<u32> = Ref::map(b1, |t| &t.0);
930     /// assert_eq!(*b2, 5)
931     /// ```
932     #[stable(feature = "cell_map", since = "1.8.0")]
933     #[inline]
934     pub fn map<U: ?Sized, F>(orig: Ref<'b, T>, f: F) -> Ref<'b, U>
935         where F: FnOnce(&T) -> &U
936     {
937         Ref {
938             value: f(orig.value),
939             borrow: orig.borrow,
940         }
941     }
942 }
943
944 #[unstable(feature = "coerce_unsized", issue = "27732")]
945 impl<'b, T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Ref<'b, U>> for Ref<'b, T> {}
946
947 impl<'b, T: ?Sized> RefMut<'b, T> {
948     /// Make a new `RefMut` for a component of the borrowed data, e.g. an enum
949     /// variant.
950     ///
951     /// The `RefCell` is already mutably borrowed, so this cannot fail.
952     ///
953     /// This is an associated function that needs to be used as
954     /// `RefMut::map(...)`.  A method would interfere with methods of the same
955     /// name on the contents of a `RefCell` used through `Deref`.
956     ///
957     /// # Example
958     ///
959     /// ```
960     /// use std::cell::{RefCell, RefMut};
961     ///
962     /// let c = RefCell::new((5, 'b'));
963     /// {
964     ///     let b1: RefMut<(u32, char)> = c.borrow_mut();
965     ///     let mut b2: RefMut<u32> = RefMut::map(b1, |t| &mut t.0);
966     ///     assert_eq!(*b2, 5);
967     ///     *b2 = 42;
968     /// }
969     /// assert_eq!(*c.borrow(), (42, 'b'));
970     /// ```
971     #[stable(feature = "cell_map", since = "1.8.0")]
972     #[inline]
973     pub fn map<U: ?Sized, F>(orig: RefMut<'b, T>, f: F) -> RefMut<'b, U>
974         where F: FnOnce(&mut T) -> &mut U
975     {
976         RefMut {
977             value: f(orig.value),
978             borrow: orig.borrow,
979         }
980     }
981 }
982
983 struct BorrowRefMut<'b> {
984     borrow: &'b Cell<BorrowFlag>,
985 }
986
987 impl<'b> Drop for BorrowRefMut<'b> {
988     #[inline]
989     fn drop(&mut self) {
990         let borrow = self.borrow.get();
991         debug_assert!(borrow == WRITING);
992         self.borrow.set(UNUSED);
993     }
994 }
995
996 impl<'b> BorrowRefMut<'b> {
997     #[inline]
998     fn new(borrow: &'b Cell<BorrowFlag>) -> Option<BorrowRefMut<'b>> {
999         match borrow.get() {
1000             UNUSED => {
1001                 borrow.set(WRITING);
1002                 Some(BorrowRefMut { borrow: borrow })
1003             },
1004             _ => None,
1005         }
1006     }
1007 }
1008
1009 /// A wrapper type for a mutably borrowed value from a `RefCell<T>`.
1010 ///
1011 /// See the [module-level documentation](index.html) for more.
1012 #[stable(feature = "rust1", since = "1.0.0")]
1013 pub struct RefMut<'b, T: ?Sized + 'b> {
1014     value: &'b mut T,
1015     borrow: BorrowRefMut<'b>,
1016 }
1017
1018 #[stable(feature = "rust1", since = "1.0.0")]
1019 impl<'b, T: ?Sized> Deref for RefMut<'b, T> {
1020     type Target = T;
1021
1022     #[inline]
1023     fn deref(&self) -> &T {
1024         self.value
1025     }
1026 }
1027
1028 #[stable(feature = "rust1", since = "1.0.0")]
1029 impl<'b, T: ?Sized> DerefMut for RefMut<'b, T> {
1030     #[inline]
1031     fn deref_mut(&mut self) -> &mut T {
1032         self.value
1033     }
1034 }
1035
1036 #[unstable(feature = "coerce_unsized", issue = "27732")]
1037 impl<'b, T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<RefMut<'b, U>> for RefMut<'b, T> {}
1038
1039 /// The core primitive for interior mutability in Rust.
1040 ///
1041 /// `UnsafeCell<T>` is a type that wraps some `T` and indicates unsafe interior operations on the
1042 /// wrapped type. Types with an `UnsafeCell<T>` field are considered to have an 'unsafe interior'.
1043 /// The `UnsafeCell<T>` type is the only legal way to obtain aliasable data that is considered
1044 /// mutable. In general, transmuting an `&T` type into an `&mut T` is considered undefined behavior.
1045 ///
1046 /// The compiler makes optimizations based on the knowledge that `&T` is not mutably aliased or
1047 /// mutated, and that `&mut T` is unique. When building abstractions like `Cell`, `RefCell`,
1048 /// `Mutex`, etc, you need to turn these optimizations off. `UnsafeCell` is the only legal way
1049 /// to do this. When `UnsafeCell<T>` is immutably aliased, it is still safe to obtain a mutable
1050 /// reference to its interior and/or to mutate it. However, it is up to the abstraction designer
1051 /// to ensure that no two mutable references obtained this way are active at the same time, and
1052 /// that there are no active mutable references or mutations when an immutable reference is obtained
1053 /// from the cell. This is often done via runtime checks.
1054 ///
1055 /// Note that while mutating or mutably aliasing the contents of an `& UnsafeCell<T>` is
1056 /// okay (provided you enforce the invariants some other way); it is still undefined behavior
1057 /// to have multiple `&mut UnsafeCell<T>` aliases.
1058 ///
1059 ///
1060 /// Types like `Cell<T>` and `RefCell<T>` use this type to wrap their internal data.
1061 ///
1062 /// # Examples
1063 ///
1064 /// ```
1065 /// use std::cell::UnsafeCell;
1066 /// use std::marker::Sync;
1067 ///
1068 /// # #[allow(dead_code)]
1069 /// struct NotThreadSafe<T> {
1070 ///     value: UnsafeCell<T>,
1071 /// }
1072 ///
1073 /// unsafe impl<T> Sync for NotThreadSafe<T> {}
1074 /// ```
1075 #[lang = "unsafe_cell"]
1076 #[stable(feature = "rust1", since = "1.0.0")]
1077 pub struct UnsafeCell<T: ?Sized> {
1078     value: T,
1079 }
1080
1081 #[stable(feature = "rust1", since = "1.0.0")]
1082 impl<T: ?Sized> !Sync for UnsafeCell<T> {}
1083
1084 impl<T> UnsafeCell<T> {
1085     /// Constructs a new instance of `UnsafeCell` which will wrap the specified
1086     /// value.
1087     ///
1088     /// All access to the inner value through methods is `unsafe`.
1089     ///
1090     /// # Examples
1091     ///
1092     /// ```
1093     /// use std::cell::UnsafeCell;
1094     ///
1095     /// let uc = UnsafeCell::new(5);
1096     /// ```
1097     #[stable(feature = "rust1", since = "1.0.0")]
1098     #[inline]
1099     pub const fn new(value: T) -> UnsafeCell<T> {
1100         UnsafeCell { value: value }
1101     }
1102
1103     /// Unwraps the value.
1104     ///
1105     /// # Safety
1106     ///
1107     /// This function is unsafe because this thread or another thread may currently be
1108     /// inspecting the inner value.
1109     ///
1110     /// # Examples
1111     ///
1112     /// ```
1113     /// use std::cell::UnsafeCell;
1114     ///
1115     /// let uc = UnsafeCell::new(5);
1116     ///
1117     /// let five = unsafe { uc.into_inner() };
1118     /// ```
1119     #[inline]
1120     #[stable(feature = "rust1", since = "1.0.0")]
1121     pub unsafe fn into_inner(self) -> T {
1122         self.value
1123     }
1124 }
1125
1126 impl<T: ?Sized> UnsafeCell<T> {
1127     /// Gets a mutable pointer to the wrapped value.
1128     ///
1129     /// This can be cast to a pointer of any kind.
1130     /// Ensure that the access is unique when casting to
1131     /// `&mut T`, and ensure that there are no mutations or mutable
1132     /// aliases going on when casting to `&T`
1133     ///
1134     /// # Examples
1135     ///
1136     /// ```
1137     /// use std::cell::UnsafeCell;
1138     ///
1139     /// let uc = UnsafeCell::new(5);
1140     ///
1141     /// let five = uc.get();
1142     /// ```
1143     #[inline]
1144     #[stable(feature = "rust1", since = "1.0.0")]
1145     pub fn get(&self) -> *mut T {
1146         &self.value as *const T as *mut T
1147     }
1148 }
1149
1150 #[stable(feature = "unsafe_cell_default", since = "1.9.0")]
1151 impl<T: Default> Default for UnsafeCell<T> {
1152     /// Creates an `UnsafeCell`, with the `Default` value for T.
1153     fn default() -> UnsafeCell<T> {
1154         UnsafeCell::new(Default::default())
1155     }
1156 }
1157
1158 #[stable(feature = "cell_from", since = "1.12.0")]
1159 impl<T> From<T> for UnsafeCell<T> {
1160     fn from(t: T) -> UnsafeCell<T> {
1161         UnsafeCell::new(t)
1162     }
1163 }
1164
1165 #[unstable(feature = "coerce_unsized", issue = "27732")]
1166 impl<T: CoerceUnsized<U>, U> CoerceUnsized<UnsafeCell<U>> for UnsafeCell<T> {}
1167
1168 #[allow(unused)]
1169 fn assert_coerce_unsized(a: UnsafeCell<&i32>, b: Cell<&i32>, c: RefCell<&i32>) {
1170     let _: UnsafeCell<&Send> = a;
1171     let _: Cell<&Send> = b;
1172     let _: RefCell<&Send> = c;
1173 }