]> git.lizzy.rs Git - rust.git/blob - src/libstd/sync/future.rs
d6f413a082854eb08a25c857419a1ca9fe99bb46
[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 into_inner(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     /// Deprecated, use into_inner() instead
67     #[deprecated = "renamed to into_inner()"]
68     pub fn unwrap(self) -> A { self.into_inner() }
69
70     pub fn get_ref<'a>(&'a mut self) -> &'a A {
71         /*!
72         * Executes the future's closure and then returns a reference
73         * to the result.  The reference lasts as long as
74         * the future.
75         */
76         match self.state {
77             Forced(ref v) => return v,
78             Evaluating => panic!("Recursive forcing of future!"),
79             Pending(_) => {
80                 match replace(&mut self.state, Evaluating) {
81                     Forced(_) | Evaluating => panic!("Logic error."),
82                     Pending(f) => {
83                         self.state = Forced(f());
84                         self.get_ref()
85                     }
86                 }
87             }
88         }
89     }
90
91     pub fn from_value(val: A) -> Future<A> {
92         /*!
93          * Create a future from a value.
94          *
95          * The value is immediately available and calling `get` later will
96          * not block.
97          */
98
99         Future {state: Forced(val)}
100     }
101
102     pub fn from_fn(f: proc():Send -> A) -> Future<A> {
103         /*!
104          * Create a future from a function.
105          *
106          * The first time that the value is requested it will be retrieved by
107          * calling the function.  Note that this function is a local
108          * function. It is not spawned into another task.
109          */
110
111         Future {state: Pending(f)}
112     }
113 }
114
115 impl<A:Send> Future<A> {
116     pub fn from_receiver(rx: Receiver<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         Future::from_fn(proc() {
125             rx.recv()
126         })
127     }
128
129     pub fn spawn(blk: proc():Send -> A) -> Future<A> {
130         /*!
131          * Create a future from a unique closure.
132          *
133          * The closure will be run in a new task and its result used as the
134          * value of the future.
135          */
136
137         let (tx, rx) = channel();
138
139         spawn(proc() {
140             // Don't panic if the other end has hung up
141             let _ = tx.send_opt(blk());
142         });
143
144         Future::from_receiver(rx)
145     }
146 }
147
148 #[cfg(test)]
149 mod test {
150     use prelude::*;
151     use sync::Future;
152     use task;
153     use comm::{channel, Sender};
154
155     #[test]
156     fn test_from_value() {
157         let mut f = Future::from_value("snail".to_string());
158         assert_eq!(f.get(), "snail".to_string());
159     }
160
161     #[test]
162     fn test_from_receiver() {
163         let (tx, rx) = channel();
164         tx.send("whale".to_string());
165         let mut f = Future::from_receiver(rx);
166         assert_eq!(f.get(), "whale".to_string());
167     }
168
169     #[test]
170     fn test_from_fn() {
171         let mut f = Future::from_fn(proc() "brail".to_string());
172         assert_eq!(f.get(), "brail".to_string());
173     }
174
175     #[test]
176     fn test_interface_get() {
177         let mut f = Future::from_value("fail".to_string());
178         assert_eq!(f.get(), "fail".to_string());
179     }
180
181     #[test]
182     fn test_interface_unwrap() {
183         let f = Future::from_value("fail".to_string());
184         assert_eq!(f.unwrap(), "fail".to_string());
185     }
186
187     #[test]
188     fn test_get_ref_method() {
189         let mut f = Future::from_value(22i);
190         assert_eq!(*f.get_ref(), 22);
191     }
192
193     #[test]
194     fn test_spawn() {
195         let mut f = Future::spawn(proc() "bale".to_string());
196         assert_eq!(f.get(), "bale".to_string());
197     }
198
199     #[test]
200     #[should_fail]
201     fn test_future_panic() {
202         let mut f = Future::spawn(proc() panic!());
203         let _x: String = f.get();
204     }
205
206     #[test]
207     fn test_sendable_future() {
208         let expected = "schlorf";
209         let (tx, rx) = channel();
210         let f = Future::spawn(proc() { expected });
211         task::spawn(proc() {
212             let mut f = f;
213             tx.send(f.get());
214         });
215         assert_eq!(rx.recv(), expected);
216     }
217 }