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
#![doc(html_logo_url = "https://avatars3.githubusercontent.com/u/15439811?v=3&s=200",
       html_favicon_url = "https://iorust.github.io/favicon.ico",
       html_root_url = "https://iorust.github.io",
       html_playground_url = "https://play.rust-lang.org",
       issue_tracker_base_url = "https://github.com/iorust/thunks/issues")]

//! Asynchronous composer for Rust.

// use std::thread;
use std::sync::mpsc::{Receiver, sync_channel};
use std::boxed::{Box};

pub struct Thunk<T, E>(Box<Fn(Box<Fn(Result<T, E>) + Send + 'static>) + Send + 'static>);

impl<T, E> Thunk<T, E> where T: Send + 'static, E: Send + 'static {
    pub fn new<F>(task: F) -> Thunk<T, E>
    where F: Fn(Box<Fn(Result<T, E>) + Send + 'static>) + Send + 'static {
        Thunk(Box::new(task))
    }

    pub fn seq(thunk_vec: Vec<Thunk<T, E>>) -> Thunk<Vec<T>, E> {
        let thunk_vec = Box::new(thunk_vec);
        Thunk::new(move |cb| {
            let mut res: Vec<T> = Vec::new();
            for thunk in thunk_vec.iter() {
                match thunk.await() {
                    Ok(val) => res.push(val),
                    Err(err) => {
                        cb(Err(err));
                        return;
                    }
                }
            }
            cb(Ok(res));
        })
    }

    pub fn all(thunk_vec: Vec<Thunk<T, E>>) -> Thunk<Vec<T>, E> {
        let thunk_vec = Box::new(thunk_vec);
        Thunk::new(move |cb| {
            let mut res: Vec<T> = Vec::new();
            let rx_vec: Vec<Receiver<Result<T, E>>> = thunk_vec.iter()
                .map(|t| t.call_thunk()).collect();

            for rx in rx_vec.iter() {
                match rx.recv().unwrap() {
                    Ok(val) => res.push(val),
                    Err(err) => {
                        cb(Err(err));
                        return;
                    }
                }
            }
            cb(Ok(res));
        })
    }

    pub fn await(&self) -> Result<T, E> {
        self.call_thunk().recv().unwrap()
    }

    fn call_thunk(&self) -> Receiver<Result<T, E>> {
        let (tx, rx) = sync_channel::<Result<T, E>>(1);
        (self.0)(Box::new(move |res| {
            tx.try_send(res).unwrap();
        }));
        rx
    }
}

#[cfg(test)]
mod tests {
    use std::thread;
    use std::time::Duration;
    use super::*;

    #[test]
    fn thunk() {
        let thunk: Thunk<i32, &str> = Thunk::new(|cb| {
            thread::spawn(move || {
                thread::sleep(Duration::new(3, 0));
                cb(Ok(1));
            });
        });
        let res = thunk.await().unwrap();
        // println!("{:?}", res);
        assert_eq!(res, 1);
    }

    #[test]
    fn thunk_seq() {
        let thunk_vec: Vec<Thunk<i32, &str>> = vec![
            Thunk::new(|cb| {
                thread::spawn(move || {
                    thread::sleep(Duration::new(1, 0));
                    cb(Ok(1));
                });
            }),
            Thunk::new(|cb| {
                thread::spawn(move || {
                    thread::sleep(Duration::new(1, 0));
                    cb(Ok(2));
                });
            }),
            Thunk::new(|cb| {
                thread::spawn(move || {
                    thread::sleep(Duration::new(1, 0));
                    cb(Ok(3));
                });
            })
        ];
        let res = Thunk::seq(thunk_vec).await().unwrap();
        assert_eq!(res, vec![1, 2, 3]);
    }

    #[test]
    fn thunk_all() {
        let thunk_vec: Vec<Thunk<i32, &str>> = vec![
            Thunk::new(|cb| {
                thread::spawn(move || {
                    thread::sleep(Duration::new(1, 0));
                    cb(Ok(1));
                });
            }),
            Thunk::new(|cb| {
                thread::spawn(move || {
                    thread::sleep(Duration::new(1, 0));
                    cb(Ok(2));
                });
            }),
            Thunk::new(|cb| {
                thread::spawn(move || {
                    thread::sleep(Duration::new(1, 0));
                    cb(Ok(3));
                });
            })
        ];
        let res = Thunk::all(thunk_vec).await().unwrap();
        assert_eq!(res, vec![1, 2, 3]);
    }
}