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.
12 * A type representing values that may be computed concurrently and
13 * operations for working with them.
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) });
23 * println!("fib(5000) = {}", delayed_fib.get())
27 #![allow(missing_docs)]
30 use core::mem::replace;
32 use self::FutureState::*;
33 use comm::{Receiver, channel};
36 /// A type encapsulating the result of a computation which may not be complete
37 pub struct Future<A> {
38 state: FutureState<A>,
42 Pending(proc():Send -> A),
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()
56 /// Gets the value from this future, forcing evaluation.
57 pub fn into_inner(mut self) -> A {
59 let state = replace(&mut self.state, Evaluating);
62 _ => panic!( "Logic error." ),
66 /// Deprecated, use into_inner() instead
67 #[deprecated = "renamed to into_inner()"]
68 pub fn unwrap(self) -> A { self.into_inner() }
70 pub fn get_ref<'a>(&'a mut self) -> &'a A {
72 * Executes the future's closure and then returns a reference
73 * to the result. The reference lasts as long as
77 Forced(ref v) => return v,
78 Evaluating => panic!("Recursive forcing of future!"),
80 match replace(&mut self.state, Evaluating) {
81 Forced(_) | Evaluating => panic!("Logic error."),
83 self.state = Forced(f());
91 pub fn from_value(val: A) -> Future<A> {
93 * Create a future from a value.
95 * The value is immediately available and calling `get` later will
99 Future {state: Forced(val)}
102 pub fn from_fn(f: proc():Send -> A) -> Future<A> {
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(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(proc() {
129 pub fn spawn(blk: proc():Send -> A) -> Future<A> {
131 * Create a future from a unique closure.
133 * The closure will be run in a new task and its result used as the
134 * value of the future.
137 let (tx, rx) = channel();
140 // Don't panic if the other end has hung up
141 let _ = tx.send_opt(blk());
144 Future::from_receiver(rx)
153 use comm::{channel, Sender};
156 fn test_from_value() {
157 let mut f = Future::from_value("snail".to_string());
158 assert_eq!(f.get(), "snail".to_string());
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());
171 let mut f = Future::from_fn(proc() "brail".to_string());
172 assert_eq!(f.get(), "brail".to_string());
176 fn test_interface_get() {
177 let mut f = Future::from_value("fail".to_string());
178 assert_eq!(f.get(), "fail".to_string());
182 fn test_interface_unwrap() {
183 let f = Future::from_value("fail".to_string());
184 assert_eq!(f.unwrap(), "fail".to_string());
188 fn test_get_ref_method() {
189 let mut f = Future::from_value(22i);
190 assert_eq!(*f.get_ref(), 22);
195 let mut f = Future::spawn(proc() "bale".to_string());
196 assert_eq!(f.get(), "bale".to_string());
201 fn test_future_panic() {
202 let mut f = Future::spawn(proc() panic!());
203 let _x: String = f.get();
207 fn test_sendable_future() {
208 let expected = "schlorf";
209 let (tx, rx) = channel();
210 let f = Future::spawn(proc() { expected });
215 assert_eq!(rx.recv(), expected);