From c9a070f711a6fdaf505f522cb8809749c9190e38 Mon Sep 17 00:00:00 2001 From: mat Date: Sun, 19 Jun 2022 22:01:54 -0500 Subject: [PATCH] Fix some clippy warnings --- Cargo.lock | 16 +++++++++ azalea-client/Cargo.toml | 1 + azalea-client/src/account.rs | 9 +---- azalea-client/src/client.rs | 61 ++++++++++++++++++++++----------- azalea-entity/src/lib.rs | 2 +- azalea-world/src/bit_storage.rs | 6 ++-- azalea-world/src/chunk.rs | 10 +++--- azalea-world/src/entity.rs | 8 ++++- azalea-world/src/lib.rs | 7 ++-- bot/src/main.rs | 9 +++-- 10 files changed, 83 insertions(+), 46 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a3ceba57..59edd75e 100755 --- a/Cargo.lock +++ b/Cargo.lock @@ -109,6 +109,7 @@ dependencies = [ "azalea-entity", "azalea-protocol", "azalea-world", + "owning_ref", "tokio", ] @@ -891,6 +892,15 @@ version = "11.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ab1bc2a289d34bd04a330323ac98a1b4bc82c9d9fcb1e66b63caa84da26b575" +[[package]] +name = "owning_ref" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ff55baddef9e4ad00f88b6c743a2a8062d4c6ade126c2a528644b8e444d52ce" +dependencies = [ + "stable_deref_trait", +] + [[package]] name = "packet-macros" version = "0.1.0" @@ -1239,6 +1249,12 @@ dependencies = [ "winapi", ] +[[package]] +name = "stable_deref_trait" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" + [[package]] name = "syn" version = "1.0.96" diff --git a/azalea-client/Cargo.toml b/azalea-client/Cargo.toml index cc34f03a..9c9ae746 100755 --- a/azalea-client/Cargo.toml +++ b/azalea-client/Cargo.toml @@ -12,4 +12,5 @@ azalea-crypto = {path = "../azalea-crypto"} azalea-entity = {path = "../azalea-entity"} azalea-protocol = {path = "../azalea-protocol"} azalea-world = {path = "../azalea-world"} +owning_ref = "0.4.1" tokio = {version = "1.18.0", features = ["sync"]} diff --git a/azalea-client/src/account.rs b/azalea-client/src/account.rs index 00a5d0f6..0bcad630 100644 --- a/azalea-client/src/account.rs +++ b/azalea-client/src/account.rs @@ -1,12 +1,5 @@ use crate::Client; -use azalea_protocol::{ - packets::game::{ - clientbound_player_chat_packet::ClientboundPlayerChatPacket, - clientbound_system_chat_packet::ClientboundSystemChatPacket, - }, - ServerAddress, -}; -use std::fmt::Debug; +use azalea_protocol::ServerAddress; ///! Connect to Minecraft servers. diff --git a/azalea-client/src/client.rs b/azalea-client/src/client.rs index dc2fe70f..3dd206b5 100644 --- a/azalea-client/src/client.rs +++ b/azalea-client/src/client.rs @@ -20,7 +20,8 @@ use azalea_protocol::{ }, resolver, ServerAddress, }; -use azalea_world::{ChunkStorage, EntityStorage, World}; +use azalea_world::World; +use owning_ref::OwningRef; use std::{ fmt::Debug, sync::{Arc, Mutex}, @@ -42,7 +43,7 @@ pub enum Event { #[derive(Debug, Clone)] pub enum ChatPacket { System(ClientboundSystemChatPacket), - Player(ClientboundPlayerChatPacket), + Player(Box), } // impl ChatPacket { @@ -65,6 +66,7 @@ pub struct Client { /// Whether we should ignore errors when decoding packets. const IGNORE_ERRORS: bool = !cfg!(debug_assertions); +#[derive(Debug)] struct HandleError(String); impl Client { @@ -172,9 +174,17 @@ impl Client { loop { let r = conn.lock().await.read().await; match r { - Ok(packet) => { - Self::handle(&packet, &tx, &state, &conn).await; - } + Ok(packet) => match Self::handle(&packet, &tx, &state, &conn).await { + Ok(_) => {} + Err(e) => { + println!("Error handling packet: {:?}", e); + if IGNORE_ERRORS { + continue; + } else { + panic!("Error handling packet: {:?}", e); + } + } + }, Err(e) => { if IGNORE_ERRORS { println!("Error: {:?}", e); @@ -242,7 +252,9 @@ impl Client { .expect("name is not a string") == p.dimension_type.to_string() }) - .expect(&format!("No dimension_type with name {}", p.dimension_type)) + .unwrap_or_else(|| { + panic!("No dimension_type with name {}", p.dimension_type) + }) .as_compound() .unwrap() .get("element") @@ -256,13 +268,11 @@ impl Client { .expect("height tag is not an int")) .try_into() .expect("height is not a u32"); - let min_y = (*dimension_type + let min_y = *dimension_type .get("min_y") .expect("No min_y tag") .as_int() - .expect("min_y tag is not an int")) - .try_into() - .expect("min_y is not an i32"); + .expect("min_y tag is not an int"); state.world = Some(World::new(16, height, min_y)); } @@ -308,7 +318,7 @@ impl Client { GamePacket::ClientboundUpdateRecipesPacket(_p) => { println!("Got update recipes packet"); } - GamePacket::ClientboundEntityEventPacket(p) => { + GamePacket::ClientboundEntityEventPacket(_p) => { // println!("Got entity event packet {:?}", p); } GamePacket::ClientboundRecipePacket(_p) => { @@ -356,13 +366,13 @@ impl Client { .expect("World doesn't exist! We should've gotten a login packet by now.") .add_entity(entity); } - GamePacket::ClientboundSetEntityDataPacket(p) => { + GamePacket::ClientboundSetEntityDataPacket(_p) => { // println!("Got set entity data packet {:?}", p); } - GamePacket::ClientboundUpdateAttributesPacket(p) => { + GamePacket::ClientboundUpdateAttributesPacket(_p) => { // println!("Got update attributes packet {:?}", p); } - GamePacket::ClientboundEntityVelocityPacket(p) => { + GamePacket::ClientboundEntityVelocityPacket(_p) => { // println!("Got entity velocity packet {:?}", p); } GamePacket::ClientboundSetEntityLinkPacket(p) => { @@ -389,9 +399,9 @@ impl Client { GamePacket::ClientboundSetExperiencePacket(p) => { println!("Got set experience packet {:?}", p); } - GamePacket::ClientboundTeleportEntityPacket(p) => { + GamePacket::ClientboundTeleportEntityPacket(_p) => { // println!("Got teleport entity packet {:?}", p); - let state_lock = state.lock()?; + // let state_lock = state.lock()?; // let entity = state_lock // .world @@ -407,13 +417,13 @@ impl Client { GamePacket::ClientboundUpdateAdvancementsPacket(p) => { println!("Got update advancements packet {:?}", p); } - GamePacket::ClientboundRotateHeadPacket(p) => { + GamePacket::ClientboundRotateHeadPacket(_p) => { // println!("Got rotate head packet {:?}", p); } - GamePacket::ClientboundMoveEntityPosPacket(p) => { + GamePacket::ClientboundMoveEntityPosPacket(_p) => { // println!("Got move entity pos packet {:?}", p); } - GamePacket::ClientboundMoveEntityPosRotPacket(p) => { + GamePacket::ClientboundMoveEntityPosRotPacket(_p) => { // println!("Got move entity pos rot packet {:?}", p); } GamePacket::ClientboundMoveEntityRotPacket(p) => { @@ -431,7 +441,8 @@ impl Client { } GamePacket::ClientboundPlayerChatPacket(p) => { println!("Got player chat packet {:?}", p); - tx.send(Event::Chat(ChatPacket::Player(p.clone()))).unwrap(); + tx.send(Event::Chat(ChatPacket::Player(Box::new(p.clone())))) + .unwrap(); } GamePacket::ClientboundSystemChatPacket(p) => { println!("Got system chat packet {:?}", p); @@ -475,6 +486,16 @@ impl Client { pub async fn next(&mut self) -> Option { self.event_receiver.recv().await } + + /// Gets the `World` the client is in. + /// + /// This is basically a shortcut for `let world = client.state.lock().unwrap().world.as_ref().unwrap()`. + /// If the client hasn't received a login packet yet, this will panic. + pub fn world(&self) -> OwningRef, World> { + let state_lock: std::sync::MutexGuard = self.state.lock().unwrap(); + let state_lock_ref = OwningRef::new(state_lock); + state_lock_ref.map(|state| state.world.as_ref().expect("World doesn't exist!")) + } } impl From> for HandleError { diff --git a/azalea-entity/src/lib.rs b/azalea-entity/src/lib.rs index f776f16f..d32a1a96 100644 --- a/azalea-entity/src/lib.rs +++ b/azalea-entity/src/lib.rs @@ -1,4 +1,4 @@ -use azalea_core::{ChunkPos, EntityPos}; +use azalea_core::EntityPos; #[cfg(feature = "protocol")] use azalea_protocol::packets::game::clientbound_add_entity_packet::ClientboundAddEntityPacket; use uuid::Uuid; diff --git a/azalea-world/src/bit_storage.rs b/azalea-world/src/bit_storage.rs index 0dc81f9a..fcb3f8f9 100644 --- a/azalea-world/src/bit_storage.rs +++ b/azalea-world/src/bit_storage.rs @@ -107,7 +107,7 @@ impl BitStorage { // assert!(bits >= 1 && bits <= 32); if let Some(data) = &data { - if data.len() == 0 { + if data.is_empty() { // TODO: make 0 bit storage actually work return Ok(BitStorage::default()); } @@ -162,7 +162,7 @@ impl BitStorage { // return (int)(var3 >> var5 & this.mask); assert!( - index <= self.size - 1, + index < self.size, "Index {} out of bounds (max is {})", index, self.size - 1 @@ -181,7 +181,7 @@ impl BitStorage { // int var6 = (var1 - var3 * this.valuesPerLong) * this.bits; // this.data[var3] = var4 & ~(this.mask << var6) | ((long)var2 & this.mask) << var6; - assert!(index <= self.size - 1); + assert!(index < self.size); assert!(value <= self.mask); let cell_index = self.cell_index(index as u64); let cell = &mut self.data[cell_index as usize]; diff --git a/azalea-world/src/chunk.rs b/azalea-world/src/chunk.rs index 5de39e52..77fa8786 100644 --- a/azalea-world/src/chunk.rs +++ b/azalea-world/src/chunk.rs @@ -60,10 +60,9 @@ impl ChunkStorage { let chunk_pos = ChunkPos::from(pos); println!("chunk_pos {:?} block_pos {:?}", chunk_pos, pos); let chunk = &self[&chunk_pos]; - match chunk { - Some(chunk) => Some(chunk.lock().unwrap().get(&ChunkBlockPos::from(pos), min_y)), - None => None, - } + chunk + .as_ref() + .map(|chunk| chunk.lock().unwrap().get(&ChunkBlockPos::from(pos), min_y)) } pub fn replace_with_packet_data( @@ -137,8 +136,7 @@ impl Chunk { // TODO: make sure the section exists let section = &self.sections[section_index as usize]; let chunk_section_pos = ChunkSectionBlockPos::from(pos); - let block_state = section.get(chunk_section_pos); - block_state + section.get(chunk_section_pos) } } diff --git a/azalea-world/src/entity.rs b/azalea-world/src/entity.rs index 7077d0c4..2409995c 100644 --- a/azalea-world/src/entity.rs +++ b/azalea-world/src/entity.rs @@ -34,7 +34,7 @@ impl EntityStorage { pub fn remove_by_id(&mut self, id: u32) { if let Some(entity) = self.by_id.remove(&id) { let entity_chunk = ChunkPos::from(entity.pos()); - if let None = self.by_chunk.remove(&entity_chunk) { + if self.by_chunk.remove(&entity_chunk).is_none() { warn!("Tried to remove entity with id {id} from chunk {entity_chunk:?} but it was not found."); } } else { @@ -80,3 +80,9 @@ impl EntityStorage { .insert(entity_id); } } + +impl Default for EntityStorage { + fn default() -> Self { + Self::new() + } +} diff --git a/azalea-world/src/lib.rs b/azalea-world/src/lib.rs index 746143c7..dc538618 100644 --- a/azalea-world/src/lib.rs +++ b/azalea-world/src/lib.rs @@ -6,14 +6,13 @@ mod entity; mod palette; use azalea_block::BlockState; -use azalea_core::{BlockPos, ChunkBlockPos, ChunkPos, ChunkSectionBlockPos, EntityPos}; +use azalea_core::{BlockPos, ChunkPos, EntityPos}; use azalea_entity::Entity; -use azalea_protocol::mc_buf::{McBufReadable, McBufWritable}; pub use bit_storage::BitStorage; pub use chunk::{Chunk, ChunkStorage}; pub use entity::EntityStorage; use std::{ - io::{Read, Write}, + io::Read, ops::{Index, IndexMut}, sync::{Arc, Mutex}, }; @@ -61,7 +60,7 @@ impl World { let entity = self .entity_storage .get_mut_by_id(entity_id) - .ok_or("Moving entity that doesn't exist".to_string())?; + .ok_or_else(|| "Moving entity that doesn't exist".to_string())?; let old_chunk = ChunkPos::from(entity.pos()); let new_chunk = ChunkPos::from(&new_pos); // this is fine because we update the chunk below diff --git a/bot/src/main.rs b/bot/src/main.rs index e8ff5f95..f0f915f9 100644 --- a/bot/src/main.rs +++ b/bot/src/main.rs @@ -1,4 +1,5 @@ use azalea_client::{Account, Event}; +use azalea_core::BlockPos; #[tokio::main] async fn main() -> Result<(), Box> { @@ -20,9 +21,11 @@ async fn main() -> Result<(), Box> { // TODO: have a "loaded" or "ready" event that fires when all chunks are loaded Event::Login => {} Event::Chat(_p) => { - let state = client.state.lock().unwrap(); - let world = state.world.as_ref().unwrap(); - println!("{:#?}", world); + let world = client.world(); + world.get_block_state(&BlockPos::new(0, 0, 0)).unwrap(); + // let world = state.world.as_ref().unwrap(); + // world. + // println!("{:#?}", world); // world.get_block_state(state.player.entity.pos); // println!("{}", p.message.to_ansi(None)); // if p.message.to_ansi(None) == " ok" {