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 pub fn get_ref<'a>(&'a mut self) -> &'a A {
70 * Executes the future's closure and then returns a reference
71 * to the result. The reference lasts as long as
75 Forced(ref v) => return v,
76 Evaluating => panic!("Recursive forcing of future!"),
78 match replace(&mut self.state, Evaluating) {
79 Forced(_) | Evaluating => panic!("Logic error."),
81 self.state = Forced(f.invoke(()));
89 pub fn from_value(val: A) -> Future<A> {
91 * Create a future from a value.
93 * The value is immediately available and calling `get` later will
97 Future {state: Forced(val)}
100 pub fn from_fn<F>(f: F) -> Future<A>
101 where F : FnOnce() -> A, F : Send
104 * Create a future from a function.
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.
111 Future {state: Pending(Thunk::new(f))}
115 impl<A:Send> Future<A> {
116 pub fn from_receiver(rx: Receiver<A>) -> Future<A> {
118 * Create a future from a port
120 * The first time that the value is requested the task will block
121 * waiting for the result to be received on the port.
124 Future::from_fn(move |:| {
129 pub fn spawn<F>(blk: F) -> Future<A>
130 where F : FnOnce() -> A, F : Send
133 * Create a future from a unique closure.
135 * The closure will be run in a new task and its result used as the
136 * value of the future.
139 let (tx, rx) = channel();
141 Thread::spawn(move |:| {
142 // Don't panic if the other end has hung up
143 let _ = tx.send(blk());
146 Future::from_receiver(rx)
153 use sync::mpsc::channel;
158 fn test_from_value() {
159 let mut f = Future::from_value("snail".to_string());
160 assert_eq!(f.get(), "snail");
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");
173 let mut f = Future::from_fn(move|| "brail".to_string());
174 assert_eq!(f.get(), "brail");
178 fn test_interface_get() {
179 let mut f = Future::from_value("fail".to_string());
180 assert_eq!(f.get(), "fail");
184 fn test_interface_unwrap() {
185 let f = Future::from_value("fail".to_string());
186 assert_eq!(f.into_inner(), "fail");
190 fn test_get_ref_method() {
191 let mut f = Future::from_value(22i);
192 assert_eq!(*f.get_ref(), 22);
197 let mut f = Future::spawn(move|| "bale".to_string());
198 assert_eq!(f.get(), "bale");
203 fn test_future_panic() {
204 let mut f = Future::spawn(move|| panic!());
205 let _x: String = f.get();
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|| {
215 tx.send(f.get()).unwrap();
217 assert_eq!(rx.recv().unwrap(), expected);