-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlib.rs
392 lines (347 loc) · 11.6 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
#![feature(unboxed_closures)]
extern crate test;
use std::any::Any;
use std::io::timer;
use std::time::duration::Duration;
use std::sync::mpsc::{
Select,
Sender,
SendError,
Receiver,
channel
};
use std::collections::HashMap;
use std::thread::Thread;
pub enum FutureError{
TaskFailure(Box<Any+Send>),
HungUp
}
/// A promise is used to set the value of the associated Future
pub struct Promise<T> {
sender: Sender<Result<T, FutureError>>
}
impl<T: Send> Promise<T> {
fn new(tx: Sender<Result<T, FutureError>>) -> Promise<T>{
Promise{ sender: tx }
}
/// Completes the associated Future with value;
pub fn resolve(self, value: T) -> Result<(), T> {
match self.sender.send(Ok(value)) {
Ok(x) => Ok(x),
Err(SendError(Ok(val))) => Err(val),
_ => unreachable!(),
}
}
fn send(self, value: Result<T, FutureError>){
self.sender.send(value);
}
fn fail(self, error: FutureError) {
self.sender.send(Err(error));
}
}
/// A future represents a value that is not yet available
pub struct Future<T> {
receiver: Receiver<Result<T, FutureError>>
}
impl<T: Send> Future<T>{
fn new(rx: Receiver<Result<T, FutureError>>) -> Future<T> {
Future{ receiver: rx }
}
pub fn first_of(futures: Vec<Future<T>>) -> Future<T> {
let (p, f) = promise::<T>();
Thread::spawn(move || {
let select = Select::new();
let mut handles = HashMap::new();
for future in futures.iter() {
let handle = select.handle(&future.receiver);
let id = handle.id();
handles.insert(handle.id(), handle);
let h = handles.get_mut(&id).unwrap();
unsafe {
h.add();
}
}
{
let first = handles.get_mut(&select.wait()).unwrap();
p.send(
match first.recv() {
Ok(res) => res,
Err(_) => Err(FutureError::HungUp),
}
);
}
for (_, handle) in handles.iter_mut() {
unsafe {
handle.remove();
}
}
});
f
}
// Warning this function is pretty ugly mostly due to the move restrictions on handle for add
// and remove. It needs to be rewritten at some point.
pub fn all(futures: Vec<Future<T>>) -> Future<Vec<T>> {
let (p, f) = promise::<Vec<T>>();
Thread::spawn(move || {
let select = Select::new();
let mut handles = HashMap::new();
for (i, future) in futures.iter().enumerate() {
let handle = select.handle(&future.receiver);
let id = handle.id();
handles.insert(handle.id(), (i, handle));
let &mut (_, ref mut handle) = handles.get_mut(&id).unwrap();
unsafe {
handle.add();
}
}
let mut results: Vec<Option<T>> = futures.iter().map(|_| None).collect();
let mut error: Option<FutureError> = None;
for _ in range(0, futures.len()) {
let id = select.wait();
{
let &mut (i, ref mut handle) = handles.get_mut(&id).unwrap();
match handle.recv() {
Ok(Ok(value)) => {
*results.get_mut(i).unwrap() = Some(value);
},
Ok(Err(err)) => {
error = Some(err);
break;
},
Err(_) => {
error = Some(FutureError::HungUp);
break;
},
}
unsafe{
handle.remove();
}
}
handles.remove(&id);
}
for (_, &mut (_, ref mut handle)) in handles.iter_mut() {
unsafe {
handle.remove();
}
}
match error {
Some(err) => p.fail(err),
None => {
let _ = p.resolve(results.into_iter().map(|v| v.unwrap()).collect());
}
}
});
f
}
/// Creates a Future that completes with val.
pub fn value(val: T) -> Future<T> {
let (p, f) = promise::<T>();
let _ = p.resolve(val);
f
}
/// Creates a Future that resolves with the return value of func,
/// If func fails the failure is propagated through TaskFailure.
pub fn from_fn<F: FnOnce<(), T> + Send>(func: F) -> Future<T> {
let (p, f) = promise::<T>();
Thread::spawn(move || {
let result = Thread::scoped(move || func()).join();
match result {
Ok(val) => {
let _ = p.resolve(val);
},
Err(err) => {p.fail(FutureError::TaskFailure(err));},
};
});
f
}
/// Creates a Future just like from_fn that completes after a delay of duration.
pub fn delay<F: FnOnce<(), T>+Send>(func: F, duration: Duration) -> Future<T> {
Future::from_fn(move || {
timer::sleep(duration);
func()
})
}
/// If this Future completes with a value the new Future completes with func(value).
/// If thie Future completes with an errorthe new Future completes with the same error.
pub fn map<B: Send, F: FnOnce<(T,), B>+Send>(self, func: F) -> Future<B> {
let (p ,f) = promise::<B>();
self.on_result(move |res| {
match res {
Ok(val) => {
let result = Thread::scoped(move || func(val)).join();
match result {
Ok(mapped) => {
let _ = p.resolve(mapped);
},
Err(err) => {p.fail(FutureError::TaskFailure(err));},
};
},
Err(err) => p.fail(err),
};
});
f
}
/// Synchronously waits for the result of the Future and returns it.
pub fn get(self) -> Result<T, FutureError> {
match self.receiver.recv() {
Ok(res) => res,
Err(_) => Err(FutureError::HungUp),
}
}
/// Registers a function f that is called with the result of the Future.
/// This function does not block.
pub fn on_result<F: FnOnce<(Result<T, FutureError>,), ()>+Send>(self, f: F) {
Thread::spawn(move || {
let result = self.get();
f(result);
});
}
/// Registers a function f that is called if the Future completes with a value.
/// This function does not block.
pub fn on_success<F: FnOnce<(T,), ()>+Send>(self, f: F) {
Thread::spawn(move || {
match self.get() {
Ok(value) => f(value),
_ => (),
}
});
}
/// Registers a function f that is called if the Future completes with an error.
/// This function does not block.
pub fn on_failure<F: FnOnce<(FutureError,), ()>+Send>(self, f: F) {
Thread::spawn(move || {
match self.get() {
Err(err) => f(err),
_ => () ,
}
});
}
/// Registers a function f that is called if the Future completes with a value.
/// This function does not block.
pub fn on_complete<S: FnOnce<(T,),()>+Send, F: FnOnce<(FutureError,),()>+Send>(self, success: S, failure: F) {
Thread::spawn(move || {
match self.get() {
Ok(value) => success(value),
Err(err) => failure(err),
}
});
}
}
/// Creates a Future and the associated Promise to complete it.
pub fn promise<T :Send>() -> (Promise<T>, Future<T>) {
let (tx, rx) = channel();
(Promise::new(tx), Future::new(rx))
}
#[cfg(test)]
mod tests {
use super::{promise, Future, FutureError};
use std::boxed::BoxAny;
use std::time::duration::Duration;
use std::io::timer;
use std::sync::mpsc::{
channel
};
use std::thread::Thread;
#[test]
fn test_future(){
let (p, f) = promise();
assert_eq!(p.resolve(123us), Ok(()));
assert_eq!(f.get().ok(), Some(123us));
}
#[test]
fn test_future_hungup(){
let (p, f) = promise::<usize>();
Thread::spawn(move || {
timer::sleep(Duration::seconds(1));
p;
});
match f.get() {
Err(FutureError::HungUp) => (),
_ => panic!("should not happen"),
}
}
#[test]
fn test_future_from_fn(){
let f = Future::from_fn(move || 123us);
assert_eq!(f.get().ok(), Some(123us));
}
#[test]
fn test_future_from_fn_fail(){
let f = Future::from_fn(move || {
panic!("ooops");
123us
});
let err = match f.get() {
Err(FutureError::TaskFailure(err)) => err,
_ => panic!("should not happen"),
};
assert!(err.is::<&'static str>());
assert_eq!(*err.downcast::<&'static str>().unwrap(), "ooops");
}
#[test]
fn test_future_delay(){
let f = Future::delay(move || 123us, Duration::seconds(3));
//TODO: test delay
assert_eq!(f.get().ok(), Some(123us));
}
#[test]
fn test_future_first_of(){
let f1 = Future::delay(move || "slow", Duration::seconds(3));
let f2 = Future::from_fn(move || "fast");
let f3 = Future::first_of(vec![f1,f2]);
assert_eq!(f3.get().ok(), Some("fast"));
}
#[test]
fn test_future_all_failure(){
let f1 = Future::delay(move || "slow", Duration::seconds(3));
let f2 = Future::delay(move || panic!("medium"), Duration::seconds(1));
let f3 = Future::from_fn(move || "fast");
let f4 = Future::all(vec![f1,f2,f3]);
let err = match f4.get() {
Err(FutureError::TaskFailure(err)) => err,
_ => panic!("should not happen"),
};
assert_eq!(*err.downcast::<&'static str>().unwrap(), "medium");
}
#[test]
fn test_future_all_success(){
let f1 = Future::delay(move || "slow", Duration::seconds(3));
let f2 = Future::delay(move || "medium", Duration::seconds(1));
let f3 = Future::from_fn(move || "fast");
let f4 = Future::all(vec![f1,f2,f3]);
assert_eq!(f4.get().ok().unwrap(), vec!["slow", "medium", "fast"]);
}
#[test]
fn test_future_value(){
let f = Future::value(123us);
assert_eq!(f.get().ok(), Some(123us));
}
#[test]
fn test_future_on_result(){
let (tx, rx) = channel();
let f = Future::delay(move || 123us, Duration::seconds(1));
f.on_result(move |x| {
tx.send(x);
});
assert_eq!(rx.recv().ok().unwrap().ok().unwrap(), 123us)
}
#[test]
fn test_future_on_success(){
let (tx, rx) = channel();
let f = Future::delay(move || 123us, Duration::seconds(1));
f.on_success(move |x| {
tx.send(x);
});
assert_eq!(rx.recv().ok().unwrap(), 123us)
}
#[test]
fn test_future_map(){
let (tx, rx) = channel();
let f = Future::value(3us);
f.map(move |x| x*x)
.on_success(move |x| {
tx.send(x);
});
assert_eq!(rx.recv().ok().unwrap(), 9us);
}
}