rbdc/net/
socket.rs

1#![allow(dead_code)]
2
3use std::io;
4use std::path::Path;
5use std::pin::Pin;
6use std::task::{Context, Poll};
7
8use crate::rt::{AsyncRead, AsyncWrite, TcpStream};
9
10#[derive(Debug)]
11pub enum Socket {
12    Tcp(TcpStream),
13
14    #[cfg(unix)]
15    Unix(crate::rt::UnixStream),
16}
17
18impl Socket {
19    pub async fn connect_tcp(host: &str, port: u16) -> io::Result<Self> {
20        // Trim square brackets from host if it's an IPv6 address as the `url` crate doesn't do that.
21        TcpStream::connect((host.trim_matches(|c| c == '[' || c == ']'), port))
22            .await
23            .map(Socket::Tcp)
24    }
25
26    #[cfg(unix)]
27    pub async fn connect_uds(path: impl AsRef<Path>) -> io::Result<Self> {
28        crate::rt::UnixStream::connect(path.as_ref())
29            .await
30            .map(Socket::Unix)
31    }
32
33    #[cfg(not(unix))]
34    pub async fn connect_uds(_: impl AsRef<Path>) -> io::Result<Self> {
35        Err(io::Error::new(
36            io::ErrorKind::Other,
37            "Unix domain sockets are not supported outside Unix platforms.",
38        ))
39    }
40
41    pub async fn shutdown(&mut self) -> io::Result<()> {
42        {
43            use crate::rt::AsyncWriteExt;
44
45            match self {
46                Socket::Tcp(s) => s.shutdown().await,
47
48                #[cfg(unix)]
49                Socket::Unix(s) => s.shutdown().await,
50            }
51        }
52    }
53}
54
55impl AsyncRead for Socket {
56    fn poll_read(
57        mut self: Pin<&mut Self>,
58        cx: &mut Context<'_>,
59        buf: &mut super::PollReadBuf<'_>,
60    ) -> Poll<io::Result<super::PollReadOut>> {
61        match &mut *self {
62            Socket::Tcp(s) => Pin::new(s).poll_read(cx, buf),
63
64            #[cfg(unix)]
65            Socket::Unix(s) => Pin::new(s).poll_read(cx, buf),
66        }
67    }
68}
69
70impl AsyncWrite for Socket {
71    fn poll_write(
72        mut self: Pin<&mut Self>,
73        cx: &mut Context<'_>,
74        buf: &[u8],
75    ) -> Poll<io::Result<usize>> {
76        match &mut *self {
77            Socket::Tcp(s) => Pin::new(s).poll_write(cx, buf),
78
79            #[cfg(unix)]
80            Socket::Unix(s) => Pin::new(s).poll_write(cx, buf),
81        }
82    }
83
84    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
85        match &mut *self {
86            Socket::Tcp(s) => Pin::new(s).poll_flush(cx),
87
88            #[cfg(unix)]
89            Socket::Unix(s) => Pin::new(s).poll_flush(cx),
90        }
91    }
92
93    fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
94        match &mut *self {
95            Socket::Tcp(s) => Pin::new(s).poll_shutdown(cx),
96
97            #[cfg(unix)]
98            Socket::Unix(s) => Pin::new(s).poll_shutdown(cx),
99        }
100    }
101}