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 unwrap(mut self) -> A {
59 let state = replace(&mut self.state, Evaluating);
62 _ => panic!( "Logic error." ),
66 pub fn get_ref<'a>(&'a mut self) -> &'a A {
68 * Executes the future's closure and then returns a reference
69 * to the result. The reference lasts as long as
73 Forced(ref v) => return v,
74 Evaluating => panic!("Recursive forcing of future!"),
76 match replace(&mut self.state, Evaluating) {
77 Forced(_) | Evaluating => panic!("Logic error."),
79 self.state = Forced(f());
87 pub fn from_value(val: A) -> Future<A> {
89 * Create a future from a value.
91 * The value is immediately available and calling `get` later will
95 Future {state: Forced(val)}
98 pub fn from_fn(f: proc():Send -> A) -> Future<A> {
100 * Create a future from a function.
102 * The first time that the value is requested it will be retrieved by
103 * calling the function. Note that this function is a local
104 * function. It is not spawned into another task.
107 Future {state: Pending(f)}
111 impl<A:Send> Future<A> {
112 pub fn from_receiver(rx: Receiver<A>) -> Future<A> {
114 * Create a future from a port
116 * The first time that the value is requested the task will block
117 * waiting for the result to be received on the port.
120 Future::from_fn(proc() {
125 pub fn spawn(blk: proc():Send -> A) -> Future<A> {
127 * Create a future from a unique closure.
129 * The closure will be run in a new task and its result used as the
130 * value of the future.
133 let (tx, rx) = channel();
136 // Don't panic if the other end has hung up
137 let _ = tx.send_opt(blk());
140 Future::from_receiver(rx)
149 use comm::{channel, Sender};
152 fn test_from_value() {
153 let mut f = Future::from_value("snail".to_string());
154 assert_eq!(f.get(), "snail".to_string());
158 fn test_from_receiver() {
159 let (tx, rx) = channel();
160 tx.send("whale".to_string());
161 let mut f = Future::from_receiver(rx);
162 assert_eq!(f.get(), "whale".to_string());
167 let mut f = Future::from_fn(proc() "brail".to_string());
168 assert_eq!(f.get(), "brail".to_string());
172 fn test_interface_get() {
173 let mut f = Future::from_value("fail".to_string());
174 assert_eq!(f.get(), "fail".to_string());
178 fn test_interface_unwrap() {
179 let f = Future::from_value("fail".to_string());
180 assert_eq!(f.unwrap(), "fail".to_string());
184 fn test_get_ref_method() {
185 let mut f = Future::from_value(22i);
186 assert_eq!(*f.get_ref(), 22);
191 let mut f = Future::spawn(proc() "bale".to_string());
192 assert_eq!(f.get(), "bale".to_string());
197 fn test_future_panic() {
198 let mut f = Future::spawn(proc() panic!());
199 let _x: String = f.get();
203 fn test_sendable_future() {
204 let expected = "schlorf";
205 let (tx, rx) = channel();
206 let f = Future::spawn(proc() { expected });
211 assert_eq!(rx.recv(), expected);
215 fn test_dropped_future_doesnt_panic() {
216 struct Bomb(Sender<bool>);
218 local_data_key!(LOCAL: Bomb)
222 let Bomb(ref tx) = *self;
223 tx.send(task::failing());
227 // Spawn a future, but drop it immediately. When we receive the result
228 // later on, we should never view the task as having panicked.
229 let (tx, rx) = channel();
230 drop(Future::spawn(proc() {
231 LOCAL.replace(Some(Bomb(tx)));
234 // Make sure the future didn't panic the task.