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