microasync_util/io/read/
tcpstream.rs

1extern crate std;
2
3use core::{
4    future::Future,
5    pin::Pin,
6    task::{Context, Poll},
7};
8use std::{
9    io::{self, ErrorKind, Read},
10    net::{SocketAddr, TcpListener, TcpStream},
11};
12
13use super::{ReadExactFuture, ReadFuture};
14
15impl<'a> Future for ReadFuture<'a, TcpStream> {
16    type Output = Result<usize, io::Error>;
17
18    fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
19        let me = self.get_mut();
20        me.0.set_nonblocking(true)
21            .expect("unable to set nonblocking-mode.");
22        let r = Read::read(me.0, me.1);
23        me.0.set_nonblocking(false)
24            .expect("unable to clear nonblocking-mode.");
25
26        match r {
27            Ok(x) => Poll::Ready(Ok(x)),
28            Err(e) if e.kind() == ErrorKind::WouldBlock => Poll::Pending,
29            Err(e) => Poll::Ready(Err(e)),
30        }
31    }
32}
33
34impl<'a> Future for ReadExactFuture<'a, TcpStream> {
35    type Output = Result<(), io::Error>;
36
37    fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
38        let me = self.get_mut();
39        me.0.set_nonblocking(true)
40            .expect("unable to set nonblocking-mode.");
41        let r = Read::read_exact(me.0, me.1);
42        me.0.set_nonblocking(false)
43            .expect("unable to clear nonblocking-mode.");
44
45        match r {
46            Ok(x) => Poll::Ready(Ok(x)),
47            Err(e) if e.kind() == ErrorKind::WouldBlock => Poll::Pending,
48            Err(e) => Poll::Ready(Err(e)),
49        }
50    }
51}
52
53pub struct AcceptFuture<'a>(&'a mut TcpListener);
54
55impl<'a> Future for AcceptFuture<'a> {
56    type Output = Result<(TcpStream, SocketAddr), io::Error>;
57
58    fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
59        let me = self.get_mut();
60        me.0.set_nonblocking(true)
61            .expect("unable to set nonblocking-mode.");
62        let r = me.0.accept();
63        me.0.set_nonblocking(false)
64            .expect("unable to clear nonblocking-mode.");
65
66        match r {
67            Ok(x) => Poll::Ready(Ok(x)),
68            Err(e) if e.kind() == ErrorKind::WouldBlock => Poll::Pending,
69            Err(e) => Poll::Ready(Err(e)),
70        }
71    }
72}
73
74/// Returns an AcceptFuture, which is an async TcpListener::accept call.
75pub fn accept(listener: &mut TcpListener) -> AcceptFuture {
76    AcceptFuture(listener)
77}