| 1 | use crate::net::Socket; |
| 2 | |
| 3 | use std::io::{self, Read, Write}; |
| 4 | use std::task::{Context, Poll}; |
| 5 | |
| 6 | use futures_core::ready; |
| 7 | use futures_util::future; |
| 8 | |
| 9 | pub struct StdSocket<S> { |
| 10 | pub socket: S, |
| 11 | wants_read: bool, |
| 12 | wants_write: bool, |
| 13 | } |
| 14 | |
| 15 | impl<S: Socket> StdSocket<S> { |
| 16 | pub fn new(socket: S) -> Self { |
| 17 | Self { |
| 18 | socket, |
| 19 | wants_read: false, |
| 20 | wants_write: false, |
| 21 | } |
| 22 | } |
| 23 | |
| 24 | pub fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> { |
| 25 | if self.wants_write { |
| 26 | ready!(self.socket.poll_write_ready(cx))?; |
| 27 | self.wants_write = false; |
| 28 | } |
| 29 | |
| 30 | if self.wants_read { |
| 31 | ready!(self.socket.poll_read_ready(cx))?; |
| 32 | self.wants_read = false; |
| 33 | } |
| 34 | |
| 35 | Poll::Ready(Ok(())) |
| 36 | } |
| 37 | |
| 38 | pub async fn ready(&mut self) -> io::Result<()> { |
| 39 | future::poll_fn(|cx| self.poll_ready(cx)).await |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | impl<S: Socket> Read for StdSocket<S> { |
| 44 | fn read(&mut self, mut buf: &mut [u8]) -> io::Result<usize> { |
| 45 | self.wants_read = true; |
| 46 | let read = self.socket.try_read(&mut buf)?; |
| 47 | self.wants_read = false; |
| 48 | |
| 49 | Ok(read) |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | impl<S: Socket> Write for StdSocket<S> { |
| 54 | fn write(&mut self, buf: &[u8]) -> io::Result<usize> { |
| 55 | self.wants_write = true; |
| 56 | let written = self.socket.try_write(buf)?; |
| 57 | self.wants_write = false; |
| 58 | Ok(written) |
| 59 | } |
| 60 | |
| 61 | fn flush(&mut self) -> io::Result<()> { |
| 62 | // NOTE: TCP sockets and unix sockets are both no-ops for flushes |
| 63 | Ok(()) |
| 64 | } |
| 65 | } |