async_await/
lib.rs

1extern crate futures;
2
3pub use futures::*;
4pub use std::thread;
5
6#[macro_export]
7macro_rules! async {
8    ($e: expr) => ({
9        let (tx, rx) = oneshot();
10        thread::spawn(move || {
11            tx.complete($e);
12        });
13        rx
14    });
15    ($block:block) => ({
16        let (tx, rx) = oneshot();
17        thread::spawn(move || {
18            tx.complete($block);
19        });
20        rx
21    });
22}
23
24#[macro_export]
25macro_rules! await {
26    ($f: expr) => {
27        $f.wait().unwrap()
28    };
29    ($f: expr, $d: expr) => {
30        match $f.wait() {
31            Ok(e) => e,
32            Err(_) => $d
33        }
34    }
35}
36
37#[test]
38fn test_simple_async() {
39    let a = async!{42};
40    assert_eq!(a.wait().unwrap(), 42);
41}
42
43#[test]
44fn test_complex_async() {
45    let f1 = async!{42};
46    let f2 = async!{18};
47    let transformation = f1.map(|v| v * 2).join((f2.map(|v| v + 5)))
48        .and_then(|(v1, v2)| Ok(v1 - v2));
49    assert_eq!(61, await!{transformation});
50}
51
52#[test]
53fn test_block() {
54    let f1 = async!{{
55        let f1 = async!{42};
56        await!{f1.map(|v| v * 2)}
57    }};
58    assert_eq!(84, await!{f1})
59}
60
61#[test]
62fn test_await() {
63    let a = async!{42};
64    assert_eq!(await!(a), 42);
65}
66
67#[test]
68fn test_default() {
69    let a = async!{panic!("i")};
70    let res = await!(a, 9711);
71    assert_eq!(res, 9711);
72}