[mio] 使用io结果简化异常处理

This commit is contained in:
lubeilin
2024-02-29 22:25:11 +08:00
parent 9e1bd28e2d
commit 573537fbfb
2 changed files with 16 additions and 11 deletions
+5 -5
View File
@@ -1,4 +1,4 @@
use crate::error::*;
use std::io;
#[derive(Eq, PartialEq, Copy, Clone, Debug)]
pub enum Protocol {
@@ -50,7 +50,7 @@ pub enum InErrorPacket<B> {
}
impl<B: AsRef<[u8]>> InErrorPacket<B> {
pub fn new(protocol: u8, buffer: B) -> Result<InErrorPacket<B>> {
pub fn new(protocol: u8, buffer: B) -> io::Result<InErrorPacket<B>> {
match Protocol::from(protocol) {
Protocol::TokenError => Ok(InErrorPacket::TokenError),
Protocol::Disconnect => Ok(InErrorPacket::Disconnect),
@@ -68,16 +68,16 @@ pub struct ErrorPacket<B> {
}
impl<B: AsRef<[u8]>> ErrorPacket<B> {
pub fn new(buffer: B) -> Result<ErrorPacket<B>> {
pub fn new(buffer: B) -> io::Result<ErrorPacket<B>> {
Ok(Self { buffer })
}
}
impl<B: AsRef<[u8]>> ErrorPacket<B> {
pub fn message(&self) -> Result<String> {
pub fn message(&self) -> io::Result<String> {
match String::from_utf8(self.buffer.as_ref().to_vec()) {
Ok(str) => Ok(str),
Err(_) => Err(Error::InvalidPacket),
Err(_) => Err(io::Error::new(io::ErrorKind::Other, "Utf8Error")),
}
}
}
+11 -6
View File
@@ -28,14 +28,14 @@ pub mod service_packet;
#[derive(Eq, PartialEq, Copy, Clone, Debug)]
pub enum Version {
V1,
UnKnow(u8),
Unknown(u8),
}
impl From<u8> for Version {
fn from(value: u8) -> Self {
match value {
1 => Version::V1,
val => Version::UnKnow(val),
val => Version::Unknown(val),
}
}
}
@@ -44,7 +44,7 @@ impl Into<u8> for Version {
fn into(self) -> u8 {
match self {
Version::V1 => 1,
Version::UnKnow(val) => val,
Version::Unknown(val) => val,
}
}
}
@@ -61,7 +61,7 @@ pub enum Protocol {
IpTurn,
/// 转发其他数据
OtherTurn,
UnKnow(u8),
Unknown(u8),
}
impl From<u8> for Protocol {
@@ -72,7 +72,7 @@ impl From<u8> for Protocol {
3 => Protocol::Control,
4 => Protocol::IpTurn,
5 => Protocol::OtherTurn,
val => Protocol::UnKnow(val),
val => Protocol::Unknown(val),
}
}
}
@@ -85,7 +85,7 @@ impl Into<u8> for Protocol {
Protocol::Control => 3,
Protocol::IpTurn => 4,
Protocol::OtherTurn => 5,
Protocol::UnKnow(val) => val,
Protocol::Unknown(val) => val,
}
}
}
@@ -220,6 +220,11 @@ impl<B: AsRef<[u8]> + AsMut<[u8]>> NetPacket<B> {
pub fn set_ttl(&mut self, ttl: u8) {
self.buffer.as_mut()[3] = (self.buffer.as_mut()[3] & MAX_SOURCE) | (MAX_TTL & ttl);
}
pub fn incr_ttl(&mut self) -> u8 {
let ttl = self.ttl() - 1;
self.set_ttl(ttl);
ttl
}
pub fn set_source_ttl(&mut self, source_ttl: u8) {
self.buffer.as_mut()[3] = (source_ttl << 4) | (MAX_TTL & self.buffer.as_ref()[3]);
}