Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add async send and recv functions to AsyncSession #2

Merged
merged 3 commits into from
Sep 13, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions src/async_session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,33 @@ impl AsyncSession {
e => panic!("WaitForMultipleObjects returned unexpected value {:?}", e),
}
}

pub async fn recv(&self, buf: &mut [u8]) -> std::io::Result<usize> {
loop {
match self.session.try_receive() {
Ok(Some(packet)) => {
// it seems to be standard practice to truncate rather than return an error,
// in the context of TUN/TAP the packet lengths can be read anyway
let size = packet.bytes.len().min(buf.len());
AaronKutch marked this conversation as resolved.
Show resolved Hide resolved
buf[..size].copy_from_slice(&packet.bytes[..size]);
return Ok(size);
}
Ok(None) => {
let read_event = self.session.get_read_wait_event()?;
let shutdown_event = self.session.shutdown_event.get_handle();
blocking::unblock(move || Self::wait_for_read(read_event, shutdown_event)).await;
}
Err(err) => return Err(std::io::Error::new(std::io::ErrorKind::Other, err)),
}
}
}

pub async fn send(&self, buf: &[u8]) -> std::io::Result<usize> {
let packet = self.session.allocate_send_packet(buf.len() as _)?;
packet.bytes.copy_from_slice(buf);
self.session.send_packet(packet);
Ok(buf.len())
}
}

impl AsyncRead for AsyncSession {
Expand Down