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
/// Dummy object implementing reactor-trait common interfaces on top of tokio
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Tokio;

#[cfg(unix)]
mod unix {
    use crate::Tokio;
    use async_trait::async_trait;
    use futures_core::Stream;
    use futures_io::{AsyncRead, AsyncWrite};
    use reactor_trait::{AsyncIOHandle, IOHandle, Reactor};
    use std::{
        io::{self, IoSlice, IoSliceMut, Read, Write},
        pin::Pin,
        task::{Context, Poll},
        time::{Duration, Instant},
    };
    use tokio::{io::unix::AsyncFd, runtime::Handle};
    use tokio_stream::{wrappers::IntervalStream, StreamExt};

    #[derive(Debug)]
    pub(super) struct TokioReactor(pub(super) Handle);

    #[async_trait]
    impl Reactor for Tokio {
        fn register(&self, socket: IOHandle) -> io::Result<Box<dyn AsyncIOHandle + Send>> {
            Ok(Box::new(AsyncFdWrapper(AsyncFd::new(socket)?)))
        }

        async fn sleep(&self, dur: Duration) {
            tokio::time::sleep(dur).await;
        }

        fn interval(&self, dur: Duration) -> Box<dyn Stream<Item = Instant>> {
            Box::new(
                IntervalStream::new(tokio::time::interval(dur)).map(tokio::time::Instant::into_std),
            )
        }
    }

    struct AsyncFdWrapper(AsyncFd<IOHandle>);

    impl AsyncFdWrapper {
        fn read<F: FnOnce(&mut AsyncFd<IOHandle>) -> futures_io::Result<usize>>(
            &mut self,
            cx: &mut Context<'_>,
            f: F,
        ) -> Option<Poll<futures_io::Result<usize>>> {
            Some(match self.0.poll_read_ready_mut(cx) {
                Poll::Pending => Poll::Pending,
                Poll::Ready(Err(e)) => Poll::Ready(Err(e)),
                Poll::Ready(Ok(mut guard)) => match guard.try_io(f) {
                    Ok(res) => Poll::Ready(res),
                    Err(_) => return None,
                },
            })
        }

        fn write<R, F: FnOnce(&mut AsyncFd<IOHandle>) -> futures_io::Result<R>>(
            &mut self,
            cx: &mut Context<'_>,
            f: F,
        ) -> Option<Poll<futures_io::Result<R>>> {
            Some(match self.0.poll_write_ready_mut(cx) {
                Poll::Pending => Poll::Pending,
                Poll::Ready(Err(e)) => Poll::Ready(Err(e)),
                Poll::Ready(Ok(mut guard)) => match guard.try_io(f) {
                    Ok(res) => Poll::Ready(res),
                    Err(_) => return None,
                },
            })
        }
    }

    impl AsyncRead for AsyncFdWrapper {
        fn poll_read(
            mut self: Pin<&mut Self>,
            cx: &mut Context<'_>,
            buf: &mut [u8],
        ) -> Poll<futures_io::Result<usize>> {
            loop {
                if let Some(res) = self.read(cx, |socket| socket.get_mut().read(buf)) {
                    return res;
                }
            }
        }

        fn poll_read_vectored(
            mut self: Pin<&mut Self>,
            cx: &mut Context<'_>,
            bufs: &mut [IoSliceMut<'_>],
        ) -> Poll<futures_io::Result<usize>> {
            loop {
                if let Some(res) = self.read(cx, |socket| socket.get_mut().read_vectored(bufs)) {
                    return res;
                }
            }
        }
    }

    impl AsyncWrite for AsyncFdWrapper {
        fn poll_write(
            mut self: Pin<&mut Self>,
            cx: &mut Context<'_>,
            buf: &[u8],
        ) -> Poll<futures_io::Result<usize>> {
            loop {
                if let Some(res) = self.write(cx, |socket| socket.get_mut().write(buf)) {
                    return res;
                }
            }
        }

        fn poll_write_vectored(
            mut self: Pin<&mut Self>,
            cx: &mut Context<'_>,
            bufs: &[IoSlice<'_>],
        ) -> Poll<futures_io::Result<usize>> {
            loop {
                if let Some(res) = self.write(cx, |socket| socket.get_mut().write_vectored(bufs)) {
                    return res;
                }
            }
        }

        fn poll_flush(
            mut self: Pin<&mut Self>,
            cx: &mut Context<'_>,
        ) -> Poll<futures_io::Result<()>> {
            loop {
                if let Some(res) = self.write(cx, |socket| socket.get_mut().flush()) {
                    return res;
                }
            }
        }

        fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<futures_io::Result<()>> {
            self.poll_flush(cx)
        }
    }
}