Skip to content

Commit

Permalink
feat(net): add from_std for Listener (#376)
Browse files Browse the repository at this point in the history
  • Loading branch information
Berrysoft authored Feb 18, 2025
1 parent 68a9aad commit c75093f
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
9 changes: 8 additions & 1 deletion compio-net/src/tcp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,13 @@ impl TcpListener {
.await
}

/// Creates new TcpListener from a [`std::net::TcpListener`].
pub fn from_std(stream: std::net::TcpListener) -> io::Result<Self> {
Ok(Self {
inner: Socket::from_socket2(Socket2::from(stream))?,
})
}

/// Close the socket. If the returned future is dropped before polling, the
/// socket won't be closed.
pub fn close(self) -> impl Future<Output = io::Result<()>> {
Expand Down Expand Up @@ -167,7 +174,7 @@ impl TcpStream {
.await
}

/// Creates new TcpStream from a std::net::TcpStream.
/// Creates new TcpStream from a [`std::net::TcpStream`].
pub fn from_std(stream: std::net::TcpStream) -> io::Result<Self> {
Ok(Self {
inner: Socket::from_socket2(Socket2::from(stream))?,
Expand Down
21 changes: 16 additions & 5 deletions compio-net/src/unix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,14 @@ impl UnixListener {
Ok(UnixListener { inner: socket })
}

#[cfg(unix)]
/// Creates new UnixListener from a [`std::os::unix::net::UnixListener`].
pub fn from_std(stream: std::os::unix::net::UnixListener) -> io::Result<Self> {
Ok(Self {
inner: Socket::from_socket2(Socket2::from(stream))?,
})
}

/// Close the socket. If the returned future is dropped before polling, the
/// socket won't be closed.
pub fn close(self) -> impl Future<Output = io::Result<()>> {
Expand Down Expand Up @@ -148,7 +156,7 @@ impl UnixStream {
}

#[cfg(unix)]
/// Creates new UnixStream from a std::os::unix::net::UnixStream.
/// Creates new UnixStream from a [`std::os::unix::net::UnixStream`].
pub fn from_std(stream: std::os::unix::net::UnixStream) -> io::Result<Self> {
Ok(Self {
inner: Socket::from_socket2(Socket2::from(stream))?,
Expand Down Expand Up @@ -286,10 +294,13 @@ fn empty_unix_socket() -> SockAddr {
unsafe {
SockAddr::try_init(|addr, len| {
let addr: *mut SOCKADDR_UN = addr.cast();
std::ptr::write(addr, SOCKADDR_UN {
sun_family: AF_UNIX,
sun_path: [0; 108],
});
std::ptr::write(
addr,
SOCKADDR_UN {
sun_family: AF_UNIX,
sun_path: [0; 108],
},
);
std::ptr::write(len, 3);
Ok(())
})
Expand Down

0 comments on commit c75093f

Please sign in to comment.