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