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 //! # #![feature(std_misc)]
18 //! use std::sync::Future;
20 //! // a fake, for now
21 //! fn fib(n: u32) -> u32 { 42 };
23 //! let mut delayed_fib = Future::spawn(move || fib(5000));
27 //! println!("fib(5000) = {}", delayed_fib.get())
30 #![allow(missing_docs)]
31 #![unstable(feature = "future",
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")]
37 use core::mem::replace;
40 use self::FutureState::*;
41 use sync::mpsc::{Receiver, channel};
45 /// A type encapsulating the result of a computation which may not be complete
46 pub struct Future<A> {
47 state: FutureState<A>,
51 Pending(Thunk<'static,(),A>),
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()
65 /// Gets the value from this future, forcing evaluation.
66 pub fn into_inner(mut self) -> A {
68 let state = replace(&mut self.state, Evaluating);
71 _ => panic!( "Logic error." ),
75 pub fn get_ref<'a>(&'a mut self) -> &'a A {
77 * Executes the future's closure and then returns a reference
78 * to the result. The reference lasts as long as
82 Forced(ref v) => return v,
83 Evaluating => panic!("Recursive forcing of future!"),
85 match replace(&mut self.state, Evaluating) {
86 Forced(_) | Evaluating => panic!("Logic error."),
88 self.state = Forced(f());
96 pub fn from_value(val: A) -> Future<A> {
98 * Create a future from a value.
100 * The value is immediately available and calling `get` later will
104 Future {state: Forced(val)}
107 pub fn from_fn<F>(f: F) -> Future<A>
108 where F : FnOnce() -> A, F : Send + 'static
111 * Create a future from a function.
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.
118 Future {state: Pending(Box::new(f))}
122 impl<A:Send+'static> Future<A> {
123 pub fn from_receiver(rx: Receiver<A>) -> Future<A> {
125 * Create a future from a port
127 * The first time that the value is requested the task will block
128 * waiting for the result to be received on the port.
131 Future::from_fn(move || {
136 pub fn spawn<F>(blk: F) -> Future<A>
137 where F : FnOnce() -> A, F : Send + 'static
140 * Create a future from a unique closure.
142 * The closure will be run in a new task and its result used as the
143 * value of the future.
146 let (tx, rx) = channel();
148 thread::spawn(move || {
149 // Don't panic if the other end has hung up
150 let _ = tx.send(blk());
153 Future::from_receiver(rx)
160 use sync::mpsc::channel;
165 fn test_from_value() {
166 let mut f = Future::from_value("snail".to_string());
167 assert_eq!(f.get(), "snail");
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");
180 let mut f = Future::from_fn(move|| "brail".to_string());
181 assert_eq!(f.get(), "brail");
185 fn test_interface_get() {
186 let mut f = Future::from_value("fail".to_string());
187 assert_eq!(f.get(), "fail");
191 fn test_interface_unwrap() {
192 let f = Future::from_value("fail".to_string());
193 assert_eq!(f.into_inner(), "fail");
197 fn test_get_ref_method() {
198 let mut f = Future::from_value(22);
199 assert_eq!(*f.get_ref(), 22);
204 let mut f = Future::spawn(move|| "bale".to_string());
205 assert_eq!(f.get(), "bale");
210 fn test_future_panic() {
211 let mut f = Future::spawn(move|| panic!());
212 let _x: String = f.get();
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|| {
222 tx.send(f.get()).unwrap();
224 assert_eq!(rx.recv().unwrap(), expected);