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