mirror of
https://github.com/tribufu/rust-gamedig
synced 2026-05-18 09:35:50 +00:00
[Protocols] Cargo clippy optimizations
This commit is contained in:
parent
e6562d30cb
commit
e163774685
13 changed files with 57 additions and 65 deletions
|
|
@ -10,7 +10,8 @@ Games:
|
|||
- [Serious Sam](https://www.gog.com/game/serious_sam_the_first_encounter) support.
|
||||
|
||||
### Breaking:
|
||||
None.
|
||||
Protocols:
|
||||
- Valve: Request type enums have been renamed from all caps to starting-only uppercase, ex: `INFO` to `Info`
|
||||
|
||||
# 0.2.1 - 03/03/2023
|
||||
### Changes:
|
||||
|
|
|
|||
|
|
@ -100,7 +100,7 @@ impl Bufferer {
|
|||
|
||||
pub fn get_string_utf8(&mut self) -> GDResult<String> {
|
||||
let sub_buf = &self.data[self.position..];
|
||||
if sub_buf.len() == 0 {
|
||||
if sub_buf.is_empty() {
|
||||
return Err(PacketUnderflow);
|
||||
}
|
||||
|
||||
|
|
@ -115,11 +115,11 @@ impl Bufferer {
|
|||
|
||||
pub fn get_string_utf8_unended(&mut self) -> GDResult<String> {
|
||||
let sub_buf = &self.data[self.position..];
|
||||
if sub_buf.len() == 0 {
|
||||
if sub_buf.is_empty() {
|
||||
return Err(PacketUnderflow);
|
||||
}
|
||||
|
||||
let value = std::str::from_utf8(&sub_buf)
|
||||
let value = std::str::from_utf8(sub_buf)
|
||||
.map_err(|_| PacketBad)?.to_string();
|
||||
|
||||
self.position += value.len();
|
||||
|
|
@ -128,7 +128,7 @@ impl Bufferer {
|
|||
|
||||
pub fn get_string_utf16(&mut self) -> GDResult<String> {
|
||||
let sub_buf = &self.data[self.position..];
|
||||
if sub_buf.len() == 0 {
|
||||
if sub_buf.is_empty() {
|
||||
return Err(PacketUnderflow);
|
||||
}
|
||||
|
||||
|
|
@ -138,8 +138,7 @@ impl Bufferer {
|
|||
Endianess::Big => u16::from_be_bytes([a[0], a[1]])
|
||||
}).collect();
|
||||
|
||||
let value = String::from_utf16(&paired_buf)
|
||||
.map_err(|_| PacketBad)?.to_string();
|
||||
let value = String::from_utf16(&paired_buf).map_err(|_| PacketBad)?;
|
||||
|
||||
self.position += value.len() * 2;
|
||||
Ok(value)
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
|
||||
//! Game Server Query Library.
|
||||
//!
|
||||
//! # An usage example:
|
||||
//! # Usage example:
|
||||
//!
|
||||
//! ```no_run
|
||||
//!use gamedig::games::tf2;
|
||||
|
|
|
|||
|
|
@ -172,15 +172,15 @@ pub fn query(address: &str, port: u16, timeout_settings: Option<TimeoutSettings>
|
|||
map: server_vars.remove("mapname").ok_or(GDError::PacketBad)?,
|
||||
map_title: server_vars.remove("maptitle"),
|
||||
admin_contact: server_vars.remove("AdminEMail"),
|
||||
admin_name: server_vars.remove("AdminName").or(server_vars.remove("admin")),
|
||||
admin_name: server_vars.remove("AdminName").or_else(|| server_vars.remove("admin")),
|
||||
has_password: has_password(&mut server_vars)?,
|
||||
game_type: server_vars.remove("gametype").ok_or(GDError::PacketBad)?,
|
||||
game_version: server_vars.remove("gamever").ok_or(GDError::PacketBad)?,
|
||||
players_maximum,
|
||||
players_online: players.len(),
|
||||
players_minimum: server_vars.remove("minplayers").unwrap_or("0".to_string()).parse().map_err(|_| GDError::TypeParse)?,
|
||||
players_minimum: server_vars.remove("minplayers").unwrap_or_else(|| "0".to_string()).parse().map_err(|_| GDError::TypeParse)?,
|
||||
players,
|
||||
tournament: server_vars.remove("tournament").unwrap_or("true".to_string()).to_lowercase().parse().map_err(|_| GDError::TypeParse)?,
|
||||
tournament: server_vars.remove("tournament").unwrap_or_else(|| "true".to_string()).to_lowercase().parse().map_err(|_| GDError::TypeParse)?,
|
||||
unused_entries: server_vars
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -71,7 +71,7 @@ impl Bedrock {
|
|||
error_by_expected_size(remaining_length, buffer.remaining_length())?;
|
||||
|
||||
let binding = buffer.get_string_utf8_unended()?;
|
||||
let status: Vec<&str> = binding.split(";").collect();
|
||||
let status: Vec<&str> = binding.split(';').collect();
|
||||
|
||||
// We must have at least 6 values
|
||||
if status.len() < 6 {
|
||||
|
|
@ -85,8 +85,8 @@ impl Bedrock {
|
|||
version_protocol: status[2].to_string(),
|
||||
players_maximum: status[5].parse().map_err(|_| TypeParse)?,
|
||||
players_online: 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())),
|
||||
id: status.get(6).map(|v| v.to_string()),
|
||||
map: status.get(7).map(|v| v.to_string()),
|
||||
game_mode: match status.get(8) {
|
||||
None => None,
|
||||
Some(v) => Some(GameMode::from_bedrock(v)?)
|
||||
|
|
|
|||
|
|
@ -39,7 +39,7 @@ impl LegacyBV1_8 {
|
|||
|
||||
let packet_string = buffer.get_string_utf16()?;
|
||||
|
||||
let split: Vec<&str> = packet_string.split("§").collect();
|
||||
let split: Vec<&str> = packet_string.split('§').collect();
|
||||
error_by_expected_size(3, split.len())?;
|
||||
|
||||
let description = split[0].to_string();
|
||||
|
|
|
|||
|
|
@ -44,7 +44,7 @@ impl LegacyV1_4 {
|
|||
|
||||
let packet_string = buffer.get_string_utf16()?;
|
||||
|
||||
let split: Vec<&str> = packet_string.split("§").collect();
|
||||
let split: Vec<&str> = packet_string.split('§').collect();
|
||||
error_by_expected_size(3, split.len())?;
|
||||
|
||||
let description = split[0].to_string();
|
||||
|
|
|
|||
|
|
@ -49,7 +49,7 @@ impl LegacyV1_6 {
|
|||
pub fn get_response(buffer: &mut Bufferer) -> GDResult<JavaResponse> {
|
||||
let packet_string = buffer.get_string_utf16()?;
|
||||
|
||||
let split: Vec<&str> = packet_string.split("\x00").collect();
|
||||
let split: Vec<&str> = packet_string.split('\x00').collect();
|
||||
error_by_expected_size(5, split.len())?;
|
||||
|
||||
let version_protocol = split[0].parse()
|
||||
|
|
|
|||
|
|
@ -174,14 +174,13 @@ pub(crate) fn as_varint(value: i32) -> Vec<u8> {
|
|||
|
||||
pub(crate) fn get_string(buffer: &mut Bufferer) -> GDResult<String> {
|
||||
let length = get_varint(buffer)? as usize;
|
||||
let mut text = vec![0; length];
|
||||
let mut text = Vec::with_capacity(length);
|
||||
|
||||
for i in 0..length {
|
||||
text[i] = buffer.get_u8()?;
|
||||
for _ in 0..length {
|
||||
text.push(buffer.get_u8()?)
|
||||
}
|
||||
|
||||
Ok(String::from_utf8(text)
|
||||
.map_err(|_| PacketBad)?)
|
||||
String::from_utf8(text).map_err(|_| PacketBad)
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
|
|
|
|||
|
|
@ -32,7 +32,7 @@ impl Packet {
|
|||
header: initial.header,
|
||||
kind: initial.kind,
|
||||
payload: match kind {
|
||||
Request::INFO => {
|
||||
Request::Info => {
|
||||
initial.payload.extend(challenge);
|
||||
initial.payload
|
||||
},
|
||||
|
|
@ -46,7 +46,7 @@ impl Packet {
|
|||
header: 4294967295, //FF FF FF FF
|
||||
kind: kind as u8,
|
||||
payload: match kind {
|
||||
Request::INFO => String::from("Source Engine Query\0").into_bytes(),
|
||||
Request::Info => String::from("Source Engine Query\0").into_bytes(),
|
||||
_ => vec![0xFF, 0xFF, 0xFF, 0xFF]
|
||||
}
|
||||
}
|
||||
|
|
@ -124,10 +124,8 @@ impl SplitPacket {
|
|||
let mut decompressed_payload = Vec::with_capacity(decompressed_size);
|
||||
decoder.read(&mut decompressed_payload).map_err(|_| Decompress)?;
|
||||
|
||||
if decompressed_payload.len() != decompressed_size {
|
||||
Err(Decompress)
|
||||
}
|
||||
else if crc32fast::hash(&decompressed_payload) != self.uncompressed_crc32.unwrap() {
|
||||
if decompressed_payload.len() != decompressed_size
|
||||
|| crc32fast::hash(&decompressed_payload) != self.uncompressed_crc32.unwrap() {
|
||||
Err(Decompress)
|
||||
}
|
||||
else {
|
||||
|
|
@ -162,13 +160,13 @@ impl ValveProtocol {
|
|||
let header = buffer.get_u8()?;
|
||||
buffer.move_position_backward(1);
|
||||
if header == 0xFE { //the packet is split
|
||||
let mut main_packet = SplitPacket::new(&engine, protocol, &mut buffer)?;
|
||||
let mut main_packet = SplitPacket::new(engine, protocol, &mut buffer)?;
|
||||
let mut chunk_packets = Vec::with_capacity((main_packet.total - 1) as usize);
|
||||
|
||||
for _ in 1..main_packet.total {
|
||||
let new_data = self.socket.receive(Some(buffer_size))?;
|
||||
buffer = Bufferer::new_with_data(Endianess::Little, &new_data);
|
||||
let chunk_packet = SplitPacket::new(&engine, protocol, &mut buffer)?;
|
||||
let chunk_packet = SplitPacket::new(engine, protocol, &mut buffer)?;
|
||||
chunk_packets.push(chunk_packet);
|
||||
}
|
||||
|
||||
|
|
@ -266,7 +264,7 @@ impl ValveProtocol {
|
|||
|
||||
/// Get the server information's.
|
||||
fn get_server_info(&mut self, engine: &Engine) -> GDResult<ServerInfo> {
|
||||
let mut buffer = self.get_request_data(&engine, 0, Request::INFO)?;
|
||||
let mut buffer = self.get_request_data(engine, 0, Request::Info)?;
|
||||
|
||||
if let Engine::GoldSrc(force) = engine {
|
||||
if *force {
|
||||
|
|
@ -365,7 +363,7 @@ impl ValveProtocol {
|
|||
|
||||
/// Get the server player's.
|
||||
fn get_server_players(&mut self, engine: &Engine, protocol: u8) -> GDResult<Vec<ServerPlayer>> {
|
||||
let mut buffer = self.get_request_data(&engine, protocol, Request::PLAYERS)?;
|
||||
let mut buffer = self.get_request_data(engine, protocol, Request::Players)?;
|
||||
|
||||
let count = buffer.get_u8()? as usize;
|
||||
let mut players: Vec<ServerPlayer> = Vec::with_capacity(count);
|
||||
|
|
@ -393,7 +391,7 @@ impl ValveProtocol {
|
|||
|
||||
/// Get the server's rules.
|
||||
fn get_server_rules(&mut self, engine: &Engine, protocol: u8) -> GDResult<HashMap<String, String>> {
|
||||
let mut buffer = self.get_request_data(&engine, protocol, Request::RULES)?;
|
||||
let mut buffer = self.get_request_data(engine, protocol, Request::Rules)?;
|
||||
|
||||
let count = buffer.get_u16()? as usize;
|
||||
let mut rules: HashMap<String, String> = HashMap::with_capacity(count);
|
||||
|
|
@ -416,7 +414,7 @@ impl ValveProtocol {
|
|||
/// Query a server by providing the address, the port, the app, gather and timeout settings.
|
||||
/// Providing None to the settings results in using the default values for them (GatherSettings::[default](GatheringSettings::default), TimeoutSettings::[default](TimeoutSettings::default)).
|
||||
pub fn query(address: &str, port: u16, engine: Engine, gather_settings: Option<GatheringSettings>, timeout_settings: Option<TimeoutSettings>) -> GDResult<Response> {
|
||||
let response_gather_settings = gather_settings.unwrap_or(GatheringSettings::default());
|
||||
let response_gather_settings = gather_settings.unwrap_or_default();
|
||||
get_response(address, port, engine, response_gather_settings, timeout_settings)
|
||||
}
|
||||
|
||||
|
|
@ -426,21 +424,19 @@ fn get_response(address: &str, port: u16, engine: Engine, gather_settings: Gathe
|
|||
let info = client.get_server_info(&engine)?;
|
||||
let protocol = info.protocol;
|
||||
|
||||
if let Engine::Source(source_app) = &engine {
|
||||
if let Some(appids) = source_app {
|
||||
let mut is_specified_id = false;
|
||||
if let Engine::Source(Some(appids)) = &engine {
|
||||
let mut is_specified_id = false;
|
||||
|
||||
if appids.0 == info.appid {
|
||||
if appids.0 == info.appid {
|
||||
is_specified_id = true;
|
||||
} else if let Some(dedicated_appid) = appids.1 {
|
||||
if dedicated_appid == info.appid {
|
||||
is_specified_id = true;
|
||||
} else if let Some(dedicated_appid) = appids.1 {
|
||||
if dedicated_appid == info.appid {
|
||||
is_specified_id = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !is_specified_id {
|
||||
return Err(BadGame(format!("AppId: {}", info.appid)));
|
||||
}
|
||||
if !is_specified_id {
|
||||
return Err(BadGame(format!("AppId: {}", info.appid)));
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -124,19 +124,19 @@ pub(crate) fn get_optional_extracted_data(data: Option<ExtraData>) -> (Option<u1
|
|||
}
|
||||
|
||||
/// The type of the request, see the [protocol](https://developer.valvesoftware.com/wiki/Server_queries).
|
||||
#[derive(PartialEq, Copy, Clone)]
|
||||
#[derive(Eq, PartialEq, Copy, Clone)]
|
||||
#[repr(u8)]
|
||||
pub(crate) enum Request {
|
||||
/// Known as `A2S_INFO`
|
||||
INFO = 0x54,
|
||||
Info = 0x54,
|
||||
/// Known as `A2S_PLAYERS`
|
||||
PLAYERS = 0x55,
|
||||
Players = 0x55,
|
||||
/// Known as `A2S_RULES`
|
||||
RULES = 0x56
|
||||
Rules = 0x56
|
||||
}
|
||||
|
||||
/// Supported steam apps
|
||||
#[derive(PartialEq, Clone)]
|
||||
#[derive(Eq, PartialEq, Clone)]
|
||||
pub enum SteamApp {
|
||||
/// Counter-Strike
|
||||
CS,
|
||||
|
|
@ -272,7 +272,7 @@ impl SteamApp {
|
|||
}
|
||||
|
||||
/// Engine type.
|
||||
#[derive(PartialEq, Clone)]
|
||||
#[derive(Eq, PartialEq, Clone)]
|
||||
pub enum Engine {
|
||||
/// A Source game, the argument represents the possible steam app ids, if its **None**, let
|
||||
/// the query find it, if its **Some**, the query fails if the response id is not the first
|
||||
|
|
@ -391,7 +391,7 @@ pub mod game {
|
|||
game: response.info.game,
|
||||
appid: response.info.appid,
|
||||
players_online: response.info.players_online,
|
||||
players_details: response.players.unwrap_or(vec![]).iter().map(Player::from_valve_response).collect(),
|
||||
players_details: response.players.unwrap_or_default().iter().map(Player::from_valve_response).collect(),
|
||||
players_maximum: response.info.players_maximum,
|
||||
players_bots: response.info.players_bots,
|
||||
server_type: response.info.server_type,
|
||||
|
|
@ -403,7 +403,7 @@ pub mod game {
|
|||
tv_port,
|
||||
tv_name,
|
||||
keywords,
|
||||
rules: response.rules.unwrap_or(HashMap::new())
|
||||
rules: response.rules.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -31,7 +31,7 @@ impl Socket for TcpSocket {
|
|||
}
|
||||
|
||||
fn apply_timeout(&self, timeout_settings: Option<TimeoutSettings>) -> GDResult<()> {
|
||||
let settings = timeout_settings.unwrap_or(TimeoutSettings::default());
|
||||
let settings = timeout_settings.unwrap_or_default();
|
||||
self.socket.set_read_timeout(settings.get_read()).unwrap(); //unwrapping because TimeoutSettings::new
|
||||
self.socket.set_write_timeout(settings.get_write()).unwrap(); //checks if these are 0 and throws an error
|
||||
|
||||
|
|
@ -39,7 +39,7 @@ impl Socket for TcpSocket {
|
|||
}
|
||||
|
||||
fn send(&mut self, data: &[u8]) -> GDResult<()> {
|
||||
self.socket.write(&data).map_err(|_| PacketSend)?;
|
||||
self.socket.write(data).map_err(|_| PacketSend)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
@ -68,7 +68,7 @@ impl Socket for UdpSocket {
|
|||
}
|
||||
|
||||
fn apply_timeout(&self, timeout_settings: Option<TimeoutSettings>) -> GDResult<()> {
|
||||
let settings = timeout_settings.unwrap_or(TimeoutSettings::default());
|
||||
let settings = timeout_settings.unwrap_or_default();
|
||||
self.socket.set_read_timeout(settings.get_read()).unwrap(); //unwrapping because TimeoutSettings::new
|
||||
self.socket.set_write_timeout(settings.get_write()).unwrap(); //checks if these are 0 and throws an error
|
||||
|
||||
|
|
@ -76,7 +76,7 @@ impl Socket for UdpSocket {
|
|||
}
|
||||
|
||||
fn send(&mut self, data: &[u8]) -> GDResult<()> {
|
||||
self.socket.send_to(&data, &self.complete_address).map_err(|_| PacketSend)?;
|
||||
self.socket.send_to(data, &self.complete_address).map_err(|_| PacketSend)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
|
|||
13
src/utils.rs
13
src/utils.rs
|
|
@ -1,15 +1,12 @@
|
|||
use std::cmp::Ordering;
|
||||
use crate::GDResult;
|
||||
use crate::GDError::{PacketOverflow, PacketUnderflow};
|
||||
|
||||
pub fn error_by_expected_size(expected: usize, size: usize) -> GDResult<()> {
|
||||
if size < expected {
|
||||
Err(PacketUnderflow)
|
||||
}
|
||||
else if size > expected {
|
||||
Err(PacketOverflow)
|
||||
}
|
||||
else {
|
||||
Ok(())
|
||||
match size.cmp(&expected) {
|
||||
Ordering::Greater => Err(PacketOverflow),
|
||||
Ordering::Less => Err(PacketUnderflow),
|
||||
Ordering::Equal => Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue