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.
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.
11 //! A type representing values that may be computed concurrently and operations
12 //! for working with them.
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())
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"]
31 use core::mem::replace;
33 use self::FutureState::*;
34 use sync::mpsc::{Receiver, channel};
38 /// A type encapsulating the result of a computation which may not be complete
39 pub struct Future<A> {
40 state: FutureState<A>,
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()
58 /// Gets the value from this future, forcing evaluation.
59 pub fn into_inner(mut self) -> A {
61 let state = replace(&mut self.state, Evaluating);
64 _ => panic!( "Logic error." ),
68 /// Deprecated, use into_inner() instead
69 #[deprecated = "renamed to into_inner()"]
70 pub fn unwrap(self) -> A { self.into_inner() }
72 pub fn get_ref<'a>(&'a mut self) -> &'a A {
74 * Executes the future's closure and then returns a reference
75 * to the result. The reference lasts as long as
79 Forced(ref v) => return v,
80 Evaluating => panic!("Recursive forcing of future!"),
82 match replace(&mut self.state, Evaluating) {
83 Forced(_) | Evaluating => panic!("Logic error."),
85 self.state = Forced(f.invoke(()));
93 pub fn from_value(val: A) -> Future<A> {
95 * Create a future from a value.
97 * The value is immediately available and calling `get` later will
101 Future {state: Forced(val)}
104 pub fn from_fn<F>(f: F) -> Future<A>
105 where F : FnOnce() -> A, F : Send
108 * Create a future from a function.
110 * The first time that the value is requested it will be retrieved by
111 * calling the function. Note that this function is a local
112 * function. It is not spawned into another task.
115 Future {state: Pending(Thunk::new(f))}
119 impl<A:Send> Future<A> {
120 pub fn from_receiver(rx: Receiver<A>) -> Future<A> {
122 * Create a future from a port
124 * The first time that the value is requested the task will block
125 * waiting for the result to be received on the port.
128 Future::from_fn(move |:| {
133 pub fn spawn<F>(blk: F) -> Future<A>
134 where F : FnOnce() -> A, F : Send
137 * Create a future from a unique closure.
139 * The closure will be run in a new task and its result used as the
140 * value of the future.
143 let (tx, rx) = channel();
145 Thread::spawn(move |:| {
146 // Don't panic if the other end has hung up
147 let _ = tx.send(blk());
150 Future::from_receiver(rx)
157 use sync::mpsc::channel;
162 fn test_from_value() {
163 let mut f = Future::from_value("snail".to_string());
164 assert_eq!(f.get(), "snail");
168 fn test_from_receiver() {
169 let (tx, rx) = channel();
170 tx.send("whale".to_string()).unwrap();
171 let mut f = Future::from_receiver(rx);
172 assert_eq!(f.get(), "whale");
177 let mut f = Future::from_fn(move|| "brail".to_string());
178 assert_eq!(f.get(), "brail");
182 fn test_interface_get() {
183 let mut f = Future::from_value("fail".to_string());
184 assert_eq!(f.get(), "fail");
188 fn test_interface_unwrap() {
189 let f = Future::from_value("fail".to_string());
190 assert_eq!(f.into_inner(), "fail");
194 fn test_get_ref_method() {
195 let mut f = Future::from_value(22i);
196 assert_eq!(*f.get_ref(), 22);
201 let mut f = Future::spawn(move|| "bale".to_string());
202 assert_eq!(f.get(), "bale");
207 fn test_future_panic() {
208 let mut f = Future::spawn(move|| panic!());
209 let _x: String = f.get();
213 fn test_sendable_future() {
214 let expected = "schlorf";
215 let (tx, rx) = channel();
216 let f = Future::spawn(move|| { expected });
217 let _t = Thread::spawn(move|| {
219 tx.send(f.get()).unwrap();
221 assert_eq!(rx.recv().unwrap(), expected);