tokio_postgres/
socket.rs

1use std::io;
2use std::pin::Pin;
3use std::task::{Context, Poll};
4use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
5use tokio::net::TcpStream;
6#[cfg(unix)]
7use tokio::net::UnixStream;
8
9#[derive(Debug)]
10enum Inner {
11    Tcp(TcpStream),
12    #[cfg(unix)]
13    Unix(UnixStream),
14}
15
16/// The standard stream type used by the crate.
17///
18/// Requires the `runtime` Cargo feature (enabled by default).
19#[derive(Debug)]
20pub struct Socket(Inner);
21
22impl Socket {
23    pub(crate) fn new_tcp(stream: TcpStream) -> Socket {
24        Socket(Inner::Tcp(stream))
25    }
26
27    #[cfg(unix)]
28    pub(crate) fn new_unix(stream: UnixStream) -> Socket {
29        Socket(Inner::Unix(stream))
30    }
31}
32
33impl AsyncRead for Socket {
34    fn poll_read(
35        mut self: Pin<&mut Self>,
36        cx: &mut Context<'_>,
37        buf: &mut ReadBuf<'_>,
38    ) -> Poll<io::Result<()>> {
39        match &mut self.0 {
40            Inner::Tcp(s) => Pin::new(s).poll_read(cx, buf),
41            #[cfg(unix)]
42            Inner::Unix(s) => Pin::new(s).poll_read(cx, buf),
43        }
44    }
45}
46
47impl AsyncWrite for Socket {
48    fn poll_write(
49        mut self: Pin<&mut Self>,
50        cx: &mut Context<'_>,
51        buf: &[u8],
52    ) -> Poll<io::Result<usize>> {
53        match &mut self.0 {
54            Inner::Tcp(s) => Pin::new(s).poll_write(cx, buf),
55            #[cfg(unix)]
56            Inner::Unix(s) => Pin::new(s).poll_write(cx, buf),
57        }
58    }
59
60    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
61        match &mut self.0 {
62            Inner::Tcp(s) => Pin::new(s).poll_flush(cx),
63            #[cfg(unix)]
64            Inner::Unix(s) => Pin::new(s).poll_flush(cx),
65        }
66    }
67
68    fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
69        match &mut self.0 {
70            Inner::Tcp(s) => Pin::new(s).poll_shutdown(cx),
71            #[cfg(unix)]
72            Inner::Unix(s) => Pin::new(s).poll_shutdown(cx),
73        }
74    }
75}