]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/steal.rs
Breaking change upgrades
[rust.git] / src / librustc / ty / steal.rs
1 // Copyright 2012-2015 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 use rustc_data_structures::sync::{RwLock, ReadGuard, MappedReadGuard};
12 use std::mem;
13
14 /// The `Steal` struct is intended to used as the value for a query.
15 /// Specifically, we sometimes have queries (*cough* MIR *cough*)
16 /// where we create a large, complex value that we want to iteratively
17 /// update (e.g., optimize). We could clone the value for each
18 /// optimization, but that'd be expensive. And yet we don't just want
19 /// to mutate it in place, because that would spoil the idea that
20 /// queries are these pure functions that produce an immutable value
21 /// (since if you did the query twice, you could observe the
22 /// mutations). So instead we have the query produce a `&'tcx
23 /// Steal<Mir<'tcx>>` (to be very specific). Now we can read from this
24 /// as much as we want (using `borrow()`), but you can also
25 /// `steal()`. Once you steal, any further attempt to read will panic.
26 /// Therefore we know that -- assuming no ICE -- nobody is observing
27 /// the fact that the MIR was updated.
28 ///
29 /// Obviously, whenever you have a query that yields a `Steal` value,
30 /// you must treat it with caution, and make sure that you know that
31 /// -- once the value is stolen -- it will never be read from again.
32 ///
33 /// FIXME(#41710) -- what is the best way to model linear queries?
34 pub struct Steal<T> {
35     value: RwLock<Option<T>>
36 }
37
38 impl<T> Steal<T> {
39     pub fn new(value: T) -> Self {
40         Steal {
41             value: RwLock::new(Some(value))
42         }
43     }
44
45     pub fn borrow(&self) -> MappedReadGuard<T> {
46         ReadGuard::map(self.value.borrow(), |opt| match *opt {
47             None => bug!("attempted to read from stolen value"),
48             Some(ref v) => v
49         })
50     }
51
52     pub fn steal(&self) -> T {
53         let value_ref = &mut *self.value.try_write().expect("stealing value which is locked");
54         let value = mem::replace(value_ref, None);
55         value.expect("attempt to read from stolen value")
56     }
57 }