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