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
extern crate futures;
#[cfg(test)] #[macro_use] extern crate mdo;
#[cfg(test)] extern crate futures_cpupool;

pub mod future {
    use futures::future::*;

    pub fn bind<T, E, TF: Future<Item=T, Error=E> + Sized, IFU: IntoFuture<Error = E>, F: FnOnce(T) -> IFU>(m: TF, f: F) -> AndThen<TF, IFU, F> {
        m.and_then(f)
    }

    pub fn ret<T, E>(x: T) -> FutureResult<T, E> {
        ok::<T, E>(x)
    }

}

pub mod stream {
    use futures::{Async, Poll};
    use futures::future::{Future, FutureResult, ok};
    use futures::stream::*;

    /// bind for Stream, equivalent to `m.map(f).flatten()`
    pub fn bind<E, I, U, F>(m: I, f: F) -> Flatten<Map<I, F>>
        where I: Stream<Error = E> + Sized,
              U: Stream<Error = E> + Sized,
              F: FnMut(<I as Stream>::Item) -> U
    {
        m.map(f).flatten()
    }

    pub fn ret<T, E>(x: T) -> WrappedStream<FutureResult<T, E>> {
        new(Some(ok::<T, E>(x)))
    }

    pub fn mzero<T, E>() -> WrappedStream<FutureResult<T, E>> {
        new(None)
    }

    /// A stream that wraps a single future or nothing (representing an empty stream)
    pub struct WrappedStream<F: Future> {
        future: Option<F>,
    }

    pub fn new<F: Future>(future: Option<F>) -> WrappedStream<F> {
        WrappedStream { future: future }
    }

    impl<F: Future> Stream for WrappedStream<F> {
        type Item = F::Item;
        type Error = F::Error;

        fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
            let ret = match self.future {
                None => return Ok(Async::Ready(None)),
                Some(ref mut future) => {
                    match future.poll() {
                        Ok(Async::NotReady) => return Ok(Async::NotReady),
                        Err(e) => Err(e),
                        Ok(Async::Ready(r)) => Ok(r),
                    }
                }
            };
            self.future = None;
            ret.map(|r| Async::Ready(Some(r)))
        }
    }

}

#[cfg(test)]
mod tests {
    use futures_cpupool::CpuPool;
    use std::vec::Vec;
    use futures::{Future, stream, Stream};

    #[test]
    fn future_mdo() {
        use futures::future::ok;
        use super::future::{bind, ret};
        let pool = CpuPool::new_num_cpus();

        let get_num = ok::<u32, String>(42);
        let get_factor = ok::<u32, String>(2);

        let res = mdo! {
            arg =<< get_num;
            fact =<< get_factor;
            ret ret(arg * fact)
        };

        let val = pool.spawn(res);

        assert_eq!(val.wait().unwrap(), 84);
    }

    #[test]
    fn stream_bind() {
        use super::stream::{bind, ret, mzero};

        let l = bind(stream_range(0, 3), move |x| stream_range(x, 3));
        assert_eq!(execute(l), vec![0, 1, 2, 1, 2, 2]);

        let l = bind(stream_range(0, 3),
                     move |x| bind(stream_range(0, 3), move |y| ret(x + y)));
        assert_eq!(execute(l), vec![0, 1, 2, 1, 2, 3, 2, 3, 4]);

        let l = bind(stream_range(1, 11), move |z| {
            bind(stream_range(1, z + 1), move |y| {
                bind(stream_range(1, y + 1), move |x| {
                    bind(if x * x + y * y == z * z {
                             ret(())
                         } else {
                             mzero()
                         },
                         move |_| ret((x, y, z)))
                })
            })
        });
        assert_eq!(execute(l), vec![(3, 4, 5), (6, 8, 10)]);
    }

    #[test]
    fn stream_mdo() {
        use super::stream::{bind, ret, mzero};
        let l = mdo! {
            x =<< stream_range(0, 3);
            ret stream_range(x, 3)
        };
        assert_eq!(execute(l), vec![0, 1, 2, 1, 2, 2]);
        let l = mdo! {
            x =<< stream_range(0, 3);
            y =<< stream_range(0, 3);
            ret ret(x + y)
        };
        assert_eq!(execute(l), vec![0, 1, 2, 1, 2, 3, 2, 3, 4]);
        let l = mdo! {
            z =<< stream_range(1, 11);
            y =<< stream_range(1, z);
            x =<< stream_range(1, y + 1);
            let test = x * x + y * y == z * z;
            when test;
            let res = (x, y, z);
            ret ret(res)
        };
        assert_eq!(execute(l), vec![(3, 4, 5), (6, 8, 10)]);
    }

    #[test]
    fn stream_ignore() {
        use super::stream::{bind, ret};
        let l = mdo! {
            x =<< stream_range(0, 5);
            ign stream_range(0, 2);
            ret ret(x)
        };
        assert_eq!(execute(l), vec![0, 0, 1, 1, 2, 2, 3, 3, 4, 4]);
    }

    // Generate a stream from start (inclusive) to end (exclusive)
    fn stream_range(start: u32, end: u32) -> stream::BoxStream<u32, String> {
        stream::iter((start..end).map(Ok::<u32, String>)).boxed()
    }

    // execute the stream on a CpuPool and return a future of the
    // collected result
    fn execute<T, S>(s: S) -> Vec<T>
        where T: Send + 'static,
              S: Stream<Item = T, Error = String> + Send + 'static
    {
        let pool = CpuPool::new_num_cpus();
        let v = pool.spawn(s.collect());
        v.wait().unwrap()
    }

}