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