Browse Source

throw errors if there isnt enough data to read in PSOPacketData

pull/3/head
jake 5 years ago
parent
commit
e0d271d703
  1. 23
      src/lib.rs

23
src/lib.rs

@ -10,14 +10,13 @@ use std::io::Read;
pub enum PacketParseError { pub enum PacketParseError {
NotEnoughBytes, NotEnoughBytes,
WrongPacketCommand, WrongPacketCommand,
WrongPacketForServerType,
WrongPacketForServerType(u16),
WrongPacketSize(u16, usize), WrongPacketSize(u16, usize),
DataStructNotLargeEnough(u64, usize), DataStructNotLargeEnough(u64, usize),
InvalidValue, InvalidValue,
ReadError, ReadError,
} }
trait PSOPacketData { trait PSOPacketData {
//fn size(&self) -> usize; //fn size(&self) -> usize;
fn from_bytes<R: Read>(cursor: &mut R) -> Result<Self, PacketParseError> where Self: Sized; fn from_bytes<R: Read>(cursor: &mut R) -> Result<Self, PacketParseError> where Self: Sized;
@ -27,8 +26,12 @@ trait PSOPacketData {
impl PSOPacketData for u8 { impl PSOPacketData for u8 {
fn from_bytes<R: Read>(cursor: &mut R) -> Result<u8, PacketParseError> { fn from_bytes<R: Read>(cursor: &mut R) -> Result<u8, PacketParseError> {
let mut bytes = [0u8; 1]; let mut bytes = [0u8; 1];
cursor.read(&mut bytes).map_err(|_| PacketParseError::ReadError)?;
let len = cursor.read(&mut bytes).map_err(|_| PacketParseError::ReadError)?;
if len == 1 {
Ok(bytes[0]) Ok(bytes[0])
} else{
Err(PacketParseError::NotEnoughBytes)
}
} }
fn as_bytes(&self) -> Vec<u8> { fn as_bytes(&self) -> Vec<u8> {
vec![*self] vec![*self]
@ -38,9 +41,14 @@ impl PSOPacketData for u8 {
impl PSOPacketData for u32 { impl PSOPacketData for u32 {
fn from_bytes<R: Read>(cursor: &mut R) -> Result<u32, PacketParseError> { fn from_bytes<R: Read>(cursor: &mut R) -> Result<u32, PacketParseError> {
let mut bytes = [0u8; 4]; let mut bytes = [0u8; 4];
cursor.read(&mut bytes).map_err(|_| PacketParseError::ReadError)?;
let len = cursor.read(&mut bytes).map_err(|_| PacketParseError::ReadError)?;
if len == 4 {
Ok(u32::from_le_bytes(bytes)) Ok(u32::from_le_bytes(bytes))
} }
else {
Err(PacketParseError::NotEnoughBytes)
}
}
fn as_bytes(&self) -> Vec<u8> { fn as_bytes(&self) -> Vec<u8> {
u32::to_le_bytes(*self).to_vec() u32::to_le_bytes(*self).to_vec()
} }
@ -49,9 +57,14 @@ impl PSOPacketData for u32 {
impl PSOPacketData for u16 { impl PSOPacketData for u16 {
fn from_bytes<R: Read>(cursor: &mut R) -> Result<u16, PacketParseError> { fn from_bytes<R: Read>(cursor: &mut R) -> Result<u16, PacketParseError> {
let mut bytes = [0u8; 2]; let mut bytes = [0u8; 2];
cursor.read(&mut bytes).map_err(|_| PacketParseError::ReadError)?;
let len = cursor.read(&mut bytes).map_err(|_| PacketParseError::ReadError)?;
if len == 2 {
Ok(u16::from_le_bytes(bytes)) Ok(u16::from_le_bytes(bytes))
} }
else {
Err(PacketParseError::NotEnoughBytes)
}
}
fn as_bytes(&self) -> Vec<u8> { fn as_bytes(&self) -> Vec<u8> {
u16::to_le_bytes(*self).to_vec() u16::to_le_bytes(*self).to_vec()
} }

Loading…
Cancel
Save