throw errors if there isnt enough data to read in PSOPacketData
This commit is contained in:
parent
ae521ccbb2
commit
e0d271d703
29
src/lib.rs
29
src/lib.rs
@ -10,14 +10,13 @@ use std::io::Read;
|
||||
pub enum PacketParseError {
|
||||
NotEnoughBytes,
|
||||
WrongPacketCommand,
|
||||
WrongPacketForServerType,
|
||||
WrongPacketForServerType(u16),
|
||||
WrongPacketSize(u16, usize),
|
||||
DataStructNotLargeEnough(u64, usize),
|
||||
InvalidValue,
|
||||
ReadError,
|
||||
}
|
||||
|
||||
|
||||
trait PSOPacketData {
|
||||
//fn size(&self) -> usize;
|
||||
fn from_bytes<R: Read>(cursor: &mut R) -> Result<Self, PacketParseError> where Self: Sized;
|
||||
@ -27,8 +26,12 @@ trait PSOPacketData {
|
||||
impl PSOPacketData for u8 {
|
||||
fn from_bytes<R: Read>(cursor: &mut R) -> Result<u8, PacketParseError> {
|
||||
let mut bytes = [0u8; 1];
|
||||
cursor.read(&mut bytes).map_err(|_| PacketParseError::ReadError)?;
|
||||
Ok(bytes[0])
|
||||
let len = cursor.read(&mut bytes).map_err(|_| PacketParseError::ReadError)?;
|
||||
if len == 1 {
|
||||
Ok(bytes[0])
|
||||
} else{
|
||||
Err(PacketParseError::NotEnoughBytes)
|
||||
}
|
||||
}
|
||||
fn as_bytes(&self) -> Vec<u8> {
|
||||
vec![*self]
|
||||
@ -38,8 +41,13 @@ impl PSOPacketData for u8 {
|
||||
impl PSOPacketData for u32 {
|
||||
fn from_bytes<R: Read>(cursor: &mut R) -> Result<u32, PacketParseError> {
|
||||
let mut bytes = [0u8; 4];
|
||||
cursor.read(&mut bytes).map_err(|_| PacketParseError::ReadError)?;
|
||||
Ok(u32::from_le_bytes(bytes))
|
||||
let len = cursor.read(&mut bytes).map_err(|_| PacketParseError::ReadError)?;
|
||||
if len == 4 {
|
||||
Ok(u32::from_le_bytes(bytes))
|
||||
}
|
||||
else {
|
||||
Err(PacketParseError::NotEnoughBytes)
|
||||
}
|
||||
}
|
||||
fn as_bytes(&self) -> Vec<u8> {
|
||||
u32::to_le_bytes(*self).to_vec()
|
||||
@ -49,8 +57,13 @@ impl PSOPacketData for u32 {
|
||||
impl PSOPacketData for u16 {
|
||||
fn from_bytes<R: Read>(cursor: &mut R) -> Result<u16, PacketParseError> {
|
||||
let mut bytes = [0u8; 2];
|
||||
cursor.read(&mut bytes).map_err(|_| PacketParseError::ReadError)?;
|
||||
Ok(u16::from_le_bytes(bytes))
|
||||
let len = cursor.read(&mut bytes).map_err(|_| PacketParseError::ReadError)?;
|
||||
if len == 2 {
|
||||
Ok(u16::from_le_bytes(bytes))
|
||||
}
|
||||
else {
|
||||
Err(PacketParseError::NotEnoughBytes)
|
||||
}
|
||||
}
|
||||
fn as_bytes(&self) -> Vec<u8> {
|
||||
u16::to_le_bytes(*self).to_vec()
|
||||
|
Loading…
x
Reference in New Issue
Block a user