]> git.lizzy.rs Git - rust.git/blob - src/libcore/cell.rs
Auto merge of #35414 - jupp0r:feature/test-threads-flag, r=alexcrichton
[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>` provides `get` and `set`
19 //! methods that change the interior value with a single method call. `Cell<T>` though is only
20 //! compatible with types that implement `Copy`. For other types, one must use the `RefCell<T>`
21 //! type, acquiring a write lock before mutating.
22 //!
23 //! `RefCell<T>` uses Rust's lifetimes to implement 'dynamic borrowing', a process whereby one can
24 //! claim temporary, exclusive, mutable access to the inner value. Borrows for `RefCell<T>`s are
25 //! tracked 'at runtime', unlike Rust's native reference types which are entirely tracked
26 //! statically, at compile time. Because `RefCell<T>` borrows are dynamic it is possible to attempt
27 //! to borrow a value that is already mutably borrowed; when this happens it results in thread
28 //! panic.
29 //!
30 //! # When to choose interior mutability
31 //!
32 //! The more common inherited mutability, where one must have unique access to mutate a value, is
33 //! one of the key language elements that enables Rust to reason strongly about pointer aliasing,
34 //! statically preventing crash bugs. Because of that, inherited mutability is preferred, and
35 //! interior mutability is something of a last resort. Since cell types enable mutation where it
36 //! would otherwise be disallowed though, there are occasions when interior mutability might be
37 //! appropriate, or even *must* be used, e.g.
38 //!
39 //! * Introducing mutability 'inside' of something immutable
40 //! * Implementation details of logically-immutable methods.
41 //! * Mutating implementations of `Clone`.
42 //!
43 //! ## Introducing mutability 'inside' of something immutable
44 //!
45 //! Many shared smart pointer types, including `Rc<T>` and `Arc<T>`, provide containers that can be
46 //! cloned and shared between multiple parties. Because the contained values may be
47 //! multiply-aliased, they can only be borrowed with `&`, not `&mut`. Without cells it would be
48 //! impossible to mutate data inside of these smart pointers at all.
49 //!
50 //! It's very common then to put a `RefCell<T>` inside shared pointer types to reintroduce
51 //! mutability:
52 //!
53 //! ```
54 //! use std::collections::HashMap;
55 //! use std::cell::RefCell;
56 //! use std::rc::Rc;
57 //!
58 //! fn main() {
59 //!     let shared_map: Rc<RefCell<_>> = Rc::new(RefCell::new(HashMap::new()));
60 //!     shared_map.borrow_mut().insert("africa", 92388);
61 //!     shared_map.borrow_mut().insert("kyoto", 11837);
62 //!     shared_map.borrow_mut().insert("piccadilly", 11826);
63 //!     shared_map.borrow_mut().insert("marbles", 38);
64 //! }
65 //! ```
66 //!
67 //! Note that this example uses `Rc<T>` and not `Arc<T>`. `RefCell<T>`s are for single-threaded
68 //! scenarios. Consider using `RwLock<T>` or `Mutex<T>` if you need shared mutability in a
69 //! multi-threaded situation.
70 //!
71 //! ## Implementation details of logically-immutable methods
72 //!
73 //! Occasionally it may be desirable not to expose in an API that there is mutation happening
74 //! "under the hood". This may be because logically the operation is immutable, but e.g. caching
75 //! forces the implementation to perform mutation; or because you must employ mutation to implement
76 //! a trait method that was originally defined to take `&self`.
77 //!
78 //! ```
79 //! # #![allow(dead_code)]
80 //! use std::cell::RefCell;
81 //!
82 //! struct Graph {
83 //!     edges: Vec<(i32, i32)>,
84 //!     span_tree_cache: RefCell<Option<Vec<(i32, i32)>>>
85 //! }
86 //!
87 //! impl Graph {
88 //!     fn minimum_spanning_tree(&self) -> Vec<(i32, i32)> {
89 //!         // Create a new scope to contain the lifetime of the
90 //!         // dynamic borrow
91 //!         {
92 //!             // Take a reference to the inside of cache cell
93 //!             let mut cache = self.span_tree_cache.borrow_mut();
94 //!             if cache.is_some() {
95 //!                 return cache.as_ref().unwrap().clone();
96 //!             }
97 //!
98 //!             let span_tree = self.calc_span_tree();
99 //!             *cache = Some(span_tree);
100 //!         }
101 //!
102 //!         // Recursive call to return the just-cached value.
103 //!         // Note that if we had not let the previous borrow
104 //!         // of the cache fall out of scope then the subsequent
105 //!         // recursive borrow would cause a dynamic thread panic.
106 //!         // This is the major hazard of using `RefCell`.
107 //!         self.minimum_spanning_tree()
108 //!     }
109 //! #   fn calc_span_tree(&self) -> Vec<(i32, i32)> { vec![] }
110 //! }
111 //! ```
112 //!
113 //! ## Mutating implementations of `Clone`
114 //!
115 //! This is simply a special - but common - case of the previous: hiding mutability for operations
116 //! that appear to be immutable. The `clone` method is expected to not change the source value, and
117 //! is declared to take `&self`, not `&mut self`. Therefore any mutation that happens in the
118 //! `clone` method must use cell types. For example, `Rc<T>` maintains its reference counts within a
119 //! `Cell<T>`.
120 //!
121 //! ```
122 //! use std::cell::Cell;
123 //!
124 //! struct Rc<T> {
125 //!     ptr: *mut RcBox<T>
126 //! }
127 //!
128 //! struct RcBox<T> {
129 //! # #[allow(dead_code)]
130 //!     value: T,
131 //!     refcount: Cell<usize>
132 //! }
133 //!
134 //! impl<T> Clone for Rc<T> {
135 //!     fn clone(&self) -> Rc<T> {
136 //!         unsafe {
137 //!             (*self.ptr).refcount.set((*self.ptr).refcount.get() + 1);
138 //!             Rc { ptr: self.ptr }
139 //!         }
140 //!     }
141 //! }
142 //! ```
143 //!
144
145 #![stable(feature = "rust1", since = "1.0.0")]
146
147 use clone::Clone;
148 use cmp::{PartialEq, Eq, PartialOrd, Ord, Ordering};
149 use default::Default;
150 use fmt::{self, Debug, Display};
151 use marker::{Copy, PhantomData, Send, Sync, Sized, Unsize};
152 use ops::{Deref, DerefMut, Drop, FnOnce, CoerceUnsized};
153 use option::Option;
154 use option::Option::{None, Some};
155 use result::Result;
156 use result::Result::{Ok, Err};
157
158 /// A mutable memory location that admits only `Copy` data.
159 ///
160 /// See the [module-level documentation](index.html) for more.
161 #[stable(feature = "rust1", since = "1.0.0")]
162 pub struct Cell<T> {
163     value: UnsafeCell<T>,
164 }
165
166 impl<T:Copy> Cell<T> {
167     /// Creates a new `Cell` containing the given value.
168     ///
169     /// # Examples
170     ///
171     /// ```
172     /// use std::cell::Cell;
173     ///
174     /// let c = Cell::new(5);
175     /// ```
176     #[stable(feature = "rust1", since = "1.0.0")]
177     #[inline]
178     pub const fn new(value: T) -> Cell<T> {
179         Cell {
180             value: UnsafeCell::new(value),
181         }
182     }
183
184     /// Returns a copy of the contained value.
185     ///
186     /// # Examples
187     ///
188     /// ```
189     /// use std::cell::Cell;
190     ///
191     /// let c = Cell::new(5);
192     ///
193     /// let five = c.get();
194     /// ```
195     #[inline]
196     #[stable(feature = "rust1", since = "1.0.0")]
197     pub fn get(&self) -> T {
198         unsafe{ *self.value.get() }
199     }
200
201     /// Sets the contained value.
202     ///
203     /// # Examples
204     ///
205     /// ```
206     /// use std::cell::Cell;
207     ///
208     /// let c = Cell::new(5);
209     ///
210     /// c.set(10);
211     /// ```
212     #[inline]
213     #[stable(feature = "rust1", since = "1.0.0")]
214     pub fn set(&self, value: T) {
215         unsafe {
216             *self.value.get() = value;
217         }
218     }
219
220     /// Returns a reference to the underlying `UnsafeCell`.
221     ///
222     /// # Examples
223     ///
224     /// ```
225     /// #![feature(as_unsafe_cell)]
226     ///
227     /// use std::cell::Cell;
228     ///
229     /// let c = Cell::new(5);
230     ///
231     /// let uc = c.as_unsafe_cell();
232     /// ```
233     #[inline]
234     #[unstable(feature = "as_unsafe_cell", issue = "27708")]
235     pub fn as_unsafe_cell(&self) -> &UnsafeCell<T> {
236         &self.value
237     }
238
239     /// Returns a mutable reference to the underlying data.
240     ///
241     /// This call borrows `Cell` mutably (at compile-time) which guarantees
242     /// that we possess the only reference.
243     ///
244     /// # Examples
245     ///
246     /// ```
247     /// use std::cell::Cell;
248     ///
249     /// let mut c = Cell::new(5);
250     /// *c.get_mut() += 1;
251     ///
252     /// assert_eq!(c.get(), 6);
253     /// ```
254     #[inline]
255     #[stable(feature = "cell_get_mut", since = "1.11.0")]
256     pub fn get_mut(&mut self) -> &mut T {
257         unsafe {
258             &mut *self.value.get()
259         }
260     }
261 }
262
263 #[stable(feature = "rust1", since = "1.0.0")]
264 unsafe impl<T> Send for Cell<T> where T: Send {}
265
266 #[stable(feature = "rust1", since = "1.0.0")]
267 impl<T> !Sync for Cell<T> {}
268
269 #[stable(feature = "rust1", since = "1.0.0")]
270 impl<T:Copy> Clone for Cell<T> {
271     #[inline]
272     fn clone(&self) -> Cell<T> {
273         Cell::new(self.get())
274     }
275 }
276
277 #[stable(feature = "rust1", since = "1.0.0")]
278 impl<T:Default + Copy> Default for Cell<T> {
279     #[inline]
280     fn default() -> Cell<T> {
281         Cell::new(Default::default())
282     }
283 }
284
285 #[stable(feature = "rust1", since = "1.0.0")]
286 impl<T:PartialEq + Copy> PartialEq for Cell<T> {
287     #[inline]
288     fn eq(&self, other: &Cell<T>) -> bool {
289         self.get() == other.get()
290     }
291 }
292
293 #[stable(feature = "cell_eq", since = "1.2.0")]
294 impl<T:Eq + Copy> Eq for Cell<T> {}
295
296 #[stable(feature = "cell_ord", since = "1.10.0")]
297 impl<T:PartialOrd + Copy> PartialOrd for Cell<T> {
298     #[inline]
299     fn partial_cmp(&self, other: &Cell<T>) -> Option<Ordering> {
300         self.get().partial_cmp(&other.get())
301     }
302
303     #[inline]
304     fn lt(&self, other: &Cell<T>) -> bool {
305         self.get() < other.get()
306     }
307
308     #[inline]
309     fn le(&self, other: &Cell<T>) -> bool {
310         self.get() <= other.get()
311     }
312
313     #[inline]
314     fn gt(&self, other: &Cell<T>) -> bool {
315         self.get() > other.get()
316     }
317
318     #[inline]
319     fn ge(&self, other: &Cell<T>) -> bool {
320         self.get() >= other.get()
321     }
322 }
323
324 #[stable(feature = "cell_ord", since = "1.10.0")]
325 impl<T:Ord + Copy> Ord for Cell<T> {
326     #[inline]
327     fn cmp(&self, other: &Cell<T>) -> Ordering {
328         self.get().cmp(&other.get())
329     }
330 }
331
332 /// A mutable memory location with dynamically checked borrow rules
333 ///
334 /// See the [module-level documentation](index.html) for more.
335 #[stable(feature = "rust1", since = "1.0.0")]
336 pub struct RefCell<T: ?Sized> {
337     borrow: Cell<BorrowFlag>,
338     value: UnsafeCell<T>,
339 }
340
341 /// An enumeration of values returned from the `state` method on a `RefCell<T>`.
342 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
343 #[unstable(feature = "borrow_state", issue = "27733")]
344 pub enum BorrowState {
345     /// The cell is currently being read, there is at least one active `borrow`.
346     Reading,
347     /// The cell is currently being written to, there is an active `borrow_mut`.
348     Writing,
349     /// There are no outstanding borrows on this cell.
350     Unused,
351 }
352
353 /// An error returned by [`RefCell::try_borrow`](struct.RefCell.html#method.try_borrow).
354 #[unstable(feature = "try_borrow", issue = "35070")]
355 pub struct BorrowError<'a, T: 'a + ?Sized> {
356     marker: PhantomData<&'a RefCell<T>>,
357 }
358
359 #[unstable(feature = "try_borrow", issue = "35070")]
360 impl<'a, T: ?Sized> Debug for BorrowError<'a, T> {
361     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
362         f.debug_struct("BorrowError").finish()
363     }
364 }
365
366 #[unstable(feature = "try_borrow", issue = "35070")]
367 impl<'a, T: ?Sized> Display for BorrowError<'a, T> {
368     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
369         Display::fmt("already mutably borrowed", f)
370     }
371 }
372
373 /// An error returned by [`RefCell::try_borrow_mut`](struct.RefCell.html#method.try_borrow_mut).
374 #[unstable(feature = "try_borrow", issue = "35070")]
375 pub struct BorrowMutError<'a, T: 'a + ?Sized> {
376     marker: PhantomData<&'a RefCell<T>>,
377 }
378
379 #[unstable(feature = "try_borrow", issue = "35070")]
380 impl<'a, T: ?Sized> Debug for BorrowMutError<'a, T> {
381     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
382         f.debug_struct("BorrowMutError").finish()
383     }
384 }
385
386 #[unstable(feature = "try_borrow", issue = "35070")]
387 impl<'a, T: ?Sized> Display for BorrowMutError<'a, T> {
388     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
389         Display::fmt("already borrowed", f)
390     }
391 }
392
393 // Values [1, MAX-1] represent the number of `Ref` active
394 // (will not outgrow its range since `usize` is the size of the address space)
395 type BorrowFlag = usize;
396 const UNUSED: BorrowFlag = 0;
397 const WRITING: BorrowFlag = !0;
398
399 impl<T> RefCell<T> {
400     /// Creates a new `RefCell` containing `value`.
401     ///
402     /// # Examples
403     ///
404     /// ```
405     /// use std::cell::RefCell;
406     ///
407     /// let c = RefCell::new(5);
408     /// ```
409     #[stable(feature = "rust1", since = "1.0.0")]
410     #[inline]
411     pub const fn new(value: T) -> RefCell<T> {
412         RefCell {
413             value: UnsafeCell::new(value),
414             borrow: Cell::new(UNUSED),
415         }
416     }
417
418     /// Consumes the `RefCell`, returning the wrapped value.
419     ///
420     /// # Examples
421     ///
422     /// ```
423     /// use std::cell::RefCell;
424     ///
425     /// let c = RefCell::new(5);
426     ///
427     /// let five = c.into_inner();
428     /// ```
429     #[stable(feature = "rust1", since = "1.0.0")]
430     #[inline]
431     pub fn into_inner(self) -> T {
432         // Since this function takes `self` (the `RefCell`) by value, the
433         // compiler statically verifies that it is not currently borrowed.
434         // Therefore the following assertion is just a `debug_assert!`.
435         debug_assert!(self.borrow.get() == UNUSED);
436         unsafe { self.value.into_inner() }
437     }
438 }
439
440 impl<T: ?Sized> RefCell<T> {
441     /// Query the current state of this `RefCell`
442     ///
443     /// The returned value can be dispatched on to determine if a call to
444     /// `borrow` or `borrow_mut` would succeed.
445     ///
446     /// # Examples
447     ///
448     /// ```
449     /// #![feature(borrow_state)]
450     ///
451     /// use std::cell::{BorrowState, RefCell};
452     ///
453     /// let c = RefCell::new(5);
454     ///
455     /// match c.borrow_state() {
456     ///     BorrowState::Writing => println!("Cannot be borrowed"),
457     ///     BorrowState::Reading => println!("Cannot be borrowed mutably"),
458     ///     BorrowState::Unused => println!("Can be borrowed (mutably as well)"),
459     /// }
460     /// ```
461     #[unstable(feature = "borrow_state", issue = "27733")]
462     #[inline]
463     pub fn borrow_state(&self) -> BorrowState {
464         match self.borrow.get() {
465             WRITING => BorrowState::Writing,
466             UNUSED => BorrowState::Unused,
467             _ => BorrowState::Reading,
468         }
469     }
470
471     /// Immutably borrows the wrapped value.
472     ///
473     /// The borrow lasts until the returned `Ref` exits scope. Multiple
474     /// immutable borrows can be taken out at the same time.
475     ///
476     /// # Panics
477     ///
478     /// Panics if the value is currently mutably borrowed. For a non-panicking variant, use
479     /// [`try_borrow`](#method.try_borrow).
480     ///
481     /// # Examples
482     ///
483     /// ```
484     /// use std::cell::RefCell;
485     ///
486     /// let c = RefCell::new(5);
487     ///
488     /// let borrowed_five = c.borrow();
489     /// let borrowed_five2 = c.borrow();
490     /// ```
491     ///
492     /// An example of panic:
493     ///
494     /// ```
495     /// use std::cell::RefCell;
496     /// use std::thread;
497     ///
498     /// let result = thread::spawn(move || {
499     ///    let c = RefCell::new(5);
500     ///    let m = c.borrow_mut();
501     ///
502     ///    let b = c.borrow(); // this causes a panic
503     /// }).join();
504     ///
505     /// assert!(result.is_err());
506     /// ```
507     #[stable(feature = "rust1", since = "1.0.0")]
508     #[inline]
509     pub fn borrow(&self) -> Ref<T> {
510         self.try_borrow().expect("already mutably borrowed")
511     }
512
513     /// Immutably borrows the wrapped value, returning an error if the value is currently mutably
514     /// borrowed.
515     ///
516     /// The borrow lasts until the returned `Ref` exits scope. Multiple immutable borrows can be
517     /// taken out at the same time.
518     ///
519     /// This is the non-panicking variant of [`borrow`](#method.borrow).
520     ///
521     /// # Examples
522     ///
523     /// ```
524     /// #![feature(try_borrow)]
525     ///
526     /// use std::cell::RefCell;
527     ///
528     /// let c = RefCell::new(5);
529     ///
530     /// {
531     ///     let m = c.borrow_mut();
532     ///     assert!(c.try_borrow().is_err());
533     /// }
534     ///
535     /// {
536     ///     let m = c.borrow();
537     ///     assert!(c.try_borrow().is_ok());
538     /// }
539     /// ```
540     #[unstable(feature = "try_borrow", issue = "35070")]
541     #[inline]
542     pub fn try_borrow(&self) -> Result<Ref<T>, BorrowError<T>> {
543         match BorrowRef::new(&self.borrow) {
544             Some(b) => Ok(Ref {
545                 value: unsafe { &*self.value.get() },
546                 borrow: b,
547             }),
548             None => Err(BorrowError { marker: PhantomData }),
549         }
550     }
551
552     /// Mutably borrows the wrapped value.
553     ///
554     /// The borrow lasts until the returned `RefMut` exits scope. The value
555     /// cannot be borrowed while this borrow is active.
556     ///
557     /// # Panics
558     ///
559     /// Panics if the value is currently borrowed. For a non-panicking variant, use
560     /// [`try_borrow_mut`](#method.try_borrow_mut).
561     ///
562     /// # Examples
563     ///
564     /// ```
565     /// use std::cell::RefCell;
566     ///
567     /// let c = RefCell::new(5);
568     ///
569     /// *c.borrow_mut() = 7;
570     ///
571     /// assert_eq!(*c.borrow(), 7);
572     /// ```
573     ///
574     /// An example of panic:
575     ///
576     /// ```
577     /// use std::cell::RefCell;
578     /// use std::thread;
579     ///
580     /// let result = thread::spawn(move || {
581     ///    let c = RefCell::new(5);
582     ///    let m = c.borrow();
583     ///
584     ///    let b = c.borrow_mut(); // this causes a panic
585     /// }).join();
586     ///
587     /// assert!(result.is_err());
588     /// ```
589     #[stable(feature = "rust1", since = "1.0.0")]
590     #[inline]
591     pub fn borrow_mut(&self) -> RefMut<T> {
592         self.try_borrow_mut().expect("already borrowed")
593     }
594
595     /// Mutably borrows the wrapped value, returning an error if the value is currently borrowed.
596     ///
597     /// The borrow lasts until the returned `RefMut` exits scope. The value cannot be borrowed
598     /// while this borrow is active.
599     ///
600     /// This is the non-panicking variant of [`borrow_mut`](#method.borrow_mut).
601     ///
602     /// # Examples
603     ///
604     /// ```
605     /// #![feature(try_borrow)]
606     ///
607     /// use std::cell::RefCell;
608     ///
609     /// let c = RefCell::new(5);
610     ///
611     /// {
612     ///     let m = c.borrow();
613     ///     assert!(c.try_borrow_mut().is_err());
614     /// }
615     ///
616     /// assert!(c.try_borrow_mut().is_ok());
617     /// ```
618     #[unstable(feature = "try_borrow", issue = "35070")]
619     #[inline]
620     pub fn try_borrow_mut(&self) -> Result<RefMut<T>, BorrowMutError<T>> {
621         match BorrowRefMut::new(&self.borrow) {
622             Some(b) => Ok(RefMut {
623                 value: unsafe { &mut *self.value.get() },
624                 borrow: b,
625             }),
626             None => Err(BorrowMutError { marker: PhantomData }),
627         }
628     }
629
630     /// Returns a reference to the underlying `UnsafeCell`.
631     ///
632     /// This can be used to circumvent `RefCell`'s safety checks.
633     ///
634     /// This function is `unsafe` because `UnsafeCell`'s field is public.
635     ///
636     /// # Examples
637     ///
638     /// ```
639     /// #![feature(as_unsafe_cell)]
640     ///
641     /// use std::cell::RefCell;
642     ///
643     /// let c = RefCell::new(5);
644     /// let c = unsafe { c.as_unsafe_cell() };
645     /// ```
646     #[inline]
647     #[unstable(feature = "as_unsafe_cell", issue = "27708")]
648     pub unsafe fn as_unsafe_cell(&self) -> &UnsafeCell<T> {
649         &self.value
650     }
651
652     /// Returns a mutable reference to the underlying data.
653     ///
654     /// This call borrows `RefCell` mutably (at compile-time) so there is no
655     /// need for dynamic checks.
656     ///
657     /// # Examples
658     ///
659     /// ```
660     /// use std::cell::RefCell;
661     ///
662     /// let mut c = RefCell::new(5);
663     /// *c.get_mut() += 1;
664     ///
665     /// assert_eq!(c, RefCell::new(6));
666     /// ```
667     #[inline]
668     #[stable(feature = "cell_get_mut", since = "1.11.0")]
669     pub fn get_mut(&mut self) -> &mut T {
670         unsafe {
671             &mut *self.value.get()
672         }
673     }
674 }
675
676 #[stable(feature = "rust1", since = "1.0.0")]
677 unsafe impl<T: ?Sized> Send for RefCell<T> where T: Send {}
678
679 #[stable(feature = "rust1", since = "1.0.0")]
680 impl<T: ?Sized> !Sync for RefCell<T> {}
681
682 #[stable(feature = "rust1", since = "1.0.0")]
683 impl<T: Clone> Clone for RefCell<T> {
684     #[inline]
685     fn clone(&self) -> RefCell<T> {
686         RefCell::new(self.borrow().clone())
687     }
688 }
689
690 #[stable(feature = "rust1", since = "1.0.0")]
691 impl<T:Default> Default for RefCell<T> {
692     #[inline]
693     fn default() -> RefCell<T> {
694         RefCell::new(Default::default())
695     }
696 }
697
698 #[stable(feature = "rust1", since = "1.0.0")]
699 impl<T: ?Sized + PartialEq> PartialEq for RefCell<T> {
700     #[inline]
701     fn eq(&self, other: &RefCell<T>) -> bool {
702         *self.borrow() == *other.borrow()
703     }
704 }
705
706 #[stable(feature = "cell_eq", since = "1.2.0")]
707 impl<T: ?Sized + Eq> Eq for RefCell<T> {}
708
709 #[stable(feature = "cell_ord", since = "1.10.0")]
710 impl<T: ?Sized + PartialOrd> PartialOrd for RefCell<T> {
711     #[inline]
712     fn partial_cmp(&self, other: &RefCell<T>) -> Option<Ordering> {
713         self.borrow().partial_cmp(&*other.borrow())
714     }
715
716     #[inline]
717     fn lt(&self, other: &RefCell<T>) -> bool {
718         *self.borrow() < *other.borrow()
719     }
720
721     #[inline]
722     fn le(&self, other: &RefCell<T>) -> bool {
723         *self.borrow() <= *other.borrow()
724     }
725
726     #[inline]
727     fn gt(&self, other: &RefCell<T>) -> bool {
728         *self.borrow() > *other.borrow()
729     }
730
731     #[inline]
732     fn ge(&self, other: &RefCell<T>) -> bool {
733         *self.borrow() >= *other.borrow()
734     }
735 }
736
737 #[stable(feature = "cell_ord", since = "1.10.0")]
738 impl<T: ?Sized + Ord> Ord for RefCell<T> {
739     #[inline]
740     fn cmp(&self, other: &RefCell<T>) -> Ordering {
741         self.borrow().cmp(&*other.borrow())
742     }
743 }
744
745 struct BorrowRef<'b> {
746     borrow: &'b Cell<BorrowFlag>,
747 }
748
749 impl<'b> BorrowRef<'b> {
750     #[inline]
751     fn new(borrow: &'b Cell<BorrowFlag>) -> Option<BorrowRef<'b>> {
752         match borrow.get() {
753             WRITING => None,
754             b => {
755                 borrow.set(b + 1);
756                 Some(BorrowRef { borrow: borrow })
757             },
758         }
759     }
760 }
761
762 impl<'b> Drop for BorrowRef<'b> {
763     #[inline]
764     fn drop(&mut self) {
765         let borrow = self.borrow.get();
766         debug_assert!(borrow != WRITING && borrow != UNUSED);
767         self.borrow.set(borrow - 1);
768     }
769 }
770
771 impl<'b> Clone for BorrowRef<'b> {
772     #[inline]
773     fn clone(&self) -> BorrowRef<'b> {
774         // Since this Ref exists, we know the borrow flag
775         // is not set to WRITING.
776         let borrow = self.borrow.get();
777         debug_assert!(borrow != UNUSED);
778         // Prevent the borrow counter from overflowing.
779         assert!(borrow != WRITING);
780         self.borrow.set(borrow + 1);
781         BorrowRef { borrow: self.borrow }
782     }
783 }
784
785 /// Wraps a borrowed reference to a value in a `RefCell` box.
786 /// A wrapper type for an immutably borrowed value from a `RefCell<T>`.
787 ///
788 /// See the [module-level documentation](index.html) for more.
789 #[stable(feature = "rust1", since = "1.0.0")]
790 pub struct Ref<'b, T: ?Sized + 'b> {
791     value: &'b T,
792     borrow: BorrowRef<'b>,
793 }
794
795 #[stable(feature = "rust1", since = "1.0.0")]
796 impl<'b, T: ?Sized> Deref for Ref<'b, T> {
797     type Target = T;
798
799     #[inline]
800     fn deref(&self) -> &T {
801         self.value
802     }
803 }
804
805 impl<'b, T: ?Sized> Ref<'b, T> {
806     /// Copies a `Ref`.
807     ///
808     /// The `RefCell` is already immutably borrowed, so this cannot fail.
809     ///
810     /// This is an associated function that needs to be used as
811     /// `Ref::clone(...)`.  A `Clone` implementation or a method would interfere
812     /// with the widespread use of `r.borrow().clone()` to clone the contents of
813     /// a `RefCell`.
814     #[unstable(feature = "cell_extras",
815                reason = "likely to be moved to a method, pending language changes",
816                issue = "27746")]
817     #[inline]
818     pub fn clone(orig: &Ref<'b, T>) -> Ref<'b, T> {
819         Ref {
820             value: orig.value,
821             borrow: orig.borrow.clone(),
822         }
823     }
824
825     /// Make a new `Ref` for a component of the borrowed data.
826     ///
827     /// The `RefCell` is already immutably borrowed, so this cannot fail.
828     ///
829     /// This is an associated function that needs to be used as `Ref::map(...)`.
830     /// A method would interfere with methods of the same name on the contents
831     /// of a `RefCell` used through `Deref`.
832     ///
833     /// # Example
834     ///
835     /// ```
836     /// use std::cell::{RefCell, Ref};
837     ///
838     /// let c = RefCell::new((5, 'b'));
839     /// let b1: Ref<(u32, char)> = c.borrow();
840     /// let b2: Ref<u32> = Ref::map(b1, |t| &t.0);
841     /// assert_eq!(*b2, 5)
842     /// ```
843     #[stable(feature = "cell_map", since = "1.8.0")]
844     #[inline]
845     pub fn map<U: ?Sized, F>(orig: Ref<'b, T>, f: F) -> Ref<'b, U>
846         where F: FnOnce(&T) -> &U
847     {
848         Ref {
849             value: f(orig.value),
850             borrow: orig.borrow,
851         }
852     }
853 }
854
855 #[unstable(feature = "coerce_unsized", issue = "27732")]
856 impl<'b, T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Ref<'b, U>> for Ref<'b, T> {}
857
858 impl<'b, T: ?Sized> RefMut<'b, T> {
859     /// Make a new `RefMut` for a component of the borrowed data, e.g. an enum
860     /// variant.
861     ///
862     /// The `RefCell` is already mutably borrowed, so this cannot fail.
863     ///
864     /// This is an associated function that needs to be used as
865     /// `RefMut::map(...)`.  A method would interfere with methods of the same
866     /// name on the contents of a `RefCell` used through `Deref`.
867     ///
868     /// # Example
869     ///
870     /// ```
871     /// use std::cell::{RefCell, RefMut};
872     ///
873     /// let c = RefCell::new((5, 'b'));
874     /// {
875     ///     let b1: RefMut<(u32, char)> = c.borrow_mut();
876     ///     let mut b2: RefMut<u32> = RefMut::map(b1, |t| &mut t.0);
877     ///     assert_eq!(*b2, 5);
878     ///     *b2 = 42;
879     /// }
880     /// assert_eq!(*c.borrow(), (42, 'b'));
881     /// ```
882     #[stable(feature = "cell_map", since = "1.8.0")]
883     #[inline]
884     pub fn map<U: ?Sized, F>(orig: RefMut<'b, T>, f: F) -> RefMut<'b, U>
885         where F: FnOnce(&mut T) -> &mut U
886     {
887         RefMut {
888             value: f(orig.value),
889             borrow: orig.borrow,
890         }
891     }
892 }
893
894 struct BorrowRefMut<'b> {
895     borrow: &'b Cell<BorrowFlag>,
896 }
897
898 impl<'b> Drop for BorrowRefMut<'b> {
899     #[inline]
900     fn drop(&mut self) {
901         let borrow = self.borrow.get();
902         debug_assert!(borrow == WRITING);
903         self.borrow.set(UNUSED);
904     }
905 }
906
907 impl<'b> BorrowRefMut<'b> {
908     #[inline]
909     fn new(borrow: &'b Cell<BorrowFlag>) -> Option<BorrowRefMut<'b>> {
910         match borrow.get() {
911             UNUSED => {
912                 borrow.set(WRITING);
913                 Some(BorrowRefMut { borrow: borrow })
914             },
915             _ => None,
916         }
917     }
918 }
919
920 /// A wrapper type for a mutably borrowed value from a `RefCell<T>`.
921 ///
922 /// See the [module-level documentation](index.html) for more.
923 #[stable(feature = "rust1", since = "1.0.0")]
924 pub struct RefMut<'b, T: ?Sized + 'b> {
925     value: &'b mut T,
926     borrow: BorrowRefMut<'b>,
927 }
928
929 #[stable(feature = "rust1", since = "1.0.0")]
930 impl<'b, T: ?Sized> Deref for RefMut<'b, T> {
931     type Target = T;
932
933     #[inline]
934     fn deref(&self) -> &T {
935         self.value
936     }
937 }
938
939 #[stable(feature = "rust1", since = "1.0.0")]
940 impl<'b, T: ?Sized> DerefMut for RefMut<'b, T> {
941     #[inline]
942     fn deref_mut(&mut self) -> &mut T {
943         self.value
944     }
945 }
946
947 #[unstable(feature = "coerce_unsized", issue = "27732")]
948 impl<'b, T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<RefMut<'b, U>> for RefMut<'b, T> {}
949
950 /// The core primitive for interior mutability in Rust.
951 ///
952 /// `UnsafeCell<T>` is a type that wraps some `T` and indicates unsafe interior operations on the
953 /// wrapped type. Types with an `UnsafeCell<T>` field are considered to have an 'unsafe interior'.
954 /// The `UnsafeCell<T>` type is the only legal way to obtain aliasable data that is considered
955 /// mutable. In general, transmuting an `&T` type into an `&mut T` is considered undefined behavior.
956 ///
957 /// The compiler makes optimizations based on the knowledge that `&T` is not mutably aliased or
958 /// mutated, and that `&mut T` is unique. When building abstractions like `Cell`, `RefCell`,
959 /// `Mutex`, etc, you need to turn these optimizations off. `UnsafeCell` is the only legal way
960 /// to do this. When `UnsafeCell<T>` is immutably aliased, it is still safe to obtain a mutable
961 /// reference to its interior and/or to mutate it. However, it is up to the abstraction designer
962 /// to ensure that no two mutable references obtained this way are active at the same time, and
963 /// that there are no active mutable references or mutations when an immutable reference is obtained
964 /// from the cell. This is often done via runtime checks.
965 ///
966 /// Note that while mutating or mutably aliasing the contents of an `& UnsafeCell<T>` is
967 /// okay (provided you enforce the invariants some other way); it is still undefined behavior
968 /// to have multiple `&mut UnsafeCell<T>` aliases.
969 ///
970 ///
971 /// Types like `Cell<T>` and `RefCell<T>` use this type to wrap their internal data.
972 ///
973 /// # Examples
974 ///
975 /// ```
976 /// use std::cell::UnsafeCell;
977 /// use std::marker::Sync;
978 ///
979 /// # #[allow(dead_code)]
980 /// struct NotThreadSafe<T> {
981 ///     value: UnsafeCell<T>,
982 /// }
983 ///
984 /// unsafe impl<T> Sync for NotThreadSafe<T> {}
985 /// ```
986 #[lang = "unsafe_cell"]
987 #[stable(feature = "rust1", since = "1.0.0")]
988 pub struct UnsafeCell<T: ?Sized> {
989     value: T,
990 }
991
992 #[stable(feature = "rust1", since = "1.0.0")]
993 impl<T: ?Sized> !Sync for UnsafeCell<T> {}
994
995 impl<T> UnsafeCell<T> {
996     /// Constructs a new instance of `UnsafeCell` which will wrap the specified
997     /// value.
998     ///
999     /// All access to the inner value through methods is `unsafe`.
1000     ///
1001     /// # Examples
1002     ///
1003     /// ```
1004     /// use std::cell::UnsafeCell;
1005     ///
1006     /// let uc = UnsafeCell::new(5);
1007     /// ```
1008     #[stable(feature = "rust1", since = "1.0.0")]
1009     #[inline]
1010     pub const fn new(value: T) -> UnsafeCell<T> {
1011         UnsafeCell { value: value }
1012     }
1013
1014     /// Unwraps the value.
1015     ///
1016     /// # Safety
1017     ///
1018     /// This function is unsafe because this thread or another thread may currently be
1019     /// inspecting the inner value.
1020     ///
1021     /// # Examples
1022     ///
1023     /// ```
1024     /// use std::cell::UnsafeCell;
1025     ///
1026     /// let uc = UnsafeCell::new(5);
1027     ///
1028     /// let five = unsafe { uc.into_inner() };
1029     /// ```
1030     #[inline]
1031     #[stable(feature = "rust1", since = "1.0.0")]
1032     pub unsafe fn into_inner(self) -> T {
1033         self.value
1034     }
1035 }
1036
1037 impl<T: ?Sized> UnsafeCell<T> {
1038     /// Gets a mutable pointer to the wrapped value.
1039     ///
1040     /// This can be cast to a pointer of any kind.
1041     /// Ensure that the access is unique when casting to
1042     /// `&mut T`, and ensure that there are no mutations or mutable
1043     /// aliases going on when casting to `&T`
1044     ///
1045     /// # Examples
1046     ///
1047     /// ```
1048     /// use std::cell::UnsafeCell;
1049     ///
1050     /// let uc = UnsafeCell::new(5);
1051     ///
1052     /// let five = uc.get();
1053     /// ```
1054     #[inline]
1055     #[stable(feature = "rust1", since = "1.0.0")]
1056     pub fn get(&self) -> *mut T {
1057         &self.value as *const T as *mut T
1058     }
1059 }
1060
1061 #[stable(feature = "unsafe_cell_default", since = "1.9.0")]
1062 impl<T: Default> Default for UnsafeCell<T> {
1063     fn default() -> UnsafeCell<T> {
1064         UnsafeCell::new(Default::default())
1065     }
1066 }