ntex_tokio/
lib.rs

1use std::{io::Result, net, net::SocketAddr};
2
3use ntex_io::Io;
4use ntex_service::cfg::SharedCfg;
5
6mod io;
7
8pub use self::io::{SocketOptions, TokioIoBoxed};
9
10struct TcpStream(tokio::net::TcpStream);
11
12#[cfg(unix)]
13struct UnixStream(tokio::net::UnixStream);
14
15/// Opens a TCP connection to a remote host.
16pub async fn tcp_connect(addr: SocketAddr, cfg: SharedCfg) -> Result<Io> {
17    let sock = tokio::net::TcpStream::connect(addr).await?;
18    sock.set_nodelay(true)?;
19    Ok(Io::new(TcpStream(sock), cfg))
20}
21
22#[cfg(unix)]
23/// Opens a unix stream connection.
24pub async fn unix_connect<'a, P>(addr: P, cfg: SharedCfg) -> Result<Io>
25where
26    P: AsRef<std::path::Path> + 'a,
27{
28    let sock = tokio::net::UnixStream::connect(addr).await?;
29    Ok(Io::new(UnixStream(sock), cfg))
30}
31
32/// Convert std TcpStream to tokio's TcpStream
33pub fn from_tcp_stream(stream: net::TcpStream, cfg: SharedCfg) -> Result<Io> {
34    stream.set_nonblocking(true)?;
35    stream.set_nodelay(true)?;
36    Ok(Io::new(
37        TcpStream(tokio::net::TcpStream::from_std(stream)?),
38        cfg,
39    ))
40}
41
42#[cfg(unix)]
43/// Convert std UnixStream to tokio's UnixStream
44pub fn from_unix_stream(
45    stream: std::os::unix::net::UnixStream,
46    cfg: SharedCfg,
47) -> Result<Io> {
48    stream.set_nonblocking(true)?;
49    Ok(Io::new(
50        UnixStream(tokio::net::UnixStream::from_std(stream)?),
51        cfg,
52    ))
53}