Skip to content

Commit

Permalink
[Lib] Add the implementation of AsFd
Browse files Browse the repository at this point in the history
Signed-off-by: csh <[email protected]>
  • Loading branch information
L-jasmine committed Sep 2, 2024
1 parent c0f3e2f commit 13091a5
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
20 changes: 19 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ pub use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr};
use std::{
io::{self, Read, Write},
net::{SocketAddrV4, SocketAddrV6},
os::wasi::prelude::{AsRawFd, FromRawFd, IntoRawFd},
os::fd::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd},
};

#[derive(Debug)]
Expand All @@ -28,6 +28,12 @@ impl AsMut<socket::Socket> for TcpStream {
}
}

impl AsFd for TcpStream {
fn as_fd(&self) -> BorrowedFd<'_> {
unsafe { BorrowedFd::borrow_raw(self.as_raw_fd()) }
}
}

#[derive(Debug)]
pub struct TcpListener {
s: socket::Socket,
Expand All @@ -47,6 +53,12 @@ impl AsMut<socket::Socket> for TcpListener {
}
}

impl AsFd for TcpListener {
fn as_fd(&self) -> BorrowedFd<'_> {
unsafe { BorrowedFd::borrow_raw(self.as_raw_fd()) }
}
}

#[derive(Debug)]
pub struct UdpSocket {
s: socket::Socket,
Expand All @@ -64,6 +76,12 @@ impl AsMut<socket::Socket> for UdpSocket {
}
}

impl AsFd for UdpSocket {
fn as_fd(&self) -> BorrowedFd<'_> {
unsafe { BorrowedFd::borrow_raw(self.as_raw_fd()) }
}
}

impl TcpStream {
/// Create TCP socket and connect to the given address.
///
Expand Down
8 changes: 7 additions & 1 deletion src/socket.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::io;
use std::mem::MaybeUninit;
use std::net::{Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr, SocketAddrV4, SocketAddrV6};
use std::os::wasi::prelude::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
use std::os::fd::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, RawFd};

#[derive(Copy, Clone, Debug)]
#[repr(u8, align(1))]
Expand Down Expand Up @@ -1307,6 +1307,12 @@ impl AsRawFd for Socket {
}
}

impl AsFd for Socket {
fn as_fd(&self) -> BorrowedFd<'_> {
unsafe { BorrowedFd::borrow_raw(self.as_raw_fd()) }
}
}

impl IntoRawFd for Socket {
fn into_raw_fd(self) -> RawFd {
let fd = self.fd;
Expand Down

0 comments on commit 13091a5

Please sign in to comment.