Skip to content

Commit

Permalink
Add io::Result::io_to_con()
Browse files Browse the repository at this point in the history
  • Loading branch information
zmerp committed Aug 8, 2023
1 parent f3e7ef1 commit 25c5a9e
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 13 deletions.
22 changes: 21 additions & 1 deletion alvr/common/src/connection_result.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use anyhow::Result;
use std::{error::Error, fmt::Display};
use std::{error::Error, fmt::Display, io};

pub enum ConnectionError {
TryAgain,
Expand Down Expand Up @@ -29,6 +29,7 @@ macro_rules! con_bail {
}

pub trait ToCon<T> {
/// Convert result to ConResult. The error is always mapped to `Other()`
fn to_con(self) -> ConResult<T>;
}

Expand Down Expand Up @@ -62,3 +63,22 @@ impl<T> AnyhowToCon<T> for Result<T, anyhow::Error> {
}
}
}

pub trait IOToCon<T> {
fn io_to_con(self) -> ConResult<T>;
}

impl<T> IOToCon<T> for io::Result<T> {
fn io_to_con(self) -> ConResult<T> {
match self {
Ok(value) => Ok(value),
Err(e) => {
if e.kind() == io::ErrorKind::TimedOut || e.kind() == io::ErrorKind::WouldBlock {
Err(ConnectionError::TryAgain)
} else {
Err(ConnectionError::Other(e.into()))
}
}
}
}
}
14 changes: 2 additions & 12 deletions alvr/server/src/sockets.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use alvr_common::{anyhow::Result, con_bail, ConResult, ToCon, ALVR_NAME};
use alvr_common::{anyhow::Result, con_bail, ConResult, IOToCon, ToCon, ALVR_NAME};
use alvr_sockets::{CONTROL_PORT, HANDSHAKE_PACKET_SIZE_BYTES, LOCAL_IP};
use std::{
io::ErrorKind,
net::{IpAddr, UdpSocket},
time::Duration,
};
Expand All @@ -24,16 +23,7 @@ impl WelcomeSocket {

// Returns: client IP, client hostname
pub fn recv(&mut self) -> ConResult<(String, IpAddr)> {
let (size, address) = match self.socket.recv_from(&mut self.buffer) {
Ok(pair) => pair,
Err(e) => {
if matches!(e.kind(), ErrorKind::TimedOut | ErrorKind::WouldBlock) {
return alvr_common::try_again();
} else {
con_bail!("{e}");
}
}
};
let (size, address) = self.socket.recv_from(&mut self.buffer).io_to_con()?;

if size == HANDSHAKE_PACKET_SIZE_BYTES
&& &self.buffer[..ALVR_NAME.len()] == ALVR_NAME.as_bytes()
Expand Down

0 comments on commit 25c5a9e

Please sign in to comment.