diff --git a/src/games/jc2mp.rs b/src/games/jc2mp.rs index 2adfa0f..67948c0 100644 --- a/src/games/jc2mp.rs +++ b/src/games/jc2mp.rs @@ -56,8 +56,8 @@ impl CommonResponse for Response { } } -fn parse_players_and_teams(packet: Vec) -> GDResult> { - let mut buf = Buffer::::new(&packet); +fn parse_players_and_teams(packet: &[u8]) -> GDResult> { + let mut buf = Buffer::::new(packet); let count = buf.read::()?; let mut players = Vec::with_capacity(count as usize); @@ -67,7 +67,7 @@ fn parse_players_and_teams(packet: Vec) -> GDResult> { name: buf.read_string::(None)?, steam_id: buf.read_string::(None)?, ping: buf.read::()?, - }) + }); } Ok(players) @@ -93,7 +93,7 @@ pub fn query_with_timeout( .ok_or(PacketBad.context("First packet missing"))?; let (mut server_vars, remaining_data) = data_to_map(data)?; - let players = parse_players_and_teams(remaining_data)?; + let players = parse_players_and_teams(&remaining_data)?; let players_maximum = server_vars .remove("maxplayers") diff --git a/src/games/mod.rs b/src/games/mod.rs index 73ce796..0613f53 100644 --- a/src/games/mod.rs +++ b/src/games/mod.rs @@ -123,7 +123,7 @@ use std::net::{IpAddr, SocketAddr}; /// Definition of a game #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Eq)] pub struct Game { /// Full name of the game pub name: &'static str, diff --git a/src/games/ts.rs b/src/games/ts.rs index a92e141..ab6dd23 100644 --- a/src/games/ts.rs +++ b/src/games/ts.rs @@ -29,8 +29,8 @@ impl TheShipPlayer { name: player.name.clone(), score: player.score, duration: player.duration, - deaths: player.deaths.unwrap(), - money: player.money.unwrap(), + deaths: player.deaths.unwrap(), // TODO! Err here! + money: player.money.unwrap(), // TODO! Err here! } } } @@ -93,7 +93,7 @@ impl Response { pub fn new_from_valve_response(response: valve::Response) -> Self { let (port, steam_id, tv_port, tv_name, keywords) = get_optional_extracted_data(response.info.extra_data); - let the_unwrapped_ship = response.info.the_ship.unwrap(); + let the_unwrapped_ship = response.info.the_ship.unwrap(); // TODO! Err here! Self { protocol_version: response.info.protocol_version, diff --git a/src/protocols/gamespy/mod.rs b/src/protocols/gamespy/mod.rs index 3118d98..e46698f 100644 --- a/src/protocols/gamespy/mod.rs +++ b/src/protocols/gamespy/mod.rs @@ -9,7 +9,7 @@ pub use protocols::*; /// Versions of the gamespy protocol #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Eq)] pub enum GameSpyVersion { One, Two, @@ -17,7 +17,7 @@ pub enum GameSpyVersion { } /// Versioned response type -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Eq)] pub enum VersionedResponse<'a> { One(&'a one::Response), Two(&'a two::Response), @@ -25,7 +25,7 @@ pub enum VersionedResponse<'a> { } /// Versioned player type -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Eq)] pub enum VersionedPlayer<'a> { One(&'a one::Player), Two(&'a two::Player), diff --git a/src/protocols/gamespy/protocols/one/protocol.rs b/src/protocols/gamespy/protocols/one/protocol.rs index ec7d4f8..1baaed3 100644 --- a/src/protocols/gamespy/protocols/one/protocol.rs +++ b/src/protocols/gamespy/protocols/one/protocol.rs @@ -24,7 +24,7 @@ fn get_server_values( let mut socket = UdpSocket::new(address)?; socket.apply_timeout(timeout_settings)?; - socket.send("\\status\\xserverquery".as_bytes())?; + socket.send(b"\\status\\xserverquery")?; let mut received_query_id: Option = None; let mut parts: Vec = Vec::new(); @@ -44,10 +44,9 @@ fn get_server_values( for i in 0 .. splited.len() / 2 { let position = i * 2; let key = splited[position].clone(); - let value = match splited.get(position + 1) { - None => "".to_string(), - Some(v) => v.clone(), - }; + let value = splited + .get(position + 1) + .map_or_else(String::new, |v| v.clone()); server_values.insert(key, value); } @@ -74,10 +73,10 @@ fn get_server_values( if received_query_id.is_some() && received_query_id != query_id { return Err(GDErrorKind::PacketBad.into()); // wrong query id! - } else { - received_query_id = query_id; } + received_query_id = query_id; + match parts.contains(&part) { true => Err(GDErrorKind::PacketBad)?, false => parts.push(part), diff --git a/src/protocols/gamespy/protocols/three/protocol.rs b/src/protocols/gamespy/protocols/three/protocol.rs index f0f46a8..d6f534b 100644 --- a/src/protocols/gamespy/protocols/three/protocol.rs +++ b/src/protocols/gamespy/protocols/three/protocol.rs @@ -167,7 +167,7 @@ impl GameSpy3 { values[packet_id] = buf.remaining_bytes().to_vec(); } - if values.iter().any(|v| v.is_empty()) { + if values.iter().any(Vec::is_empty) { return Err(PacketBad.context("One (or more) packets is empty")); } @@ -244,7 +244,7 @@ fn parse_players_and_teams(packets: Vec>) -> GDResult<(Vec, Vec< true => None, false => { if v != &"t" { - Err(GDErrorKind::PacketBad)? + Err(GDErrorKind::PacketBad)?; } Some(v) @@ -267,7 +267,7 @@ fn parse_players_and_teams(packets: Vec>) -> GDResult<(Vec, Vec< } while data.len() <= offset { - data.push(HashMap::new()) + data.push(HashMap::new()); } let entry_data = data.get_mut(offset).unwrap(); @@ -311,7 +311,7 @@ fn parse_players_and_teams(packets: Vec>) -> GDResult<(Vec, Vec< .ok_or(GDErrorKind::PacketBad)? .parse() .map_err(|e| TypeParse.context(e))?, - }) + }); } let mut teams: Vec = Vec::new(); @@ -330,7 +330,7 @@ fn parse_players_and_teams(packets: Vec>) -> GDResult<(Vec, Vec< .ok_or(GDErrorKind::PacketBad)? .parse() .map_err(|e| TypeParse.context(e))?, - }) + }); } Ok((players, teams)) diff --git a/src/protocols/gamespy/protocols/two/protocol.rs b/src/protocols/gamespy/protocols/two/protocol.rs index 613315a..93a8aa8 100644 --- a/src/protocols/gamespy/protocols/two/protocol.rs +++ b/src/protocols/gamespy/protocols/two/protocol.rs @@ -32,7 +32,7 @@ macro_rules! table_extract_parse { fn data_as_table(data: &mut Buffer) -> GDResult<(HashMap>, usize)> { if data.read::()? != 0 { - Err(GDErrorKind::PacketBad)? + Err(GDErrorKind::PacketBad)?; } let rows = data.read::()? as usize; @@ -46,7 +46,7 @@ fn data_as_table(data: &mut Buffer) -> GDResult<(HashMap(None)?; while !current_column.is_empty() { column_heads.push(current_column); - current_column = data.read_string::(None)? + current_column = data.read_string::(None)?; } let columns = column_heads.len(); @@ -63,7 +63,7 @@ fn data_as_table(data: &mut Buffer) -> GDResult<(HashMap(None)?; table .get_mut(column) @@ -131,7 +131,7 @@ fn get_teams(bufferer: &mut Buffer) -> GDResult> { teams.push(Team { name: table_extract!(table, "team_t", index).clone(), score: table_extract_parse!(table, "score_t", index), - }) + }); } Ok(teams) @@ -148,7 +148,7 @@ fn get_players(bufferer: &mut Buffer) -> GDResult> { score: table_extract_parse!(table, "score_", index), ping: table_extract_parse!(table, "ping_", index), team_index: table_extract_parse!(table, "team_", index), - }) + }); } Ok(players) diff --git a/src/protocols/minecraft/protocol/bedrock.rs b/src/protocols/minecraft/protocol/bedrock.rs index e9b9ca3..db9f87b 100644 --- a/src/protocols/minecraft/protocol/bedrock.rs +++ b/src/protocols/minecraft/protocol/bedrock.rs @@ -50,7 +50,7 @@ impl Bedrock { } // Checking for our nonce directly from a u64 (as the nonce is 8 bytes). - if buffer.read::()? != 9833440827789222417 { + if buffer.read::()? != 9_833_440_827_789_222_417 { return Err(PacketBad.context("Invalid nonce")); } @@ -59,11 +59,11 @@ impl Bedrock { buffer.move_cursor(8)?; // Verifying the magic value (as we need 16 bytes, cast to two u64 values) - if buffer.read::()? != 18374403896610127616 { + if buffer.read::()? != 18_374_403_896_610_127_616 { return Err(PacketBad.context("Invalid magic")); } - if buffer.read::()? != 8671175388723805693 { + if buffer.read::()? != 8_671_175_388_723_805_693 { return Err(PacketBad.context("Invalid magic")); } @@ -86,8 +86,8 @@ impl Bedrock { protocol_version: status[2].to_string(), players_maximum: status[5].parse().map_err(|e| TypeParse.context(e))?, players_online: status[4].parse().map_err(|e| TypeParse.context(e))?, - id: status.get(6).map(|v| v.to_string()), - map: status.get(7).map(|v| v.to_string()), + id: status.get(6).map(std::string::ToString::to_string), + map: status.get(7).map(std::string::ToString::to_string), game_mode: match status.get(8) { None => None, Some(v) => Some(GameMode::from_bedrock(v)?), @@ -97,6 +97,6 @@ impl Bedrock { } pub fn query(address: &SocketAddr, timeout_settings: Option) -> GDResult { - Bedrock::new(address, timeout_settings)?.get_info() + Self::new(address, timeout_settings)?.get_info() } } diff --git a/src/protocols/minecraft/protocol/java.rs b/src/protocols/minecraft/protocol/java.rs index cbf6afa..19eb080 100644 --- a/src/protocols/minecraft/protocol/java.rs +++ b/src/protocols/minecraft/protocol/java.rs @@ -121,7 +121,7 @@ impl Java { players.push(Player { name: player["name"].as_str().ok_or(PacketBad)?.to_string(), id: player["id"].as_str().ok_or(PacketBad)?.to_string(), - }) + }); } players @@ -144,6 +144,6 @@ impl Java { } pub fn query(address: &SocketAddr, timeout_settings: Option) -> GDResult { - Java::new(address, timeout_settings)?.get_info() + Self::new(address, timeout_settings)?.get_info() } } diff --git a/src/protocols/minecraft/protocol/legacy_bv1_8.rs b/src/protocols/minecraft/protocol/legacy_bv1_8.rs index d6b40af..ec50486 100644 --- a/src/protocols/minecraft/protocol/legacy_bv1_8.rs +++ b/src/protocols/minecraft/protocol/legacy_bv1_8.rs @@ -65,6 +65,6 @@ impl LegacyBV1_8 { } pub fn query(address: &SocketAddr, timeout_settings: Option) -> GDResult { - LegacyBV1_8::new(address, timeout_settings)?.get_info() + Self::new(address, timeout_settings)?.get_info() } } diff --git a/src/protocols/minecraft/protocol/legacy_v1_4.rs b/src/protocols/minecraft/protocol/legacy_v1_4.rs index 9d0fa06..bab741b 100644 --- a/src/protocols/minecraft/protocol/legacy_v1_4.rs +++ b/src/protocols/minecraft/protocol/legacy_v1_4.rs @@ -68,6 +68,6 @@ impl LegacyV1_4 { } pub fn query(address: &SocketAddr, timeout_settings: Option) -> GDResult { - LegacyV1_4::new(address, timeout_settings)?.get_info() + Self::new(address, timeout_settings)?.get_info() } } diff --git a/src/protocols/minecraft/protocol/legacy_v1_6.rs b/src/protocols/minecraft/protocol/legacy_v1_6.rs index 939f9b4..ce1486b 100644 --- a/src/protocols/minecraft/protocol/legacy_v1_6.rs +++ b/src/protocols/minecraft/protocol/legacy_v1_6.rs @@ -94,14 +94,14 @@ impl LegacyV1_6 { let length = buffer.read::()? * 2; error_by_expected_size((length + 3) as usize, data.len())?; - if !LegacyV1_6::is_protocol(&mut buffer)? { + if !Self::is_protocol(&mut buffer)? { return Err(ProtocolFormat.context("Not legacy 1.6 protocol")); } - LegacyV1_6::get_response(&mut buffer) + Self::get_response(&mut buffer) } pub fn query(address: &SocketAddr, timeout_settings: Option) -> GDResult { - LegacyV1_6::new(address, timeout_settings)?.get_info() + Self::new(address, timeout_settings)?.get_info() } } diff --git a/src/protocols/minecraft/types.rs b/src/protocols/minecraft/types.rs index 6110984..3e61016 100644 --- a/src/protocols/minecraft/types.rs +++ b/src/protocols/minecraft/types.rs @@ -55,7 +55,7 @@ impl CommonPlayer for Player { } /// Versioned response type -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Eq)] pub enum VersionedResponse<'a> { Bedrock(&'a BedrockResponse), Java(&'a JavaResponse), @@ -170,12 +170,12 @@ pub enum GameMode { impl GameMode { pub fn from_bedrock(value: &&str) -> GDResult { match *value { - "Survival" => Ok(GameMode::Survival), - "Creative" => Ok(GameMode::Creative), - "Hardcore" => Ok(GameMode::Hardcore), - "Spectator" => Ok(GameMode::Spectator), - "Adventure" => Ok(GameMode::Adventure), - _ => Err(UnknownEnumCast.context(format!("Unknown gamemode {:?}", value))), + "Survival" => Ok(Self::Survival), + "Creative" => Ok(Self::Creative), + "Hardcore" => Ok(Self::Hardcore), + "Spectator" => Ok(Self::Spectator), + "Adventure" => Ok(Self::Adventure), + _ => Err(UnknownEnumCast.context(format!("Unknown gamemode {value:?}"))), } } } @@ -183,7 +183,7 @@ impl GameMode { pub(crate) fn get_varint(buffer: &mut Buffer) -> GDResult { let mut result = 0; - let msb: u8 = 0b10000000; + let msb: u8 = 0b1000_0000; let mask: u8 = !msb; for i in 0 .. 5 { @@ -208,8 +208,8 @@ pub(crate) fn as_varint(value: i32) -> Vec { let mut bytes = vec![]; let mut reading_value = value; - let msb: u8 = 0b10000000; - let mask: i32 = 0b01111111; + let msb: u8 = 0b1000_0000; + let mask: i32 = 0b0111_1111; for _ in 0 .. 5 { let tmp = (reading_value & mask) as u8; @@ -217,12 +217,12 @@ pub(crate) fn as_varint(value: i32) -> Vec { reading_value &= !mask; reading_value = reading_value.rotate_right(7); - if reading_value != 0 { - bytes.push(tmp | msb); - } else { + if reading_value == 0 { bytes.push(tmp); break; } + + bytes.push(tmp | msb); } bytes @@ -239,10 +239,10 @@ pub(crate) fn get_string(buffer: &mut Buffer) -> GDResult Vec { +#[allow(dead_code)] // TODO! Look if this is needed anymore +pub(crate) fn as_string(value: &str) -> Vec { let mut buf = as_varint(value.len() as i32); - buf.extend(value.as_bytes().to_vec()); + buf.extend(value.as_bytes()); buf } diff --git a/src/protocols/quake/client.rs b/src/protocols/quake/client.rs index 3f14c8f..b0e3108 100644 --- a/src/protocols/quake/client.rs +++ b/src/protocols/quake/client.rs @@ -10,7 +10,7 @@ use std::collections::HashMap; use std::net::SocketAddr; use std::slice::Iter; -pub(crate) trait QuakeClient { +pub trait QuakeClient { type Player; fn get_send_header<'a>() -> &'a str; @@ -34,13 +34,13 @@ fn get_data(address: &SocketAddr, timeout_settings: Option< let data = socket.receive(None)?; let mut bufferer = Buffer::::new(&data); - if bufferer.read::()? != 4294967295 { + if bufferer.read::()? != u32::MAX { return Err(PacketBad.context("Expected 4294967295")); } let response_header = Client::get_response_header().as_bytes(); if !bufferer.remaining_bytes().starts_with(response_header) { - Err(GDErrorKind::PacketBad)? + Err(GDErrorKind::PacketBad)?; } bufferer.move_cursor(response_header.len() as isize)?; @@ -91,7 +91,7 @@ fn get_players(bufferer: &mut Buffer) -> GDRe Ok(players) } -pub(crate) fn client_query( +pub fn client_query( address: &SocketAddr, timeout_settings: Option, ) -> GDResult> { @@ -125,7 +125,7 @@ pub(crate) fn client_query( }) } -pub(crate) fn remove_wrapping_quotes<'a>(string: &&'a str) -> &'a str { +pub fn remove_wrapping_quotes<'a>(string: &&'a str) -> &'a str { match string.starts_with('\"') && string.ends_with('\"') { false => string, true => &string[1 .. string.len() - 1], diff --git a/src/protocols/quake/mod.rs b/src/protocols/quake/mod.rs index a893cf7..dfaaedd 100644 --- a/src/protocols/quake/mod.rs +++ b/src/protocols/quake/mod.rs @@ -12,7 +12,7 @@ pub use types::*; mod client; #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Eq)] pub enum QuakeVersion { One, Two, diff --git a/src/protocols/types.rs b/src/protocols/types.rs index b26ab7f..ed8a8de 100644 --- a/src/protocols/types.rs +++ b/src/protocols/types.rs @@ -9,7 +9,7 @@ use serde::{Deserialize, Serialize}; /// Enumeration of all custom protocols #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Eq)] pub enum ProprietaryProtocol { TheShip, FFOW, @@ -18,7 +18,7 @@ pub enum ProprietaryProtocol { /// Enumeration of all valid protocol types #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Eq)] pub enum Protocol { Gamespy(gamespy::GameSpyVersion), Minecraft(Option), @@ -102,7 +102,7 @@ pub trait CommonResponse { } #[cfg_attr(feature = "serde", derive(Deserialize, Serialize))] -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Eq)] pub struct CommonResponseJson<'a> { pub name: Option<&'a str>, pub description: Option<&'a str>, @@ -135,7 +135,7 @@ pub trait CommonPlayer { } #[cfg_attr(feature = "serde", derive(Deserialize, Serialize))] -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Eq)] pub struct CommonPlayerJson<'a> { pub name: &'a str, pub score: Option, @@ -169,10 +169,10 @@ impl TimeoutSettings { } /// Get the read timeout. - pub fn get_read(&self) -> Option { self.read } + pub const fn get_read(&self) -> Option { self.read } /// Get the write timeout. - pub fn get_write(&self) -> Option { self.write } + pub const fn get_write(&self) -> Option { self.write } } impl Default for TimeoutSettings { diff --git a/src/protocols/valve/protocol.rs b/src/protocols/valve/protocol.rs index 37ccdca..9aa8b14 100644 --- a/src/protocols/valve/protocol.rs +++ b/src/protocols/valve/protocol.rs @@ -273,7 +273,7 @@ impl ValveProtocol { if let Engine::GoldSrc(force) = engine { if *force { - return ValveProtocol::get_goldsrc_server_info(&mut buffer); + return Self::get_goldsrc_server_info(&mut buffer); } } diff --git a/src/protocols/valve/types.rs b/src/protocols/valve/types.rs index c937743..fde61f0 100644 --- a/src/protocols/valve/types.rs +++ b/src/protocols/valve/types.rs @@ -20,9 +20,9 @@ pub enum Server { impl Server { pub(crate) fn from_gldsrc(value: u8) -> GDResult { Ok(match value { - 100 => Server::Dedicated, //'d' - 108 => Server::NonDedicated, //'l' - 112 => Server::TV, //'p' + 100 => Self::Dedicated, //'d' + 108 => Self::NonDedicated, //'l' + 112 => Self::TV, //'p' _ => Err(UnknownEnumCast)?, }) } @@ -40,9 +40,9 @@ pub enum Environment { impl Environment { pub(crate) fn from_gldsrc(value: u8) -> GDResult { Ok(match value { - 108 => Environment::Linux, //'l' - 119 => Environment::Windows, //'w' - 109 | 111 => Environment::Mac, //'m' or 'o' + 108 => Self::Linux, //'l' + 119 => Self::Windows, //'w' + 109 | 111 => Self::Mac, //'m' or 'o' _ => Err(UnknownEnumCast)?, }) } @@ -204,7 +204,7 @@ pub(crate) struct Packet { impl Packet { pub fn new(kind: u8, payload: Vec) -> Self { Self { - header: 4294967295, // FF FF FF FF + header: u32::MAX, // FF FF FF FF kind, payload, } @@ -241,9 +241,9 @@ pub(crate) enum Request { } impl Request { - pub fn get_default_payload(&self) -> Vec { + pub fn get_default_payload(self) -> Vec { match self { - Request::Info => String::from("Source Engine Query\0").into_bytes(), + Self::Info => String::from("Source Engine Query\0").into_bytes(), _ => vec![0xFF, 0xFF, 0xFF, 0xFF], } } @@ -341,50 +341,46 @@ pub enum SteamApp { impl SteamApp { /// Get the specified app as engine. - pub fn as_engine(&self) -> Engine { + pub const fn as_engine(&self) -> Engine { match self { - SteamApp::CS => Engine::GoldSrc(false), // 10 - SteamApp::TFC => Engine::GoldSrc(false), // 20 - SteamApp::DOD => Engine::GoldSrc(false), // 30 - SteamApp::CSCZ => Engine::GoldSrc(false), // 80 - SteamApp::CSS => Engine::new_source(240), - SteamApp::DODS => Engine::new_source(300), - SteamApp::HL2DM => Engine::new_source(320), - SteamApp::HLDMS => Engine::new_source(360), - SteamApp::TF2 => Engine::new_source(440), - SteamApp::L4D => Engine::new_source(500), - SteamApp::L4D2 => Engine::new_source(550), - SteamApp::ALIENS => Engine::new_source(630), - SteamApp::CSGO => Engine::new_source(730), - SteamApp::TS => Engine::new_source(2400), - SteamApp::GM => Engine::new_source(4000), - SteamApp::AOC => Engine::new_source(17510), - SteamApp::INSMIC => Engine::new_source(17700), - SteamApp::ARMA2OA => Engine::new_source(33930), - SteamApp::PZ => Engine::new_source(108600), - SteamApp::INS => Engine::new_source(222880), - SteamApp::SC => Engine::GoldSrc(false), // 225840 - SteamApp::SDTD => Engine::new_source(251570), - SteamApp::RUST => Engine::new_source(252490), - SteamApp::BO => Engine::new_source(296300), - SteamApp::DST => Engine::new_source(322320), - SteamApp::BB2 => Engine::new_source(346330), - SteamApp::CCURE => Engine::new_source(355180), - SteamApp::BM => Engine::new_source(362890), - SteamApp::COSU => Engine::new_source(366090), - SteamApp::AVORION => Engine::new_source(445220), - SteamApp::DOI => Engine::new_source(447820), - SteamApp::TF => Engine::new_source(556450), - SteamApp::UNTURNED => Engine::new_source(304930), - SteamApp::ASE => Engine::new_source(346110), - SteamApp::BAT1944 => Engine::new_source(489940), - SteamApp::INSS => Engine::new_source(581320), - SteamApp::ASRD => Engine::new_source(563560), - SteamApp::ROR2 => Engine::new_source(632360), - SteamApp::OHD => Engine::new_source_with_dedicated(736590, 950900), - SteamApp::ONSET => Engine::new_source(1105810), - SteamApp::VR => Engine::new_source(1604030), - SteamApp::HLL => Engine::new_source(686810), + Self::CSS => Engine::new_source(240), + Self::DODS => Engine::new_source(300), + Self::HL2DM => Engine::new_source(320), + Self::HLDMS => Engine::new_source(360), + Self::TF2 => Engine::new_source(440), + Self::L4D => Engine::new_source(500), + Self::L4D2 => Engine::new_source(550), + Self::ALIENS => Engine::new_source(630), + Self::CSGO => Engine::new_source(730), + Self::TS => Engine::new_source(2400), + Self::GM => Engine::new_source(4000), + Self::AOC => Engine::new_source(17510), + Self::INSMIC => Engine::new_source(17700), + Self::ARMA2OA => Engine::new_source(33930), + Self::PZ => Engine::new_source(108_600), + Self::INS => Engine::new_source(222_880), + Self::SDTD => Engine::new_source(251_570), + Self::RUST => Engine::new_source(252_490), + Self::BO => Engine::new_source(296_300), + Self::DST => Engine::new_source(322_320), + Self::BB2 => Engine::new_source(346_330), + Self::CCURE => Engine::new_source(355_180), + Self::BM => Engine::new_source(362_890), + Self::COSU => Engine::new_source(366_090), + Self::AVORION => Engine::new_source(445_220), + Self::DOI => Engine::new_source(447_820), + Self::TF => Engine::new_source(556_450), + Self::UNTURNED => Engine::new_source(304_930), + Self::ASE => Engine::new_source(346_110), + Self::BAT1944 => Engine::new_source(489_940), + Self::INSS => Engine::new_source(581_320), + Self::ASRD => Engine::new_source(563_560), + Self::ROR2 => Engine::new_source(632_360), + Self::OHD => Engine::new_source_with_dedicated(736_590, 950_900), + Self::ONSET => Engine::new_source(1_105_810), + Self::VR => Engine::new_source(1_604_030), + Self::HLL => Engine::new_source(686_810), + _ => Engine::GoldSrc(false), // CS - 10, TFC - 20, DOD - 30, CSCZ - 80, SC - 225840 } } } @@ -404,10 +400,10 @@ pub enum Engine { } impl Engine { - pub fn new_source(appid: u32) -> Self { Engine::Source(Some((appid, None))) } + pub const fn new_source(appid: u32) -> Self { Self::Source(Some((appid, None))) } - pub fn new_source_with_dedicated(appid: u32, dedicated_appid: u32) -> Self { - Engine::Source(Some((appid, Some(dedicated_appid)))) + pub const fn new_source_with_dedicated(appid: u32, dedicated_appid: u32) -> Self { + Self::Source(Some((appid, Some(dedicated_appid)))) } } diff --git a/src/services/valve_master_server/service.rs b/src/services/valve_master_server/service.rs index 60401ad..98d6161 100644 --- a/src/services/valve_master_server/service.rs +++ b/src/services/valve_master_server/service.rs @@ -16,10 +16,9 @@ pub fn default_master_address() -> SocketAddr { } fn construct_payload(region: Region, filters: &Option, last_ip: &str, last_port: u16) -> Vec { - let filters_bytes: Vec = match filters { - None => vec![0x00], - Some(f) => f.to_bytes(), - }; + let filters_bytes: Vec = filters + .as_ref() + .map_or_else(|| vec![0x00], |f| f.to_bytes()); let region_byte = &[region as u8]; @@ -71,8 +70,8 @@ impl ValveMasterServer { let received_data = self.socket.receive(Some(1400))?; let mut buf = Buffer::::new(&received_data); - if buf.read::()? != 4294967295 || buf.read::()? != 26122 { - return Err(PacketBad.context("Expected 4294967295 or 26122")); + if buf.read::()? != u32::MAX || buf.read::()? != 26122 { + return Err(PacketBad.context("Expected 4294967295 followed by 26122")); } let mut ips: Vec<(IpAddr, u16)> = Vec::new(); diff --git a/src/services/valve_master_server/types.rs b/src/services/valve_master_server/types.rs index 27f8c21..f7050b1 100644 --- a/src/services/valve_master_server/types.rs +++ b/src/services/valve_master_server/types.rs @@ -27,7 +27,7 @@ pub enum Filter { HasGameDir(String), } -fn bool_as_char_u8(b: &bool) -> u8 { +const fn bool_as_char_u8(b: &bool) -> u8 { match b { true => b'1', false => b'0', @@ -39,33 +39,33 @@ impl Filter { let mut bytes: Vec = Vec::new(); match self { - Filter::IsSecured(secured) => { - bytes = "\\secure\\".as_bytes().to_vec(); + Self::IsSecured(secured) => { + bytes = b"\\secure\\".to_vec(); bytes.extend([bool_as_char_u8(secured)]); } - Filter::RunsMap(map) => { - bytes = "\\map\\".as_bytes().to_vec(); + Self::RunsMap(map) => { + bytes = b"\\map\\".to_vec(); bytes.extend(map.as_bytes()); } - Filter::CanHavePassword(password) => { - bytes = "\\password\\".as_bytes().to_vec(); + Self::CanHavePassword(password) => { + bytes = b"\\password\\".to_vec(); bytes.extend([bool_as_char_u8(password)]); } - Filter::CanBeEmpty(empty) => { - bytes = "\\empty\\".as_bytes().to_vec(); + Self::CanBeEmpty(empty) => { + bytes = b"\\empty\\".to_vec(); bytes.extend([bool_as_char_u8(empty)]); } - Filter::CanBeFull(full) => { - bytes = "\\full\\".as_bytes().to_vec(); + Self::CanBeFull(full) => { + bytes = b"\\full\\".to_vec(); bytes.extend([bool_as_char_u8(full)]); } - Filter::RunsAppID(id) => { - bytes = "\\appid\\".as_bytes().to_vec(); + Self::RunsAppID(id) => { + bytes = b"\\appid\\".to_vec(); bytes.extend(id.to_string().as_bytes()); } - Filter::HasTags(tags) => { + Self::HasTags(tags) => { if !tags.is_empty() { - bytes = "\\gametype\\".as_bytes().to_vec(); + bytes = b"\\gametype\\".to_vec(); for tag in tags.iter() { bytes.extend(tag.as_bytes()); bytes.extend([b',']); @@ -74,48 +74,48 @@ impl Filter { bytes.pop(); } } - Filter::NotAppID(id) => { - bytes = "\\napp\\".as_bytes().to_vec(); + Self::NotAppID(id) => { + bytes = b"\\napp\\".to_vec(); bytes.extend(id.to_string().as_bytes()); } - Filter::IsEmpty(empty) => { - bytes = "\\noplayers\\".as_bytes().to_vec(); + Self::IsEmpty(empty) => { + bytes = b"\\noplayers\\".to_vec(); bytes.extend([bool_as_char_u8(empty)]); } - Filter::MatchName(name) => { - bytes = "\\name_match\\".as_bytes().to_vec(); + Self::MatchName(name) => { + bytes = b"\\name_match\\".to_vec(); bytes.extend(name.as_bytes()); } - Filter::MatchVersion(version) => { - bytes = "\\version_match\\".as_bytes().to_vec(); + Self::MatchVersion(version) => { + bytes = b"\\version_match\\".to_vec(); bytes.extend(version.as_bytes()); } - Filter::RestrictUniqueIP(unique) => { - bytes = "\\collapse_addr_hash\\".as_bytes().to_vec(); + Self::RestrictUniqueIP(unique) => { + bytes = b"\\collapse_addr_hash\\".to_vec(); bytes.extend([bool_as_char_u8(unique)]); } - Filter::OnAddress(address) => { - bytes = "\\gameaddr\\".as_bytes().to_vec(); + Self::OnAddress(address) => { + bytes = b"\\gameaddr\\".to_vec(); bytes.extend(address.as_bytes()); } - Filter::Whitelisted(whitelisted) => { - bytes = "\\white\\".as_bytes().to_vec(); + Self::Whitelisted(whitelisted) => { + bytes = b"\\white\\".to_vec(); bytes.extend([bool_as_char_u8(whitelisted)]); } - Filter::SpectatorProxy(condition) => { - bytes = "\\proxy\\".as_bytes().to_vec(); + Self::SpectatorProxy(condition) => { + bytes = b"\\proxy\\".to_vec(); bytes.extend([bool_as_char_u8(condition)]); } - Filter::IsDedicated(dedicated) => { - bytes = "\\dedicated\\".as_bytes().to_vec(); + Self::IsDedicated(dedicated) => { + bytes = b"\\dedicated\\".to_vec(); bytes.extend([bool_as_char_u8(dedicated)]); } - Filter::RunsLinux(linux) => { - bytes = "\\linux\\".as_bytes().to_vec(); + Self::RunsLinux(linux) => { + bytes = b"\\linux\\".to_vec(); bytes.extend([bool_as_char_u8(linux)]); } - Filter::HasGameDir(game_dir) => { - bytes = "\\gamedir\\".as_bytes().to_vec(); + Self::HasGameDir(game_dir) => { + bytes = b"\\gamedir\\".to_vec(); bytes.extend(game_dir.as_bytes()); } } @@ -144,7 +144,7 @@ pub struct SearchFilters { } impl Default for SearchFilters { - fn default() -> Self { SearchFilters::new() } + fn default() -> Self { Self::new() } } impl SearchFilters { @@ -210,14 +210,8 @@ impl SearchFilters { bytes.extend(filter.to_bytes()) } - bytes.extend(SearchFilters::special_filter_to_bytes( - "nand", - &self.nand_filters, - )); - bytes.extend(SearchFilters::special_filter_to_bytes( - "nor", - &self.nor_filters, - )); + bytes.extend(Self::special_filter_to_bytes("nand", &self.nand_filters)); + bytes.extend(Self::special_filter_to_bytes("nor", &self.nor_filters)); bytes.extend([0x00]); bytes diff --git a/src/utils.rs b/src/utils.rs index e890284..b06a75d 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -10,7 +10,7 @@ pub fn error_by_expected_size(expected: usize, size: usize) -> GDResult<()> { } } -pub fn u8_lower_upper(n: u8) -> (u8, u8) { (n & 15, n >> 4) } +pub const fn u8_lower_upper(n: u8) -> (u8, u8) { (n & 15, n >> 4) } #[cfg(test)] mod tests {