]> git.lizzy.rs Git - rust.git/blob - src/libstd/sync/future.rs
Merge pull request #20510 from tshepang/patch-6
[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 //! A type representing values that may be computed concurrently and operations
12 //! for working with them.
13 //!
14 //! # Example
15 //!
16 //! ```rust
17 //! use std::sync::Future;
18 //! # fn fib(n: uint) -> uint {42};
19 //! # fn make_a_sandwich() {};
20 //! let mut delayed_fib = Future::spawn(move|| { fib(5000) });
21 //! make_a_sandwich();
22 //! println!("fib(5000) = {}", delayed_fib.get())
23 //! ```
24
25 #![allow(missing_docs)]
26 #![unstable = "futures as-is have yet to be deeply reevaluated with recent \
27                core changes to Rust's synchronization story, and will likely \
28                become stable in the future but are unstable until that time"]
29
30 use core::prelude::*;
31 use core::mem::replace;
32
33 use self::FutureState::*;
34 use sync::mpsc::{Receiver, channel};
35 use thunk::{Thunk};
36 use thread::Thread;
37
38 /// A type encapsulating the result of a computation which may not be complete
39 pub struct Future<A> {
40     state: FutureState<A>,
41 }
42
43 enum FutureState<A> {
44     Pending(Thunk<(),A>),
45     Evaluating,
46     Forced(A)
47 }
48
49 /// Methods on the `future` type
50 impl<A:Clone> Future<A> {
51     pub fn get(&mut self) -> A {
52         //! Get the value of the future.
53         (*(self.get_ref())).clone()
54     }
55 }
56
57 impl<A> Future<A> {
58     /// Gets the value from this future, forcing evaluation.
59     pub fn into_inner(mut self) -> A {
60         self.get_ref();
61         let state = replace(&mut self.state, Evaluating);
62         match state {
63             Forced(v) => v,
64             _ => panic!( "Logic error." ),
65         }
66     }
67
68     pub fn get_ref<'a>(&'a mut self) -> &'a A {
69         /*!
70         * Executes the future's closure and then returns a reference
71         * to the result.  The reference lasts as long as
72         * the future.
73         */
74         match self.state {
75             Forced(ref v) => return v,
76             Evaluating => panic!("Recursive forcing of future!"),
77             Pending(_) => {
78                 match replace(&mut self.state, Evaluating) {
79                     Forced(_) | Evaluating => panic!("Logic error."),
80                     Pending(f) => {
81                         self.state = Forced(f.invoke(()));
82                         self.get_ref()
83                     }
84                 }
85             }
86         }
87     }
88
89     pub fn from_value(val: A) -> Future<A> {
90         /*!
91          * Create a future from a value.
92          *
93          * The value is immediately available and calling `get` later will
94          * not block.
95          */
96
97         Future {state: Forced(val)}
98     }
99
100     pub fn from_fn<F>(f: F) -> Future<A>
101         where F : FnOnce() -> A, F : Send
102     {
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(Thunk::new(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(move |:| {
125             rx.recv().unwrap()
126         })
127     }
128
129     pub fn spawn<F>(blk: F) -> Future<A>
130         where F : FnOnce() -> A, F : Send
131     {
132         /*!
133          * Create a future from a unique closure.
134          *
135          * The closure will be run in a new task and its result used as the
136          * value of the future.
137          */
138
139         let (tx, rx) = channel();
140
141         Thread::spawn(move |:| {
142             // Don't panic if the other end has hung up
143             let _ = tx.send(blk());
144         }).detach();
145
146         Future::from_receiver(rx)
147     }
148 }
149
150 #[cfg(test)]
151 mod test {
152     use prelude::v1::*;
153     use sync::mpsc::channel;
154     use sync::Future;
155     use thread::Thread;
156
157     #[test]
158     fn test_from_value() {
159         let mut f = Future::from_value("snail".to_string());
160         assert_eq!(f.get(), "snail");
161     }
162
163     #[test]
164     fn test_from_receiver() {
165         let (tx, rx) = channel();
166         tx.send("whale".to_string()).unwrap();
167         let mut f = Future::from_receiver(rx);
168         assert_eq!(f.get(), "whale");
169     }
170
171     #[test]
172     fn test_from_fn() {
173         let mut f = Future::from_fn(move|| "brail".to_string());
174         assert_eq!(f.get(), "brail");
175     }
176
177     #[test]
178     fn test_interface_get() {
179         let mut f = Future::from_value("fail".to_string());
180         assert_eq!(f.get(), "fail");
181     }
182
183     #[test]
184     fn test_interface_unwrap() {
185         let f = Future::from_value("fail".to_string());
186         assert_eq!(f.into_inner(), "fail");
187     }
188
189     #[test]
190     fn test_get_ref_method() {
191         let mut f = Future::from_value(22i);
192         assert_eq!(*f.get_ref(), 22);
193     }
194
195     #[test]
196     fn test_spawn() {
197         let mut f = Future::spawn(move|| "bale".to_string());
198         assert_eq!(f.get(), "bale");
199     }
200
201     #[test]
202     #[should_fail]
203     fn test_future_panic() {
204         let mut f = Future::spawn(move|| panic!());
205         let _x: String = f.get();
206     }
207
208     #[test]
209     fn test_sendable_future() {
210         let expected = "schlorf";
211         let (tx, rx) = channel();
212         let f = Future::spawn(move|| { expected });
213         let _t = Thread::spawn(move|| {
214             let mut f = f;
215             tx.send(f.get()).unwrap();
216         });
217         assert_eq!(rx.recv().unwrap(), expected);
218     }
219 }