]> git.lizzy.rs Git - rust.git/blob - src/libcore/cell.rs
175dabaf1d2cb999f070e9944b24a3ef6aaf0733
[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 inherited mutability roots to shared types.
40 //! * Implementation details of logically-immutable methods.
41 //! * Mutating implementations of `Clone`.
42 //!
43 //! ## Introducing inherited mutability roots to shared types
44 //!
45 //! 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 as shared references, not mutable references.
48 //! Without cells it would be impossible to mutate data inside of shared boxes 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 `Mutex<T>` if you need shared mutability in a multi-threaded
69 //! 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 //! use std::cell::RefCell;
80 //!
81 //! struct Graph {
82 //!     edges: Vec<(i32, i32)>,
83 //!     span_tree_cache: RefCell<Option<Vec<(i32, i32)>>>
84 //! }
85 //!
86 //! impl Graph {
87 //!     fn minimum_spanning_tree(&self) -> Vec<(i32, i32)> {
88 //!         // Create a new scope to contain the lifetime of the
89 //!         // dynamic borrow
90 //!         {
91 //!             // Take a reference to the inside of cache cell
92 //!             let mut cache = self.span_tree_cache.borrow_mut();
93 //!             if cache.is_some() {
94 //!                 return cache.as_ref().unwrap().clone();
95 //!             }
96 //!
97 //!             let span_tree = self.calc_span_tree();
98 //!             *cache = Some(span_tree);
99 //!         }
100 //!
101 //!         // Recursive call to return the just-cached value.
102 //!         // Note that if we had not let the previous borrow
103 //!         // of the cache fall out of scope then the subsequent
104 //!         // recursive borrow would cause a dynamic thread panic.
105 //!         // This is the major hazard of using `RefCell`.
106 //!         self.minimum_spanning_tree()
107 //!     }
108 //! #   fn calc_span_tree(&self) -> Vec<(i32, i32)> { vec![] }
109 //! }
110 //! ```
111 //!
112 //! ## Mutating implementations of `Clone`
113 //!
114 //! This is simply a special - but common - case of the previous: hiding mutability for operations
115 //! that appear to be immutable. The `clone` method is expected to not change the source value, and
116 //! is declared to take `&self`, not `&mut self`. Therefore any mutation that happens in the
117 //! `clone` method must use cell types. For example, `Rc<T>` maintains its reference counts within a
118 //! `Cell<T>`.
119 //!
120 //! ```
121 //! use std::cell::Cell;
122 //!
123 //! struct Rc<T> {
124 //!     ptr: *mut RcBox<T>
125 //! }
126 //!
127 //! struct RcBox<T> {
128 //!     value: T,
129 //!     refcount: Cell<usize>
130 //! }
131 //!
132 //! impl<T> Clone for Rc<T> {
133 //!     fn clone(&self) -> Rc<T> {
134 //!         unsafe {
135 //!             (*self.ptr).refcount.set((*self.ptr).refcount.get() + 1);
136 //!             Rc { ptr: self.ptr }
137 //!         }
138 //!     }
139 //! }
140 //! ```
141 //!
142
143 #![stable(feature = "rust1", since = "1.0.0")]
144
145 use clone::Clone;
146 use cmp::{PartialEq, Eq};
147 use default::Default;
148 use marker::{Copy, Send, Sync, Sized};
149 use ops::{Deref, DerefMut, Drop, FnOnce};
150 use option::Option;
151 use option::Option::{None, Some};
152
153 /// A mutable memory location that admits only `Copy` data.
154 ///
155 /// See the [module-level documentation](index.html) for more.
156 #[stable(feature = "rust1", since = "1.0.0")]
157 pub struct Cell<T> {
158     value: UnsafeCell<T>,
159 }
160
161 impl<T:Copy> Cell<T> {
162     /// Creates a new `Cell` containing the given value.
163     ///
164     /// # Examples
165     ///
166     /// ```
167     /// use std::cell::Cell;
168     ///
169     /// let c = Cell::new(5);
170     /// ```
171     #[stable(feature = "rust1", since = "1.0.0")]
172     #[inline]
173     pub const fn new(value: T) -> Cell<T> {
174         Cell {
175             value: UnsafeCell::new(value),
176         }
177     }
178
179     /// Returns a copy of the contained value.
180     ///
181     /// # Examples
182     ///
183     /// ```
184     /// use std::cell::Cell;
185     ///
186     /// let c = Cell::new(5);
187     ///
188     /// let five = c.get();
189     /// ```
190     #[inline]
191     #[stable(feature = "rust1", since = "1.0.0")]
192     pub fn get(&self) -> T {
193         unsafe{ *self.value.get() }
194     }
195
196     /// Sets the contained value.
197     ///
198     /// # Examples
199     ///
200     /// ```
201     /// use std::cell::Cell;
202     ///
203     /// let c = Cell::new(5);
204     ///
205     /// c.set(10);
206     /// ```
207     #[inline]
208     #[stable(feature = "rust1", since = "1.0.0")]
209     pub fn set(&self, value: T) {
210         unsafe {
211             *self.value.get() = value;
212         }
213     }
214
215     /// Returns a reference to the underlying `UnsafeCell`.
216     ///
217     /// # Unsafety
218     ///
219     /// This function is `unsafe` because `UnsafeCell`'s field is public.
220     ///
221     /// # Examples
222     ///
223     /// ```
224     /// # #![feature(core)]
225     /// use std::cell::Cell;
226     ///
227     /// let c = Cell::new(5);
228     ///
229     /// let uc = unsafe { c.as_unsafe_cell() };
230     /// ```
231     #[inline]
232     #[unstable(feature = "core")]
233     pub unsafe fn as_unsafe_cell<'a>(&'a self) -> &'a UnsafeCell<T> {
234         &self.value
235     }
236 }
237
238 #[stable(feature = "rust1", since = "1.0.0")]
239 unsafe impl<T> Send for Cell<T> where T: Send {}
240
241 #[stable(feature = "rust1", since = "1.0.0")]
242 impl<T:Copy> Clone for Cell<T> {
243     #[inline]
244     fn clone(&self) -> Cell<T> {
245         Cell::new(self.get())
246     }
247 }
248
249 #[stable(feature = "rust1", since = "1.0.0")]
250 impl<T:Default + Copy> Default for Cell<T> {
251     #[stable(feature = "rust1", since = "1.0.0")]
252     #[inline]
253     fn default() -> Cell<T> {
254         Cell::new(Default::default())
255     }
256 }
257
258 #[stable(feature = "rust1", since = "1.0.0")]
259 impl<T:PartialEq + Copy> PartialEq for Cell<T> {
260     #[inline]
261     fn eq(&self, other: &Cell<T>) -> bool {
262         self.get() == other.get()
263     }
264 }
265
266 #[stable(feature = "cell_eq", since = "1.2.0")]
267 impl<T:Eq + Copy> Eq for Cell<T> {}
268
269 /// A mutable memory location with dynamically checked borrow rules
270 ///
271 /// See the [module-level documentation](index.html) for more.
272 #[stable(feature = "rust1", since = "1.0.0")]
273 pub struct RefCell<T: ?Sized> {
274     borrow: Cell<BorrowFlag>,
275     value: UnsafeCell<T>,
276 }
277
278 /// An enumeration of values returned from the `state` method on a `RefCell<T>`.
279 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
280 #[unstable(feature = "std_misc")]
281 pub enum BorrowState {
282     /// The cell is currently being read, there is at least one active `borrow`.
283     Reading,
284     /// The cell is currently being written to, there is an active `borrow_mut`.
285     Writing,
286     /// There are no outstanding borrows on this cell.
287     Unused,
288 }
289
290 // Values [1, MAX-1] represent the number of `Ref` active
291 // (will not outgrow its range since `usize` is the size of the address space)
292 type BorrowFlag = usize;
293 const UNUSED: BorrowFlag = 0;
294 const WRITING: BorrowFlag = !0;
295
296 impl<T> RefCell<T> {
297     /// Creates a new `RefCell` containing `value`.
298     ///
299     /// # Examples
300     ///
301     /// ```
302     /// use std::cell::RefCell;
303     ///
304     /// let c = RefCell::new(5);
305     /// ```
306     #[stable(feature = "rust1", since = "1.0.0")]
307     #[inline]
308     pub const fn new(value: T) -> RefCell<T> {
309         RefCell {
310             value: UnsafeCell::new(value),
311             borrow: Cell::new(UNUSED),
312         }
313     }
314
315     /// Consumes the `RefCell`, returning the wrapped value.
316     ///
317     /// # Examples
318     ///
319     /// ```
320     /// use std::cell::RefCell;
321     ///
322     /// let c = RefCell::new(5);
323     ///
324     /// let five = c.into_inner();
325     /// ```
326     #[stable(feature = "rust1", since = "1.0.0")]
327     #[inline]
328     pub fn into_inner(self) -> T {
329         // Since this function takes `self` (the `RefCell`) by value, the
330         // compiler statically verifies that it is not currently borrowed.
331         // Therefore the following assertion is just a `debug_assert!`.
332         debug_assert!(self.borrow.get() == UNUSED);
333         unsafe { self.value.into_inner() }
334     }
335 }
336
337 impl<T: ?Sized> RefCell<T> {
338     /// Query the current state of this `RefCell`
339     ///
340     /// The returned value can be dispatched on to determine if a call to
341     /// `borrow` or `borrow_mut` would succeed.
342     #[unstable(feature = "std_misc")]
343     #[inline]
344     pub fn borrow_state(&self) -> BorrowState {
345         match self.borrow.get() {
346             WRITING => BorrowState::Writing,
347             UNUSED => BorrowState::Unused,
348             _ => BorrowState::Reading,
349         }
350     }
351
352     /// Immutably borrows the wrapped value.
353     ///
354     /// The borrow lasts until the returned `Ref` exits scope. Multiple
355     /// immutable borrows can be taken out at the same time.
356     ///
357     /// # Panics
358     ///
359     /// Panics if the value is currently mutably borrowed.
360     ///
361     /// # Examples
362     ///
363     /// ```
364     /// use std::cell::RefCell;
365     ///
366     /// let c = RefCell::new(5);
367     ///
368     /// let borrowed_five = c.borrow();
369     /// let borrowed_five2 = c.borrow();
370     /// ```
371     ///
372     /// An example of panic:
373     ///
374     /// ```
375     /// use std::cell::RefCell;
376     /// use std::thread;
377     ///
378     /// let result = thread::spawn(move || {
379     ///    let c = RefCell::new(5);
380     ///    let m = c.borrow_mut();
381     ///
382     ///    let b = c.borrow(); // this causes a panic
383     /// }).join();
384     ///
385     /// assert!(result.is_err());
386     /// ```
387     #[stable(feature = "rust1", since = "1.0.0")]
388     #[inline]
389     pub fn borrow<'a>(&'a self) -> Ref<'a, T> {
390         match BorrowRef::new(&self.borrow) {
391             Some(b) => Ref {
392                 _value: unsafe { &*self.value.get() },
393                 _borrow: b,
394             },
395             None => panic!("RefCell<T> already mutably borrowed"),
396         }
397     }
398
399     /// Mutably borrows the wrapped value.
400     ///
401     /// The borrow lasts until the returned `RefMut` exits scope. The value
402     /// cannot be borrowed while this borrow is active.
403     ///
404     /// # Panics
405     ///
406     /// Panics if the value is currently borrowed.
407     ///
408     /// # Examples
409     ///
410     /// ```
411     /// use std::cell::RefCell;
412     ///
413     /// let c = RefCell::new(5);
414     ///
415     /// let borrowed_five = c.borrow_mut();
416     /// ```
417     ///
418     /// An example of panic:
419     ///
420     /// ```
421     /// use std::cell::RefCell;
422     /// use std::thread;
423     ///
424     /// let result = thread::spawn(move || {
425     ///    let c = RefCell::new(5);
426     ///    let m = c.borrow();
427     ///
428     ///    let b = c.borrow_mut(); // this causes a panic
429     /// }).join();
430     ///
431     /// assert!(result.is_err());
432     /// ```
433     #[stable(feature = "rust1", since = "1.0.0")]
434     #[inline]
435     pub fn borrow_mut<'a>(&'a self) -> RefMut<'a, T> {
436         match BorrowRefMut::new(&self.borrow) {
437             Some(b) => RefMut {
438                 _value: unsafe { &mut *self.value.get() },
439                 _borrow: b,
440             },
441             None => panic!("RefCell<T> already borrowed"),
442         }
443     }
444
445     /// Returns a reference to the underlying `UnsafeCell`.
446     ///
447     /// This can be used to circumvent `RefCell`'s safety checks.
448     ///
449     /// This function is `unsafe` because `UnsafeCell`'s field is public.
450     #[inline]
451     #[unstable(feature = "core")]
452     pub unsafe fn as_unsafe_cell<'a>(&'a self) -> &'a UnsafeCell<T> {
453         &self.value
454     }
455 }
456
457 #[stable(feature = "rust1", since = "1.0.0")]
458 unsafe impl<T: ?Sized> Send for RefCell<T> where T: Send {}
459
460 #[stable(feature = "rust1", since = "1.0.0")]
461 impl<T: Clone> Clone for RefCell<T> {
462     #[inline]
463     fn clone(&self) -> RefCell<T> {
464         RefCell::new(self.borrow().clone())
465     }
466 }
467
468 #[stable(feature = "rust1", since = "1.0.0")]
469 impl<T:Default> Default for RefCell<T> {
470     #[stable(feature = "rust1", since = "1.0.0")]
471     #[inline]
472     fn default() -> RefCell<T> {
473         RefCell::new(Default::default())
474     }
475 }
476
477 #[stable(feature = "rust1", since = "1.0.0")]
478 impl<T: ?Sized + PartialEq> PartialEq for RefCell<T> {
479     #[inline]
480     fn eq(&self, other: &RefCell<T>) -> bool {
481         *self.borrow() == *other.borrow()
482     }
483 }
484
485 #[stable(feature = "cell_eq", since = "1.2.0")]
486 impl<T: ?Sized + Eq> Eq for RefCell<T> {}
487
488 struct BorrowRef<'b> {
489     _borrow: &'b Cell<BorrowFlag>,
490 }
491
492 impl<'b> BorrowRef<'b> {
493     #[inline]
494     fn new(borrow: &'b Cell<BorrowFlag>) -> Option<BorrowRef<'b>> {
495         match borrow.get() {
496             WRITING => None,
497             b => {
498                 borrow.set(b + 1);
499                 Some(BorrowRef { _borrow: borrow })
500             },
501         }
502     }
503 }
504
505 impl<'b> Drop for BorrowRef<'b> {
506     #[inline]
507     fn drop(&mut self) {
508         let borrow = self._borrow.get();
509         debug_assert!(borrow != WRITING && borrow != UNUSED);
510         self._borrow.set(borrow - 1);
511     }
512 }
513
514 impl<'b> Clone for BorrowRef<'b> {
515     #[inline]
516     fn clone(&self) -> BorrowRef<'b> {
517         // Since this Ref exists, we know the borrow flag
518         // is not set to WRITING.
519         let borrow = self._borrow.get();
520         debug_assert!(borrow != WRITING && borrow != UNUSED);
521         self._borrow.set(borrow + 1);
522         BorrowRef { _borrow: self._borrow }
523     }
524 }
525
526 /// Wraps a borrowed reference to a value in a `RefCell` box.
527 /// A wrapper type for an immutably borrowed value from a `RefCell<T>`.
528 ///
529 /// See the [module-level documentation](index.html) for more.
530 #[stable(feature = "rust1", since = "1.0.0")]
531 pub struct Ref<'b, T: ?Sized + 'b> {
532     // FIXME #12808: strange name to try to avoid interfering with
533     // field accesses of the contained type via Deref
534     _value: &'b T,
535     _borrow: BorrowRef<'b>,
536 }
537
538 #[stable(feature = "rust1", since = "1.0.0")]
539 impl<'b, T: ?Sized> Deref for Ref<'b, T> {
540     type Target = T;
541
542     #[inline]
543     fn deref<'a>(&'a self) -> &'a T {
544         self._value
545     }
546 }
547
548 /// Copies a `Ref`.
549 ///
550 /// The `RefCell` is already immutably borrowed, so this cannot fail.
551 ///
552 /// A `Clone` implementation would interfere with the widespread
553 /// use of `r.borrow().clone()` to clone the contents of a `RefCell`.
554 #[deprecated(since = "1.2.0", reason = "moved to a `Ref::clone` associated function")]
555 #[unstable(feature = "core",
556            reason = "likely to be moved to a method, pending language changes")]
557 #[inline]
558 pub fn clone_ref<'b, T:Clone>(orig: &Ref<'b, T>) -> Ref<'b, T> {
559     Ref::clone(orig)
560 }
561
562 impl<'b, T: ?Sized> Ref<'b, T> {
563     /// Copies a `Ref`.
564     ///
565     /// The `RefCell` is already immutably borrowed, so this cannot fail.
566     ///
567     /// This is an associated function that needs to be used as `Ref::clone(...)`.
568     /// A `Clone` implementation or a method would interfere with the widespread
569     /// use of `r.borrow().clone()` to clone the contents of a `RefCell`.
570     #[unstable(feature = "cell_extras",
571                reason = "likely to be moved to a method, pending language changes")]
572     #[inline]
573     pub fn clone(orig: &Ref<'b, T>) -> Ref<'b, T> {
574         Ref {
575             _value: orig._value,
576             _borrow: orig._borrow.clone(),
577         }
578     }
579
580     /// Make a new `Ref` for a component of the borrowed data.
581     ///
582     /// The `RefCell` is already immutably borrowed, so this cannot fail.
583     ///
584     /// This is an associated function that needs to be used as `Ref::map(...)`.
585     /// A method would interfere with methods of the same name on the contents of a `RefCell`
586     /// used through `Deref`.
587     ///
588     /// # Example
589     ///
590     /// ```
591     /// # #![feature(cell_extras)]
592     /// use std::cell::{RefCell, Ref};
593     ///
594     /// let c = RefCell::new((5, 'b'));
595     /// let b1: Ref<(u32, char)> = c.borrow();
596     /// let b2: Ref<u32> = Ref::map(b1, |t| &t.0);
597     /// assert_eq!(*b2, 5)
598     /// ```
599     #[unstable(feature = "cell_extras", reason = "recently added")]
600     #[inline]
601     pub fn map<U: ?Sized, F>(orig: Ref<'b, T>, f: F) -> Ref<'b, U>
602         where F: FnOnce(&T) -> &U
603     {
604         Ref {
605             _value: f(orig._value),
606             _borrow: orig._borrow,
607         }
608     }
609
610     /// Make a new `Ref` for a optional component of the borrowed data, e.g. an enum variant.
611     ///
612     /// The `RefCell` is already immutably borrowed, so this cannot fail.
613     ///
614     /// This is an associated function that needs to be used as `Ref::filter_map(...)`.
615     /// A method would interfere with methods of the same name on the contents of a `RefCell`
616     /// used through `Deref`.
617     ///
618     /// # Example
619     ///
620     /// ```
621     /// # #![feature(cell_extras)]
622     /// use std::cell::{RefCell, Ref};
623     ///
624     /// let c = RefCell::new(Ok(5));
625     /// let b1: Ref<Result<u32, ()>> = c.borrow();
626     /// let b2: Ref<u32> = Ref::filter_map(b1, |o| o.as_ref().ok()).unwrap();
627     /// assert_eq!(*b2, 5)
628     /// ```
629     #[unstable(feature = "cell_extras", reason = "recently added")]
630     #[inline]
631     pub fn filter_map<U: ?Sized, F>(orig: Ref<'b, T>, f: F) -> Option<Ref<'b, U>>
632         where F: FnOnce(&T) -> Option<&U>
633     {
634         f(orig._value).map(move |new| Ref {
635             _value: new,
636             _borrow: orig._borrow,
637         })
638     }
639 }
640
641 impl<'b, T: ?Sized> RefMut<'b, T> {
642     /// Make a new `RefMut` for a component of the borrowed data, e.g. an enum variant.
643     ///
644     /// The `RefCell` is already mutably borrowed, so this cannot fail.
645     ///
646     /// This is an associated function that needs to be used as `RefMut::map(...)`.
647     /// A method would interfere with methods of the same name on the contents of a `RefCell`
648     /// used through `Deref`.
649     ///
650     /// # Example
651     ///
652     /// ```
653     /// # #![feature(cell_extras)]
654     /// use std::cell::{RefCell, RefMut};
655     ///
656     /// let c = RefCell::new((5, 'b'));
657     /// {
658     ///     let b1: RefMut<(u32, char)> = c.borrow_mut();
659     ///     let mut b2: RefMut<u32> = RefMut::map(b1, |t| &mut t.0);
660     ///     assert_eq!(*b2, 5);
661     ///     *b2 = 42;
662     /// }
663     /// assert_eq!(*c.borrow(), (42, 'b'));
664     /// ```
665     #[unstable(feature = "cell_extras", reason = "recently added")]
666     #[inline]
667     pub fn map<U: ?Sized, F>(orig: RefMut<'b, T>, f: F) -> RefMut<'b, U>
668         where F: FnOnce(&mut T) -> &mut U
669     {
670         RefMut {
671             _value: f(orig._value),
672             _borrow: orig._borrow,
673         }
674     }
675
676     /// Make a new `RefMut` for a optional component of the borrowed data, e.g. an enum variant.
677     ///
678     /// The `RefCell` is already mutably borrowed, so this cannot fail.
679     ///
680     /// This is an associated function that needs to be used as `RefMut::filter_map(...)`.
681     /// A method would interfere with methods of the same name on the contents of a `RefCell`
682     /// used through `Deref`.
683     ///
684     /// # Example
685     ///
686     /// ```
687     /// # #![feature(cell_extras)]
688     /// use std::cell::{RefCell, RefMut};
689     ///
690     /// let c = RefCell::new(Ok(5));
691     /// {
692     ///     let b1: RefMut<Result<u32, ()>> = c.borrow_mut();
693     ///     let mut b2: RefMut<u32> = RefMut::filter_map(b1, |o| o.as_mut().ok()).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     #[inline]
701     pub fn filter_map<U: ?Sized, F>(orig: RefMut<'b, T>, f: F) -> Option<RefMut<'b, U>>
702         where F: FnOnce(&mut T) -> Option<&mut U>
703     {
704         let RefMut { _value, _borrow } = orig;
705         f(_value).map(move |new| RefMut {
706             _value: new,
707             _borrow: _borrow,
708         })
709     }
710 }
711
712 struct BorrowRefMut<'b> {
713     _borrow: &'b Cell<BorrowFlag>,
714 }
715
716 impl<'b> Drop for BorrowRefMut<'b> {
717     #[inline]
718     fn drop(&mut self) {
719         let borrow = self._borrow.get();
720         debug_assert!(borrow == WRITING);
721         self._borrow.set(UNUSED);
722     }
723 }
724
725 impl<'b> BorrowRefMut<'b> {
726     #[inline]
727     fn new(borrow: &'b Cell<BorrowFlag>) -> Option<BorrowRefMut<'b>> {
728         match borrow.get() {
729             UNUSED => {
730                 borrow.set(WRITING);
731                 Some(BorrowRefMut { _borrow: borrow })
732             },
733             _ => None,
734         }
735     }
736 }
737
738 /// A wrapper type for a mutably borrowed value from a `RefCell<T>`.
739 ///
740 /// See the [module-level documentation](index.html) for more.
741 #[stable(feature = "rust1", since = "1.0.0")]
742 pub struct RefMut<'b, T: ?Sized + 'b> {
743     // FIXME #12808: strange name to try to avoid interfering with
744     // field accesses of the contained type via Deref
745     _value: &'b mut T,
746     _borrow: BorrowRefMut<'b>,
747 }
748
749 #[stable(feature = "rust1", since = "1.0.0")]
750 impl<'b, T: ?Sized> Deref for RefMut<'b, T> {
751     type Target = T;
752
753     #[inline]
754     fn deref<'a>(&'a self) -> &'a T {
755         self._value
756     }
757 }
758
759 #[stable(feature = "rust1", since = "1.0.0")]
760 impl<'b, T: ?Sized> DerefMut for RefMut<'b, T> {
761     #[inline]
762     fn deref_mut<'a>(&'a mut self) -> &'a mut T {
763         self._value
764     }
765 }
766
767 /// The core primitive for interior mutability in Rust.
768 ///
769 /// `UnsafeCell<T>` is a type that wraps some `T` and indicates unsafe interior operations on the
770 /// wrapped type. Types with an `UnsafeCell<T>` field are considered to have an 'unsafe interior'.
771 /// The `UnsafeCell<T>` type is the only legal way to obtain aliasable data that is considered
772 /// mutable. In general, transmuting an `&T` type into an `&mut T` is considered undefined behavior.
773 ///
774 /// Types like `Cell<T>` and `RefCell<T>` use this type to wrap their internal data.
775 ///
776 /// # Examples
777 ///
778 /// ```
779 /// use std::cell::UnsafeCell;
780 /// use std::marker::Sync;
781 ///
782 /// struct NotThreadSafe<T> {
783 ///     value: UnsafeCell<T>,
784 /// }
785 ///
786 /// unsafe impl<T> Sync for NotThreadSafe<T> {}
787 /// ```
788 ///
789 /// **NOTE:** `UnsafeCell<T>`'s fields are public to allow static initializers. It is not
790 /// recommended to access its fields directly, `get` should be used instead.
791 #[lang = "unsafe_cell"]
792 #[stable(feature = "rust1", since = "1.0.0")]
793 pub struct UnsafeCell<T: ?Sized> {
794     /// Wrapped value
795     ///
796     /// This field should not be accessed directly, it is made public for static
797     /// initializers.
798     #[deprecated(since = "1.2.0", reason = "use `get` to access the wrapped \
799         value or `new` to initialize `UnsafeCell` in statics")]
800     #[unstable(feature = "core")]
801     pub value: T,
802 }
803
804 impl<T: ?Sized> !Sync for UnsafeCell<T> {}
805
806 impl<T> UnsafeCell<T> {
807     /// Constructs a new instance of `UnsafeCell` which will wrap the specified
808     /// value.
809     ///
810     /// All access to the inner value through methods is `unsafe`, and it is highly discouraged to
811     /// access the fields directly.
812     ///
813     /// # Examples
814     ///
815     /// ```
816     /// use std::cell::UnsafeCell;
817     ///
818     /// let uc = UnsafeCell::new(5);
819     /// ```
820     #[stable(feature = "rust1", since = "1.0.0")]
821     #[inline]
822     pub const fn new(value: T) -> UnsafeCell<T> {
823         #![allow(deprecated)]
824         UnsafeCell { value: value }
825     }
826
827     /// Unwraps the value.
828     ///
829     /// # Unsafety
830     ///
831     /// This function is unsafe because this thread or another thread may currently be
832     /// inspecting the inner value.
833     ///
834     /// # Examples
835     ///
836     /// ```
837     /// use std::cell::UnsafeCell;
838     ///
839     /// let uc = UnsafeCell::new(5);
840     ///
841     /// let five = unsafe { uc.into_inner() };
842     /// ```
843     #[inline]
844     #[stable(feature = "rust1", since = "1.0.0")]
845     pub unsafe fn into_inner(self) -> T {
846         #![allow(deprecated)]
847         self.value
848     }
849 }
850
851 impl<T: ?Sized> UnsafeCell<T> {
852     /// Gets a mutable pointer to the wrapped value.
853     ///
854     /// # Examples
855     ///
856     /// ```
857     /// use std::cell::UnsafeCell;
858     ///
859     /// let uc = UnsafeCell::new(5);
860     ///
861     /// let five = uc.get();
862     /// ```
863     #[inline]
864     #[stable(feature = "rust1", since = "1.0.0")]
865     pub fn get(&self) -> *mut T {
866         // FIXME(#23542) Replace with type ascription.
867         #![allow(trivial_casts)]
868         #![allow(deprecated)]
869         &self.value as *const T as *mut T
870     }
871 }