]> git.lizzy.rs Git - rust.git/blob - src/libstd/sync/future.rs
std: Add a new top-level thread_local module
[rust.git] / src / libstd / sync / 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  * use std::sync::Future;
19  * # fn fib(n: uint) -> uint {42};
20  * # fn make_a_sandwich() {};
21  * let mut delayed_fib = Future::spawn(proc() { fib(5000) });
22  * make_a_sandwich();
23  * println!("fib(5000) = {}", delayed_fib.get())
24  * ```
25  */
26
27 #![allow(missing_docs)]
28
29 use core::prelude::*;
30 use core::mem::replace;
31
32 use self::FutureState::*;
33 use comm::{Receiver, channel};
34 use task::spawn;
35
36 /// A type encapsulating the result of a computation which may not be complete
37 pub struct Future<A> {
38     state: FutureState<A>,
39 }
40
41 enum FutureState<A> {
42     Pending(proc():Send -> A),
43     Evaluating,
44     Forced(A)
45 }
46
47 /// Methods on the `future` type
48 impl<A:Clone> Future<A> {
49     pub fn get(&mut self) -> A {
50         //! Get the value of the future.
51         (*(self.get_ref())).clone()
52     }
53 }
54
55 impl<A> Future<A> {
56     /// Gets the value from this future, forcing evaluation.
57     pub fn unwrap(mut self) -> A {
58         self.get_ref();
59         let state = replace(&mut self.state, Evaluating);
60         match state {
61             Forced(v) => v,
62             _ => panic!( "Logic error." ),
63         }
64     }
65
66     pub fn get_ref<'a>(&'a mut self) -> &'a A {
67         /*!
68         * Executes the future's closure and then returns a reference
69         * to the result.  The reference lasts as long as
70         * the future.
71         */
72         match self.state {
73             Forced(ref v) => return v,
74             Evaluating => panic!("Recursive forcing of future!"),
75             Pending(_) => {
76                 match replace(&mut self.state, Evaluating) {
77                     Forced(_) | Evaluating => panic!("Logic error."),
78                     Pending(f) => {
79                         self.state = Forced(f());
80                         self.get_ref()
81                     }
82                 }
83             }
84         }
85     }
86
87     pub fn from_value(val: A) -> Future<A> {
88         /*!
89          * Create a future from a value.
90          *
91          * The value is immediately available and calling `get` later will
92          * not block.
93          */
94
95         Future {state: Forced(val)}
96     }
97
98     pub fn from_fn(f: proc():Send -> A) -> Future<A> {
99         /*!
100          * Create a future from a function.
101          *
102          * The first time that the value is requested it will be retrieved by
103          * calling the function.  Note that this function is a local
104          * function. It is not spawned into another task.
105          */
106
107         Future {state: Pending(f)}
108     }
109 }
110
111 impl<A:Send> Future<A> {
112     pub fn from_receiver(rx: Receiver<A>) -> Future<A> {
113         /*!
114          * Create a future from a port
115          *
116          * The first time that the value is requested the task will block
117          * waiting for the result to be received on the port.
118          */
119
120         Future::from_fn(proc() {
121             rx.recv()
122         })
123     }
124
125     pub fn spawn(blk: proc():Send -> A) -> Future<A> {
126         /*!
127          * Create a future from a unique closure.
128          *
129          * The closure will be run in a new task and its result used as the
130          * value of the future.
131          */
132
133         let (tx, rx) = channel();
134
135         spawn(proc() {
136             // Don't panic if the other end has hung up
137             let _ = tx.send_opt(blk());
138         });
139
140         Future::from_receiver(rx)
141     }
142 }
143
144 #[cfg(test)]
145 mod test {
146     use prelude::*;
147     use sync::Future;
148     use task;
149     use comm::{channel, Sender};
150
151     #[test]
152     fn test_from_value() {
153         let mut f = Future::from_value("snail".to_string());
154         assert_eq!(f.get(), "snail".to_string());
155     }
156
157     #[test]
158     fn test_from_receiver() {
159         let (tx, rx) = channel();
160         tx.send("whale".to_string());
161         let mut f = Future::from_receiver(rx);
162         assert_eq!(f.get(), "whale".to_string());
163     }
164
165     #[test]
166     fn test_from_fn() {
167         let mut f = Future::from_fn(proc() "brail".to_string());
168         assert_eq!(f.get(), "brail".to_string());
169     }
170
171     #[test]
172     fn test_interface_get() {
173         let mut f = Future::from_value("fail".to_string());
174         assert_eq!(f.get(), "fail".to_string());
175     }
176
177     #[test]
178     fn test_interface_unwrap() {
179         let f = Future::from_value("fail".to_string());
180         assert_eq!(f.unwrap(), "fail".to_string());
181     }
182
183     #[test]
184     fn test_get_ref_method() {
185         let mut f = Future::from_value(22i);
186         assert_eq!(*f.get_ref(), 22);
187     }
188
189     #[test]
190     fn test_spawn() {
191         let mut f = Future::spawn(proc() "bale".to_string());
192         assert_eq!(f.get(), "bale".to_string());
193     }
194
195     #[test]
196     #[should_fail]
197     fn test_future_panic() {
198         let mut f = Future::spawn(proc() panic!());
199         let _x: String = f.get();
200     }
201
202     #[test]
203     fn test_sendable_future() {
204         let expected = "schlorf";
205         let (tx, rx) = channel();
206         let f = Future::spawn(proc() { expected });
207         task::spawn(proc() {
208             let mut f = f;
209             tx.send(f.get());
210         });
211         assert_eq!(rx.recv(), expected);
212     }
213 }