]> git.lizzy.rs Git - rust.git/blob - src/libstd/sync/future.rs
doc: remove incomplete sentence
[rust.git] / src / libstd / sync / future.rs
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.
4 //
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.
10
11 //! A type representing values that may be computed concurrently and operations
12 //! for working with them.
13 //!
14 //! # Example
15 //!
16 //! ```rust
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())
23 //! ```
24
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"]
29
30 use core::prelude::*;
31 use core::mem::replace;
32
33 use self::FutureState::*;
34 use sync::mpsc::{Receiver, channel};
35 use thunk::{Thunk};
36 use thread::Thread;
37
38 /// A type encapsulating the result of a computation which may not be complete
39 pub struct Future<A> {
40     state: FutureState<A>,
41 }
42
43 enum FutureState<A> {
44     Pending(Thunk<(),A>),
45     Evaluating,
46     Forced(A)
47 }
48
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()
54     }
55 }
56
57 impl<A> Future<A> {
58     /// Gets the value from this future, forcing evaluation.
59     pub fn into_inner(mut self) -> A {
60         self.get_ref();
61         let state = replace(&mut self.state, Evaluating);
62         match state {
63             Forced(v) => v,
64             _ => panic!( "Logic error." ),
65         }
66     }
67
68     /// Deprecated, use into_inner() instead
69     #[deprecated = "renamed to into_inner()"]
70     pub fn unwrap(self) -> A { self.into_inner() }
71
72     pub fn get_ref<'a>(&'a mut self) -> &'a A {
73         /*!
74         * Executes the future's closure and then returns a reference
75         * to the result.  The reference lasts as long as
76         * the future.
77         */
78         match self.state {
79             Forced(ref v) => return v,
80             Evaluating => panic!("Recursive forcing of future!"),
81             Pending(_) => {
82                 match replace(&mut self.state, Evaluating) {
83                     Forced(_) | Evaluating => panic!("Logic error."),
84                     Pending(f) => {
85                         self.state = Forced(f.invoke(()));
86                         self.get_ref()
87                     }
88                 }
89             }
90         }
91     }
92
93     pub fn from_value(val: A) -> Future<A> {
94         /*!
95          * Create a future from a value.
96          *
97          * The value is immediately available and calling `get` later will
98          * not block.
99          */
100
101         Future {state: Forced(val)}
102     }
103
104     pub fn from_fn<F>(f: F) -> Future<A>
105         where F : FnOnce() -> A, F : Send
106     {
107         /*!
108          * Create a future from a function.
109          *
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.
113          */
114
115         Future {state: Pending(Thunk::new(f))}
116     }
117 }
118
119 impl<A:Send> Future<A> {
120     pub fn from_receiver(rx: Receiver<A>) -> Future<A> {
121         /*!
122          * Create a future from a port
123          *
124          * The first time that the value is requested the task will block
125          * waiting for the result to be received on the port.
126          */
127
128         Future::from_fn(move |:| {
129             rx.recv().unwrap()
130         })
131     }
132
133     pub fn spawn<F>(blk: F) -> Future<A>
134         where F : FnOnce() -> A, F : Send
135     {
136         /*!
137          * Create a future from a unique closure.
138          *
139          * The closure will be run in a new task and its result used as the
140          * value of the future.
141          */
142
143         let (tx, rx) = channel();
144
145         Thread::spawn(move |:| {
146             // Don't panic if the other end has hung up
147             let _ = tx.send(blk());
148         }).detach();
149
150         Future::from_receiver(rx)
151     }
152 }
153
154 #[cfg(test)]
155 mod test {
156     use prelude::v1::*;
157     use sync::mpsc::channel;
158     use sync::Future;
159     use thread::Thread;
160
161     #[test]
162     fn test_from_value() {
163         let mut f = Future::from_value("snail".to_string());
164         assert_eq!(f.get(), "snail");
165     }
166
167     #[test]
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");
173     }
174
175     #[test]
176     fn test_from_fn() {
177         let mut f = Future::from_fn(move|| "brail".to_string());
178         assert_eq!(f.get(), "brail");
179     }
180
181     #[test]
182     fn test_interface_get() {
183         let mut f = Future::from_value("fail".to_string());
184         assert_eq!(f.get(), "fail");
185     }
186
187     #[test]
188     fn test_interface_unwrap() {
189         let f = Future::from_value("fail".to_string());
190         assert_eq!(f.into_inner(), "fail");
191     }
192
193     #[test]
194     fn test_get_ref_method() {
195         let mut f = Future::from_value(22i);
196         assert_eq!(*f.get_ref(), 22);
197     }
198
199     #[test]
200     fn test_spawn() {
201         let mut f = Future::spawn(move|| "bale".to_string());
202         assert_eq!(f.get(), "bale");
203     }
204
205     #[test]
206     #[should_fail]
207     fn test_future_panic() {
208         let mut f = Future::spawn(move|| panic!());
209         let _x: String = f.get();
210     }
211
212     #[test]
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|| {
218             let mut f = f;
219             tx.send(f.get()).unwrap();
220         });
221         assert_eq!(rx.recv().unwrap(), expected);
222     }
223 }