]> git.lizzy.rs Git - rust.git/blob - src/libcore/cell.rs
Add `get_mut` methods to the `RefCell` and `Cell`
[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};
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     #[inline]
241     #[unstable(feature = "cell_get_mut", issue = "33444")]
242     pub fn get_mut(&mut self) -> &mut T {
243         unsafe {
244             &mut *self.value.get()
245         }
246     }
247 }
248
249 #[stable(feature = "rust1", since = "1.0.0")]
250 unsafe impl<T> Send for Cell<T> where T: Send {}
251
252 #[stable(feature = "rust1", since = "1.0.0")]
253 impl<T> !Sync for Cell<T> {}
254
255 #[stable(feature = "rust1", since = "1.0.0")]
256 impl<T:Copy> Clone for Cell<T> {
257     #[inline]
258     fn clone(&self) -> Cell<T> {
259         Cell::new(self.get())
260     }
261 }
262
263 #[stable(feature = "rust1", since = "1.0.0")]
264 impl<T:Default + Copy> Default for Cell<T> {
265     #[inline]
266     fn default() -> Cell<T> {
267         Cell::new(Default::default())
268     }
269 }
270
271 #[stable(feature = "rust1", since = "1.0.0")]
272 impl<T:PartialEq + Copy> PartialEq for Cell<T> {
273     #[inline]
274     fn eq(&self, other: &Cell<T>) -> bool {
275         self.get() == other.get()
276     }
277 }
278
279 #[stable(feature = "cell_eq", since = "1.2.0")]
280 impl<T:Eq + Copy> Eq for Cell<T> {}
281
282 /// A mutable memory location with dynamically checked borrow rules
283 ///
284 /// See the [module-level documentation](index.html) for more.
285 #[stable(feature = "rust1", since = "1.0.0")]
286 pub struct RefCell<T: ?Sized> {
287     borrow: Cell<BorrowFlag>,
288     value: UnsafeCell<T>,
289 }
290
291 /// An enumeration of values returned from the `state` method on a `RefCell<T>`.
292 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
293 #[unstable(feature = "borrow_state", issue = "27733")]
294 pub enum BorrowState {
295     /// The cell is currently being read, there is at least one active `borrow`.
296     Reading,
297     /// The cell is currently being written to, there is an active `borrow_mut`.
298     Writing,
299     /// There are no outstanding borrows on this cell.
300     Unused,
301 }
302
303 // Values [1, MAX-1] represent the number of `Ref` active
304 // (will not outgrow its range since `usize` is the size of the address space)
305 type BorrowFlag = usize;
306 const UNUSED: BorrowFlag = 0;
307 const WRITING: BorrowFlag = !0;
308
309 impl<T> RefCell<T> {
310     /// Creates a new `RefCell` containing `value`.
311     ///
312     /// # Examples
313     ///
314     /// ```
315     /// use std::cell::RefCell;
316     ///
317     /// let c = RefCell::new(5);
318     /// ```
319     #[stable(feature = "rust1", since = "1.0.0")]
320     #[inline]
321     pub const fn new(value: T) -> RefCell<T> {
322         RefCell {
323             value: UnsafeCell::new(value),
324             borrow: Cell::new(UNUSED),
325         }
326     }
327
328     /// Consumes the `RefCell`, returning the wrapped value.
329     ///
330     /// # Examples
331     ///
332     /// ```
333     /// use std::cell::RefCell;
334     ///
335     /// let c = RefCell::new(5);
336     ///
337     /// let five = c.into_inner();
338     /// ```
339     #[stable(feature = "rust1", since = "1.0.0")]
340     #[inline]
341     pub fn into_inner(self) -> T {
342         // Since this function takes `self` (the `RefCell`) by value, the
343         // compiler statically verifies that it is not currently borrowed.
344         // Therefore the following assertion is just a `debug_assert!`.
345         debug_assert!(self.borrow.get() == UNUSED);
346         unsafe { self.value.into_inner() }
347     }
348 }
349
350 impl<T: ?Sized> RefCell<T> {
351     /// Query the current state of this `RefCell`
352     ///
353     /// The returned value can be dispatched on to determine if a call to
354     /// `borrow` or `borrow_mut` would succeed.
355     #[unstable(feature = "borrow_state", issue = "27733")]
356     #[inline]
357     pub fn borrow_state(&self) -> BorrowState {
358         match self.borrow.get() {
359             WRITING => BorrowState::Writing,
360             UNUSED => BorrowState::Unused,
361             _ => BorrowState::Reading,
362         }
363     }
364
365     /// Immutably borrows the wrapped value.
366     ///
367     /// The borrow lasts until the returned `Ref` exits scope. Multiple
368     /// immutable borrows can be taken out at the same time.
369     ///
370     /// # Panics
371     ///
372     /// Panics if the value is currently mutably borrowed.
373     ///
374     /// # Examples
375     ///
376     /// ```
377     /// use std::cell::RefCell;
378     ///
379     /// let c = RefCell::new(5);
380     ///
381     /// let borrowed_five = c.borrow();
382     /// let borrowed_five2 = c.borrow();
383     /// ```
384     ///
385     /// An example of panic:
386     ///
387     /// ```
388     /// use std::cell::RefCell;
389     /// use std::thread;
390     ///
391     /// let result = thread::spawn(move || {
392     ///    let c = RefCell::new(5);
393     ///    let m = c.borrow_mut();
394     ///
395     ///    let b = c.borrow(); // this causes a panic
396     /// }).join();
397     ///
398     /// assert!(result.is_err());
399     /// ```
400     #[stable(feature = "rust1", since = "1.0.0")]
401     #[inline]
402     pub fn borrow(&self) -> Ref<T> {
403         match BorrowRef::new(&self.borrow) {
404             Some(b) => Ref {
405                 value: unsafe { &*self.value.get() },
406                 borrow: b,
407             },
408             None => panic!("RefCell<T> already mutably borrowed"),
409         }
410     }
411
412     /// Mutably borrows the wrapped value.
413     ///
414     /// The borrow lasts until the returned `RefMut` exits scope. The value
415     /// cannot be borrowed while this borrow is active.
416     ///
417     /// # Panics
418     ///
419     /// Panics if the value is currently borrowed.
420     ///
421     /// # Examples
422     ///
423     /// ```
424     /// use std::cell::RefCell;
425     ///
426     /// let c = RefCell::new(5);
427     ///
428     /// *c.borrow_mut() = 7;
429     ///
430     /// assert_eq!(*c.borrow(), 7);
431     /// ```
432     ///
433     /// An example of panic:
434     ///
435     /// ```
436     /// use std::cell::RefCell;
437     /// use std::thread;
438     ///
439     /// let result = thread::spawn(move || {
440     ///    let c = RefCell::new(5);
441     ///    let m = c.borrow();
442     ///
443     ///    let b = c.borrow_mut(); // this causes a panic
444     /// }).join();
445     ///
446     /// assert!(result.is_err());
447     /// ```
448     #[stable(feature = "rust1", since = "1.0.0")]
449     #[inline]
450     pub fn borrow_mut(&self) -> RefMut<T> {
451         match BorrowRefMut::new(&self.borrow) {
452             Some(b) => RefMut {
453                 value: unsafe { &mut *self.value.get() },
454                 borrow: b,
455             },
456             None => panic!("RefCell<T> already borrowed"),
457         }
458     }
459
460     /// Returns a reference to the underlying `UnsafeCell`.
461     ///
462     /// This can be used to circumvent `RefCell`'s safety checks.
463     ///
464     /// This function is `unsafe` because `UnsafeCell`'s field is public.
465     #[inline]
466     #[unstable(feature = "as_unsafe_cell", issue = "27708")]
467     pub unsafe fn as_unsafe_cell(&self) -> &UnsafeCell<T> {
468         &self.value
469     }
470
471     /// Returns a mutable reference to the underlying data.
472     ///
473     /// This call borrows `RefCell` mutably (at compile-time) so there is no
474     /// need for dynamic checks.
475     #[inline]
476     #[unstable(feature = "cell_get_mut", issue="33444")]
477     pub fn get_mut(&mut self) -> &mut T {
478         unsafe {
479             &mut *self.value.get()
480         }
481     }
482 }
483
484 #[stable(feature = "rust1", since = "1.0.0")]
485 unsafe impl<T: ?Sized> Send for RefCell<T> where T: Send {}
486
487 #[stable(feature = "rust1", since = "1.0.0")]
488 impl<T: ?Sized> !Sync for RefCell<T> {}
489
490 #[stable(feature = "rust1", since = "1.0.0")]
491 impl<T: Clone> Clone for RefCell<T> {
492     #[inline]
493     fn clone(&self) -> RefCell<T> {
494         RefCell::new(self.borrow().clone())
495     }
496 }
497
498 #[stable(feature = "rust1", since = "1.0.0")]
499 impl<T:Default> Default for RefCell<T> {
500     #[inline]
501     fn default() -> RefCell<T> {
502         RefCell::new(Default::default())
503     }
504 }
505
506 #[stable(feature = "rust1", since = "1.0.0")]
507 impl<T: ?Sized + PartialEq> PartialEq for RefCell<T> {
508     #[inline]
509     fn eq(&self, other: &RefCell<T>) -> bool {
510         *self.borrow() == *other.borrow()
511     }
512 }
513
514 #[stable(feature = "cell_eq", since = "1.2.0")]
515 impl<T: ?Sized + Eq> Eq for RefCell<T> {}
516
517 struct BorrowRef<'b> {
518     borrow: &'b Cell<BorrowFlag>,
519 }
520
521 impl<'b> BorrowRef<'b> {
522     #[inline]
523     fn new(borrow: &'b Cell<BorrowFlag>) -> Option<BorrowRef<'b>> {
524         match borrow.get() {
525             WRITING => None,
526             b => {
527                 borrow.set(b + 1);
528                 Some(BorrowRef { borrow: borrow })
529             },
530         }
531     }
532 }
533
534 impl<'b> Drop for BorrowRef<'b> {
535     #[inline]
536     fn drop(&mut self) {
537         let borrow = self.borrow.get();
538         debug_assert!(borrow != WRITING && borrow != UNUSED);
539         self.borrow.set(borrow - 1);
540     }
541 }
542
543 impl<'b> Clone for BorrowRef<'b> {
544     #[inline]
545     fn clone(&self) -> BorrowRef<'b> {
546         // Since this Ref exists, we know the borrow flag
547         // is not set to WRITING.
548         let borrow = self.borrow.get();
549         debug_assert!(borrow != WRITING && borrow != UNUSED);
550         self.borrow.set(borrow + 1);
551         BorrowRef { borrow: self.borrow }
552     }
553 }
554
555 /// Wraps a borrowed reference to a value in a `RefCell` box.
556 /// A wrapper type for an immutably borrowed value from a `RefCell<T>`.
557 ///
558 /// See the [module-level documentation](index.html) for more.
559 #[stable(feature = "rust1", since = "1.0.0")]
560 pub struct Ref<'b, T: ?Sized + 'b> {
561     value: &'b T,
562     borrow: BorrowRef<'b>,
563 }
564
565 #[stable(feature = "rust1", since = "1.0.0")]
566 impl<'b, T: ?Sized> Deref for Ref<'b, T> {
567     type Target = T;
568
569     #[inline]
570     fn deref(&self) -> &T {
571         self.value
572     }
573 }
574
575 impl<'b, T: ?Sized> Ref<'b, T> {
576     /// Copies a `Ref`.
577     ///
578     /// The `RefCell` is already immutably borrowed, so this cannot fail.
579     ///
580     /// This is an associated function that needs to be used as
581     /// `Ref::clone(...)`.  A `Clone` implementation or a method would interfere
582     /// with the widespread use of `r.borrow().clone()` to clone the contents of
583     /// a `RefCell`.
584     #[unstable(feature = "cell_extras",
585                reason = "likely to be moved to a method, pending language changes",
586                issue = "27746")]
587     #[inline]
588     pub fn clone(orig: &Ref<'b, T>) -> Ref<'b, T> {
589         Ref {
590             value: orig.value,
591             borrow: orig.borrow.clone(),
592         }
593     }
594
595     /// Make a new `Ref` for a component of the borrowed data.
596     ///
597     /// The `RefCell` is already immutably borrowed, so this cannot fail.
598     ///
599     /// This is an associated function that needs to be used as `Ref::map(...)`.
600     /// A method would interfere with methods of the same name on the contents
601     /// of a `RefCell` used through `Deref`.
602     ///
603     /// # Example
604     ///
605     /// ```
606     /// use std::cell::{RefCell, Ref};
607     ///
608     /// let c = RefCell::new((5, 'b'));
609     /// let b1: Ref<(u32, char)> = c.borrow();
610     /// let b2: Ref<u32> = Ref::map(b1, |t| &t.0);
611     /// assert_eq!(*b2, 5)
612     /// ```
613     #[stable(feature = "cell_map", since = "1.8.0")]
614     #[inline]
615     pub fn map<U: ?Sized, F>(orig: Ref<'b, T>, f: F) -> Ref<'b, U>
616         where F: FnOnce(&T) -> &U
617     {
618         Ref {
619             value: f(orig.value),
620             borrow: orig.borrow,
621         }
622     }
623
624     /// Make a new `Ref` for an optional component of the borrowed data, e.g. an
625     /// enum variant.
626     ///
627     /// The `RefCell` is already immutably borrowed, so this cannot fail.
628     ///
629     /// This is an associated function that needs to be used as
630     /// `Ref::filter_map(...)`.  A method would interfere with methods of the
631     /// same name on the contents of a `RefCell` used through `Deref`.
632     ///
633     /// # Example
634     ///
635     /// ```
636     /// # #![feature(cell_extras)]
637     /// use std::cell::{RefCell, Ref};
638     ///
639     /// let c = RefCell::new(Ok(5));
640     /// let b1: Ref<Result<u32, ()>> = c.borrow();
641     /// let b2: Ref<u32> = Ref::filter_map(b1, |o| o.as_ref().ok()).unwrap();
642     /// assert_eq!(*b2, 5)
643     /// ```
644     #[unstable(feature = "cell_extras", reason = "recently added",
645                issue = "27746")]
646     #[rustc_deprecated(since = "1.8.0", reason = "can be built on `Ref::map`: \
647         https://crates.io/crates/ref_filter_map")]
648     #[inline]
649     pub fn filter_map<U: ?Sized, F>(orig: Ref<'b, T>, f: F) -> Option<Ref<'b, U>>
650         where F: FnOnce(&T) -> Option<&U>
651     {
652         f(orig.value).map(move |new| Ref {
653             value: new,
654             borrow: orig.borrow,
655         })
656     }
657 }
658
659 #[unstable(feature = "coerce_unsized", issue = "27732")]
660 impl<'b, T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Ref<'b, U>> for Ref<'b, T> {}
661
662 impl<'b, T: ?Sized> RefMut<'b, T> {
663     /// Make a new `RefMut` for a component of the borrowed data, e.g. an enum
664     /// variant.
665     ///
666     /// The `RefCell` is already mutably borrowed, so this cannot fail.
667     ///
668     /// This is an associated function that needs to be used as
669     /// `RefMut::map(...)`.  A method would interfere with methods of the same
670     /// name on the contents of a `RefCell` used through `Deref`.
671     ///
672     /// # Example
673     ///
674     /// ```
675     /// use std::cell::{RefCell, RefMut};
676     ///
677     /// let c = RefCell::new((5, 'b'));
678     /// {
679     ///     let b1: RefMut<(u32, char)> = c.borrow_mut();
680     ///     let mut b2: RefMut<u32> = RefMut::map(b1, |t| &mut t.0);
681     ///     assert_eq!(*b2, 5);
682     ///     *b2 = 42;
683     /// }
684     /// assert_eq!(*c.borrow(), (42, 'b'));
685     /// ```
686     #[stable(feature = "cell_map", since = "1.8.0")]
687     #[inline]
688     pub fn map<U: ?Sized, F>(orig: RefMut<'b, T>, f: F) -> RefMut<'b, U>
689         where F: FnOnce(&mut T) -> &mut U
690     {
691         RefMut {
692             value: f(orig.value),
693             borrow: orig.borrow,
694         }
695     }
696
697     /// Make a new `RefMut` for an optional component of the borrowed data, e.g.
698     /// an enum variant.
699     ///
700     /// The `RefCell` is already mutably borrowed, so this cannot fail.
701     ///
702     /// This is an associated function that needs to be used as
703     /// `RefMut::filter_map(...)`.  A method would interfere with methods of the
704     /// same name on the contents of a `RefCell` used through `Deref`.
705     ///
706     /// # Example
707     ///
708     /// ```
709     /// # #![feature(cell_extras)]
710     /// use std::cell::{RefCell, RefMut};
711     ///
712     /// let c = RefCell::new(Ok(5));
713     /// {
714     ///     let b1: RefMut<Result<u32, ()>> = c.borrow_mut();
715     ///     let mut b2: RefMut<u32> = RefMut::filter_map(b1, |o| {
716     ///         o.as_mut().ok()
717     ///     }).unwrap();
718     ///     assert_eq!(*b2, 5);
719     ///     *b2 = 42;
720     /// }
721     /// assert_eq!(*c.borrow(), Ok(42));
722     /// ```
723     #[unstable(feature = "cell_extras", reason = "recently added",
724                issue = "27746")]
725     #[rustc_deprecated(since = "1.8.0", reason = "can be built on `RefMut::map`: \
726         https://crates.io/crates/ref_filter_map")]
727     #[inline]
728     pub fn filter_map<U: ?Sized, F>(orig: RefMut<'b, T>, f: F) -> Option<RefMut<'b, U>>
729         where F: FnOnce(&mut T) -> Option<&mut U>
730     {
731         let RefMut { value, borrow } = orig;
732         f(value).map(move |new| RefMut {
733             value: new,
734             borrow: borrow,
735         })
736     }
737 }
738
739 struct BorrowRefMut<'b> {
740     borrow: &'b Cell<BorrowFlag>,
741 }
742
743 impl<'b> Drop for BorrowRefMut<'b> {
744     #[inline]
745     fn drop(&mut self) {
746         let borrow = self.borrow.get();
747         debug_assert!(borrow == WRITING);
748         self.borrow.set(UNUSED);
749     }
750 }
751
752 impl<'b> BorrowRefMut<'b> {
753     #[inline]
754     fn new(borrow: &'b Cell<BorrowFlag>) -> Option<BorrowRefMut<'b>> {
755         match borrow.get() {
756             UNUSED => {
757                 borrow.set(WRITING);
758                 Some(BorrowRefMut { borrow: borrow })
759             },
760             _ => None,
761         }
762     }
763 }
764
765 /// A wrapper type for a mutably borrowed value from a `RefCell<T>`.
766 ///
767 /// See the [module-level documentation](index.html) for more.
768 #[stable(feature = "rust1", since = "1.0.0")]
769 pub struct RefMut<'b, T: ?Sized + 'b> {
770     value: &'b mut T,
771     borrow: BorrowRefMut<'b>,
772 }
773
774 #[stable(feature = "rust1", since = "1.0.0")]
775 impl<'b, T: ?Sized> Deref for RefMut<'b, T> {
776     type Target = T;
777
778     #[inline]
779     fn deref(&self) -> &T {
780         self.value
781     }
782 }
783
784 #[stable(feature = "rust1", since = "1.0.0")]
785 impl<'b, T: ?Sized> DerefMut for RefMut<'b, T> {
786     #[inline]
787     fn deref_mut(&mut self) -> &mut T {
788         self.value
789     }
790 }
791
792 #[unstable(feature = "coerce_unsized", issue = "27732")]
793 impl<'b, T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<RefMut<'b, U>> for RefMut<'b, T> {}
794
795 /// The core primitive for interior mutability in Rust.
796 ///
797 /// `UnsafeCell<T>` is a type that wraps some `T` and indicates unsafe interior operations on the
798 /// wrapped type. Types with an `UnsafeCell<T>` field are considered to have an 'unsafe interior'.
799 /// The `UnsafeCell<T>` type is the only legal way to obtain aliasable data that is considered
800 /// mutable. In general, transmuting an `&T` type into an `&mut T` is considered undefined behavior.
801 ///
802 /// Types like `Cell<T>` and `RefCell<T>` use this type to wrap their internal data.
803 ///
804 /// # Examples
805 ///
806 /// ```
807 /// use std::cell::UnsafeCell;
808 /// use std::marker::Sync;
809 ///
810 /// # #[allow(dead_code)]
811 /// struct NotThreadSafe<T> {
812 ///     value: UnsafeCell<T>,
813 /// }
814 ///
815 /// unsafe impl<T> Sync for NotThreadSafe<T> {}
816 /// ```
817 #[lang = "unsafe_cell"]
818 #[stable(feature = "rust1", since = "1.0.0")]
819 pub struct UnsafeCell<T: ?Sized> {
820     value: T,
821 }
822
823 #[stable(feature = "rust1", since = "1.0.0")]
824 impl<T: ?Sized> !Sync for UnsafeCell<T> {}
825
826 impl<T> UnsafeCell<T> {
827     /// Constructs a new instance of `UnsafeCell` which will wrap the specified
828     /// value.
829     ///
830     /// All access to the inner value through methods is `unsafe`.
831     ///
832     /// # Examples
833     ///
834     /// ```
835     /// use std::cell::UnsafeCell;
836     ///
837     /// let uc = UnsafeCell::new(5);
838     /// ```
839     #[stable(feature = "rust1", since = "1.0.0")]
840     #[inline]
841     pub const fn new(value: T) -> UnsafeCell<T> {
842         UnsafeCell { value: value }
843     }
844
845     /// Unwraps the value.
846     ///
847     /// # Safety
848     ///
849     /// This function is unsafe because this thread or another thread may currently be
850     /// inspecting the inner value.
851     ///
852     /// # Examples
853     ///
854     /// ```
855     /// use std::cell::UnsafeCell;
856     ///
857     /// let uc = UnsafeCell::new(5);
858     ///
859     /// let five = unsafe { uc.into_inner() };
860     /// ```
861     #[inline]
862     #[stable(feature = "rust1", since = "1.0.0")]
863     pub unsafe fn into_inner(self) -> T {
864         self.value
865     }
866 }
867
868 impl<T: ?Sized> UnsafeCell<T> {
869     /// Gets a mutable pointer to the wrapped value.
870     ///
871     /// # Examples
872     ///
873     /// ```
874     /// use std::cell::UnsafeCell;
875     ///
876     /// let uc = UnsafeCell::new(5);
877     ///
878     /// let five = uc.get();
879     /// ```
880     #[inline]
881     #[stable(feature = "rust1", since = "1.0.0")]
882     pub fn get(&self) -> *mut T {
883         &self.value as *const T as *mut T
884     }
885 }
886
887 #[stable(feature = "unsafe_cell_default", since = "1.9.0")]
888 impl<T: Default> Default for UnsafeCell<T> {
889     fn default() -> UnsafeCell<T> {
890         UnsafeCell::new(Default::default())
891     }
892 }