Skip to content

Commit

Permalink
Add async unix send/recv apis for unix
Browse files Browse the repository at this point in the history
Since unix uses AsyncFd from tokio, it is easier to wait for Ready
on AsyncFd and call sync send/recv apis

This commit does not take care of windows, which is not as straight-forward as posix variants.
  • Loading branch information
kp-mariappan-ramasamy committed Jul 23, 2024
1 parent f7610f6 commit 7e6c4bc
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/async/unix_device.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ use core::task::{Context, Poll};
use futures_core::ready;
use std::io::{IoSlice, Read, Write};
use tokio::io::unix::AsyncFd;
use tokio::io::Interest;
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
use tokio_util::codec::Framed;

Expand Down Expand Up @@ -59,6 +60,24 @@ impl AsyncDevice {
// associate mtu with the capacity of ReadBuf
Framed::with_capacity(self, codec, mtu as usize)
}

/// Recv a packet from tun device
pub async fn recv(&self, buf: &mut [u8]) -> std::io::Result<usize> {
let guard = self.inner.readable().await?;
guard
.get_ref()
.async_io(Interest::READABLE, |inner| inner.recv(buf))
.await
}

/// Send a packet to tun device
pub async fn send(&self, buf: &[u8]) -> std::io::Result<usize> {
let guard = self.inner.writable().await?;
guard
.get_ref()
.async_io(Interest::WRITABLE, |inner| inner.send(buf))
.await
}
}

impl AsyncRead for AsyncDevice {
Expand Down
10 changes: 10 additions & 0 deletions src/async/win_device.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,16 @@ impl AsyncDevice {
// guarantee to avoid the mtu of wintun may far away larger than the default provided capacity of ReadBuf of Framed
Framed::with_capacity(self, codec, mtu as usize)
}

/// Recv a packet from tun device - Not implemented for windows
pub async fn recv(&self, buf: &mut [u8]) -> std::io::Result<usize> {
unimplemented!()
}

/// Send a packet to tun device - Not implemented for windows
pub async fn send(&self, buf: &[u8]) -> std::io::Result<usize> {
unimplemented!()
}
}

impl AsyncRead for AsyncDevice {
Expand Down

0 comments on commit 7e6c4bc

Please sign in to comment.