ntex_async_std/
lib.rs

1use std::{io::Result, net, net::SocketAddr};
2
3use ntex_bytes::PoolRef;
4use ntex_io::Io;
5
6mod io;
7mod signals;
8
9pub use self::signals::{signal, Signal};
10
11#[derive(Clone)]
12struct TcpStream(async_std::net::TcpStream);
13
14#[cfg(unix)]
15#[derive(Clone)]
16struct UnixStream(async_std::os::unix::net::UnixStream);
17
18/// Opens a TCP connection to a remote host.
19pub async fn tcp_connect(addr: SocketAddr) -> Result<Io> {
20    let sock = async_std::net::TcpStream::connect(addr).await?;
21    sock.set_nodelay(true)?;
22    Ok(Io::new(TcpStream(sock)))
23}
24
25/// Opens a TCP connection to a remote host and use specified memory pool.
26pub async fn tcp_connect_in(addr: SocketAddr, pool: PoolRef) -> Result<Io> {
27    let sock = async_std::net::TcpStream::connect(addr).await?;
28    sock.set_nodelay(true)?;
29    Ok(Io::with_memory_pool(TcpStream(sock), pool))
30}
31
32#[cfg(unix)]
33/// Opens a unix stream connection.
34pub async fn unix_connect<P>(addr: P) -> Result<Io>
35where
36    P: AsRef<async_std::path::Path>,
37{
38    let sock = async_std::os::unix::net::UnixStream::connect(addr).await?;
39    Ok(Io::new(UnixStream(sock)))
40}
41
42#[cfg(unix)]
43/// Opens a unix stream connection and specified memory pool.
44pub async fn unix_connect_in<P>(addr: P, pool: PoolRef) -> Result<Io>
45where
46    P: AsRef<async_std::path::Path>,
47{
48    let sock = async_std::os::unix::net::UnixStream::connect(addr).await?;
49    Ok(Io::with_memory_pool(UnixStream(sock), pool))
50}
51
52/// Convert std TcpStream to async-std's TcpStream
53pub fn from_tcp_stream(stream: net::TcpStream) -> Result<Io> {
54    stream.set_nonblocking(true)?;
55    stream.set_nodelay(true)?;
56    Ok(Io::new(TcpStream(async_std::net::TcpStream::from(stream))))
57}
58
59#[cfg(unix)]
60/// Convert std UnixStream to async-std's UnixStream
61pub fn from_unix_stream(stream: std::os::unix::net::UnixStream) -> Result<Io> {
62    stream.set_nonblocking(true)?;
63    Ok(Io::new(UnixStream(From::from(stream))))
64}