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