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