diff --git a/src/bufferer.rs b/src/bufferer.rs index 5db3f60..b3be8c8 100644 --- a/src/bufferer.rs +++ b/src/bufferer.rs @@ -1,4 +1,5 @@ -use crate::{GDError, GDResult}; +use crate::GDResult; +use crate::GDError::{PacketBad, PacketUnderflow}; pub enum Endianess { Little, Big @@ -25,7 +26,7 @@ impl Bufferer { pub fn get_u8(&mut self) -> GDResult { if self.check_size(1) { - return Err(GDError::PacketUnderflow("Unexpectedly short packet for getting an u8.".to_string())); + return Err(PacketUnderflow); } let value = self.data[self.position]; @@ -35,7 +36,7 @@ impl Bufferer { pub fn get_u16(&mut self) -> GDResult { if self.check_size(2) { - return Err(GDError::PacketUnderflow("Unexpectedly short packet for getting an u16.".to_string())); + return Err(PacketUnderflow); } let source_data: [u8; 2] = (&self.data[self.position..self.position + 2]).try_into().unwrap(); @@ -51,7 +52,7 @@ impl Bufferer { pub fn get_u32(&mut self) -> GDResult { if self.check_size(4) { - return Err(GDError::PacketUnderflow("Unexpectedly short packet for getting an u32.".to_string())); + return Err(PacketUnderflow); } let source_data: [u8; 4] = (&self.data[self.position..self.position + 4]).try_into().unwrap(); @@ -67,7 +68,7 @@ impl Bufferer { pub fn get_f32(&mut self) -> GDResult { if self.check_size(4) { - return Err(GDError::PacketUnderflow("Unexpectedly short packet for getting an f32.".to_string())); + return Err(PacketUnderflow); } let source_data: [u8; 4] = (&self.data[self.position..self.position + 4]).try_into().unwrap(); @@ -83,7 +84,7 @@ impl Bufferer { pub fn get_u64(&mut self) -> GDResult { if self.check_size(8) { - return Err(GDError::PacketUnderflow("Unexpectedly short packet for getting an u64.".to_string())); + return Err(PacketUnderflow); } let source_data: [u8; 8] = (&self.data[self.position..self.position + 8]).try_into().unwrap(); @@ -100,13 +101,13 @@ impl Bufferer { pub fn get_string_utf8(&mut self) -> GDResult { let sub_buf = &self.data[self.position..]; if sub_buf.len() == 0 { - return Err(GDError::PacketUnderflow("Unexpectedly short packet for getting an utf8 string.".to_string())); + return Err(PacketUnderflow); } let first_null_position = sub_buf.iter().position(|&x| x == 0) - .ok_or(GDError::PacketBad("Unexpectedly formatted packet for getting an utf8 string.".to_string()))?; + .ok_or(PacketBad)?; let value = std::str::from_utf8(&sub_buf[..first_null_position]) - .map_err(|_| GDError::PacketBad("Badly formatted utf8 string.".to_string()))?.to_string(); + .map_err(|_| PacketBad)?.to_string(); self.position += value.len() + 1; Ok(value) @@ -115,11 +116,11 @@ impl Bufferer { pub fn get_string_utf8_unended(&mut self) -> GDResult { let sub_buf = &self.data[self.position..]; if sub_buf.len() == 0 { - return Err(GDError::PacketUnderflow("Unexpectedly short packet for getting an utf8 unended string.".to_string())); + return Err(PacketUnderflow); } let value = std::str::from_utf8(&sub_buf) - .map_err(|_| GDError::PacketBad("Badly formatted utf8 unended string.".to_string()))?.to_string(); + .map_err(|_| PacketBad)?.to_string(); self.position += value.len(); Ok(value) @@ -128,7 +129,7 @@ impl Bufferer { pub fn get_string_utf16(&mut self) -> GDResult { let sub_buf = &self.data[self.position..]; if sub_buf.len() == 0 { - return Err(GDError::PacketUnderflow("Unexpectedly short packet for getting an utf16 string.".to_string())); + return Err(PacketUnderflow); } let paired_buf: Vec = sub_buf.chunks_exact(2) @@ -138,7 +139,7 @@ impl Bufferer { }).collect(); let value = String::from_utf16(&paired_buf) - .map_err(|_| GDError::PacketBad("Badly formatted utf16 string.".to_string()))?.to_string(); + .map_err(|_| PacketBad)?.to_string(); self.position += value.len() * 2; Ok(value) diff --git a/src/errors.rs b/src/errors.rs index 5f5cae4..45e1aa3 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -1,9 +1,6 @@ //! The library's possible errors. -use core::fmt; -use std::fmt::Formatter; - /// Result of Type and GDError. pub type GDResult = Result; @@ -11,55 +8,33 @@ pub type GDResult = Result; #[derive(Debug, Clone)] pub enum GDError { /// The received packet was bigger than the buffer size. - PacketOverflow(String), + PacketOverflow, /// The received packet was shorter than the expected one. - PacketUnderflow(String), - /// The received packet was badly formatted. - PacketBad(String), + PacketUnderflow, + /// The received packet is badly formatted. + PacketBad, /// Couldn't send the packet. - PacketSend(String), + PacketSend, /// Couldn't send the receive. - PacketReceive(String), + PacketReceive, /// Couldn't decompress data. - Decompress(String), + Decompress, /// Unknown cast while translating a value to an enum. UnknownEnumCast, - /// The server queried is not from the queried game. - BadGame(String), - /// Couldn't bind a socket. - SocketBind(String), /// Invalid input. - InvalidInput(String), + InvalidInput, /// Couldn't create a socket connection. - SocketConnect(String), + SocketConnect, + /// Couldn't bind a socket. + SocketBind, /// Couldn't parse a json string. - JsonParse(String), + JsonParse, + /// The server queried is not from the queried game. + BadGame, /// Couldn't automatically query. AutoQuery, /// A protocol-defined expected format was not met. - ProtocolFormat(String), + ProtocolFormat, /// Couldn't parse a value. - TypeParse(String), -} - -impl fmt::Display for GDError { - fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { - match self { - GDError::PacketOverflow(details) => write!(f, "Packet overflow: {details}"), - GDError::PacketUnderflow(details) => write!(f, "Packet underflow: {details}"), - GDError::PacketBad(details) => write!(f, "Packet bad: {details}"), - GDError::PacketSend(details) => write!(f, "Couldn't send a packet: {details}"), - GDError::PacketReceive(details) => write!(f, "Couldn't receive a packet: {details}"), - GDError::Decompress(details) => write!(f, "Couldn't decompress data: {details}"), - GDError::UnknownEnumCast => write!(f, "Unknown enum cast encountered."), - GDError::BadGame(details) => write!(f, "Queried another game that the supposed one: {details}"), - GDError::SocketBind(details) => write!(f, "Socket bind: {details}"), - GDError::InvalidInput(details) => write!(f, "Invalid input: {details}"), - GDError::SocketConnect(details) => write!(f, "Socket connect: {details}"), - GDError::JsonParse(details) => write!(f, "Json parse: {details}"), - GDError::AutoQuery => write!(f, "Auto query failed."), - GDError::ProtocolFormat(details) => write!(f, "Protocol rule: {details}"), - GDError::TypeParse(details) => write!(f, "Type parse: {details}"), - } - } + TypeParse, } diff --git a/src/protocols/minecraft/protocol/bedrock.rs b/src/protocols/minecraft/protocol/bedrock.rs index 50ff0ca..b731cb0 100644 --- a/src/protocols/minecraft/protocol/bedrock.rs +++ b/src/protocols/minecraft/protocol/bedrock.rs @@ -4,8 +4,9 @@ This file has code that has been documented by the NodeJS GameDig library (MIT) https://github.com/gamedig/node-gamedig/blob/master/protocols/minecraftbedrock.js */ -use crate::{GDError, GDResult}; +use crate::GDResult; use crate::bufferer::{Bufferer, Endianess}; +use crate::GDError::{PacketBad, TypeParse}; use crate::protocols::minecraft::{BedrockResponse, GameMode, Server}; use crate::protocols::types::TimeoutSettings; use crate::socket::{Socket, UdpSocket}; @@ -45,12 +46,12 @@ impl Bedrock { let mut buffer = Bufferer::new_with_data(Endianess::Little, &self.socket.receive(None)?); if buffer.get_u8()? != 0x1c { - return Err(GDError::PacketBad("Invalid message id.".to_string())); + return Err(PacketBad); } // Checking for our nonce directly from a u64 (as the nonce is 8 bytes). if buffer.get_u64()? != 9833440827789222417 { - return Err(GDError::PacketBad("Invalid nonce.".to_string())); + return Err(PacketBad); } // These 8 bytes are identical to the serverId string we receive in decimal below @@ -58,11 +59,11 @@ impl Bedrock { // Verifying the magic value (as we need 16 bytes, cast to two u64 values) if buffer.get_u64()? != 18374403896610127616 { - return Err(GDError::PacketBad("Invalid magic (part 1).".to_string())); + return Err(PacketBad); } if buffer.get_u64()? != 8671175388723805693 { - return Err(GDError::PacketBad("Invalid magic (part 2).".to_string())); + return Err(PacketBad); } let remaining_length = buffer.as_endianess(Endianess::Big).get_u16()? as usize; @@ -74,7 +75,7 @@ impl Bedrock { // We must have at least 6 values if status.len() < 6 { - return Err(GDError::PacketBad("Not enough status parts.".to_string())); + return Err(PacketBad); } Ok(BedrockResponse { @@ -82,8 +83,8 @@ impl Bedrock { name: status[1].to_string(), version_name: status[3].to_string(), version_protocol: status[2].to_string(), - max_players: status[5].parse().map_err(|_| GDError::TypeParse("couldn't parse.".to_string()))?, - online_players: status[4].parse().map_err(|_| GDError::TypeParse("couldn't parse.".to_string()))?, + max_players: status[5].parse().map_err(|_| TypeParse)?, + online_players: status[4].parse().map_err(|_| TypeParse)?, id: status.get(6).and_then(|v| Some(v.to_string())), map: status.get(7).and_then(|v| Some(v.to_string())), game_mode: match status.get(8) { diff --git a/src/protocols/minecraft/protocol/java.rs b/src/protocols/minecraft/protocol/java.rs index c042241..a2611e6 100644 --- a/src/protocols/minecraft/protocol/java.rs +++ b/src/protocols/minecraft/protocol/java.rs @@ -1,5 +1,6 @@ use serde_json::Value; -use crate::{GDError, GDResult}; +use crate::GDResult; +use crate::GDError::{JsonParse, PacketBad}; use crate::bufferer::{Bufferer, Endianess}; use crate::protocols::minecraft::{as_varint, get_string, get_varint, Player, Response, Server}; use crate::protocols::types::TimeoutSettings; @@ -72,33 +73,33 @@ impl Java { let mut buffer = self.receive()?; if get_varint(&mut buffer)? != 0 { //first var int is the packet id - return Err(GDError::PacketBad("Bad receive packet id.".to_string())); + return Err(PacketBad); } let json_response = get_string(&mut buffer)?; let value_response: Value = serde_json::from_str(&json_response) - .map_err(|e| GDError::JsonParse(e.to_string()))?; + .map_err(|_|JsonParse)?; let version_name = value_response["version"]["name"].as_str() - .ok_or(GDError::PacketBad("Couldn't get expected string.".to_string()))?.to_string(); + .ok_or(PacketBad)?.to_string(); let version_protocol = value_response["version"]["protocol"].as_i64() - .ok_or(GDError::PacketBad("Couldn't get expected number.".to_string()))? as i32; + .ok_or(PacketBad)? as i32; let max_players = value_response["players"]["max"].as_u64() - .ok_or(GDError::PacketBad("Couldn't get expected number.".to_string()))? as u32; + .ok_or(PacketBad)? as u32; let online_players = value_response["players"]["online"].as_u64() - .ok_or(GDError::PacketBad("Couldn't get expected number.".to_string()))? as u32; + .ok_or(PacketBad)? as u32; let sample_players: Option> = match value_response["players"]["sample"].is_null() { true => None, false => Some({ let players_values = value_response["players"]["sample"].as_array() - .ok_or(GDError::PacketBad("Couldn't get expected array.".to_string()))?; + .ok_or(PacketBad)?; let mut players = Vec::with_capacity(players_values.len()); for player in players_values { players.push(Player { - name: player["name"].as_str().ok_or(GDError::PacketBad("Couldn't get expected string.".to_string()))?.to_string(), - id: player["id"].as_str().ok_or(GDError::PacketBad("Couldn't get expected string.".to_string()))?.to_string() + name: player["name"].as_str().ok_or(PacketBad)?.to_string(), + id: player["id"].as_str().ok_or(PacketBad)?.to_string() }) } diff --git a/src/protocols/minecraft/protocol/legacy_bv1_8.rs b/src/protocols/minecraft/protocol/legacy_bv1_8.rs index 0da7d6e..caa251c 100644 --- a/src/protocols/minecraft/protocol/legacy_bv1_8.rs +++ b/src/protocols/minecraft/protocol/legacy_bv1_8.rs @@ -1,6 +1,7 @@ -use crate::{GDError, GDResult}; +use crate::GDResult; use crate::bufferer::{Bufferer, Endianess}; +use crate::GDError::{PacketBad, ProtocolFormat}; use crate::protocols::minecraft::{LegacyGroup, Response, Server}; use crate::protocols::types::TimeoutSettings; use crate::socket::{Socket, TcpSocket}; @@ -30,7 +31,7 @@ impl LegacyBV1_8 { let mut buffer = Bufferer::new_with_data(Endianess::Big, &self.socket.receive(None)?); if buffer.get_u8()? != 0xFF { - return Err(GDError::ProtocolFormat("Expected 0xFF at the begin of the packet.".to_string())); + return Err(ProtocolFormat); } let length = buffer.get_u16()? * 2; @@ -43,9 +44,9 @@ impl LegacyBV1_8 { let description = split[0].to_string(); let online_players = split[1].parse() - .map_err(|_| GDError::PacketBad("Failed to parse to expected int.".to_string()))?; + .map_err(|_| PacketBad)?; let max_players = split[2].parse() - .map_err(|_| GDError::PacketBad("Failed to parse to expected int.".to_string()))?; + .map_err(|_| PacketBad)?; Ok(Response { version_name: "Beta 1.8+".to_string(), diff --git a/src/protocols/minecraft/protocol/legacy_v1_4.rs b/src/protocols/minecraft/protocol/legacy_v1_4.rs index 108b53d..e201dd1 100644 --- a/src/protocols/minecraft/protocol/legacy_v1_4.rs +++ b/src/protocols/minecraft/protocol/legacy_v1_4.rs @@ -1,6 +1,7 @@ -use crate::{GDError, GDResult}; +use crate::GDResult; use crate::bufferer::{Bufferer, Endianess}; +use crate::GDError::{PacketBad, ProtocolFormat}; use crate::protocols::minecraft::{LegacyGroup, Response, Server}; use crate::protocols::minecraft::protocol::legacy_v1_6::LegacyV1_6; use crate::protocols::types::TimeoutSettings; @@ -31,7 +32,7 @@ impl LegacyV1_4 { let mut buffer = Bufferer::new_with_data(Endianess::Big, &self.socket.receive(None)?); if buffer.get_u8()? != 0xFF { - return Err(GDError::ProtocolFormat("Expected 0xFF at the begin of the packet.".to_string())); + return Err(ProtocolFormat); } let length = buffer.get_u16()? * 2; @@ -48,9 +49,9 @@ impl LegacyV1_4 { let description = split[0].to_string(); let online_players = split[1].parse() - .map_err(|_| GDError::PacketBad("Failed to parse to expected int.".to_string()))?; + .map_err(|_| PacketBad)?; let max_players = split[2].parse() - .map_err(|_| GDError::PacketBad("Failed to parse to expected int.".to_string()))?; + .map_err(|_| PacketBad)?; Ok(Response { version_name: "1.4+".to_string(), diff --git a/src/protocols/minecraft/protocol/legacy_v1_6.rs b/src/protocols/minecraft/protocol/legacy_v1_6.rs index cd92380..0f80e44 100644 --- a/src/protocols/minecraft/protocol/legacy_v1_6.rs +++ b/src/protocols/minecraft/protocol/legacy_v1_6.rs @@ -1,4 +1,5 @@ -use crate::{GDError, GDResult}; +use crate::GDResult; +use crate::GDError::{PacketBad, ProtocolFormat}; use crate::bufferer::{Bufferer, Endianess}; use crate::protocols::minecraft::{LegacyGroup, Response, Server}; use crate::protocols::types::TimeoutSettings; @@ -52,13 +53,13 @@ impl LegacyV1_6 { error_by_expected_size(5, split.len())?; let version_protocol = split[0].parse() - .map_err(|_| GDError::PacketBad("Failed to parse to expected int.".to_string()))?; + .map_err(|_| PacketBad)?; let version_name = split[1].to_string(); let description = split[2].to_string(); let online_players = split[3].parse() - .map_err(|_| GDError::PacketBad("Failed to parse to expected int.".to_string()))?; + .map_err(|_| PacketBad)?; let max_players = split[4].parse() - .map_err(|_| GDError::PacketBad("Failed to parse to expected int.".to_string()))?; + .map_err(|_| PacketBad)?; Ok(Response { version_name, @@ -80,14 +81,14 @@ impl LegacyV1_6 { let mut buffer = Bufferer::new_with_data(Endianess::Big, &self.socket.receive(None)?); if buffer.get_u8()? != 0xFF { - return Err(GDError::ProtocolFormat("Expected a certain byte (0xFF) at the begin of the packet.".to_string())); + return Err(ProtocolFormat); } let length = buffer.get_u16()? * 2; error_by_expected_size((length + 3) as usize, buffer.data_length())?; if !LegacyV1_6::is_protocol(&mut buffer)? { - return Err(GDError::ProtocolFormat("Expected certain bytes at the beginning of the packet.".to_string())); + return Err(ProtocolFormat); } LegacyV1_6::get_response(&mut buffer) diff --git a/src/protocols/minecraft/protocol/mod.rs b/src/protocols/minecraft/protocol/mod.rs index a3ae26a..2750b45 100644 --- a/src/protocols/minecraft/protocol/mod.rs +++ b/src/protocols/minecraft/protocol/mod.rs @@ -1,4 +1,5 @@ -use crate::{GDError, GDResult}; +use crate::GDError::AutoQuery; +use crate::GDResult; use crate::protocols::minecraft::{BedrockResponse, LegacyGroup, Response}; use crate::protocols::minecraft::protocol::bedrock::Bedrock; use crate::protocols::minecraft::protocol::java::Java; @@ -27,7 +28,7 @@ pub fn query(address: &str, port: u16, timeout_settings: Option return Ok(response); } - Err(GDError::AutoQuery) + Err(AutoQuery) } /// Query a Java Server. @@ -49,7 +50,7 @@ pub fn query_legacy(address: &str, port: u16, timeout_settings: Option Ok(GameMode::Hardcore), "Spectator" => Ok(GameMode::Spectator), "Adventure" => Ok(GameMode::Adventure), - _ => Err(GDError::UnknownEnumCast) + _ => Err(UnknownEnumCast) } } } @@ -136,7 +137,7 @@ pub(crate) fn get_varint(buffer: &mut Bufferer) -> GDResult { // The 5th byte is only allowed to have the 4 smallest bits set if i == 4 && (current_byte & 0xf0 != 0) { - return Err(GDError::PacketBad("Couldn't parse to VarInt: Overflow.".to_string())) + return Err(PacketBad) } if (current_byte & msb) == 0 { @@ -180,7 +181,7 @@ pub(crate) fn get_string(buffer: &mut Bufferer) -> GDResult { } Ok(String::from_utf8(text) - .map_err(|_| GDError::PacketBad("Couldn't parse to a Minecraft String.".to_string()))?) + .map_err(|_| PacketBad)?) } #[allow(dead_code)] diff --git a/src/protocols/types.rs b/src/protocols/types.rs index bb2719d..eebeb88 100644 --- a/src/protocols/types.rs +++ b/src/protocols/types.rs @@ -1,5 +1,6 @@ use std::time::Duration; -use crate::{GDError, GDResult}; +use crate::GDResult; +use crate::GDError::InvalidInput; /// Timeout settings for socket operations #[derive(Clone)] @@ -13,13 +14,13 @@ impl TimeoutSettings { pub fn new(read: Option, write: Option) -> GDResult { if let Some(read_duration) = read { if read_duration == Duration::new(0, 0) { - return Err(GDError::InvalidInput("Can't pass duration 0 to timeout settings.".to_string())) + return Err(InvalidInput) } } if let Some(write_duration) = write { if write_duration == Duration::new(0, 0) { - return Err(GDError::InvalidInput("Can't pass duration 0 to timeout settings.".to_string())) + return Err(InvalidInput) } } diff --git a/src/protocols/valve/protocol.rs b/src/protocols/valve/protocol.rs index 014066b..fa489fe 100644 --- a/src/protocols/valve/protocol.rs +++ b/src/protocols/valve/protocol.rs @@ -1,7 +1,8 @@ use std::collections::HashMap; use bzip2_rs::decoder::Decoder; -use crate::{GDError, GDResult}; +use crate::GDResult; use crate::bufferer::{Bufferer, Endianess}; +use crate::GDError::{BadGame, Decompress, UnknownEnumCast}; use crate::protocols::types::TimeoutSettings; use crate::protocols::valve::{App, ModData, SteamID}; use crate::protocols::valve::types::{Environment, ExtraData, GatheringSettings, Request, Response, Server, ServerInfo, ServerPlayer, TheShip}; @@ -116,18 +117,18 @@ impl SplitPacket { fn get_payload(&self) -> GDResult> { if self.compressed { let mut decoder = Decoder::new(); - decoder.write(&self.payload).map_err(|e| GDError::Decompress(e.to_string()))?; + decoder.write(&self.payload).map_err(|_| Decompress)?; let decompressed_size = self.decompressed_size.unwrap() as usize; let mut decompressed_payload = Vec::with_capacity(decompressed_size); - decoder.read(&mut decompressed_payload).map_err(|e| GDError::Decompress(e.to_string()))?; + decoder.read(&mut decompressed_payload).map_err(|_| Decompress)?; if decompressed_payload.len() != decompressed_size { - Err(GDError::Decompress("The decompressed payload size doesn't match the expected one.".to_string())) + Err(Decompress) } else if crc32fast::hash(&decompressed_payload) != self.uncompressed_crc32.unwrap() { - Err(GDError::Decompress("The decompressed crc32 hash does not match the expected one.".to_string())) + Err(Decompress) } else { Ok(decompressed_payload) @@ -213,12 +214,12 @@ impl ValveProtocol { 68 => Server::Dedicated, //'D' 76 => Server::NonDedicated, //'L' 80 => Server::TV, //'P' - _ => Err(GDError::UnknownEnumCast)? + _ => Err(UnknownEnumCast)? }; let environment_type = match buffer.get_u8()? { 76 => Environment::Linux, //'L' 87 => Environment::Windows, //'W' - _ => Err(GDError::UnknownEnumCast)? + _ => Err(UnknownEnumCast)? }; let has_password = buffer.get_u8()? == 1; let is_mod = buffer.get_u8()? == 1; @@ -281,13 +282,13 @@ impl ValveProtocol { 100 => Server::Dedicated, //'d' 108 => Server::NonDedicated, //'l' 112 => Server::TV, //'p' - _ => Err(GDError::UnknownEnumCast)? + _ => Err(UnknownEnumCast)? }; let environment_type = match buffer.get_u8()? { 108 => Environment::Linux, //'l' 119 => Environment::Windows, //'w' 109 | 111 => Environment::Mac, //'m' or 'o' - _ => Err(GDError::UnknownEnumCast)? + _ => Err(UnknownEnumCast)? }; let has_password = buffer.get_u8()? == 1; let vac_secured = buffer.get_u8()? == 1; @@ -432,7 +433,7 @@ fn get_response(address: &str, port: u16, app: App, gather_settings: GatheringSe if let App::Source(x) = &app { if let Some(appid) = x { if *appid != info.appid { - return Err(GDError::BadGame(format!("Expected {}, found {} instead!", *appid, info.appid))); + return Err(BadGame); } } } diff --git a/src/socket.rs b/src/socket.rs index 65765a5..33889b8 100644 --- a/src/socket.rs +++ b/src/socket.rs @@ -1,6 +1,7 @@ use std::io::{Read, Write}; use std::net; -use crate::{GDError, GDResult}; +use crate::GDResult; +use crate::GDError::{PacketReceive, PacketSend, SocketBind, SocketConnect}; use crate::protocols::types::TimeoutSettings; use crate::utils::address_and_port_as_string; @@ -22,7 +23,7 @@ pub struct TcpSocket { impl Socket for TcpSocket { fn new(address: &str, port: u16) -> GDResult { let complete_address = address_and_port_as_string(address, port); - let socket = net::TcpStream::connect(complete_address).map_err(|e| GDError::SocketConnect(e.to_string()))?; + let socket = net::TcpStream::connect(complete_address).map_err(|_| SocketConnect)?; Ok(Self { socket @@ -38,13 +39,13 @@ impl Socket for TcpSocket { } fn send(&mut self, data: &[u8]) -> GDResult<()> { - self.socket.write(&data).map_err(|e| GDError::PacketSend(e.to_string()))?; + self.socket.write(&data).map_err(|_| PacketSend)?; Ok(()) } fn receive(&mut self, size: Option) -> GDResult> { let mut buf = Vec::with_capacity(size.unwrap_or(DEFAULT_PACKET_SIZE)); - self.socket.read_to_end(&mut buf).map_err(|e| GDError::PacketReceive(e.to_string()))?; + self.socket.read_to_end(&mut buf).map_err(|_| PacketReceive)?; Ok(buf) } @@ -58,7 +59,7 @@ pub struct UdpSocket { impl Socket for UdpSocket { fn new(address: &str, port: u16) -> GDResult { let complete_address = address_and_port_as_string(address, port); - let socket = net::UdpSocket::bind("0.0.0.0:0").map_err(|e| GDError::SocketBind(e.to_string()))?; + let socket = net::UdpSocket::bind("0.0.0.0:0").map_err(|_| SocketBind)?; Ok(Self { socket, @@ -75,13 +76,13 @@ impl Socket for UdpSocket { } fn send(&mut self, data: &[u8]) -> GDResult<()> { - self.socket.send_to(&data, &self.complete_address).map_err(|e| GDError::PacketSend(e.to_string()))?; + self.socket.send_to(&data, &self.complete_address).map_err(|_| PacketSend)?; Ok(()) } fn receive(&mut self, size: Option) -> GDResult> { let mut buf: Vec = vec![0; size.unwrap_or(DEFAULT_PACKET_SIZE)]; - let (number_of_bytes_received, _) = self.socket.recv_from(&mut buf).map_err(|e| GDError::PacketReceive(e.to_string()))?; + let (number_of_bytes_received, _) = self.socket.recv_from(&mut buf).map_err(|_| PacketReceive)?; Ok(buf[..number_of_bytes_received].to_vec()) } diff --git a/src/utils.rs b/src/utils.rs index 0043843..ba79a83 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -1,11 +1,12 @@ -use crate::{GDResult, GDError}; +use crate::GDResult; +use crate::GDError::{PacketOverflow, PacketUnderflow}; pub fn error_by_expected_size(expected: usize, size: usize) -> GDResult<()> { if size < expected { - Err(GDError::PacketUnderflow("Unexpectedly short packet.".to_string())) + Err(PacketUnderflow) } else if size > expected { - Err(GDError::PacketOverflow("Unexpectedly long packet.".to_string())) + Err(PacketOverflow) } else { Ok(())