]> git.lizzy.rs Git - rust.git/blob - src/libextra/future.rs
7d2a0658969ab7cc62ea8273fc0c5d3d85c61432
[rust.git] / src / libextra / future.rs
1 // Copyright 2012-2013 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 /*!
12  * A type representing values that may be computed concurrently and
13  * operations for working with them.
14  *
15  * # Example
16  *
17  * ~~~ {.rust}
18  * # fn fib(n: uint) -> uint {42};
19  * # fn make_a_sandwich() {};
20  * let mut delayed_fib = extra::future::spawn (|| fib(5000) );
21  * make_a_sandwich();
22  * printfln!("fib(5000) = %?", delayed_fib.get())
23  * ~~~
24  */
25
26 #[allow(missing_doc)];
27
28
29 use std::cast;
30 use std::cell::Cell;
31 use std::comm::{PortOne, oneshot, send_one, recv_one};
32 use std::task;
33 use std::util::replace;
34
35 #[doc = "The future type"]
36 pub struct Future<A> {
37     priv state: FutureState<A>,
38 }
39
40 // n.b. It should be possible to get rid of this.
41 // Add a test, though -- tjc
42 // FIXME(#2829) -- futures should not be copyable, because they close
43 // over ~fn's that have pipes and so forth within!
44 #[unsafe_destructor]
45 impl<A> Drop for Future<A> {
46     fn drop(&self) {}
47 }
48
49 priv enum FutureState<A> {
50     Pending(~fn() -> A),
51     Evaluating,
52     Forced(A)
53 }
54
55 /// Methods on the `future` type
56 impl<A:Clone> Future<A> {
57     pub fn get(&mut self) -> A {
58         //! Get the value of the future.
59         (*(self.get_ref())).clone()
60     }
61 }
62
63 impl<A> Future<A> {
64     /// Gets the value from this future, forcing evaluation.
65     pub fn unwrap(self) -> A {
66         let mut this = self;
67         this.get_ref();
68         let state = replace(&mut this.state, Evaluating);
69         match state {
70             Forced(v) => v,
71             _ => fail!( "Logic error." ),
72         }
73     }
74 }
75
76 impl<A> Future<A> {
77     pub fn get_ref<'a>(&'a mut self) -> &'a A {
78         /*!
79         * Executes the future's closure and then returns a borrowed
80         * pointer to the result.  The borrowed pointer lasts as long as
81         * the future.
82         */
83         unsafe {
84             {
85                 match self.state {
86                     Forced(ref mut v) => { return cast::transmute(v); }
87                     Evaluating => fail!("Recursive forcing of future!"),
88                     Pending(_) => {}
89                 }
90             }
91             {
92                 let state = replace(&mut self.state, Evaluating);
93                 match state {
94                     Forced(_) | Evaluating => fail!("Logic error."),
95                     Pending(f) => {
96                         self.state = Forced(f());
97                         cast::transmute(self.get_ref())
98                     }
99                 }
100             }
101         }
102     }
103 }
104
105 pub fn from_value<A>(val: A) -> Future<A> {
106     /*!
107      * Create a future from a value.
108      *
109      * The value is immediately available and calling `get` later will
110      * not block.
111      */
112
113     Future {state: Forced(val)}
114 }
115
116 pub fn from_port<A:Send>(port: PortOne<A>) -> Future<A> {
117     /*!
118      * Create a future from a port
119      *
120      * The first time that the value is requested the task will block
121      * waiting for the result to be received on the port.
122      */
123
124     let port = Cell::new(port);
125     do from_fn {
126         recv_one(port.take())
127     }
128 }
129
130 pub fn from_fn<A>(f: ~fn() -> A) -> Future<A> {
131     /*!
132      * Create a future from a function.
133      *
134      * The first time that the value is requested it will be retrieved by
135      * calling the function.  Note that this function is a local
136      * function. It is not spawned into another task.
137      */
138
139     Future {state: Pending(f)}
140 }
141
142 pub fn spawn<A:Send>(blk: ~fn() -> A) -> Future<A> {
143     /*!
144      * Create a future from a unique closure.
145      *
146      * The closure will be run in a new task and its result used as the
147      * value of the future.
148      */
149
150     let (port, chan) = oneshot();
151
152     let chan = Cell::new(chan);
153     do task::spawn {
154         let chan = chan.take();
155         send_one(chan, blk());
156     }
157
158     return from_port(port);
159 }
160
161 #[cfg(test)]
162 mod test {
163     use future::*;
164
165     use std::cell::Cell;
166     use std::comm::{oneshot, send_one};
167     use std::task;
168
169     #[test]
170     fn test_from_value() {
171         let mut f = from_value(~"snail");
172         assert_eq!(f.get(), ~"snail");
173     }
174
175     #[test]
176     fn test_from_port() {
177         let (po, ch) = oneshot();
178         send_one(ch, ~"whale");
179         let mut f = from_port(po);
180         assert_eq!(f.get(), ~"whale");
181     }
182
183     #[test]
184     fn test_from_fn() {
185         let mut f = from_fn(|| ~"brail");
186         assert_eq!(f.get(), ~"brail");
187     }
188
189     #[test]
190     fn test_interface_get() {
191         let mut f = from_value(~"fail");
192         assert_eq!(f.get(), ~"fail");
193     }
194
195     #[test]
196     fn test_interface_unwrap() {
197         let f = from_value(~"fail");
198         assert_eq!(f.unwrap(), ~"fail");
199     }
200
201     #[test]
202     fn test_get_ref_method() {
203         let mut f = from_value(22);
204         assert_eq!(*f.get_ref(), 22);
205     }
206
207     #[test]
208     fn test_spawn() {
209         let mut f = spawn(|| ~"bale");
210         assert_eq!(f.get(), ~"bale");
211     }
212
213     #[test]
214     #[should_fail]
215     #[ignore(cfg(target_os = "win32"))]
216     fn test_futurefail() {
217         let mut f = spawn(|| fail!());
218         let _x: ~str = f.get();
219     }
220
221     #[test]
222     fn test_sendable_future() {
223         let expected = "schlorf";
224         let f = Cell::new(do spawn { expected });
225         do task::spawn {
226             let mut f = f.take();
227             let actual = f.get();
228             assert_eq!(actual, expected);
229         }
230     }
231 }