Skip to content

Commit

Permalink
Add async send and recv functions to AsyncSession
Browse files Browse the repository at this point in the history
  • Loading branch information
AaronKutch committed Sep 12, 2024
1 parent cd4df1a commit e17fa82
Showing 1 changed file with 27 additions and 0 deletions.
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());
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

0 comments on commit e17fa82

Please sign in to comment.