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
#![allow(missing_docs)]

use finchers_core::endpoint::{Context, Endpoint};
use finchers_core::task::{self, IntoTask, Task};
use finchers_core::{Error, Poll, PollResult};
use std::mem;

pub fn new<E, F, R>(endpoint: E, f: F) -> MapAsync<E, F>
where
    E: Endpoint,
    F: FnOnce(E::Output) -> R + Clone + Send + Sync,
    R: IntoTask,
    R::Task: Send,
{
    MapAsync { endpoint, f }
}

#[derive(Copy, Clone, Debug)]
pub struct MapAsync<E, F> {
    endpoint: E,
    f: F,
}

impl<E, F, R> Endpoint for MapAsync<E, F>
where
    E: Endpoint,
    F: FnOnce(E::Output) -> R + Clone + Send + Sync,
    R: IntoTask,
    R::Task: Send,
{
    type Output = R::Output;
    type Task = MapAsyncTask<E::Task, F, R>;

    fn apply(&self, cx: &mut Context) -> Option<Self::Task> {
        let task = self.endpoint.apply(cx)?;
        Some(MapAsyncTask::First(task, self.f.clone()))
    }
}

#[derive(Debug)]
pub enum MapAsyncTask<T, F, R>
where
    T: Task,
    F: FnOnce(T::Output) -> R + Send,
    R: IntoTask,
    R::Task: Send,
{
    First(T, F),
    Second(R::Task),
    Done,
}

impl<T, F, R> Task for MapAsyncTask<T, F, R>
where
    T: Task,
    F: FnOnce(T::Output) -> R + Send,
    R: IntoTask,
    R::Task: Send,
{
    type Output = R::Output;

    fn poll_task(&mut self, cx: &mut task::Context) -> PollResult<Self::Output, Error> {
        use self::MapAsyncTask::*;
        loop {
            // TODO: optimize
            match mem::replace(self, Done) {
                First(mut task, f) => match task.poll_task(cx) {
                    Poll::Pending => {
                        *self = First(task, f);
                        return Poll::Pending;
                    }
                    Poll::Ready(Ok(r)) => {
                        cx.input().enter_scope(|| {
                            *self = Second(f(r).into_task());
                        });
                        continue;
                    }
                    Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
                },
                Second(mut fut) => {
                    return match fut.poll_task(cx) {
                        Poll::Pending => {
                            *self = Second(fut);
                            Poll::Pending
                        }
                        polled => polled,
                    }
                }
                Done => panic!(),
            }
        }
    }
}