From 60f04597d1b1ee1c103ee3fc8f0e195667c681dd Mon Sep 17 00:00:00 2001 From: jake Date: Fri, 18 Jun 2021 02:11:19 -0600 Subject: [PATCH 01/25] if any of these sends fail the program should panic so unwrap is fine --- src/common/mainloop/client.rs | 16 ++++++++-------- src/common/mainloop/interserver.rs | 16 ++++++++-------- src/login/login.rs | 2 +- 3 files changed, 17 insertions(+), 17 deletions(-) diff --git a/src/common/mainloop/client.rs b/src/common/mainloop/client.rs index 31c736c..c13acbf 100644 --- a/src/common/mainloop/client.rs +++ b/src/common/mainloop/client.rs @@ -149,7 +149,7 @@ where R: RecvServerPacket + std::fmt::Debug + Send + 'static, { async_std::task::spawn(async move { - server_sender.send(ClientAction::NewClient(client_id, client_sender)).await; + server_sender.send(ClientAction::NewClient(client_id, client_sender)).await.unwrap(); let mut pkt_receiver = PacketReceiver::new(socket, cipher); loop { @@ -157,14 +157,14 @@ where Ok(pkts) => { for pkt in pkts { trace!("[recv from {:?}] {:?}", client_id, pkt); - server_sender.send(ClientAction::Packet(client_id, pkt)).await; + server_sender.send(ClientAction::Packet(client_id, pkt)).await.unwrap(); } }, Err(err) => { match err { NetworkError::ClientDisconnected => { trace!("[client disconnected] {:?}", client_id); - server_sender.send(ClientAction::Disconnect(client_id)).await; + server_sender.send(ClientAction::Disconnect(client_id)).await.unwrap(); break; } _ => { @@ -229,10 +229,10 @@ fn state_client_loop(state: Arc>, for action in actions { match action { OnConnect::Cipher((inc, outc)) => { - sender.send(ServerStateAction::Cipher(inc, outc)).await; + sender.send(ServerStateAction::Cipher(inc, outc)).await.unwrap(); }, OnConnect::Packet(pkt) => { - sender.send(ServerStateAction::Packet(pkt)).await; + sender.send(ServerStateAction::Packet(pkt)).await.unwrap(); } } } @@ -249,7 +249,7 @@ fn state_client_loop(state: Arc>, Ok(pkts) => { for (client_id, pkt) in pkts { if let Some(client) = clients.get_mut(&client_id) { - client.send(ServerStateAction::Packet(pkt)).await; + client.send(ServerStateAction::Packet(pkt)).await.unwrap(); } } }, @@ -264,12 +264,12 @@ fn state_client_loop(state: Arc>, Ok(pkts) => { for (client_id, pkt) in pkts { if let Some(client) = clients.get_mut(&client_id) { - client.send(ServerStateAction::Packet(pkt)).await; + client.send(ServerStateAction::Packet(pkt)).await.unwrap(); } } if let Some(client) = clients.get_mut(&client_id) { - client.send(ServerStateAction::Disconnect).await; + client.send(ServerStateAction::Disconnect).await.unwrap(); } } Err(err) => { diff --git a/src/common/mainloop/interserver.rs b/src/common/mainloop/interserver.rs index 526e51d..473abb4 100644 --- a/src/common/mainloop/interserver.rs +++ b/src/common/mainloop/interserver.rs @@ -79,7 +79,7 @@ where ships.insert(server_id, ship_action_sender); for (server, action) in state.on_connect(server_id).await { if let Some(sender) = ships.get_mut(&server) { - sender.send(action).await; + sender.send(action).await.unwrap(); } } }, @@ -89,7 +89,7 @@ where Ok(actions) => { for (server, action) in actions{ if let Some(sender) = ships.get_mut(&server) { - sender.send(action).await; + sender.send(action).await.unwrap(); } } }, @@ -103,7 +103,7 @@ where ships.remove(&server_id); for (server, action) in actions { if let Some(sender) = ships.get_mut(&server) { - sender.send(action).await; + sender.send(action).await.unwrap(); } } } @@ -121,7 +121,7 @@ where R: DeserializeOwned + std::fmt::Debug + Send + 'static, { async_std::task::spawn(async move { - state_loop_sender.send(InterserverInputAction::NewConnection(server_id, output_loop_sender)).await; + state_loop_sender.send(InterserverInputAction::NewConnection(server_id, output_loop_sender)).await.unwrap(); let mut msg_receiver = MessageReceiver::new(socket); loop { @@ -129,12 +129,12 @@ where match msg_receiver.recv().await { Ok(msg) => { info!("[login recv loop msg] {:?}", msg); - state_loop_sender.send(InterserverInputAction::Message(server_id, msg)).await; + state_loop_sender.send(InterserverInputAction::Message(server_id, msg)).await.unwrap(); }, Err(err) => { if let MessageReceiverError::Disconnected = err { info!("[login recv loop disconnect] {:?}", server_id); - state_loop_sender.send(InterserverInputAction::Disconnect(server_id)).await; + state_loop_sender.send(InterserverInputAction::Disconnect(server_id)).await.unwrap(); break; } info!("[login recv loop err] {:?}", err); @@ -200,7 +200,7 @@ pub fn login_listen_mainloop(state: Arc(state: Arc ServerState for LoginServerState { if let Some(username) = self.clients.remove(&id) { if let Ok(mut user) = self.entity_gateway.get_user_by_name(username).await { user.at_login = false; - self.entity_gateway.save_user(&user).await; + self.entity_gateway.save_user(&user).await?; } } Ok(Vec::new()) From bbe22a305a0dd957352cdc15377594e2d03e30da Mon Sep 17 00:00:00 2001 From: jake Date: Fri, 18 Jun 2021 02:11:52 -0600 Subject: [PATCH 02/25] properly handle an error that doesn't even occur at the moment --- src/ship/items/inventory.rs | 7 ++++++- src/ship/items/manager.rs | 2 +- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/src/ship/items/inventory.rs b/src/ship/items/inventory.rs index 35cef9f..67bb356 100644 --- a/src/ship/items/inventory.rs +++ b/src/ship/items/inventory.rs @@ -82,6 +82,11 @@ pub enum InventoryItemAddToError { ExceedsCapacity, } +#[derive(Error, Debug, Clone)] +#[error("")] +pub enum InventoryAddError { +} + impl InventoryItem { pub fn entity_ids(&self) -> Vec { match self { @@ -511,7 +516,7 @@ impl CharacterInventory { .nth(0) } - pub fn add_item(&mut self, item: InventoryItem) -> Result<(), ()> { // TODO: errors + pub fn add_item(&mut self, item: InventoryItem) -> Result<(), InventoryAddError> { // TODO: errors // TODO: check slot conflict? self.items.push(item); Ok(()) diff --git a/src/ship/items/manager.rs b/src/ship/items/manager.rs index ff554ea..bfdcca6 100644 --- a/src/ship/items/manager.rs +++ b/src/ship/items/manager.rs @@ -917,7 +917,7 @@ impl ItemManager { entity_id: entity_id, item_id: item_id, item: ItemDetail::Weapon(weapon.clone()), - })); + }))?; entity_gateway.set_character_inventory(&character.id, &inventory.as_inventory_entity(&character.id)).await?; From 64a3a1ff97eaa9a2c250322c1876093b620487eb Mon Sep 17 00:00:00 2001 From: jake Date: Fri, 18 Jun 2021 10:32:44 -0600 Subject: [PATCH 03/25] lint src/ship/shop/armor.rs --- src/ship/ship.rs | 2 +- src/ship/shops/armor.rs | 20 +++++++++++--------- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/src/ship/ship.rs b/src/ship/ship.rs index b986648..7c7bc59 100644 --- a/src/ship/ship.rs +++ b/src/ship/ship.rs @@ -303,7 +303,7 @@ impl ItemShops { ItemShops { weapon_shop: weapon_shop, tool_shop: ToolShop::new(), - armor_shop: ArmorShop::new(), + armor_shop: ArmorShop::default(), } } } diff --git a/src/ship/shops/armor.rs b/src/ship/shops/armor.rs index 2a6314f..789db56 100644 --- a/src/ship/shops/armor.rs +++ b/src/ship/shops/armor.rs @@ -19,7 +19,7 @@ pub enum ArmorShopItem { Unit(UnitType), } -const ARMOR_MULTIPLIER: f32 = 0.799999952; +const ARMOR_MULTIPLIER: f32 = 0.799_999_95; const SHIELD_MULTIPLIER: f32 = 1.5; const UNIT_MULTIPLIER: f32 = 1000.0; @@ -27,7 +27,7 @@ impl ShopItem for ArmorShopItem { fn price(&self) -> usize { match self { ArmorShopItem::Frame(frame, slot) => { - ARMOR_STATS.get(&frame) + ARMOR_STATS.get(frame) .map(|frame_stats| { let mut price = (frame_stats.dfp + frame_stats.evp) as f32; price *= price; @@ -39,7 +39,7 @@ impl ShopItem for ArmorShopItem { .unwrap_or(0xFFFF) }, ArmorShopItem::Barrier(barrier) => { - SHIELD_STATS.get(&barrier) + SHIELD_STATS.get(barrier) .map(|barrier_stats| { let mut price = (barrier_stats.dfp + barrier_stats.evp) as f32; price *= price; @@ -50,7 +50,7 @@ impl ShopItem for ArmorShopItem { .unwrap_or(0xFFFF) }, ArmorShopItem::Unit(unit) => { - UNIT_STATS.get(&unit) + UNIT_STATS.get(unit) .map(|unit_stats| { (unit_stats.stars as f32 * UNIT_MULTIPLIER) as usize }) @@ -236,8 +236,8 @@ pub struct ArmorShop { rng: R, } -impl ArmorShop { - pub fn new() -> ArmorShop { +impl Default for ArmorShop { + fn default() -> ArmorShop { ArmorShop { frame: load_frame_table(), barrier: load_barrier_table(), @@ -245,7 +245,9 @@ impl ArmorShop { rng: R::from_entropy(), } } +} +impl ArmorShop { fn generate_frame_list(&mut self, character_level: usize) -> Vec { let tier = self.frame.frame.iter() .filter(|t| t.level <= character_level) @@ -297,7 +299,7 @@ impl ArmorShop { }) .collect() }) - .unwrap_or(Vec::new()) + .unwrap_or_else(Vec::new) } pub fn generate_armor_list(&mut self, character_level: usize) -> Vec { @@ -316,12 +318,12 @@ mod test { #[test] fn test_loading_tool_shop() { - ArmorShop::::new(); + ArmorShop::::default(); } #[test] fn test_generating_some_armor() { - let mut fs = ArmorShop::::new(); + let mut fs = ArmorShop::::default(); for i in 0..200 { fs.generate_armor_list(i); } From d42491095ef5abea95b838be0963d790b057c524 Mon Sep 17 00:00:00 2001 From: jake Date: Fri, 18 Jun 2021 11:12:09 -0600 Subject: [PATCH 04/25] lint src/ship/shop/tool.rs --- src/ship/ship.rs | 2 +- src/ship/shops/tool.rs | 21 ++++++++++++--------- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/src/ship/ship.rs b/src/ship/ship.rs index 7c7bc59..294658a 100644 --- a/src/ship/ship.rs +++ b/src/ship/ship.rs @@ -302,7 +302,7 @@ impl ItemShops { ItemShops { weapon_shop: weapon_shop, - tool_shop: ToolShop::new(), + tool_shop: ToolShop::default(), armor_shop: ArmorShop::default(), } } diff --git a/src/ship/shops/tool.rs b/src/ship/shops/tool.rs index 7eecd3d..66313b5 100644 --- a/src/ship/shops/tool.rs +++ b/src/ship/shops/tool.rs @@ -53,7 +53,7 @@ impl ShopItem for ToolShopItem { fn price(&self) -> usize { match self { ToolShopItem::Tool(tool) => { - TOOL_STATS.get(&tool) + TOOL_STATS.get(tool) .map(|tool_stats| { tool_stats.price }) @@ -146,7 +146,7 @@ fn load_tool_table() -> ToolTable { let mut table: HashMap> = toml::from_str(s.as_str()).unwrap(); - ToolTable(table.remove("tools".into()).unwrap()) + ToolTable(table.remove("tools").unwrap()) } fn load_tech_table() -> TechTable { @@ -156,7 +156,7 @@ fn load_tech_table() -> TechTable { f.read_to_string(&mut s).unwrap(); let mut table: HashMap> = toml::from_str(s.as_str()).unwrap(); - let techniques = table.remove("techniques".into()).unwrap(); + let techniques = table.remove("techniques").unwrap(); let techniques = techniques.into_iter() .map(|tech_tier| { TechTier { @@ -194,15 +194,18 @@ pub struct ToolShop { rng: R, } -impl ToolShop { - pub fn new() -> ToolShop { + +impl Default for ToolShop { + fn default() -> ToolShop { ToolShop { tools: load_tool_table(), techs: load_tech_table(), rng: R::from_entropy(), } } +} +impl ToolShop { fn generate_tech_types(&mut self, character_level: usize) -> Vec { let tier = self.techs.0.iter() .filter(|t| t.level <= character_level) @@ -233,7 +236,7 @@ impl ToolShop { let tech_choice = WeightedIndex::new(tier.iter().map(|(_, e)| e.probability)).unwrap(); while techs.len() < number_of_techs { let tech_detail = tier.get(tech_choice.sample(&mut self.rng)).unwrap(); - if techs.iter().find(|t| *t == tech_detail.0).is_none() { + if !techs.iter().any(|t| t == tech_detail.0) { techs.push(*tech_detail.0); } } @@ -269,7 +272,7 @@ impl ToolShop { pub fn generate_tool_list(&mut self, character_level: usize) -> Vec { let mut tools = Vec::new().into_iter() - .chain(self.tools.0.clone().into_iter().map(|t| ToolShopItem::Tool(t))) + .chain(self.tools.0.clone().into_iter().map(ToolShopItem::Tool)) .chain(self.generate_techs(character_level).into_iter()) .collect::>(); tools.sort(); @@ -284,12 +287,12 @@ mod test { #[test] fn test_loading_tool_shop() { - ToolShop::::new(); + ToolShop::::default(); } #[test] fn test_generating_some_tools() { - let mut ts = ToolShop::::new(); + let mut ts = ToolShop::::default(); for i in 0..200 { ts.generate_tool_list(i); } From 027de8a20d125c1a449fdf9c7f9c18fc01db1dce Mon Sep 17 00:00:00 2001 From: jake Date: Fri, 18 Jun 2021 11:27:40 -0600 Subject: [PATCH 05/25] lint src/ship/shop/weapon.rs --- src/ship/shops/weapon.rs | 109 ++++++++++++++++++--------------------- 1 file changed, 51 insertions(+), 58 deletions(-) diff --git a/src/ship/shops/weapon.rs b/src/ship/shops/weapon.rs index ea2642e..d978ad9 100644 --- a/src/ship/shops/weapon.rs +++ b/src/ship/shops/weapon.rs @@ -32,14 +32,10 @@ pub struct WeaponShopItem { impl PartialEq for WeaponShopItem { fn eq(&self, other: &Self) -> bool { - if self.weapon == other.weapon && - self.special == other.special && - self.grind == other.grind && - self.attributes == other.attributes { - true - } else { - false - } + self.weapon == other.weapon && + self.special == other.special && + self.grind == other.grind && + self.attributes == other.attributes } } @@ -247,7 +243,7 @@ fn load_weapon_table(difficulty: Difficulty, section_id: SectionID) -> WeaponTab let mut table: HashMap> = toml::from_str(s.as_str()).unwrap(); - WeaponTable(table.remove("weapon_tier".into()).unwrap()) + WeaponTable(table.remove("weapon_tier").unwrap()) } fn load_special_table() -> SpecialTable { @@ -258,7 +254,7 @@ fn load_special_table() -> SpecialTable { let mut table: HashMap> = toml::from_str(s.as_str()).unwrap(); - SpecialTable(table.remove("specials".into()).unwrap()) + SpecialTable(table.remove("specials").unwrap()) } fn load_grind_table() -> GrindTable { @@ -269,7 +265,7 @@ fn load_grind_table() -> GrindTable { let mut table: HashMap> = toml::from_str(s.as_str()).unwrap(); - GrindTable(table.remove("grind".into()).unwrap()) + GrindTable(table.remove("grind").unwrap()) } fn load_alt_grind_table() -> GrindTable { @@ -280,7 +276,7 @@ fn load_alt_grind_table() -> GrindTable { let mut table: HashMap> = toml::from_str(s.as_str()).unwrap(); - GrindTable(table.remove("grind".into()).unwrap()) + GrindTable(table.remove("grind").unwrap()) } fn load_attribute1_table() -> AttributeTable { @@ -291,7 +287,7 @@ fn load_attribute1_table() -> AttributeTable { let mut table: HashMap> = toml::from_str(s.as_str()).unwrap(); - AttributeTable(table.remove("attributes".into()).unwrap()) + AttributeTable(table.remove("attributes").unwrap()) } fn load_attribute2_table() -> AttributeTable { @@ -302,7 +298,7 @@ fn load_attribute2_table() -> AttributeTable { let mut table: HashMap> = toml::from_str(s.as_str()).unwrap(); - AttributeTable(table.remove("attributes".into()).unwrap()) + AttributeTable(table.remove("attributes").unwrap()) } fn number_of_weapons_to_generate(character_level: usize) -> usize { @@ -381,8 +377,7 @@ impl WeaponShop { fn generate_alt_grind(&mut self, level: usize) -> usize { let tier = self.alt_grind.0.iter() - .filter(|t| t.level <= level) - .nth(0) + .find(|t| t.level <= level) .unwrap(); self.rng.gen_range(tier.min, tier.max+1) @@ -443,48 +438,46 @@ impl WeaponShop { } fn is_alt_grind(&self, weapon: &WeaponType) -> bool { - match (self.section_id, weapon) { - (SectionID::Viridia, WeaponType::Shot) => true, - (SectionID::Viridia, WeaponType::Spread) => true, - (SectionID::Viridia, WeaponType::Cannon) => true, - (SectionID::Viridia, WeaponType::Launcher) => true, - (SectionID::Viridia, WeaponType::Arms) => true, - (SectionID::Greenill, WeaponType::Rifle) => true, - (SectionID::Greenill, WeaponType::Sniper) => true, - (SectionID::Greenill, WeaponType::Blaster) => true, - (SectionID::Greenill, WeaponType::Beam) => true, - (SectionID::Greenill, WeaponType::Laser) => true, - (SectionID::Skyly, WeaponType::Sword) => true, - (SectionID::Skyly, WeaponType::Gigush) => true, - (SectionID::Skyly, WeaponType::Breaker) => true, - (SectionID::Skyly, WeaponType::Claymore) => true, - (SectionID::Skyly, WeaponType::Calibur) => true, - (SectionID::Bluefull, WeaponType::Partisan) => true, - (SectionID::Bluefull, WeaponType::Halbert) => true, - (SectionID::Bluefull, WeaponType::Glaive) => true, - (SectionID::Bluefull, WeaponType::Berdys) => true, - (SectionID::Bluefull, WeaponType::Gungnir) => true, - (SectionID::Purplenum, WeaponType::Mechgun) => true, - (SectionID::Purplenum, WeaponType::Assault) => true, - (SectionID::Purplenum, WeaponType::Repeater) => true, - (SectionID::Purplenum, WeaponType::Gatling) => true, - (SectionID::Purplenum, WeaponType::Vulcan) => true, - (SectionID::Pinkal, WeaponType::Cane) => true, - (SectionID::Pinkal, WeaponType::Stick) => true, - (SectionID::Pinkal, WeaponType::Mace) => true, - (SectionID::Pinkal, WeaponType::Club) => true, - (SectionID::Oran, WeaponType::Dagger) => true, - (SectionID::Oran, WeaponType::Knife) => true, - (SectionID::Oran, WeaponType::Blade) => true, - (SectionID::Oran, WeaponType::Edge) => true, - (SectionID::Oran, WeaponType::Ripper) => true, - (SectionID::Whitill, WeaponType::Slicer) => true, - (SectionID::Whitill, WeaponType::Spinner) => true, - (SectionID::Whitill, WeaponType::Cutter) => true, - (SectionID::Whitill, WeaponType::Sawcer) => true, - (SectionID::Whitill, WeaponType::Diska) => true, - _ => false, - } + matches!((self.section_id, weapon), + (SectionID::Viridia, WeaponType::Shot) | + (SectionID::Viridia, WeaponType::Spread) | + (SectionID::Viridia, WeaponType::Cannon) | + (SectionID::Viridia, WeaponType::Launcher) | + (SectionID::Viridia, WeaponType::Arms) | + (SectionID::Greenill, WeaponType::Rifle) | + (SectionID::Greenill, WeaponType::Sniper) | + (SectionID::Greenill, WeaponType::Blaster) | + (SectionID::Greenill, WeaponType::Beam) | + (SectionID::Greenill, WeaponType::Laser) | + (SectionID::Skyly, WeaponType::Sword) | + (SectionID::Skyly, WeaponType::Gigush) | + (SectionID::Skyly, WeaponType::Breaker) | + (SectionID::Skyly, WeaponType::Claymore) | + (SectionID::Skyly, WeaponType::Calibur) | + (SectionID::Bluefull, WeaponType::Partisan) | + (SectionID::Bluefull, WeaponType::Halbert) | + (SectionID::Bluefull, WeaponType::Glaive) | + (SectionID::Bluefull, WeaponType::Berdys) | + (SectionID::Bluefull, WeaponType::Gungnir) | + (SectionID::Purplenum, WeaponType::Mechgun) | + (SectionID::Purplenum, WeaponType::Assault) | + (SectionID::Purplenum, WeaponType::Repeater) | + (SectionID::Purplenum, WeaponType::Gatling) | + (SectionID::Purplenum, WeaponType::Vulcan) | + (SectionID::Pinkal, WeaponType::Cane) | + (SectionID::Pinkal, WeaponType::Stick) | + (SectionID::Pinkal, WeaponType::Mace) | + (SectionID::Pinkal, WeaponType::Club) | + (SectionID::Oran, WeaponType::Dagger) | + (SectionID::Oran, WeaponType::Knife) | + (SectionID::Oran, WeaponType::Blade) | + (SectionID::Oran, WeaponType::Edge) | + (SectionID::Oran, WeaponType::Ripper) | + (SectionID::Whitill, WeaponType::Slicer) | + (SectionID::Whitill, WeaponType::Spinner) | + (SectionID::Whitill, WeaponType::Cutter) | + (SectionID::Whitill, WeaponType::Sawcer) | + (SectionID::Whitill, WeaponType::Diska)) } fn generate_weapon(&mut self, level: usize) -> WeaponShopItem { From c3c0f031ed485ba10a70e8ebe2b6517df92709f6 Mon Sep 17 00:00:00 2001 From: jake Date: Fri, 18 Jun 2021 11:38:05 -0600 Subject: [PATCH 06/25] lint src/ship/quests.rs --- src/ship/quests.rs | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/ship/quests.rs b/src/ship/quests.rs index 5853cec..0b6be3d 100644 --- a/src/ship/quests.rs +++ b/src/ship/quests.rs @@ -73,18 +73,18 @@ fn read_dat_section_header(cursor: &mut T, episode: &Episode, ma match header { DAT_OBJECT_HEADER_ID => { let mut obj_data = vec![0u8; length as usize]; - cursor.read(&mut obj_data)?; + cursor.read_exact(&mut obj_data)?; let mut obj_cursor = Cursor::new(obj_data); - let objects = objects_from_stream(&mut obj_cursor, episode, &map_area); + let objects = objects_from_stream(&mut obj_cursor, episode, map_area); Ok(DatBlock::Object(objects)) }, DAT_ENEMY_HEADER_ID => { let mut enemy_data = vec![0u8; length as usize]; - cursor.read(&mut enemy_data)?; + cursor.read_exact(&mut enemy_data)?; let mut enemy_cursor = Cursor::new(enemy_data); - let enemies = enemy_data_from_stream(&mut enemy_cursor, &map_area, episode); + let enemies = enemy_data_from_stream(&mut enemy_cursor, map_area, episode); Ok(DatBlock::Enemy(enemies)) }, @@ -100,7 +100,7 @@ fn quest_episode(bin: &[u8]) -> Option { for bytes in bin.windows(3) { // set_episode if bytes[0] == 0xF8 && bytes[1] == 0xBC { - return Some(Episode::from_quest(bytes[2]).ok()?) + return Episode::from_quest(bytes[2]).ok() } } None @@ -121,6 +121,7 @@ fn map_area_mappings(bin: &[u8]) -> MapAreaLookup { map_areas.build() } +#[allow(clippy::type_complexity)] fn parse_dat(dat: &[u8], episode: &Episode, map_areas: &MapAreaLookup) -> Result<(Vec>, Vec>), ParseDatError> { let mut cursor = Cursor::new(dat); @@ -185,9 +186,9 @@ impl Quest { let (enemies, objects) = parse_dat(&dat, &episode, &map_areas)?; let mut prs_bin = LegacyPrsEncoder::new(Vec::new()); - prs_bin.write(&bin)?; + prs_bin.write_all(&bin)?; let mut prs_dat = LegacyPrsEncoder::new(Vec::new()); - prs_dat.write(&dat)?; + prs_dat.write_all(&dat)?; Ok(Quest { name: name, From e89821990fc1494d8bd4fa3018f9a581d24327ae Mon Sep 17 00:00:00 2001 From: jake Date: Fri, 18 Jun 2021 11:53:23 -0600 Subject: [PATCH 07/25] lint src/ship/packet/builder/ship.rs --- src/ship/packet/builder/ship.rs | 2 +- src/ship/packet/handler/ship.rs | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/ship/packet/builder/ship.rs b/src/ship/packet/builder/ship.rs index c80d562..8b3e40f 100644 --- a/src/ship/packet/builder/ship.rs +++ b/src/ship/packet/builder/ship.rs @@ -13,7 +13,7 @@ use crate::common::interserver::Ship; use libpso::packet::ship::BLOCK_MENU_ID; use crate::login::character::SHIP_MENU_ID; -pub fn ship_list(ships: &Vec) -> ShipList { +pub fn ship_list(ships: &[Ship]) -> ShipList { let ships = ships.iter() .enumerate() .map(|(i, ship)| { diff --git a/src/ship/packet/handler/ship.rs b/src/ship/packet/handler/ship.rs index 9916901..0a0c0cd 100644 --- a/src/ship/packet/handler/ship.rs +++ b/src/ship/packet/handler/ship.rs @@ -2,10 +2,10 @@ use libpso::packet::ship::*; use libpso::packet::login::RedirectClient; use crate::common::serverstate::ClientId; use crate::common::interserver::Ship; -use crate::ship::ship::{SendShipPacket, ShipError, Clients}; +use crate::ship::ship::{SendShipPacket, ShipError}; use crate::ship::packet::builder; -pub fn ship_list(id: ClientId, ship_list: &Vec) +pub fn ship_list(id: ClientId, ship_list: &[Ship]) -> Box + Send> { Box::new(vec![(id, SendShipPacket::ShipList(builder::ship::ship_list(ship_list)))].into_iter()) } @@ -15,7 +15,7 @@ pub fn block_list(id: ClientId, shipname: &str, num_blocks: usize) Box::new(vec![(id, SendShipPacket::ShipBlockList(ShipBlockList::new(shipname, num_blocks)))].into_iter()) } -pub fn selected_ship(id: ClientId, menuselect: &MenuSelect, ship_list: &Vec) +pub fn selected_ship(id: ClientId, menuselect: &MenuSelect, ship_list: &[Ship]) -> Result + Send>, ShipError> { let ship = ship_list.get(menuselect.item as usize).ok_or(ShipError::InvalidShip(menuselect.item as usize))?; let ip = u32::from_ne_bytes(ship.ip.octets()); From 3cf834ed5503e9534da236eb6efdf3924b50b2b0 Mon Sep 17 00:00:00 2001 From: jake Date: Fri, 18 Jun 2021 12:18:29 -0600 Subject: [PATCH 08/25] lint src/ship/packet/handler/* --- src/ship/packet/handler/auth.rs | 7 ++++--- src/ship/packet/handler/direct_message.rs | 22 ++++++++-------------- src/ship/packet/handler/lobby.rs | 9 +++++---- src/ship/packet/handler/message.rs | 2 +- src/ship/packet/handler/quest.rs | 14 +++++++------- src/ship/packet/handler/room.rs | 14 +++++++------- 6 files changed, 32 insertions(+), 36 deletions(-) diff --git a/src/ship/packet/handler/auth.rs b/src/ship/packet/handler/auth.rs index 23f261d..0bf5ebe 100644 --- a/src/ship/packet/handler/auth.rs +++ b/src/ship/packet/handler/auth.rs @@ -7,13 +7,14 @@ use crate::entity::gateway::EntityGateway; use crate::ship::items::ItemManager; use crate::common::interserver::ShipMessage; +#[allow(clippy::too_many_arguments)] pub async fn validate_login(id: ClientId, pkt: &Login, entity_gateway: &mut EG, clients: &mut Clients, item_manager: &mut ItemManager, shipgate_sender: &Option>, - ship_name: &String, + ship_name: &str, num_blocks: usize) -> Result, anyhow::Error> { Ok(match get_login_status(entity_gateway, pkt).await { @@ -32,10 +33,10 @@ pub async fn validate_login(id: ClientId, item_manager.load_character(entity_gateway, &character).await?; if let Some(shipgate_sender) = shipgate_sender.as_ref() { - shipgate_sender(ShipMessage::AddUser(user.id.clone())); + shipgate_sender(ShipMessage::AddUser(user.id)); } clients.insert(id, ClientState::new(user, settings, character, pkt.session)); - vec![SendShipPacket::LoginResponse(response), SendShipPacket::ShipBlockList(ShipBlockList::new(&&ship_name, num_blocks))] + vec![SendShipPacket::LoginResponse(response), SendShipPacket::ShipBlockList(ShipBlockList::new(ship_name, num_blocks))] }, Err(err) => { vec![SendShipPacket::LoginResponse(LoginResponse::by_status(err, Session::new()))] diff --git a/src/ship/packet/handler/direct_message.rs b/src/ship/packet/handler/direct_message.rs index 44a8fbf..f66fca6 100644 --- a/src/ship/packet/handler/direct_message.rs +++ b/src/ship/packet/handler/direct_message.rs @@ -65,7 +65,7 @@ pub fn guildcard_send(id: ClientId, class: client.character.char_class.into(), }), }; - send_to_client(id, target as u8, msg, &client_location) + send_to_client(id, target as u8, msg, client_location) } pub async fn request_item(id: ClientId, @@ -110,7 +110,7 @@ where }; let client = clients.get_mut(&area_client.client).ok_or(ShipError::ClientNotFound(area_client.client))?; let floor_item = item_manager.enemy_drop_item_on_local_floor(entity_gateway, &client.character, item_drop).await?; - let item_drop_msg = builder::message::item_drop(request_item.client, request_item.target, &floor_item)?; + let item_drop_msg = builder::message::item_drop(request_item.client, request_item.target, floor_item)?; item_drop_packets.push((area_client.client, SendShipPacket::Message(Message::new(GameMessage::ItemDrop(item_drop_msg))))); } @@ -135,7 +135,7 @@ where // TODO: should not need to fetch the item here to construct this packet let (item, floor_type) = item_manager.get_floor_item_by_id(&client.character, ClientItemId(pickup_item.item_id))?; - let remove_item = builder::message::remove_item_from_floor(area_client, &item)?; + let remove_item = builder::message::remove_item_from_floor(area_client, item)?; let create_item = match item { FloorItem::Individual(individual_floor_item) => Some(builder::message::create_item(area_client, item.item_id(), &individual_floor_item.item)?), FloorItem::Stacked(stacked_floor_item) => Some(builder::message::create_item(area_client, item.item_id(), &item::ItemDetail::Tool(stacked_floor_item.tool))?), @@ -216,7 +216,7 @@ EG: EntityGateway }; let client = clients.get_mut(&area_client.client).ok_or(ShipError::ClientNotFound(area_client.client))?; let floor_item = item_manager.enemy_drop_item_on_local_floor(entity_gateway, &client.character, item_drop).await?; // TODO: unwrap - let item_drop_msg = builder::message::item_drop(box_drop_request.client, box_drop_request.target, &floor_item)?; + let item_drop_msg = builder::message::item_drop(box_drop_request.client, box_drop_request.target, floor_item)?; item_drop_packets.push((area_client.client, SendShipPacket::Message(Message::new(GameMessage::ItemDrop(item_drop_msg))))) } @@ -233,7 +233,7 @@ pub async fn send_bank_list(id: ClientId, let client = clients.get(&id).ok_or(ShipError::ClientNotFound(id))?; let bank_items = item_manager.get_character_bank(&client.character)?; - let bank_items_pkt = builder::message::bank_item_list(&bank_items, client.character.bank_meseta); + let bank_items_pkt = builder::message::bank_item_list(bank_items, client.character.bank_meseta); Ok(Box::new(vec![(id, SendShipPacket::BankItemList(bank_items_pkt))].into_iter())) } @@ -277,7 +277,7 @@ where } else { let item_added_to_inventory = item_manager.player_withdraws_item(entity_gateway, &client.character, ClientItemId(bank_interaction.item_id), bank_interaction.item_amount as usize).await?; - let item_created = builder::message::create_withdrawn_inventory_item(area_client, &item_added_to_inventory)?; + let item_created = builder::message::create_withdrawn_inventory_item(area_client, item_added_to_inventory)?; vec![SendShipPacket::Message(Message::new(GameMessage::CreateItem(item_created)))] } }, @@ -357,18 +357,12 @@ where }, SHOP_OPTION_TOOL => { let item = client.tool_shop.get(buy_item.shop_index as usize).ok_or(ShipError::ShopError)?; - let remove = match item { - ToolShopItem::Tech(_) => true, - _ => false, - }; + let remove = matches!(item, ToolShopItem::Tech(_)); (item, remove) }, SHOP_OPTION_ARMOR => { let item = client.armor_shop.get(buy_item.shop_index as usize).ok_or(ShipError::ShopError)?; - let remove = match item { - ArmorShopItem::Unit(_) => true, - _ => false, - }; + let remove = matches!(item, ArmorShopItem::Unit(_)); (item, remove) }, _ => { diff --git a/src/ship/packet/handler/lobby.rs b/src/ship/packet/handler/lobby.rs index 87d9131..dc84a21 100644 --- a/src/ship/packet/handler/lobby.rs +++ b/src/ship/packet/handler/lobby.rs @@ -28,8 +28,8 @@ pub fn block_selected(id: ClientId, .character(&client.character) .stats(&stats) .level(level) - .inventory(&inventory) - .bank(&bank) + .inventory(inventory) + .bank(bank) .key_config(&client.settings.settings.key_config) .joystick_config(&client.settings.settings.joystick_config) .symbol_chat(&client.settings.settings.symbol_chats) @@ -63,6 +63,7 @@ pub fn send_player_to_lobby(id: ClientId, .map(|c| (c.client, SendShipPacket::AddToLobby(addto.clone())))).collect()) } +#[allow(clippy::too_many_arguments)] pub async fn change_lobby(id: ClientId, requested_lobby: u32, client_location: &mut ClientLocation, @@ -81,7 +82,7 @@ pub async fn change_lobby(id: ClientId, } }, RoomLobby::Room(old_room) => { - if client_location.get_client_neighbors(id).map_err(|err| -> ClientLocationError {err.into()})?.len() == 0 { + if client_location.get_client_neighbors(id)?.is_empty() { ship_rooms[old_room.0] = None; } item_manager.remove_character_from_room(&client.character); @@ -90,7 +91,7 @@ pub async fn change_lobby(id: ClientId, let leave_lobby = packet::builder::lobby::remove_from_lobby(id, client_location)?; let old_neighbors = client_location.get_client_neighbors(id).unwrap(); let mut lobby = LobbyId(requested_lobby as usize); - if let Err(_) = client_location.add_client_to_lobby(id, lobby) { + if client_location.add_client_to_lobby(id, lobby).is_err() { match prev_area { RoomLobby::Lobby(_lobby) => { let dialog = SmallDialog::new(String::from("Lobby is full.")); diff --git a/src/ship/packet/handler/message.rs b/src/ship/packet/handler/message.rs index 0ce969a..6bf2106 100644 --- a/src/ship/packet/handler/message.rs +++ b/src/ship/packet/handler/message.rs @@ -26,7 +26,7 @@ pub async fn request_exp(id: ClientId, .ok_or_else(|| ShipError::InvalidRoom(room_id.0 as u32))?; let monster = room.maps.enemy_by_id(request_exp.enemy_id as usize)?; - let monster_stats = room.monster_stats.get(&monster.monster).ok_or(ShipError::UnknownMonster(monster.monster.clone()))?; + let monster_stats = room.monster_stats.get(&monster.monster).ok_or(ShipError::UnknownMonster(monster.monster))?; let exp_gain = if request_exp.last_hitter == 1 { monster_stats.exp diff --git a/src/ship/packet/handler/quest.rs b/src/ship/packet/handler/quest.rs index 785442a..41412ac 100644 --- a/src/ship/packet/handler/quest.rs +++ b/src/ship/packet/handler/quest.rs @@ -17,8 +17,8 @@ fn parse_filename(filename_bytes: &[u8; 16]) -> Result<(u16, u16, QuestFileType) let filename = array_to_utf8(*filename_bytes).map_err(|_| ShipError::InvalidQuestFilename("NOT UTF8".to_string()))?; let (filename, suffix) = { let mut s = filename.splitn(2, '.'); - (s.next().ok_or(ShipError::InvalidQuestFilename(filename.to_owned()))?, - s.next().ok_or(ShipError::InvalidQuestFilename(filename.to_owned()))?) + (s.next().ok_or_else(|| ShipError::InvalidQuestFilename(filename.to_owned()))?, + s.next().ok_or_else(|| ShipError::InvalidQuestFilename(filename.to_owned()))?) }; let datatype = match suffix { @@ -29,8 +29,8 @@ fn parse_filename(filename_bytes: &[u8; 16]) -> Result<(u16, u16, QuestFileType) let (category, quest) = { let mut s = filename.splitn(2, '-'); - (s.next().and_then(|k| k.parse().ok()).ok_or(ShipError::InvalidQuestFilename(filename.to_owned()))?, - s.next().and_then(|k| k.parse().ok()).ok_or(ShipError::InvalidQuestFilename(filename.to_owned()))?) + (s.next().and_then(|k| k.parse().ok()).ok_or_else(|| ShipError::InvalidQuestFilename(filename.to_owned()))?, + s.next().and_then(|k| k.parse().ok()).ok_or_else(|| ShipError::InvalidQuestFilename(filename.to_owned()))?) }; Ok((category, quest, datatype)) @@ -63,7 +63,7 @@ pub fn quest_detail(id: ClientId, questdetailrequest: &QuestDetailRequest, quest q.id == questdetailrequest.quest as u16 }).ok_or(ShipError::InvalidQuest(questdetailrequest.quest as u32))?; - let qd = quest::quest_detail(&quest); + let qd = quest::quest_detail(quest); Ok(Box::new(vec![(id, SendShipPacket::QuestDetail(qd))].into_iter())) } @@ -91,9 +91,9 @@ pub fn load_quest(id: ClientId, questmenuselect: &QuestMenuSelect, quests: &Ques let area_clients = client_location.get_all_clients_by_client(id).map_err(|err| -> ClientLocationError { err.into() })?; area_clients.iter().for_each(|c| { - clients.get_mut(&c.client).map(|client| { + if let Some(client) = clients.get_mut(&c.client) { client.done_loading_quest = false; - }); + } }); Ok(Box::new(area_clients.into_iter().map(move |c| { vec![(c.client, SendShipPacket::QuestHeader(bin.clone())), (c.client, SendShipPacket::QuestHeader(dat.clone()))] diff --git a/src/ship/packet/handler/room.rs b/src/ship/packet/handler/room.rs index b02d28b..c3be9dc 100644 --- a/src/ship/packet/handler/room.rs +++ b/src/ship/packet/handler/room.rs @@ -66,8 +66,8 @@ pub fn join_room(id: ClientId, let original_area = client_location.get_area(id).unwrap(); let original_neighbors = client_location.get_client_neighbors(id).unwrap(); let room = rooms.get(pkt.item as usize) - .ok_or_else(|| ShipError::InvalidRoom(pkt.item))?.as_ref() - .ok_or_else(|| ShipError::InvalidRoom(pkt.item))?; + .ok_or(ShipError::InvalidRoom(pkt.item))?.as_ref() + .ok_or(ShipError::InvalidRoom(pkt.item))?; if room.bursting { return Ok(Box::new(vec![(id, SendShipPacket::SmallDialog(SmallDialog::new("player is bursting\nplease wait".into())))].into_iter())) } @@ -81,8 +81,8 @@ pub fn join_room(id: ClientId, item_manager.add_character_to_room(room_id, &client.character, area_client); let leader = client_location.get_room_leader(room_id).map_err(|err| -> ClientLocationError { err.into() })?; - let join_room = builder::room::join_room(id, clients, client_location, room_id, &room)?; - let add_to = builder::room::add_to_room(id, &client, &area_client, &leader, item_manager, level_table, room_id)?; + let join_room = builder::room::join_room(id, clients, client_location, room_id, room)?; + let add_to = builder::room::add_to_room(id, client, &area_client, &leader, item_manager, level_table, room_id)?; let room = rooms.get_mut(room_id.0).unwrap().as_mut().unwrap(); room.bursting = true; @@ -90,7 +90,7 @@ pub fn join_room(id: ClientId, let mut result: Box + Send> = Box::new( vec![(id, SendShipPacket::JoinRoom(join_room))] .into_iter() - .chain(original_room_clients.clone().into_iter() + .chain(original_room_clients.into_iter() .map(move |c| (c.client, SendShipPacket::AddToRoom(add_to.clone()))) )); @@ -109,9 +109,9 @@ pub fn done_bursting(id: ClientId, -> Box + Send> { let area = client_location.get_area(id).unwrap(); if let RoomLobby::Room(room_id) = area { - rooms.get_mut(room_id.0).unwrap().as_mut().map(|room| { + if let Some(room) = rooms.get_mut(room_id.0).unwrap().as_mut() { room.bursting = false; - }); + } } let area_client = client_location.get_local_client(id).unwrap(); // TODO: unwrap Box::new(client_location.get_client_neighbors(id).unwrap().into_iter() // TODO: unwrap From 60bcfd78ecc765a81712fb083d04f3899f64db55 Mon Sep 17 00:00:00 2001 From: jake Date: Fri, 18 Jun 2021 12:38:33 -0600 Subject: [PATCH 09/25] lint src/ship/packet/builder/* --- src/ship/packet/builder/lobby.rs | 4 ++-- src/ship/packet/builder/message.rs | 4 ++-- src/ship/packet/builder/quest.rs | 2 +- src/ship/packet/builder/room.rs | 4 ++-- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/ship/packet/builder/lobby.rs b/src/ship/packet/builder/lobby.rs index b0a0d8e..56213dd 100644 --- a/src/ship/packet/builder/lobby.rs +++ b/src/ship/packet/builder/lobby.rs @@ -18,7 +18,7 @@ pub fn join_lobby(id: ClientId, let playerinfo = lobby_clients.iter() .map(|area_client| { let client = clients.get(&area_client.client).ok_or(ShipError::ClientNotFound(area_client.client)).unwrap(); - player_info(0x100, &client, area_client, item_manager, level_table) + player_info(0x100, client, area_client, item_manager, level_table) }); let client = clients.get(&id).ok_or(ShipError::ClientNotFound(id)).unwrap(); @@ -55,7 +55,7 @@ pub fn add_to_lobby(id: ClientId, block: client.block as u16, event: 0, padding: 0, - playerinfo: player_info(0x100, &client, &area_client, item_manager, level_table), + playerinfo: player_info(0x100, client, &area_client, item_manager, level_table), }) } diff --git a/src/ship/packet/builder/message.rs b/src/ship/packet/builder/message.rs index 91d4149..dfe1ac5 100644 --- a/src/ship/packet/builder/message.rs +++ b/src/ship/packet/builder/message.rs @@ -142,8 +142,8 @@ pub fn player_no_longer_has_item(area_client: AreaClient, item_id: ClientItemId, } } -pub fn shop_list(shop_type: u8, items: &Vec) -> ShopList { - let items = items.into_iter() +pub fn shop_list(shop_type: u8, items: &[I]) -> ShopList { + let items = items.iter() .enumerate() .map(|(i, item)| { ShopListItem { diff --git a/src/ship/packet/builder/quest.rs b/src/ship/packet/builder/quest.rs index 089fe56..8078517 100644 --- a/src/ship/packet/builder/quest.rs +++ b/src/ship/packet/builder/quest.rs @@ -22,7 +22,7 @@ pub fn quest_category_list(quests: &QuestList) -> QuestCategoryList { } } -pub fn quest_list(category_id: u32, quests: &Vec) -> QuestOptionList { +pub fn quest_list(category_id: u32, quests: &[Quest]) -> QuestOptionList { let quest_entries = quests.iter() .map(|quest| { QuestEntry { diff --git a/src/ship/packet/builder/room.rs b/src/ship/packet/builder/room.rs index 7dda664..2eb8fc7 100644 --- a/src/ship/packet/builder/room.rs +++ b/src/ship/packet/builder/room.rs @@ -20,7 +20,7 @@ pub fn join_room(id: ClientId, let header_client = clients.get(&c.client).ok_or(ShipError::ClientNotFound(id))?; let header_area_client = client_location.get_local_client(id).map_err(|err| -> ClientLocationError { err.into() })?; acc.map(|mut a| { - a[i] = player_header(0x10000, &header_client, &header_area_client); + a[i] = player_header(0x10000, header_client, &header_area_client); a }) })?; @@ -67,7 +67,7 @@ pub fn add_to_room(_id: ClientId, block: 0, event: 0, padding: 0, - playerinfo: player_info(0x10000, client, &area_client, item_manager, level_table), + playerinfo: player_info(0x10000, client, area_client, item_manager, level_table), }) } From f6bf34e193e701fcb6b964c914fec7fd714ba049 Mon Sep 17 00:00:00 2001 From: jake Date: Fri, 18 Jun 2021 12:45:00 -0600 Subject: [PATCH 10/25] lint src/ship/drops/* --- src/ship/drops/box_drop_table.rs | 2 +- src/ship/drops/generic_weapon.rs | 18 ++++++------------ src/ship/drops/mod.rs | 2 +- src/ship/drops/rare_drop_table.rs | 21 ++++++++++----------- 4 files changed, 18 insertions(+), 25 deletions(-) diff --git a/src/ship/drops/box_drop_table.rs b/src/ship/drops/box_drop_table.rs index 94abd84..f507d27 100644 --- a/src/ship/drops/box_drop_table.rs +++ b/src/ship/drops/box_drop_table.rs @@ -170,7 +170,7 @@ impl BoxDropTable { else { None } - }).nth(0) + }).next() } fn random_box_drop(&self, map_area: &MapArea, rng: &mut R) -> Option { diff --git a/src/ship/drops/generic_weapon.rs b/src/ship/drops/generic_weapon.rs index 71e578c..28a5007 100644 --- a/src/ship/drops/generic_weapon.rs +++ b/src/ship/drops/generic_weapon.rs @@ -266,30 +266,24 @@ impl AttributeTable { fn attributes(&self, percent_pattern: &AttributePercentPattern, attribute_rate: &AttributeRate, rng: &mut R) -> [Option; 3] { let mut percents = vec![ percent_pattern.attribute1.and_then(|pattern_type| { - self.generate_attribute(&pattern_type, &attribute_rate, rng) + self.generate_attribute(&pattern_type, attribute_rate, rng) }), percent_pattern.attribute2.and_then(|pattern_type| { - self.generate_attribute(&pattern_type, &attribute_rate, rng) + self.generate_attribute(&pattern_type, attribute_rate, rng) }), percent_pattern.attribute3.and_then(|pattern_type| { - self.generate_attribute(&pattern_type, &attribute_rate, rng) + self.generate_attribute(&pattern_type, attribute_rate, rng) }), ]; percents.sort_by_key(|p| { - match p { - Some(a) => Some(a.attr), - None => None, - } + p.as_ref().map(|a| a.attr) }); percents.dedup_by_key(|p| { - match p { - Some(a) => Some(a.attr), - None => None, - } + p.as_ref().map(|a| a.attr) }); percents.iter() .fold(([None; 3], 0), |(mut acc, index), p| { // one day I'll be able to collece into an array - if let Some(_) = p { + if p.is_some() { acc[index] = *p; (acc, index + 1) } diff --git a/src/ship/drops/mod.rs b/src/ship/drops/mod.rs index edfa8db..8de0408 100644 --- a/src/ship/drops/mod.rs +++ b/src/ship/drops/mod.rs @@ -152,7 +152,7 @@ impl DropTable { return None; } - if let Some(item) = self.rare_table.get_drop(map_area, &monster, &mut self.rng) { + if let Some(item) = self.rare_table.get_drop(map_area, monster, &mut self.rng) { return Some(item); } diff --git a/src/ship/drops/rare_drop_table.rs b/src/ship/drops/rare_drop_table.rs index df9ec8d..0ca356c 100644 --- a/src/ship/drops/rare_drop_table.rs +++ b/src/ship/drops/rare_drop_table.rs @@ -30,19 +30,18 @@ pub enum RareDropItem { impl RareDropItem { pub fn from_string(name: String) -> RareDropItem { let parse_funcs: [Box Option>; 6] = [ - Box::new(|i| Some(RareDropItem::Weapon(str::parse::(&i).ok()?))), - Box::new(|i| Some(RareDropItem::Armor(str::parse::(&i).ok()?))), - Box::new(|i| Some(RareDropItem::Shield(str::parse::(&i).ok()?))), - Box::new(|i| Some(RareDropItem::Unit(str::parse::(&i).ok()?))), - Box::new(|i| Some(RareDropItem::Tool(str::parse::(&i).ok()?))), - Box::new(|i| Some(RareDropItem::Mag(str::parse::(&i).ok()?))), + Box::new(|i| Some(RareDropItem::Weapon(str::parse::(i).ok()?))), + Box::new(|i| Some(RareDropItem::Armor(str::parse::(i).ok()?))), + Box::new(|i| Some(RareDropItem::Shield(str::parse::(i).ok()?))), + Box::new(|i| Some(RareDropItem::Unit(str::parse::(i).ok()?))), + Box::new(|i| Some(RareDropItem::Tool(str::parse::(i).ok()?))), + Box::new(|i| Some(RareDropItem::Mag(str::parse::(i).ok()?))), ]; for parse in parse_funcs.iter() { - match parse(&name) { - Some(k) => return k, - None => {}, - } + if let Some (k) = parse(&name) { + return k + } } panic!() @@ -151,7 +150,7 @@ impl RareDropTable { else { None } - }).nth(0) + }).next() }) } } From 03906a7f0a30f69dcd8e58e10b06f2aa944b4ca0 Mon Sep 17 00:00:00 2001 From: jake Date: Fri, 18 Jun 2021 13:00:04 -0600 Subject: [PATCH 11/25] lint src/ship/map/* --- src/ship/map/area.rs | 6 ++++-- src/ship/map/enemy.rs | 2 +- src/ship/map/maps.rs | 9 ++++----- src/ship/map/object.rs | 2 +- src/ship/map/variant.rs | 12 ++++++------ src/ship/quests.rs | 2 +- 6 files changed, 17 insertions(+), 16 deletions(-) diff --git a/src/ship/map/area.rs b/src/ship/map/area.rs index 9621109..a26aa19 100644 --- a/src/ship/map/area.rs +++ b/src/ship/map/area.rs @@ -291,13 +291,15 @@ pub struct MapAreaLookupBuilder { map_areas: HashMap, } -impl MapAreaLookupBuilder { - pub fn new() -> MapAreaLookupBuilder { +impl Default for MapAreaLookupBuilder { + fn default() -> MapAreaLookupBuilder { MapAreaLookupBuilder { map_areas: HashMap::new() } } +} +impl MapAreaLookupBuilder { pub fn add(mut self, value: u16, map_area: MapArea) -> MapAreaLookupBuilder { self.map_areas.insert(value, map_area); self diff --git a/src/ship/map/enemy.rs b/src/ship/map/enemy.rs index 8eab744..a9601d2 100644 --- a/src/ship/map/enemy.rs +++ b/src/ship/map/enemy.rs @@ -253,7 +253,7 @@ impl MapEnemy { Ok(MapEnemy { monster: monster, - map_area: map_area.clone(), + map_area: *map_area, hp: 0, dropped_item: false, gave_exp: false, diff --git a/src/ship/map/maps.rs b/src/ship/map/maps.rs index 3f7f515..15e790c 100644 --- a/src/ship/map/maps.rs +++ b/src/ship/map/maps.rs @@ -17,14 +17,14 @@ pub fn objects_from_stream(cursor: &mut impl Read, episode: &Episode, map_area: let mut object_data = Vec::new(); while let Ok(raw_object) = RawMapObject::from_byte_stream(cursor) { - let object = MapObject::from_raw(raw_object.clone(), *episode, map_area); + let object = MapObject::from_raw(raw_object, *episode, map_area); object_data.push(object.ok()); } object_data } fn objects_from_map_data(path: PathBuf, episode: &Episode, map_area: &MapArea) -> Vec> { - let mut cursor = File::open(path.clone()).unwrap(); + let mut cursor = File::open(path).unwrap(); objects_from_stream(&mut cursor, episode, map_area) } @@ -32,8 +32,7 @@ fn parse_enemy(episode: &Episode, map_area: &MapArea, raw_enemy: RawMapEnemy) -> let enemy = MapEnemy::from_raw(raw_enemy, episode, map_area); enemy .map_or(vec![None], |monster| { - let mut monsters = Vec::new(); - monsters.push(Some(monster)); + let mut monsters = vec![Some(monster)]; match monster.monster { MonsterType::Monest => { @@ -275,7 +274,7 @@ impl Maps { let maps = Maps { enemy_data: map_variants.iter().fold(Vec::new(), |mut enemy_data, map_variant| { - enemy_data.append(&mut enemy_data_from_map_data(&map_variant, &room_mode.episode())); + enemy_data.append(&mut enemy_data_from_map_data(map_variant, &room_mode.episode())); enemy_data }), object_data: map_variants.iter().map(|map_variant| { diff --git a/src/ship/map/object.rs b/src/ship/map/object.rs index dde1e7e..e431c88 100644 --- a/src/ship/map/object.rs +++ b/src/ship/map/object.rs @@ -160,7 +160,7 @@ impl MapObject { Ok(MapObject { object: object, - map: map_area.clone(), + map: *map_area, dropped_item: false, }) } diff --git a/src/ship/map/variant.rs b/src/ship/map/variant.rs index a969960..7e85bee 100644 --- a/src/ship/map/variant.rs +++ b/src/ship/map/variant.rs @@ -198,9 +198,9 @@ impl MapVariant { MapArea::Forest1 => format!("data/maps/map_forest01_0{}_offe.dat", self.minor*2), MapArea::Forest2 => { match self.minor { - 0 => format!("data/maps/map_forest02_00_offe.dat"), - 1 => format!("data/maps/map_forest02_03_offe.dat"), - 2 => format!("data/maps/map_forest02_04_offe.dat"), + 0 => "data/maps/map_forest02_00_offe.dat".into(), + 1 => "data/maps/map_forest02_03_offe.dat".into(), + 2 => "data/maps/map_forest02_04_offe.dat".into(), _ => unreachable!() }}, MapArea::Caves1 => format!("data/maps/map_cave01_0{}_0{}_offe.dat", self.major, self.minor), @@ -302,9 +302,9 @@ impl MapVariant { MapArea::Forest1 => format!("data/maps/map_forest01_0{}o.dat", self.minor*2), MapArea::Forest2 => { match self.minor { - 0 => format!("data/maps/map_forest02_00o.dat"), - 1 => format!("data/maps/map_forest02_03o.dat"), - 2 => format!("data/maps/map_forest02_04o.dat"), + 0 => "data/maps/map_forest02_00o.dat".into(), + 1 => "data/maps/map_forest02_03o.dat".into(), + 2 => "data/maps/map_forest02_04o.dat".into(), _ => unreachable!() }}, MapArea::Caves1 => format!("data/maps/map_cave01_0{}_0{}o.dat", self.major, self.minor), diff --git a/src/ship/quests.rs b/src/ship/quests.rs index 0b6be3d..7b1316f 100644 --- a/src/ship/quests.rs +++ b/src/ship/quests.rs @@ -107,7 +107,7 @@ fn quest_episode(bin: &[u8]) -> Option { } fn map_area_mappings(bin: &[u8]) -> MapAreaLookup { - let mut map_areas = MapAreaLookupBuilder::new(); + let mut map_areas = MapAreaLookupBuilder::default(); for bytes in bin.windows(4) { // BB_Map_Designate if bytes[0] == 0xF9 && bytes[1] == 0x51 { From 3457996afde8581c71347dcd8da23d8b988db93d Mon Sep 17 00:00:00 2001 From: jake Date: Fri, 18 Jun 2021 14:08:23 -0600 Subject: [PATCH 12/25] lint src/ship/items/* --- src/ship/item_stats.rs | 4 +-- src/ship/items/bank.rs | 7 ++-- src/ship/items/floor.rs | 8 +++-- src/ship/items/inventory.rs | 48 ++++++++++---------------- src/ship/items/manager.rs | 69 ++++++++++++++++++------------------- src/ship/ship.rs | 2 +- 6 files changed, 63 insertions(+), 75 deletions(-) diff --git a/src/ship/item_stats.rs b/src/ship/item_stats.rs index c2b72b3..919c076 100644 --- a/src/ship/item_stats.rs +++ b/src/ship/item_stats.rs @@ -172,9 +172,9 @@ pub fn mag_stats() -> HashMap { pub fn mag_feed_tables() -> MagFeedTables { let mag_feed_tables: BTreeMap>> = load_data_file("data/item_stats/mag_feed_table.toml"); - MagFeedTables(mag_feed_tables.get("feedtable").unwrap().into_iter() + MagFeedTables(mag_feed_tables.get("feedtable").unwrap().iter() .map(|feed_table| { - MagFeedTable(feed_table.into_iter() + MagFeedTable(feed_table.iter() .map(|(tool, feed_stats)| { (tool.parse().unwrap(), *feed_stats) }).collect()) diff --git a/src/ship/items/bank.rs b/src/ship/items/bank.rs index e5fc03e..44b9cd1 100644 --- a/src/ship/items/bank.rs +++ b/src/ship/items/bank.rs @@ -178,13 +178,12 @@ impl CharacterBank { self.item_id_counter = base_item_id + self.items.len() as u32 + 1; } - pub fn get_item_handle_by_id<'a>(&'a mut self, item_id: ClientItemId) -> Option> { + pub fn get_item_handle_by_id(&mut self, item_id: ClientItemId) -> Option { let (index, _) = self.items.iter() .enumerate() - .filter(|(_, item)| { + .find(|(_, item)| { item.item_id() == item_id - }) - .nth(0)?; + })?; Some(BankItemHandle { bank: self, index: index, diff --git a/src/ship/items/floor.rs b/src/ship/items/floor.rs index 4e1f3f2..3083271 100644 --- a/src/ship/items/floor.rs +++ b/src/ship/items/floor.rs @@ -162,11 +162,13 @@ impl<'a> FloorItemHandle<'a> { #[derive(Debug)] pub struct RoomFloorItems(Vec); -impl RoomFloorItems { - pub fn new() -> RoomFloorItems { +impl Default for RoomFloorItems { + fn default() -> RoomFloorItems { RoomFloorItems(Vec::new()) } +} +impl RoomFloorItems { pub fn add_item(&mut self, item: FloorItem) { self.0.push(item); } @@ -186,7 +188,7 @@ impl RoomFloorItems { pub fn take_item_by_id(&mut self, item_id: ClientItemId) -> Option { self.0 .drain_filter(|i| i.item_id() == item_id) - .nth(0) + .next() } pub fn drop_individual_inventory_item(&mut self, individual_inventory_item: IndividualInventoryItem, item_drop_location: (MapArea, f32, f32, f32)) -> &IndividualFloorItem { diff --git a/src/ship/items/inventory.rs b/src/ship/items/inventory.rs index 67bb356..bbf833c 100644 --- a/src/ship/items/inventory.rs +++ b/src/ship/items/inventory.rs @@ -158,12 +158,8 @@ impl InventoryItem { // TODO: result // TOOD: delete? pub fn combine_stacks(&mut self, other_stacked_item: &mut StackedFloorItem) { - match self { - InventoryItem::Stacked(self_stacked_item) => { - self_stacked_item.entity_ids.append(&mut other_stacked_item.entity_ids); - }, - _ => { - } + if let InventoryItem::Stacked(self_stacked_item) = self { + self_stacked_item.entity_ids.append(&mut other_stacked_item.entity_ids); } } @@ -417,85 +413,80 @@ impl CharacterInventory { self.items.len() } - pub fn get_item_handle_by_id<'a>(&'a mut self, item_id: ClientItemId) -> Option> { + pub fn get_item_handle_by_id(&mut self, item_id: ClientItemId) -> Option { let (slot, _) = self.items.iter() .enumerate() - .filter(|(_, item)| { + .find(|(_, item)| { item.item_id() == item_id - }) - .nth(0)?; + })?; Some(InventoryItemHandle { inventory: self, slot: slot, }) } - pub fn get_equipped_mag_handle<'a>(&'a mut self) -> Option> { + pub fn get_equipped_mag_handle(&mut self) -> Option { let (slot, _) = self.items.iter() .enumerate() - .filter(|(_, item)| { + .find(|(_, item)| { if let InventoryItem::Individual(individual_inventory_item) = item { if let ItemDetail::Mag(_) = &individual_inventory_item.item { return self.equipped.is_equipped(&individual_inventory_item.entity_id) } } false - }) - .nth(0)?; + })?; Some(InventoryItemHandle { inventory: self, slot: slot, }) } - pub fn get_equipped_armor_handle<'a>(&'a mut self) -> Option> { + pub fn get_equipped_armor_handle(&mut self) -> Option { let (slot, _) = self.items.iter() .enumerate() - .filter(|(_, item)| { + .find(|(_, item)| { if let InventoryItem::Individual(individual_inventory_item) = item { if let ItemDetail::Armor(_) = &individual_inventory_item.item { return self.equipped.is_equipped(&individual_inventory_item.entity_id) } } false - }) - .nth(0)?; + })?; Some(InventoryItemHandle { inventory: self, slot: slot, }) } - pub fn get_equipped_shield_handle<'a>(&'a mut self) -> Option> { + pub fn get_equipped_shield_handle(&mut self) -> Option { let (slot, _) = self.items.iter() .enumerate() - .filter(|(_, item)| { + .find(|(_, item)| { if let InventoryItem::Individual(individual_inventory_item) = item { if let ItemDetail::Shield(_) = &individual_inventory_item.item { return self.equipped.is_equipped(&individual_inventory_item.entity_id) } } false - }) - .nth(0)?; + })?; Some(InventoryItemHandle { inventory: self, slot: slot, }) } - pub fn get_equipped_weapon_handle<'a>(&'a mut self) -> Option> { + pub fn get_equipped_weapon_handle(&mut self) -> Option { let (slot, _) = self.items.iter() .enumerate() - .filter(|(_, item)| { + .find(|(_, item)| { if let InventoryItem::Individual(individual_inventory_item) = item { if let ItemDetail::Weapon(_) = &individual_inventory_item.item { return self.equipped.is_equipped(&individual_inventory_item.entity_id) } } false - }) - .nth(0)?; + })?; Some(InventoryItemHandle { inventory: self, slot: slot, @@ -504,16 +495,15 @@ impl CharacterInventory { pub fn get_item_by_id(&self, item_id: ClientItemId) -> Option<&InventoryItem> { self.items.iter() - .filter(|item| { + .find(|item| { item.item_id() == item_id }) - .nth(0) } pub fn take_item_by_id(&mut self, item_id: ClientItemId) -> Option { self.items .drain_filter(|i| i.item_id() == item_id) - .nth(0) + .next() } pub fn add_item(&mut self, item: InventoryItem) -> Result<(), InventoryAddError> { // TODO: errors diff --git a/src/ship/items/manager.rs b/src/ship/items/manager.rs index bfdcca6..b975cc0 100644 --- a/src/ship/items/manager.rs +++ b/src/ship/items/manager.rs @@ -71,8 +71,8 @@ pub struct ItemManager { room_item_id_counter: HashMap ClientItemId + Send>>, } -impl ItemManager { - pub fn new() -> ItemManager { +impl Default for ItemManager { + fn default() -> ItemManager { ItemManager { id_counter: 0, character_inventory: HashMap::new(), @@ -83,7 +83,9 @@ impl ItemManager { room_item_id_counter: HashMap::new(), } } +} +impl ItemManager { pub fn next_global_item_id(&mut self) -> ClientItemId { self.id_counter += 1; ClientItemId(self.id_counter) @@ -110,11 +112,11 @@ impl ItemManager { entity_ids: items.iter().map(|i| i.id).collect(), item_id: self.next_global_item_id(), tool: items.get(0) - .ok_or(ItemManagerError::StackedItemError(items.clone()))? + .ok_or_else(|| ItemManagerError::StackedItemError(items.clone()))? .item .clone() .as_tool() - .ok_or(ItemManagerError::StackedItemError(items.clone()))? + .ok_or_else(|| ItemManagerError::StackedItemError(items.clone()))? }) }, }) @@ -137,11 +139,11 @@ impl ItemManager { entity_ids: items.iter().map(|i| i.id).collect(), item_id: self.next_global_item_id(), tool: items.get(0) - .ok_or(ItemManagerError::StackedItemError(items.clone()))? + .ok_or_else(|| ItemManagerError::StackedItemError(items.clone()))? .item .clone() .as_tool() - .ok_or(ItemManagerError::StackedItemError(items.clone()))? + .ok_or_else(|| ItemManagerError::StackedItemError(items.clone()))? }) }, }) @@ -160,18 +162,15 @@ impl ItemManager { inventory.initialize_item_ids(base_inventory_id); let base_bank_id = ((area_client.local_client.id() as u32) << 21) | 0x20000; let default_bank = self.character_bank.get_mut(&character.id); - match default_bank { - Some(default_bank) => { - default_bank.initialize_item_ids(base_bank_id); - }, - None => {}, + if let Some(default_bank ) = default_bank { + default_bank.initialize_item_ids(base_bank_id); } self.character_room.insert(character.id, room_id); - self.character_floor.insert(character.id, RoomFloorItems::new()); - self.room_floor.entry(room_id).or_insert(RoomFloorItems::new()); + self.character_floor.insert(character.id, RoomFloorItems::default()); + self.room_floor.entry(room_id).or_insert_with(RoomFloorItems::default); let mut inc = 0x00810000; - self.room_item_id_counter.entry(room_id).or_insert(Box::new(move || { + self.room_item_id_counter.entry(room_id).or_insert_with(|| Box::new(move || { inc += 1; ClientItemId(inc) })); @@ -202,13 +201,11 @@ impl ItemManager { pub fn remove_character_from_room(&mut self, character: &CharacterEntity) { self.character_inventory.remove(&character.id); self.character_floor.remove(&character.id); - self.character_room.remove(&character.id) - .as_ref() - .map(|room| { - if self.character_room.iter().find(|(_, r)| *r == room).is_none() { - self.room_floor.remove(room); - } - }); + if let Some(room) = self.character_room.remove(&character.id).as_ref() { + if self.character_room.iter().any(|(_, r)| r == room) { + self.room_floor.remove(room); + } + } } pub fn get_floor_item_by_id(&self, character: &CharacterEntity, item_id: ClientItemId) -> Result<(&FloorItem, FloorType), anyhow::Error> { @@ -220,7 +217,7 @@ impl ItemManager { .or_else(|| { shared_floor.get_item_by_id(item_id).map(|item| (item, FloorType::Shared)) }) - .ok_or(ItemManagerError::NoSuchItemId(item_id).into()) + .ok_or_else(|| ItemManagerError::NoSuchItemId(item_id).into()) } pub async fn character_picks_up_item(&mut self, entity_gateway: &mut EG, character: &mut CharacterEntity, item_id: ClientItemId) @@ -228,7 +225,7 @@ impl ItemManager { let local_floor = self.character_floor.get_mut(&character.id).ok_or(ItemManagerError::NoCharacter(character.id))?; let inventory = self.character_inventory.get_mut(&character.id).ok_or(ItemManagerError::NoCharacter(character.id))?; let room_id = self.character_room.get(&character.id).ok_or(ItemManagerError::NoCharacter(character.id))?; - let shared_floor = self.room_floor.get_mut(&room_id).ok_or(ItemManagerError::NoCharacter(character.id))?; + let shared_floor = self.room_floor.get_mut(room_id).ok_or(ItemManagerError::NoCharacter(character.id))?; let floor_item = local_floor.get_item_handle_by_id(item_id) .or_else(|| { @@ -238,7 +235,7 @@ impl ItemManager { let trigger_create_item = match floor_item.item() { Some(FloorItem::Individual(individual_floor_item)) => { - let new_inventory_item = inventory.pick_up_individual_floor_item(&individual_floor_item); + let new_inventory_item = inventory.pick_up_individual_floor_item(individual_floor_item); match new_inventory_item { Some((new_inventory_item, slot)) => { entity_gateway.change_item_location( @@ -247,7 +244,7 @@ impl ItemManager { character_id: character.id, } ).await?; - if let Some(_) = new_inventory_item.mag() { + if new_inventory_item.mag().is_some() { entity_gateway.change_mag_owner(&new_inventory_item.entity_id, character).await?; } }, @@ -258,13 +255,13 @@ impl ItemManager { TriggerCreateItem::Yes }, Some(FloorItem::Stacked(stacked_floor_item)) => { - let new_inventory_item = inventory.pick_up_stacked_floor_item(&stacked_floor_item); + let new_inventory_item = inventory.pick_up_stacked_floor_item(stacked_floor_item); match new_inventory_item { Some((new_inventory_item, slot)) => { for entity_id in &new_inventory_item.entity_ids { entity_gateway.change_item_location( - &entity_id, + entity_id, ItemLocation::Inventory { character_id: character.id, } @@ -288,7 +285,7 @@ impl ItemManager { return Err(ItemManagerError::CouldNotAddToInventory(item_id).into()); } character.meseta = std::cmp::min(character.meseta + meseta_floor_item.meseta.0, 999999); - entity_gateway.save_character(&character).await?; + entity_gateway.save_character(character).await?; TriggerCreateItem::No }, None => { @@ -381,9 +378,9 @@ impl ItemManager { }, }; - self.character_floor.entry(character.id).or_insert(RoomFloorItems::new()).add_item(floor_item); + self.character_floor.entry(character.id).or_insert_with(RoomFloorItems::default).add_item(floor_item); // TODO: make these real errors - self.character_floor.get(&character.id).ok_or(ItemManagerError::Idunnoman)?.get_item_by_id(item_id).ok_or(ItemManagerError::Idunnoman.into()) + self.character_floor.get(&character.id).ok_or(ItemManagerError::Idunnoman)?.get_item_by_id(item_id).ok_or_else(|| ItemManagerError::Idunnoman.into()) } pub async fn player_drop_item_on_shared_floor(&mut self, @@ -395,7 +392,7 @@ impl ItemManager { -> Result<(), anyhow::Error> { let inventory = self.character_inventory.get_mut(&character.id).ok_or(ItemManagerError::NoCharacter(character.id))?; let room_id = self.character_room.get(&character.id).ok_or(ItemManagerError::NoCharacter(character.id))?; - let shared_floor = self.room_floor.get_mut(&room_id).ok_or(ItemManagerError::NoCharacter(character.id))?; + let shared_floor = self.room_floor.get_mut(room_id).ok_or(ItemManagerError::NoCharacter(character.id))?; let dropped_inventory_item = inventory.take_item_by_id(item_id).ok_or(ItemManagerError::NoSuchItemId(item_id))?; @@ -439,12 +436,12 @@ impl ItemManager { amount: u32) -> Result { let room_id = self.character_room.get(&character.id).ok_or(ItemManagerError::NoCharacter(character.id))?; - let shared_floor = self.room_floor.get_mut(&room_id).ok_or(ItemManagerError::NoCharacter(character.id))?; + let shared_floor = self.room_floor.get_mut(room_id).ok_or(ItemManagerError::NoCharacter(character.id))?; if character.meseta < amount { return Err(ItemManagerError::CouldNotDropMeseta.into()) } character.meseta -= amount; - entity_gateway.save_character(&character).await?; + entity_gateway.save_character(character).await?; let item_id = self.room_item_id_counter.get_mut(room_id).ok_or(ItemManagerError::NoCharacter(character.id))?(); let floor_item = FloorItem::Meseta(MesetaFloorItem { @@ -470,7 +467,7 @@ impl ItemManager { -> Result<&StackedFloorItem, anyhow::Error> { let inventory = self.character_inventory.get_mut(&character.id).ok_or(ItemManagerError::NoCharacter(character.id))?; let room_id = self.character_room.get(&character.id).ok_or(ItemManagerError::NoCharacter(character.id))?; - let shared_floor = self.room_floor.get_mut(&room_id).ok_or(ItemManagerError::NoCharacter(character.id))?; + let shared_floor = self.room_floor.get_mut(room_id).ok_or(ItemManagerError::NoCharacter(character.id))?; let item_to_split = inventory.get_item_handle_by_id(item_id).ok_or(ItemManagerError::NoSuchItemId(item_id))?; @@ -594,7 +591,7 @@ impl ItemManager { entity_gateway.set_character_inventory(&character.id, &inventory.as_inventory_entity(&character.id)).await?; entity_gateway.set_character_bank(&character.id, &bank.as_bank_entity(&character.id, &BankName("".into())), BankName("".into())).await?; - inventory.slot(inventory_item_slot).ok_or(ItemManagerError::Idunnoman.into()) + inventory.slot(inventory_item_slot).ok_or_else(|| ItemManagerError::Idunnoman.into()) } pub async fn player_feeds_mag_item(&mut self, @@ -881,7 +878,7 @@ impl ItemManager { let sorted_inventory_items: Vec = item_ids.iter() .filter(|&client_item_id| *client_item_id < 0xFFFFFFFF) .map(|&client_item_id| inventory.get_item_by_id(ClientItemId(client_item_id))) - .filter(|&x| x.is_some() == true) + .filter(|&x| x.is_some()) .map(|x| x.cloned().unwrap()) .collect(); diff --git a/src/ship/ship.rs b/src/ship/ship.rs index 294658a..92f32e8 100644 --- a/src/ship/ship.rs +++ b/src/ship/ship.rs @@ -367,7 +367,7 @@ impl ShipServerStateBuilder { clients: HashMap::new(), level_table: CharacterLevelTable::new(), name: self.name.unwrap_or("NAMENOTSET".into()), - item_manager: items::ItemManager::new(), + item_manager: items::ItemManager::default(), quests: quests::load_quests("data/quests.toml".into()).unwrap(), ip: self.ip.unwrap_or(Ipv4Addr::new(127,0,0,1)), port: self.port.unwrap_or(SHIP_PORT), From 53ec82d9eb30784ce6e74c3225b05ddea1b838a0 Mon Sep 17 00:00:00 2001 From: jake Date: Fri, 18 Jun 2021 17:38:36 -0600 Subject: [PATCH 13/25] lint src/ship/* --- src/bin/main.rs | 6 +-- src/bin/ship.rs | 2 +- src/ship/character.rs | 22 ++++++----- src/ship/location.rs | 30 +++++++-------- src/ship/mod.rs | 1 + src/ship/packet/builder/mod.rs | 2 +- src/ship/packet/handler/lobby.rs | 2 +- src/ship/room.rs | 14 +++---- src/ship/ship.rs | 64 ++++++++++++++++---------------- 9 files changed, 73 insertions(+), 70 deletions(-) diff --git a/src/bin/main.rs b/src/bin/main.rs index f5b7823..7e60b86 100644 --- a/src/bin/main.rs +++ b/src/bin/main.rs @@ -383,7 +383,7 @@ fn main() { let thread_entity_gateway = entity_gateway.clone(); info!("[ship] starting server"); - let ship_state = Box::new(ShipServerStateBuilder::new() + let ship_state = Box::new(ShipServerStateBuilder::default() .name("US/Sona-Nyl".into()) .ip(Ipv4Addr::new(127,0,0,1)) .port(elseware::ship::ship::SHIP_PORT) @@ -392,7 +392,7 @@ fn main() { let ship_loop = ship_mainloop(*ship_state, elseware::ship::ship::SHIP_PORT, std::net::Ipv4Addr::new(127, 0, 0, 1), elseware::login::login::COMMUNICATION_PORT); let thread_entity_gateway = entity_gateway.clone(); - let ship_state = Box::new(ShipServerStateBuilder::new() + let ship_state = Box::new(ShipServerStateBuilder::default() .name("EU/Dylath-Leen".into()) .ip(Ipv4Addr::new(127,0,0,1)) .port(elseware::ship::ship::SHIP_PORT+2000) @@ -401,7 +401,7 @@ fn main() { let ship_loop2 = ship_mainloop(*ship_state, elseware::ship::ship::SHIP_PORT+2000, std::net::Ipv4Addr::new(127, 0, 0, 1), elseware::login::login::COMMUNICATION_PORT); let thread_entity_gateway = entity_gateway.clone(); - let ship_state = Box::new(ShipServerStateBuilder::new() + let ship_state = Box::new(ShipServerStateBuilder::default() .name("JP/Thalarion".into()) .ip(Ipv4Addr::new(127,0,0,1)) .port(elseware::ship::ship::SHIP_PORT+3000) diff --git a/src/bin/ship.rs b/src/bin/ship.rs index acd0675..a9e42c4 100644 --- a/src/bin/ship.rs +++ b/src/bin/ship.rs @@ -37,7 +37,7 @@ fn main() { let shipgate_token = std::env::var("SHIPGATE_TOKEN").unwrap(); let ship_name = std::env::var("SHIP_NAME").unwrap().parse().unwrap(); let ip = std::env::var("SELF_IP").unwrap().parse().unwrap(); - let ship_state = ShipServerStateBuilder::new() + let ship_state = ShipServerStateBuilder::default() .name(ship_name) .ip(ip) .port(elseware::ship::ship::SHIP_PORT) diff --git a/src/ship/character.rs b/src/ship/character.rs index efbe494..d666f01 100644 --- a/src/ship/character.rs +++ b/src/ship/character.rs @@ -9,16 +9,18 @@ pub struct CharacterBytesBuilder<'a> { level: Option, } - -impl<'a> CharacterBytesBuilder<'a> { - pub fn new() -> CharacterBytesBuilder<'a> { +impl<'a> Default for CharacterBytesBuilder<'a> { + fn default() -> CharacterBytesBuilder<'a> { CharacterBytesBuilder { character: None, stats: None, level: None, } } +} + +impl<'a> CharacterBytesBuilder<'a> { pub fn character(self, character: &'a CharacterEntity) -> CharacterBytesBuilder<'a> { CharacterBytesBuilder { character: Some(character), @@ -89,9 +91,8 @@ pub struct FullCharacterBytesBuilder<'a> { option_flags: Option, } - -impl<'a> FullCharacterBytesBuilder<'a> { - pub fn new() -> FullCharacterBytesBuilder<'a> { +impl<'a> Default for FullCharacterBytesBuilder<'a> { + fn default() -> FullCharacterBytesBuilder<'a> { FullCharacterBytesBuilder { character: None, stats: None, @@ -105,7 +106,10 @@ impl<'a> FullCharacterBytesBuilder<'a> { option_flags: None, } } +} + +impl<'a> FullCharacterBytesBuilder<'a> { pub fn character(self, character: &'a CharacterEntity) -> FullCharacterBytesBuilder<'a> { FullCharacterBytesBuilder { character: Some(character), @@ -196,9 +200,9 @@ impl<'a> FullCharacterBytesBuilder<'a> { inventory_items[11].material_count = character.materials.luck as u8; character::FullCharacter { - character: CharacterBytesBuilder::new() - .character(&character) - .stats(&stats) + character: CharacterBytesBuilder::default() + .character(character) + .stats(stats) .level(level - 1) .build(), inventory: character::Inventory { diff --git a/src/ship/location.rs b/src/ship/location.rs index c06a89e..a0c05f5 100644 --- a/src/ship/location.rs +++ b/src/ship/location.rs @@ -155,8 +155,7 @@ impl ClientLocation { let l = self.lobbies.get_mut(lobby.0).ok_or(JoinLobbyError::LobbyDoesNotExist)?; let (index, empty_slot) = l.0.iter_mut() .enumerate() - .filter(|(_, k)| k.is_none()) - .nth(0) + .find(|(_, k)| k.is_none()) .ok_or(JoinLobbyError::LobbyFull)?; *empty_slot = Some(AreaClient { client: id, @@ -173,10 +172,9 @@ impl ClientLocation { let new_lobby = LobbyId((lobby.0 + lobby_index) % 15); (new_lobby, self.add_client_to_lobby(id, new_lobby)) }) - .filter(|(_, lobby_option)| { + .find(|(_, lobby_option)| { lobby_option.is_ok() }) - .nth(0) .ok_or(JoinLobbyError::LobbyFull)?; Ok(l.0) @@ -185,8 +183,7 @@ impl ClientLocation { pub fn create_new_room(&mut self, id: ClientId) -> Result { let (index, empty_slot) = self.rooms.iter_mut() .enumerate() - .filter(|(_, r)| r.is_none()) - .nth(0) + .find(|(_, r)| r.is_none()) .ok_or(CreateRoomError::NoOpenSlots)?; *empty_slot = Some(Room([None; 4])); self.add_client_to_room(id, RoomId(index)).map_err(|_err| CreateRoomError::JoinError)?; @@ -201,8 +198,7 @@ impl ClientLocation { .ok_or(JoinRoomError::RoomDoesNotExist)?; let (index, empty_slot) = r.0.iter_mut() .enumerate() - .filter(|(_, k)| k.is_none()) - .nth(0) + .find(|(_, k)| k.is_none()) .ok_or(JoinRoomError::RoomFull)?; *empty_slot = Some(AreaClient { client: id, @@ -252,7 +248,7 @@ impl ClientLocation { let mut r = self.rooms[room.0] .as_ref() .ok_or(GetLeaderError::InvalidArea)? - .0.iter().flat_map(|k| k) + .0.iter().flatten() .collect::>(); r.sort_by_key(|k| k.time_join); let c = r.get(0).ok_or(GetLeaderError::NoClientInArea)?; @@ -261,7 +257,7 @@ impl ClientLocation { pub fn get_lobby_leader(&self, lobby: LobbyId) -> Result { let mut l = self.lobbies[lobby.0] - .0.iter().flat_map(|k| k) + .0.iter().flatten() .collect::>(); l.sort_by_key(|k| k.time_join); let c = l.get(0).ok_or(GetLeaderError::NoClientInArea)?; @@ -319,15 +315,13 @@ impl ClientLocation { RoomLobby::Room(room) => { self.get_clients_in_room(*room).map_err(|_| GetClientsError::InvalidArea)? .into_iter() - .filter(|c| c.client == id) - .nth(0) + .find(|c| c.client == id) .ok_or(GetClientsError::InvalidClient) }, RoomLobby::Lobby(lobby) => { self.get_clients_in_lobby(*lobby).map_err(|_| GetClientsError::InvalidArea)? .into_iter() - .filter(|c| c.client == id) - .nth(0) + .find(|c| c.client == id) .ok_or(GetClientsError::InvalidClient) } } @@ -361,9 +355,11 @@ impl ClientLocation { let area = self.client_location.get_mut(&id).ok_or(ClientRemovalError::ClientNotInArea)?; let client_list = match area { RoomLobby::Room(room) => { - self.rooms[room.0].as_mut().map_or(None, |r| { - Some(r.0.iter_mut()) - }) + self.rooms[room.0] + .as_mut() + .map(|r| { + r.0.iter_mut() + }) }, RoomLobby::Lobby(lobby) => { Some(self.lobbies[lobby.0].0.iter_mut()) diff --git a/src/ship/mod.rs b/src/ship/mod.rs index b9b9268..f29531b 100644 --- a/src/ship/mod.rs +++ b/src/ship/mod.rs @@ -1,3 +1,4 @@ +#[allow(clippy::module_inception)] pub mod ship; pub mod location; pub mod character; diff --git a/src/ship/packet/builder/mod.rs b/src/ship/packet/builder/mod.rs index b1fa664..e0e5301 100644 --- a/src/ship/packet/builder/mod.rs +++ b/src/ship/packet/builder/mod.rs @@ -26,7 +26,7 @@ pub fn player_header(tag: u32, client: &ClientState, area_client: &AreaClient) - pub fn player_info(tag: u32, client: &ClientState, area_client: &AreaClient, item_manager: &ItemManager, level_table: &CharacterLevelTable) -> PlayerInfo { let (level, stats) = level_table.get_stats_from_exp(client.character.char_class, client.character.exp); let inventory = item_manager.get_character_inventory(&client.character).unwrap(); - let character = CharacterBytesBuilder::new() + let character = CharacterBytesBuilder::default() .character(&client.character) .stats(&stats) .level(level - 1) diff --git a/src/ship/packet/handler/lobby.rs b/src/ship/packet/handler/lobby.rs index dc84a21..a857ce2 100644 --- a/src/ship/packet/handler/lobby.rs +++ b/src/ship/packet/handler/lobby.rs @@ -24,7 +24,7 @@ pub fn block_selected(id: ClientId, let inventory = item_manager.get_character_inventory(&client.character).unwrap(); let bank = item_manager.get_character_bank(&client.character).unwrap(); - let fc = FullCharacterBytesBuilder::new() + let fc = FullCharacterBytesBuilder::default() .character(&client.character) .stats(&stats) .level(level) diff --git a/src/ship/room.rs b/src/ship/room.rs index 904267e..5fbae80 100644 --- a/src/ship/room.rs +++ b/src/ship/room.rs @@ -40,9 +40,9 @@ impl TryFrom for Episode { } } -impl Into for Episode { - fn into(self) -> u8 { - match self { +impl From for u8 { + fn from(other: Episode) -> u8 { + match other { Episode::One => 1, Episode::Two => 2, Episode::Four => 3, @@ -83,9 +83,9 @@ impl TryFrom for Difficulty { } } -impl Into for Difficulty { - fn into(self) -> u8 { - match self { +impl From for u8 { + fn from(other: Difficulty) -> u8 { + match other { Difficulty::Normal => 0, Difficulty::Hard => 1, Difficulty::VeryHard => 2, @@ -232,7 +232,7 @@ impl RoomState { }; Ok(RoomState { - monster_stats: Box::new(load_monster_stats_table(&room_mode).map_err(|_| RoomCreationError::CouldNotLoadMonsterStats(room_mode.clone()))?), + monster_stats: Box::new(load_monster_stats_table(&room_mode).map_err(|_| RoomCreationError::CouldNotLoadMonsterStats(room_mode))?), mode: room_mode, random_seed: rand::thread_rng().gen(), name: String::from_utf16_lossy(&create_room.name).trim_matches(char::from(0)).into(), diff --git a/src/ship/ship.rs b/src/ship/ship.rs index 92f32e8..6206440 100644 --- a/src/ship/ship.rs +++ b/src/ship/ship.rs @@ -262,10 +262,10 @@ pub struct ClientState { impl ClientState { pub fn new(user: UserAccountEntity, settings: UserSettingsEntity, character: CharacterEntity, session: Session) -> ClientState { ClientState { - user: user, - settings: settings, - character: character, - session: session, + user, + settings, + character, + session, block: 0, item_drop_location: None, done_loading_quest: false, @@ -287,8 +287,8 @@ pub struct ItemShops { pub armor_shop: ArmorShop, } -impl ItemShops { - pub fn new() -> ItemShops { +impl Default for ItemShops { + fn default() -> ItemShops { let difficulty = [room::Difficulty::Normal, room::Difficulty::Hard, room::Difficulty::VeryHard, room::Difficulty::Ultimate]; let section_id = [SectionID::Viridia, SectionID::Greenill, SectionID::Skyly, SectionID::Bluefull, SectionID::Purplenum, SectionID::Pinkal, SectionID::Redria, SectionID::Oran, SectionID::Yellowboze, SectionID::Whitill]; @@ -301,7 +301,7 @@ impl ItemShops { } ItemShops { - weapon_shop: weapon_shop, + weapon_shop, tool_shop: ToolShop::default(), armor_shop: ArmorShop::default(), } @@ -318,8 +318,8 @@ pub struct ShipServerStateBuilder { num_blocks: usize, } -impl ShipServerStateBuilder { - pub fn new() -> ShipServerStateBuilder { +impl Default for ShipServerStateBuilder { + fn default() -> ShipServerStateBuilder { ShipServerStateBuilder { entity_gateway: None, name: None, @@ -329,7 +329,9 @@ impl ShipServerStateBuilder { num_blocks: 2, } } +} +impl ShipServerStateBuilder { pub fn gateway(mut self, entity_gateway: EG) -> ShipServerStateBuilder { self.entity_gateway = Some(entity_gateway); self @@ -366,16 +368,16 @@ impl ShipServerStateBuilder { entity_gateway: self.entity_gateway.unwrap(), clients: HashMap::new(), level_table: CharacterLevelTable::new(), - name: self.name.unwrap_or("NAMENOTSET".into()), + name: self.name.unwrap_or_else(|| "NAMENOTSET".into()), item_manager: items::ItemManager::default(), quests: quests::load_quests("data/quests.toml".into()).unwrap(), - ip: self.ip.unwrap_or(Ipv4Addr::new(127,0,0,1)), + ip: self.ip.unwrap_or_else(|| Ipv4Addr::new(127,0,0,1)), port: self.port.unwrap_or(SHIP_PORT), - shops: Box::new(ItemShops::new()), + shops: Box::new(ItemShops::default()), blocks: Blocks(blocks), - auth_token: self.auth_token.unwrap_or(AuthToken("".into())), + auth_token: self.auth_token.unwrap_or_else(|| AuthToken("".into())), ship_list: Vec::new(), shipgate_sender: None, } @@ -428,7 +430,7 @@ pub struct ShipServerState { impl ShipServerState { pub fn builder() -> ShipServerStateBuilder { - ShipServerStateBuilder::new() + ShipServerStateBuilder::default() } pub fn set_sender(&mut self, sender: Box) { @@ -443,7 +445,7 @@ impl ShipServerState { }, GameMessage::PlayerDropItem(player_drop_item) => { let block = self.blocks.with_client(id, &self.clients)?; - handler::message::player_drop_item(id, player_drop_item, &mut self.entity_gateway, &mut block.client_location, &mut self.clients, &mut block.rooms, &mut self.item_manager).await? + handler::message::player_drop_item(id, player_drop_item, &mut self.entity_gateway, &block.client_location, &mut self.clients, &mut block.rooms, &mut self.item_manager).await? }, GameMessage::DropCoordinates(drop_coordinates) => { let block = self.blocks.with_client(id, &self.clients)?; @@ -451,37 +453,37 @@ impl ShipServerState { }, GameMessage::PlayerNoLongerHasItem(no_longer_has_item) => { let block = self.blocks.with_client(id, &self.clients)?; - handler::message::no_longer_has_item(id, no_longer_has_item, &mut self.entity_gateway, &mut block.client_location, &mut self.clients, &mut self.item_manager).await? + handler::message::no_longer_has_item(id, no_longer_has_item, &mut self.entity_gateway, &block.client_location, &mut self.clients, &mut self.item_manager).await? }, GameMessage::PlayerChangedMap(_) | GameMessage::PlayerChangedMap2(_) | GameMessage::TellOtherPlayerMyLocation(_) | GameMessage::PlayerWarpingToFloor(_) | GameMessage::PlayerTeleported(_) | GameMessage::PlayerStopped(_) | GameMessage::PlayerLoadedIn(_) | GameMessage::PlayerWalking(_) | GameMessage::PlayerRunning(_) | GameMessage::PlayerWarped(_) | GameMessage::PlayerChangedFloor(_) | GameMessage::InitializeSpeechNpc(_) => { let block = self.blocks.with_client(id, &self.clients)?; - handler::message::update_player_position(id, &msg, &mut self.clients, &mut block.client_location, &block.rooms)? + handler::message::update_player_position(id, msg, &mut self.clients, &block.client_location, &block.rooms)? }, GameMessage::ChargeAttack(charge_attack) => { handler::message::charge_attack(id, charge_attack, &mut self.clients, &mut self.entity_gateway).await? }, GameMessage::PlayerUseItem(player_use_item) => { let block = self.blocks.with_client(id, &self.clients)?; - handler::message::use_item(id, player_use_item, &mut self.entity_gateway, &mut block.client_location, &mut self.clients, &mut self.item_manager).await? + handler::message::use_item(id, player_use_item, &mut self.entity_gateway, &block.client_location, &mut self.clients, &mut self.item_manager).await? }, GameMessage::PlayerUsedMedicalCenter(player_used_medical_center) => { - handler::message::player_used_medical_center(id, &player_used_medical_center, &mut self.entity_gateway, &mut self.clients).await? + handler::message::player_used_medical_center(id, player_used_medical_center, &mut self.entity_gateway, &mut self.clients).await? }, GameMessage::PlayerFeedMag(player_feed_mag) => { let block = self.blocks.with_client(id, &self.clients)?; - handler::message::player_feed_mag(id, &player_feed_mag, &mut self.entity_gateway, &mut block.client_location, &mut self.clients, &mut self.item_manager).await? + handler::message::player_feed_mag(id, player_feed_mag, &mut self.entity_gateway, &block.client_location, &self.clients, &mut self.item_manager).await? }, GameMessage::PlayerEquipItem(player_equip_item) => { - handler::message::player_equips_item(id, &player_equip_item, &mut self.entity_gateway, &mut self.clients, &mut self.item_manager).await? + handler::message::player_equips_item(id, player_equip_item, &mut self.entity_gateway, &self.clients, &mut self.item_manager).await? }, GameMessage::PlayerUnequipItem(player_unequip_item) => { - handler::message::player_unequips_item(id, &player_unequip_item, &mut self.entity_gateway, &mut self.clients, &mut self.item_manager).await? + handler::message::player_unequips_item(id, player_unequip_item, &mut self.entity_gateway, &self.clients, &mut self.item_manager).await? }, GameMessage::SortItems(sort_items) => { - handler::message::player_sorts_items(id, sort_items, &mut self.entity_gateway, &mut self.clients, &mut self.item_manager).await? + handler::message::player_sorts_items(id, sort_items, &mut self.entity_gateway, &self.clients, &mut self.item_manager).await? }, _ => { let cmsg = msg.clone(); @@ -502,13 +504,13 @@ impl ShipServerState { handler::direct_message::guildcard_send(id, guildcard_send, target, &block.client_location, &self.clients) }, GameMessage::RequestItem(request_item) => { - handler::direct_message::request_item(id, request_item, &mut self.entity_gateway, &mut block.client_location, &mut self.clients, &mut block.rooms, &mut self.item_manager).await? + handler::direct_message::request_item(id, request_item, &mut self.entity_gateway, &block.client_location, &mut self.clients, &mut block.rooms, &mut self.item_manager).await? }, GameMessage::PickupItem(pickup_item) => { - handler::direct_message::pickup_item(id, pickup_item, &mut self.entity_gateway, &mut block.client_location, &mut self.clients, &mut self.item_manager).await? + handler::direct_message::pickup_item(id, pickup_item, &mut self.entity_gateway, &block.client_location, &mut self.clients, &mut self.item_manager).await? }, GameMessage::BoxDropRequest(box_drop_request) => { - handler::direct_message::request_box_item(id, box_drop_request, &mut self.entity_gateway, &mut block.client_location, &mut self.clients, &mut block.rooms, &mut self.item_manager).await? + handler::direct_message::request_box_item(id, box_drop_request, &mut self.entity_gateway, &block.client_location, &mut self.clients, &mut block.rooms, &mut self.item_manager).await? }, GameMessage::BankRequest(_bank_request) => { handler::direct_message::send_bank_list(id, &self.clients, &mut self.item_manager).await? @@ -626,7 +628,7 @@ impl ServerState for ShipServerState { }, RecvShipPacket::PlayerChat(msg) => { let block = self.blocks.with_client(id, &self.clients)?; - Box::new(handler::communication::player_chat(id, msg, &block.client_location, &self.clients)?.into_iter()) + Box::new(handler::communication::player_chat(id, msg, &block.client_location, &self.clients)?) }, RecvShipPacket::CreateRoom(create_room) => { let block = self.blocks.with_client(id, &self.clients)?; @@ -706,7 +708,7 @@ impl ServerState for ShipServerState { let pkt = match block.client_location.get_area(id)? { RoomLobby::Room(room) => { - if neighbors.len() == 0 { + if neighbors.is_empty() { block.rooms[room.0] = None; } let leader = block.client_location.get_room_leader(room)?; @@ -719,7 +721,7 @@ impl ServerState for ShipServerState { }; if let Some(shipgate_sender) = self.shipgate_sender.as_ref() { - shipgate_sender(ShipMessage::RemoveUser(client.user.id.clone())); + shipgate_sender(ShipMessage::RemoveUser(client.user.id)); } block.client_location.remove_client_from_area(id); @@ -748,7 +750,7 @@ impl InterserverActor for ShipServerState { (id, ShipMessage::Authenticate(self.auth_token.clone())), (id, ShipMessage::NewShip(Ship { name: self.name.clone(), - ip: self.ip.clone(), + ip: self.ip, port: self.port, block_count: 2, })), @@ -768,7 +770,7 @@ impl InterserverActor for ShipServerState { LoginMessage::RequestUsers => { Ok(self.clients.iter() .map(|(_, client)| { - (id, ShipMessage::AddUser(client.user.id.clone())) + (id, ShipMessage::AddUser(client.user.id)) }) .collect()) } From 5d6b109cc51b33e086331a3d5df0e5270744c032 Mon Sep 17 00:00:00 2001 From: jake Date: Fri, 18 Jun 2021 17:46:22 -0600 Subject: [PATCH 14/25] lint src/login/* --- src/login/character.rs | 34 ++++++++++++++++++---------------- src/login/login.rs | 2 +- src/login/mod.rs | 3 ++- 3 files changed, 21 insertions(+), 18 deletions(-) diff --git a/src/login/character.rs b/src/login/character.rs index 82a9e28..a268d1c 100644 --- a/src/login/character.rs +++ b/src/login/character.rs @@ -86,14 +86,14 @@ impl RecvServerPacket for RecvCharacterPacket { pub enum SendCharacterPacket { LoginResponse(LoginResponse), LoginWelcome(LoginWelcome), - SendKeyAndTeamSettings(SendKeyAndTeamSettings), + SendKeyAndTeamSettings(Box), CharAck(CharAck), ChecksumAck(ChecksumAck), CharacterPreview(CharacterPreview), GuildcardDataHeader(GuildcardDataHeader), GuildcardDataChunk(Box), ParamDataHeader(ParamDataHeader), - ParamDataChunk(ParamDataChunk), + ParamDataChunk(Box), Timestamp(Timestamp), ShipList(ShipList), RedirectClient(RedirectClient), @@ -285,10 +285,12 @@ async fn new_character(entity_gateway: &mut EG, user: &UserAc }; entity_gateway.set_character_inventory(&character.id, &inventory).await?; entity_gateway.set_character_bank(&character.id, &BankEntity::default(), BankName("".into())).await?; - let mut equipped = EquippedEntity::default(); - equipped.weapon = Some(weapon.id); - equipped.armor = Some(armor.id); - equipped.mag = Some(mag.id); + let equipped = EquippedEntity { + weapon: Some(weapon.id), + armor: Some(armor.id), + mag: Some(mag.id), + ..Default::default() + }; entity_gateway.set_character_equips(&character.id, &equipped).await?; Ok(()) } @@ -336,7 +338,7 @@ impl CharacterServerState { let client = self.clients.get_mut(&id).ok_or(CharacterError::ClientNotFound(id))?; - self.connected_clients.insert(user.id.clone(), ConnectedClient { + self.connected_clients.insert(user.id, ConnectedClient { ship_id: None, expires: None, //Some(chrono::Utc::now() + chrono::Duration::minutes(1)), }); @@ -368,7 +370,7 @@ impl CharacterServerState { let client = self.clients.get_mut(&id).ok_or(CharacterError::ClientNotFound(id))?; let user = client.user.as_ref().unwrap(); - let settings = match self.entity_gateway.get_user_settings_by_user(&user).await { + let settings = match self.entity_gateway.get_user_settings_by_user(user).await { Ok(settings) => settings, Err(_) => { let user_settings = NewUserSettingsEntity::new(user.id); @@ -378,7 +380,7 @@ impl CharacterServerState { let pkt = SendKeyAndTeamSettings::new(settings.settings.key_config, settings.settings.joystick_config, 0, 0); - let pkt = SendCharacterPacket::SendKeyAndTeamSettings(pkt); + let pkt = SendCharacterPacket::SendKeyAndTeamSettings(Box::new(pkt)); Ok(vec![pkt]) } @@ -396,7 +398,7 @@ impl CharacterServerState { vec![SendCharacterPacket::CharacterPreview(CharacterPreview { slot: select.slot, character: SelectScreenCharacterBuilder::new() - .character(&char) + .character(char) .level(level) .build() })] @@ -461,7 +463,7 @@ impl CharacterServerState { let client = self.clients.get_mut(&id).ok_or(CharacterError::ClientNotFound(id))?; let mut user = client.user.as_mut().unwrap(); user.flags = setflag.flags; - self.entity_gateway.save_user(&user).await.unwrap(); + self.entity_gateway.save_user(user).await.unwrap(); Ok(None.into_iter()) } @@ -477,10 +479,10 @@ impl CharacterServerState { data[..end-start].copy_from_slice(&self.param_data[start..end]); Ok(vec![SendCharacterPacket::ParamDataChunk( - ParamDataChunk { + Box::new(ParamDataChunk { chunk: chunk as u32, data: data, - } + }) )]) } @@ -490,7 +492,7 @@ impl CharacterServerState { let client = self.clients.get_mut(&id).ok_or(CharacterError::ClientNotFound(id))?; let mut user = client.user.as_mut().unwrap(); if user.flags == USERFLAG_NEWCHAR { - new_character(&mut self.entity_gateway, &user, preview).await? + new_character(&mut self.entity_gateway, user, preview).await? } if user.flags == USERFLAG_DRESSINGROOM { // TODO: dressing room stuff @@ -499,7 +501,7 @@ impl CharacterServerState { client.session.action = SessionAction::SelectCharacter; client.session.character_slot = preview.slot as u8; user.flags = 0; - self.entity_gateway.save_user(&user).await.unwrap(); + self.entity_gateway.save_user(user).await.unwrap(); Ok(vec![SendCharacterPacket::LoginResponse(LoginResponse::by_char_select(user.guildcard, user.team_id.unwrap_or(1), client.session)), @@ -512,7 +514,7 @@ impl CharacterServerState { fn select_ship(&mut self, id: ClientId, menuselect: &MenuSelect) -> Result, anyhow::Error> { if menuselect.menu != SHIP_MENU_ID { - Err(CharacterError::InvalidMenuSelection(menuselect.menu, menuselect.item))?; + return Err(CharacterError::InvalidMenuSelection(menuselect.menu, menuselect.item).into()); } if let Some(client) = self.clients.get(&id) { diff --git a/src/login/login.rs b/src/login/login.rs index 6c0277b..f6ef7c4 100644 --- a/src/login/login.rs +++ b/src/login/login.rs @@ -102,7 +102,7 @@ impl LoginServerState { pub fn new(entity_gateway: EG, character_server_ip: net::Ipv4Addr) -> LoginServerState { LoginServerState { entity_gateway: entity_gateway, - character_server_ip: character_server_ip.into(), + character_server_ip: character_server_ip, clients: HashMap::new(), } } diff --git a/src/login/mod.rs b/src/login/mod.rs index 090d544..a5b3370 100644 --- a/src/login/mod.rs +++ b/src/login/mod.rs @@ -1,2 +1,3 @@ +#[allow(clippy::module_inception)] pub mod login; -pub mod character; \ No newline at end of file +pub mod character; From 46f1f772f437e6d88dad2f421274a83fc6ddfeb9 Mon Sep 17 00:00:00 2001 From: jake Date: Fri, 18 Jun 2021 17:51:30 -0600 Subject: [PATCH 15/25] lint src/patch/* --- src/patch/mod.rs | 3 ++- src/patch/patch.rs | 13 ++++++------- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/patch/mod.rs b/src/patch/mod.rs index ca4c5d6..323a777 100644 --- a/src/patch/mod.rs +++ b/src/patch/mod.rs @@ -1 +1,2 @@ -pub mod patch; \ No newline at end of file +#[allow(clippy::module_inception)] +pub mod patch; diff --git a/src/patch/patch.rs b/src/patch/patch.rs index 9d71f10..13a9928 100644 --- a/src/patch/patch.rs +++ b/src/patch/patch.rs @@ -2,7 +2,7 @@ use std::collections::{HashMap, HashSet}; use std::fs; use std::io; use std::io::{Read}; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use rand::Rng; use crc::{crc32, Hasher32}; use libpso::{PacketParseError, PSOPacket}; @@ -60,7 +60,7 @@ impl PatchFileTree { PatchFileTree::Directory(dir, files) => { v.push(PatchTreeIterItem::Directory(dir.clone())); for file in files { - v.append(&mut PatchFileTree::iter_dir(&file)); + v.append(&mut PatchFileTree::iter_dir(file)); } v.push(PatchTreeIterItem::UpDirectory); }, @@ -197,7 +197,7 @@ impl ServerState for PatchServerState { let p = vec![SendPatchPacket::FilesToPatchMetadata(FilesToPatchMetadata::new(total_size, total_files)), SendPatchPacket::PatchStartList(PatchStartList {}) ]; - Box::new(p.into_iter().chain(SendFileIterator::new(&self)).map(move |pkt| (id, pkt))) + Box::new(p.into_iter().chain(SendFileIterator::new(self)).map(move |pkt| (id, pkt))) } }) } @@ -214,12 +214,11 @@ fn load_patch_dir(basedir: &str, patchbase: &str, file_ids: &mut HashMap Vec Result<(u32, u32), PatchError> { +fn get_checksum_and_size(path: &Path) -> Result<(u32, u32), PatchError> { let file = fs::File::open(path)?; let size = file.metadata().unwrap().len(); let mut crc = crc32::Digest::new(crc32::IEEE); @@ -307,7 +306,7 @@ impl SendFileIterator { file_iter: Box::new(state.patch_file_tree.flatten().into_iter().filter(move |file| { match file { PatchTreeIterItem::File(_path, id) => { - file_ids_to_update.contains(&id) + file_ids_to_update.contains(id) }, _ => true, } From 95d237af6fec59edb65243ef5a147a3ae231bda8 Mon Sep 17 00:00:00 2001 From: jake Date: Fri, 18 Jun 2021 19:01:29 -0600 Subject: [PATCH 16/25] lint src/entity/item/* --- src/entity/item/armor.rs | 4 +- src/entity/item/esweapon.rs | 31 ++++----- src/entity/item/mag.rs | 21 +++--- src/entity/item/mod.rs | 14 ++-- src/entity/item/shield.rs | 4 +- src/entity/item/tool.rs | 124 +++++++++++++++++------------------- src/entity/item/unit.rs | 4 +- src/entity/item/weapon.rs | 83 ++++++++++++------------ 8 files changed, 135 insertions(+), 150 deletions(-) diff --git a/src/entity/item/armor.rs b/src/entity/item/armor.rs index 62f2c64..6d2489d 100644 --- a/src/entity/item/armor.rs +++ b/src/entity/item/armor.rs @@ -317,9 +317,9 @@ impl Armor { pub fn from_bytes(data: [u8; 16]) -> Result { let a = ArmorType::parse_type([data[0], data[1], data[2]]); - if a.is_ok() { + if let Ok(a) = a { Ok(Armor { - armor: a.unwrap(), + armor: a, dfp: data[6], evp: data[8], slots: data[5], diff --git a/src/entity/item/esweapon.rs b/src/entity/item/esweapon.rs index ace5ec1..6c00e7f 100644 --- a/src/entity/item/esweapon.rs +++ b/src/entity/item/esweapon.rs @@ -190,10 +190,10 @@ impl ESWeapon { pub fn bytes_from_name(&self) -> [u8; 6] { let mut result = [0u16; 3]; let mut letters = [0u8; 8]; - letters[0..self.name.len()].clone_from_slice(&self.name.to_uppercase().clone().into_bytes()); + letters[0..self.name.len()].clone_from_slice(&self.name.to_uppercase().into_bytes()); for letter in letters.iter_mut() { - *letter = *letter & 0x3F; + *letter &= 0x3F; } result[0] = 0x8000 + (0x20 * letters[0] as u16) + (letters[1] as u16); @@ -207,29 +207,22 @@ impl ESWeapon { // TODO: error handling, ensure name is never more than 8 pub fn name_from_bytes(namebytes: &[u8]) -> String { - let mut name: Vec = Vec::with_capacity(8); - name.extend_from_slice(namebytes); - - for _ in name.len()..name.capacity() { - name.push(0); - } - let buf: [u16; 3] = [ u16::from_be_bytes([namebytes[0], namebytes[1]]), u16::from_be_bytes([namebytes[2], namebytes[3]]), u16::from_be_bytes([namebytes[4], namebytes[5]]), ]; - name[0] = ((buf[0] - 0x8000) / 0x20 + 0x40) as u8; - name[1] = ((buf[0] - 0x8000) % 0x20 + 0x40) as u8; - - name[2] = ((buf[1] - 0x8000) / 0x400 + 0x40) as u8; - name[3] = (((buf[1] - 0x8000) % 0x400) / 0x20 + 0x40) as u8; - name[4] = (((buf[1] - 0x8000) % 0x400) % 0x20 + 0x40) as u8; - - name[5] = ((buf[2] - 0x8000) / 0x400 + 0x40) as u8; - name[6] = (((buf[2] - 0x8000) % 0x400) / 0x20 + 0x40) as u8; - name[7] = (((buf[2] - 0x8000) % 0x400) % 0x20 + 0x40) as u8; + let mut name: Vec = vec![ + ((buf[0] - 0x8000) / 0x20 + 0x40) as u8, + ((buf[0] - 0x8000) % 0x20 + 0x40) as u8, + ((buf[1] - 0x8000) / 0x400 + 0x40) as u8, + (((buf[1] - 0x8000) % 0x400) / 0x20 + 0x40) as u8, + (((buf[1] - 0x8000) % 0x400) % 0x20 + 0x40) as u8, + ((buf[2] - 0x8000) / 0x400 + 0x40) as u8, + (((buf[2] - 0x8000) % 0x400) / 0x20 + 0x40) as u8, + (((buf[2] - 0x8000) % 0x400) % 0x20 + 0x40) as u8, + ]; name.retain(|&x| x > 0x40 && x < 0x5B); diff --git a/src/entity/item/mag.rs b/src/entity/item/mag.rs index 0cb0384..348d025 100644 --- a/src/entity/item/mag.rs +++ b/src/entity/item/mag.rs @@ -43,7 +43,7 @@ lazy_static::lazy_static! { f.read_to_string(&mut s).unwrap(); let mut feed: HashMap>> = toml::from_str(&s).unwrap(); - let feed = feed.remove("feedtable".into()).unwrap(); + let feed = feed.remove("feedtable").unwrap(); feed.into_iter() .map(|table| { table.into_iter() @@ -624,7 +624,7 @@ impl Mag { fn photon_blast_count(&self) -> u8 { let mut count = 0; for i in 0..3 { - if let Some(_) = self.photon_blast[i] { + if self.photon_blast[i].is_some() { count |= 1 << i }; } @@ -633,7 +633,7 @@ impl Mag { pub fn from_bytes(data: [u8; 16]) -> Result { let m = MagType::parse_type([data[0], data[1], data[2]]); - if m.is_ok() { + if let Ok(m) = m { let mut def = u16::from_le_bytes([data[4], data[5]]); let mut pow = u16::from_le_bytes([data[6], data[7]]); let mut dex = u16::from_le_bytes([data[8], data[9]]); @@ -650,7 +650,7 @@ impl Mag { let iq = data[13] % 201; // TODO: handle invalid values. Ok(Mag{ - mag: m.unwrap(), + mag: m, def: def, pow: pow, dex: dex, @@ -739,6 +739,7 @@ impl Mag { } }, MagType::Vritra => { + #[allow(clippy::if_same_then_else)] if self.pow > self.dex && self.pow > self.mnd { self.mag = MagType::Sumba } @@ -1004,9 +1005,9 @@ impl Mag { MAG_STATS.get(&self.mag).map(|stats| { stats.photon_blast.map(|photon_blast| { if !self.photon_blast.contains(&Some(photon_blast)) { - self.photon_blast.iter_mut().find(|k| k.is_none()).map(|pb_slot| { + if let Some(pb_slot) = self.photon_blast.iter_mut().find(|k| k.is_none()) { *pb_slot = Some(photon_blast) - }); + } } }) }); @@ -1038,10 +1039,10 @@ impl Mag { } pub fn bank(&mut self) { - self.def = self.def & 0xFFFE; - self.pow = self.pow & 0xFFFE; - self.dex = self.dex & 0xFFFE; - self.mnd = self.mnd & 0xFFFE; + self.def &= 0xFFFE; + self.pow &= 0xFFFE; + self.dex &= 0xFFFE; + self.mnd &= 0xFFFE; } // TODO: this needs more checks on validity diff --git a/src/entity/item/mod.rs b/src/entity/item/mod.rs index 22e2913..9959f54 100644 --- a/src/entity/item/mod.rs +++ b/src/entity/item/mod.rs @@ -121,13 +121,13 @@ impl ItemDetail { } pub fn parse_item_from_bytes(data: [u8; 16]) -> Option { - let item_type = weapon::WeaponType::parse_type([data[0],data[1],data[2]]).map(|w| ItemType::Weapon(w)) - .or(armor::ArmorType::parse_type([data[0],data[1],data[2]]).map(|a| ItemType::Armor(a))) - .or(shield::ShieldType::parse_type([data[0],data[1],data[2]]).map(|s| ItemType::Shield(s))) - .or(unit::UnitType::parse_type([data[0],data[1],data[2]]).map(|u| ItemType::Unit(u))) - .or(mag::MagType::parse_type([data[0],data[1],data[2]]).map(|m| ItemType::Mag(m))) - .or(tool::ToolType::parse_type([data[0],data[1],data[2]]).map(|t| ItemType::Tool(t))) - .or(esweapon::ESWeaponType::parse_type([data[0],data[1],data[2]]).map(|e| ItemType::ESWeapon(e))).ok()?; + let item_type = weapon::WeaponType::parse_type([data[0],data[1],data[2]]).map(ItemType::Weapon) + .or_else(|_| armor::ArmorType::parse_type([data[0],data[1],data[2]]).map(ItemType::Armor)) + .or_else(|_| shield::ShieldType::parse_type([data[0],data[1],data[2]]).map(ItemType::Shield)) + .or_else(|_| unit::UnitType::parse_type([data[0],data[1],data[2]]).map(ItemType::Unit)) + .or_else(|_| mag::MagType::parse_type([data[0],data[1],data[2]]).map(ItemType::Mag)) + .or_else(|_| tool::ToolType::parse_type([data[0],data[1],data[2]]).map(ItemType::Tool)) + .or_else(|_| esweapon::ESWeaponType::parse_type([data[0],data[1],data[2]]).map(ItemType::ESWeapon)).ok()?; match item_type { ItemType::Weapon(_w) => Some(ItemDropType::Weapon(weapon::Weapon::from_bytes(data).ok()?)), diff --git a/src/entity/item/shield.rs b/src/entity/item/shield.rs index 852e3a0..5784fd4 100644 --- a/src/entity/item/shield.rs +++ b/src/entity/item/shield.rs @@ -537,9 +537,9 @@ impl Shield { pub fn from_bytes(data: [u8; 16]) -> Result { let s = ShieldType::parse_type([data[0], data[1], data[2]]); - if s.is_ok() { + if let Ok(s) = s { Ok(Shield{ - shield: s.unwrap(), + shield: s, dfp: data[6], evp: data[8], }) diff --git a/src/entity/item/tool.rs b/src/entity/item/tool.rs index 707b61b..054a922 100644 --- a/src/entity/item/tool.rs +++ b/src/entity/item/tool.rs @@ -186,36 +186,33 @@ pub enum ToolType { impl ToolType { pub fn is_stackable(&self) -> bool { - match self { - ToolType::Monomate => true, - ToolType::Dimate => true, - ToolType::Trimate => true, - ToolType::Monofluid => true, - ToolType::Difluid => true, - ToolType::Trifluid => true, - ToolType::SolAtomizer => true, - ToolType::MoonAtomizer => true, - ToolType::StarAtomizer => true, - ToolType::Antidote => true, - ToolType::Antiparalysis => true, - ToolType::Telepipe => true, - ToolType::TrapVision => true, - ToolType::Monogrinder => true, - ToolType::Digrinder => true, - ToolType::Trigrinder => true, - ToolType::PowerMaterial => true, - ToolType::MindMaterial => true, - ToolType::EvadeMaterial => true, - ToolType::HpMaterial => true, - ToolType::TpMaterial => true, - ToolType::DefMaterial => true, - ToolType::LuckMaterial => true, - ToolType::Addslot => true, - ToolType::PhotonDrop => true, - ToolType::PhotonSphere => true, - ToolType::PhotonCrystal => true, - _ => false, - } + matches!(self, ToolType::Monomate | + ToolType::Dimate | + ToolType::Trimate | + ToolType::Monofluid | + ToolType::Difluid | + ToolType::Trifluid | + ToolType::SolAtomizer | + ToolType::MoonAtomizer | + ToolType::StarAtomizer | + ToolType::Antidote | + ToolType::Antiparalysis | + ToolType::Telepipe | + ToolType::TrapVision | + ToolType::Monogrinder | + ToolType::Digrinder | + ToolType::Trigrinder | + ToolType::PowerMaterial | + ToolType::MindMaterial | + ToolType::EvadeMaterial | + ToolType::HpMaterial | + ToolType::TpMaterial | + ToolType::DefMaterial | + ToolType::LuckMaterial | + ToolType::Addslot | + ToolType::PhotonDrop | + ToolType::PhotonSphere | + ToolType::PhotonCrystal) } pub fn max_stack(&self) -> usize { @@ -252,39 +249,36 @@ impl ToolType { } pub fn is_mag_cell(&self) -> bool { - match self { - ToolType::CellOfMag502 => true, - ToolType::CellOfMag213 => true, - ToolType::PartsOfRobochao => true, - ToolType::HeartOfOpaOpa => true, - ToolType::HeartOfPian => true, - ToolType::HeartOfChao => true, - ToolType::HeartOfAngel => true, - ToolType::HeartOfDevil => true, - ToolType::KitOfHamburger => true, - ToolType::PanthersSpirit => true, - ToolType::KitOfMark3 => true, - ToolType::KitOfMasterSystem => true, - ToolType::KitOfGenesis => true, - ToolType::KitOfSegaSaturn => true, - ToolType::KitOfDreamcast => true, - ToolType::Tablet => true, - ToolType::DragonScale => true, - ToolType::HeavenStrikerCoat => true, - ToolType::PioneerParts => true, - ToolType::AmitiesMemo => true, - ToolType::HeartOfMorolian => true, - ToolType::RappysBeak => true, - ToolType::YahoosEngine => true, - ToolType::DPhotonCore => true, - ToolType::LibertaKit => true, - ToolType::CellOfMag0503 => true, - ToolType::CellOfMag0504 => true, - ToolType::CellOfMag0505 => true, - ToolType::CellOfMag0506 => true, - ToolType::CellOfMag0507 => true, - _ => false, - } + matches!(self, ToolType::CellOfMag502 | + ToolType::CellOfMag213 | + ToolType::PartsOfRobochao | + ToolType::HeartOfOpaOpa | + ToolType::HeartOfPian | + ToolType::HeartOfChao | + ToolType::HeartOfAngel | + ToolType::HeartOfDevil | + ToolType::KitOfHamburger | + ToolType::PanthersSpirit | + ToolType::KitOfMark3 | + ToolType::KitOfMasterSystem | + ToolType::KitOfGenesis | + ToolType::KitOfSegaSaturn | + ToolType::KitOfDreamcast | + ToolType::Tablet | + ToolType::DragonScale | + ToolType::HeavenStrikerCoat | + ToolType::PioneerParts | + ToolType::AmitiesMemo | + ToolType::HeartOfMorolian | + ToolType::RappysBeak | + ToolType::YahoosEngine | + ToolType::DPhotonCore | + ToolType::LibertaKit | + ToolType::CellOfMag0503 | + ToolType::CellOfMag0504 | + ToolType::CellOfMag0505 | + ToolType::CellOfMag0506 | + ToolType::CellOfMag0507) } pub fn value(&self) -> [u8; 3] { @@ -669,9 +663,9 @@ impl Tool { pub fn from_bytes(data: [u8; 16]) -> Result { let t = ToolType::parse_type([data[0], data[1], data[2]]); - if t.is_ok() { + if let Ok(t) = t { Ok(Tool { - tool: t.unwrap(), + tool: t, }) } else { diff --git a/src/entity/item/unit.rs b/src/entity/item/unit.rs index 1f9dd4c..df0b611 100644 --- a/src/entity/item/unit.rs +++ b/src/entity/item/unit.rs @@ -366,7 +366,7 @@ impl Unit { pub fn from_bytes(data: [u8; 16]) -> Result { let u = UnitType::parse_type([data[0], data[1], data[2]]); - if u.is_ok() { + if let Ok(u) = u { let m = match u16::from_le_bytes([data[6], data[7]]) { 0x02 => Some(UnitModifier::PlusPlus), 0x01 => Some(UnitModifier::Plus), @@ -376,7 +376,7 @@ impl Unit { }; Ok(Unit{ - unit: u.unwrap(), + unit: u, modifier: m, }) } diff --git a/src/entity/item/weapon.rs b/src/entity/item/weapon.rs index b26da45..e18eac5 100644 --- a/src/entity/item/weapon.rs +++ b/src/entity/item/weapon.rs @@ -1476,47 +1476,44 @@ impl Weapon { } pub fn apply_modifier(&mut self, modifier: &WeaponModifier) { - match modifier { - WeaponModifier::Tekked{special, percent, grind} => { - match special { - TekSpecialModifier::Plus => { - self.special = self.special.map(|special| { - special.rank_up() - }); - }, - TekSpecialModifier::Minus => { - self.special = self.special.map(|special| { - special.rank_down() - }); - }, - TekSpecialModifier::Neutral => { - }, - } - for i in 0..3 { - self.attrs[i] = self.attrs[i].map(|mut attr| { - match percent { - TekPercentModifier::PlusPlus => { - attr.value += 10; - }, - TekPercentModifier::Plus => { - attr.value += 5; - }, - TekPercentModifier::MinusMinus => { - attr.value -= 10; - }, - TekPercentModifier::Minus => { - attr.value -= 5; - }, - TekPercentModifier::Neutral => { - } - } - attr + if let WeaponModifier::Tekked{special, percent, grind} = modifier { + match special { + TekSpecialModifier::Plus => { + self.special = self.special.map(|special| { + special.rank_up() }); - } - self.grind = std::cmp::max(self.grind as i32 + grind, 0) as u8; - self.tekked = true; - }, - _ => {} + }, + TekSpecialModifier::Minus => { + self.special = self.special.map(|special| { + special.rank_down() + }); + }, + TekSpecialModifier::Neutral => { + }, + } + for i in 0..3 { + self.attrs[i] = self.attrs[i].map(|mut attr| { + match percent { + TekPercentModifier::PlusPlus => { + attr.value += 10; + }, + TekPercentModifier::Plus => { + attr.value += 5; + }, + TekPercentModifier::MinusMinus => { + attr.value -= 10; + }, + TekPercentModifier::Minus => { + attr.value -= 5; + }, + TekPercentModifier::Neutral => { + } + } + attr + }); + } + self.grind = std::cmp::max(self.grind as i32 + grind, 0) as u8; + self.tekked = true; } } @@ -1526,7 +1523,7 @@ impl Weapon { result[3] = self.grind; result[4] = self.special.map(|s| s.value()).unwrap_or(0); - if self.tekked == false { + if !self.tekked { result[4] += 0x80 }; @@ -1540,7 +1537,7 @@ impl Weapon { // TODO: error handling pub fn from_bytes(data: [u8; 16]) -> Result { let w = WeaponType::parse_type([data[0], data[1], data[2]]); - if w.is_ok() { + if let Ok(w) = w { let mut s = None; let mut t = true; let g = data[3]; @@ -1576,7 +1573,7 @@ impl Weapon { } Ok(Weapon { - weapon: w.unwrap(), + weapon: w, special: s, grind: g, attrs:[ From b6a2d55100a9ac0adde92f155a7c31fce40810e2 Mon Sep 17 00:00:00 2001 From: jake Date: Fri, 18 Jun 2021 19:03:08 -0600 Subject: [PATCH 17/25] lint src/bin/* --- src/bin/login.rs | 2 +- src/bin/ship.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/bin/login.rs b/src/bin/login.rs index 608f994..958693c 100644 --- a/src/bin/login.rs +++ b/src/bin/login.rs @@ -41,7 +41,7 @@ fn main() { let login_state = LoginServerState::new(thread_entity_gateway, charserv_ip); let login_loop = login_mainloop(login_state, elseware::login::login::LOGIN_PORT); - let char_state = CharacterServerState::new(entity_gateway, AuthToken(shipgate_token.into())); + let char_state = CharacterServerState::new(entity_gateway, AuthToken(shipgate_token)); let character_loop = character_mainloop(char_state, elseware::login::character::CHARACTER_PORT, elseware::login::login::COMMUNICATION_PORT); info!("[auth/character] starting server"); diff --git a/src/bin/ship.rs b/src/bin/ship.rs index a9e42c4..3c6d14e 100644 --- a/src/bin/ship.rs +++ b/src/bin/ship.rs @@ -42,7 +42,7 @@ fn main() { .ip(ip) .port(elseware::ship::ship::SHIP_PORT) .gateway(entity_gateway) - .auth_token(AuthToken(shipgate_token.into())) + .auth_token(AuthToken(shipgate_token)) .build(); let shipgate_ip = std::env::var("SHIPGATE_IP").unwrap().parse().unwrap(); From 6f40058b7d60476ad36ae0ba46b290858ae12fc0 Mon Sep 17 00:00:00 2001 From: jake Date: Fri, 18 Jun 2021 19:09:14 -0600 Subject: [PATCH 18/25] lint src/entity/* --- src/entity/character.rs | 44 ++++++++++++++++++++--------------------- 1 file changed, 21 insertions(+), 23 deletions(-) diff --git a/src/entity/character.rs b/src/entity/character.rs index c10bffd..6785322 100644 --- a/src/entity/character.rs +++ b/src/entity/character.rs @@ -44,9 +44,9 @@ impl From for CharacterClass { } } -impl Into for CharacterClass { - fn into(self) -> u8 { - match self { +impl From for u8 { + fn from(other: CharacterClass) -> u8 { + match other { CharacterClass::HUmar => 0, CharacterClass::HUnewearl => 1, CharacterClass::HUcast => 2, @@ -65,29 +65,27 @@ impl Into for CharacterClass { impl CharacterClass { pub fn is_human(&self) -> bool { - match self { - CharacterClass::HUmar | - CharacterClass::RAmar | CharacterClass::RAmarl | - CharacterClass::FOmar | CharacterClass::FOmarl => true, - - _ => false, - } + matches!(self, + CharacterClass::HUmar | + CharacterClass::RAmar | + CharacterClass::RAmarl | + CharacterClass::FOmar | + CharacterClass::FOmarl) } pub fn is_newman(&self) -> bool { - match self { - CharacterClass::HUnewearl | - CharacterClass::FOnewm | CharacterClass::FOnewearl => true, - _ => false, - } + matches!(self, + CharacterClass::HUnewearl | + CharacterClass::FOnewm | + CharacterClass::FOnewearl) } pub fn is_android(&self) -> bool { - match self { - CharacterClass::HUcast | CharacterClass::HUcaseal | - CharacterClass::RAcast | CharacterClass::RAcaseal => true, - _ => false, - } + matches!(self, + CharacterClass::HUcast | + CharacterClass::HUcaseal | + CharacterClass::RAcast | + CharacterClass::RAcaseal) } } @@ -124,9 +122,9 @@ impl From for SectionID { } } -impl Into for SectionID { - fn into(self) -> u8 { - match self { +impl From for u8 { + fn from(other: SectionID) -> u8 { + match other { SectionID::Viridia => 0, SectionID::Greenill => 1, SectionID::Skyly => 2, From 10c2b1ec8956f467d9bd1bbee062f77b4afb2721 Mon Sep 17 00:00:00 2001 From: jake Date: Fri, 18 Jun 2021 19:52:33 -0600 Subject: [PATCH 19/25] lint src/entity/gateway/* --- src/bin/main.rs | 2 +- src/entity/gateway/inmemory.rs | 49 +++-- src/entity/gateway/postgres/mod.rs | 1 + src/entity/gateway/postgres/models.rs | 258 ++++++++++++------------ src/entity/gateway/postgres/postgres.rs | 8 +- src/login/character.rs | 2 +- tests/test_bank.rs | 52 ++--- tests/test_character.rs | 2 +- tests/test_exp_gain.rs | 8 +- tests/test_item_actions.rs | 6 +- tests/test_item_pickup.rs | 20 +- tests/test_item_use.rs | 12 +- tests/test_mags.rs | 6 +- tests/test_rooms.rs | 2 +- tests/test_shops.rs | 26 +-- 15 files changed, 226 insertions(+), 228 deletions(-) diff --git a/src/bin/main.rs b/src/bin/main.rs index 7e60b86..e0c7207 100644 --- a/src/bin/main.rs +++ b/src/bin/main.rs @@ -48,7 +48,7 @@ fn main() { setup_logger(); async_std::task::block_on(async move { //let mut entity_gateway = PostgresGateway::new("localhost", "elsewhere", "elsewhere", ""); - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); for i in 0..5 { let fake_user = NewUserAccountEntity { diff --git a/src/entity/gateway/inmemory.rs b/src/entity/gateway/inmemory.rs index 12f9f8f..d80dca7 100644 --- a/src/entity/gateway/inmemory.rs +++ b/src/entity/gateway/inmemory.rs @@ -21,8 +21,8 @@ pub struct InMemoryGateway { weapon_modifiers: Arc>>>, } -impl InMemoryGateway { - pub fn new() -> InMemoryGateway { +impl Default for InMemoryGateway { + fn default() -> InMemoryGateway { InMemoryGateway { users: Arc::new(Mutex::new(BTreeMap::new())), user_settings: Arc::new(Mutex::new(BTreeMap::new())), @@ -47,7 +47,7 @@ impl InMemoryGateway { ItemDetail::Weapon(mut weapon) => { if let Some(weapon_modifiers) = self.weapon_modifiers.lock().unwrap().get(&item.id) { for weapon_modifier in weapon_modifiers.iter() { - weapon.apply_modifier(&weapon_modifier); + weapon.apply_modifier(weapon_modifier); } } ItemDetail::Weapon(weapon) @@ -58,23 +58,21 @@ impl InMemoryGateway { for mag_modifier in mag_modifiers.iter() { match mag_modifier { mag::MagModifier::FeedMag {food} => { - items.get(&food).map(|mag_feed| { - match mag_feed.item { - ItemDetail::Tool(mag_feed) => mag.feed(mag_feed.tool), - _ => {} + if let Some(mag_feed) = items.get(food) { + if let ItemDetail::Tool(mag_feed) = mag_feed.item { + mag.feed(mag_feed.tool) } - }); + } }, mag::MagModifier::OwnerChange(class, section_id) => { mag.change_owner(*class, *section_id) }, mag::MagModifier::MagCell(mag_cell_id) => { - items.get(&mag_cell_id).map(|mag_cell| { - match mag_cell.item { - ItemDetail::Tool(mag_cell) => mag.apply_mag_cell(mag_cell.tool.try_into().unwrap()), - _ => {} + if let Some(mag_cell) = items.get(mag_cell_id) { + if let ItemDetail::Tool(mag_cell) = mag_cell.item { + mag.apply_mag_cell(mag_cell.tool.try_into().unwrap()) } - }); + } }, _ => {} } @@ -124,7 +122,7 @@ impl EntityGateway for InMemoryGateway { async fn get_user_by_id(&self, id: UserAccountId) -> Result { let users = self.users.lock().unwrap(); - users.get(&id).map(|k| k.clone()).ok_or(GatewayError::Error) + users.get(&id).cloned().ok_or(GatewayError::Error) } async fn get_user_by_name(&self, username: String) -> Result { @@ -233,17 +231,16 @@ impl EntityGateway for InMemoryGateway { } async fn change_item_location(&mut self, item_id: &ItemEntityId, item_location: ItemLocation) -> Result<(), GatewayError> { - self.items.lock().unwrap().get_mut(&item_id) - .map(|item_entity| { - item_entity.location = item_location - }); + if let Some(item_entity) = self.items.lock().unwrap().get_mut(item_id) { + item_entity.location = item_location + } Ok(()) } async fn feed_mag(&mut self, mag_item_id: &ItemEntityId, tool_item_id: &ItemEntityId) -> Result<(), GatewayError> { self.mag_modifiers.lock().unwrap() .entry(*mag_item_id) - .or_insert(Vec::new()) + .or_insert_with(Vec::new) .push(mag::MagModifier::FeedMag { food: *tool_item_id }); @@ -253,7 +250,7 @@ impl EntityGateway for InMemoryGateway { async fn change_mag_owner(&mut self, mag_item_id: &ItemEntityId, character: &CharacterEntity) -> Result<(), GatewayError> { self.mag_modifiers.lock().unwrap() .entry(*mag_item_id) - .or_insert(Vec::new()) + .or_insert_with(Vec::new) .push(mag::MagModifier::OwnerChange(character.char_class, character.section_id)); Ok(()) } @@ -261,15 +258,15 @@ impl EntityGateway for InMemoryGateway { async fn use_mag_cell(&mut self, mag_item_id: &ItemEntityId, mag_cell_id: &ItemEntityId) -> Result<(), GatewayError> { self.mag_modifiers.lock().unwrap() .entry(*mag_item_id) - .or_insert(Vec::new()) - .push(mag::MagModifier::MagCell(mag_cell_id.clone())); + .or_insert_with(Vec::new) + .push(mag::MagModifier::MagCell(*mag_cell_id)); Ok(()) } async fn add_weapon_modifier(&mut self, item_id: &ItemEntityId, modifier: weapon::WeaponModifier) -> Result<(), GatewayError> { self.weapon_modifiers.lock().unwrap() .entry(*item_id) - .or_insert(Vec::new()) + .or_insert_with(Vec::new) .push(modifier); Ok(()) } @@ -282,7 +279,7 @@ impl EntityGateway for InMemoryGateway { .find(|(id, _)| **id == *char_id) .map(|(_, inv)| inv.clone()) .map(|inv| self.apply_modifiers(inv)) - .unwrap_or(InventoryEntity::default())) + .unwrap_or_default()) } async fn get_character_bank(&mut self, char_id: &CharacterEntityId, _bank_name: BankName) -> Result { @@ -291,7 +288,7 @@ impl EntityGateway for InMemoryGateway { .iter() .find(|(id, _)| **id == *char_id) .map(|(_, b)| b.clone()) - .unwrap_or(BankEntity::default())) + .unwrap_or_default()) } async fn set_character_inventory(&mut self, char_id: &CharacterEntityId, inventory: &InventoryEntity) -> Result<(), GatewayError> { @@ -313,7 +310,7 @@ impl EntityGateway for InMemoryGateway { .iter() .find(|(id, _)| **id == *char_id) .map(|(_, inv)| inv.clone()) - .unwrap_or(EquippedEntity::default())) + .unwrap_or_default()) } async fn set_character_equips(&mut self, char_id: &CharacterEntityId, equipped: &EquippedEntity) -> Result<(), GatewayError> { diff --git a/src/entity/gateway/postgres/mod.rs b/src/entity/gateway/postgres/mod.rs index 7ba478c..a796653 100644 --- a/src/entity/gateway/postgres/mod.rs +++ b/src/entity/gateway/postgres/mod.rs @@ -1,3 +1,4 @@ +#[allow(clippy::module_inception)] pub mod postgres; pub mod migrations; pub mod models; diff --git a/src/entity/gateway/postgres/models.rs b/src/entity/gateway/postgres/models.rs index d6a0c14..f33f399 100644 --- a/src/entity/gateway/postgres/models.rs +++ b/src/entity/gateway/postgres/models.rs @@ -23,22 +23,22 @@ pub struct PgUserAccount { at_ship: bool, } -impl Into for PgUserAccount { - fn into(self) -> UserAccountEntity { +impl From for UserAccountEntity { + fn from(other: PgUserAccount) -> UserAccountEntity { UserAccountEntity { - id: UserAccountId(self.id as u32), - username: self.username, - password: self.password, - banned_until: self.banned, - muted_until: self.muted, - created_at: self.created_at, - flags: self.flags as u32, - guildcard: self.id as u32 + 1, + id: UserAccountId(other.id as u32), + username: other.username, + password: other.password, + banned_until: other.banned, + muted_until: other.muted, + created_at: other.created_at, + flags: other.flags as u32, + guildcard: other.id as u32 + 1, team_id: None, - activated: self.activated, - at_login: self.at_login, - at_character: self.at_character, - at_ship: self.at_ship, + activated: other.activated, + at_login: other.at_login, + at_character: other.at_character, + at_ship: other.at_ship, } } } @@ -56,19 +56,19 @@ pub struct PgUserSettings { team_name: Vec, //[u16; 0x10], } -impl Into for PgUserSettings { - fn into(self) -> UserSettingsEntity { +impl From for UserSettingsEntity { + fn from(other: PgUserSettings) -> UserSettingsEntity { UserSettingsEntity { - id: UserSettingsId(self.id as u32), - user_id: UserAccountId(self.user_account as u32), + id: UserSettingsId(other.id as u32), + user_id: UserAccountId(other.user_account as u32), settings: settings::UserSettings { - blocked_users: vec_to_array(self.blocked_users.chunks(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect()), - key_config: vec_to_array(self.key_config), - joystick_config: vec_to_array(self.joystick_config), - option_flags: self.option_flags as u32, - shortcuts: vec_to_array(self.shortcuts), - symbol_chats: vec_to_array(self.symbol_chats), - team_name: vec_to_array(self.team_name.chunks(2).map(|b| u16::from_le_bytes([b[0], b[1]])).collect()), + blocked_users: vec_to_array(other.blocked_users.chunks(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect()), + key_config: vec_to_array(other.key_config), + joystick_config: vec_to_array(other.joystick_config), + option_flags: other.option_flags as u32, + shortcuts: vec_to_array(other.shortcuts), + symbol_chats: vec_to_array(other.symbol_chats), + team_name: vec_to_array(other.team_name.chunks(2).map(|b| u16::from_le_bytes([b[0], b[1]])).collect()), } } } @@ -91,9 +91,9 @@ pub enum PgCharacterClass { FOnewearl, } -impl Into for PgCharacterClass { - fn into(self) -> CharacterClass { - match self { +impl From for CharacterClass { + fn from(other: PgCharacterClass) -> CharacterClass { + match other{ PgCharacterClass::HUmar => CharacterClass::HUmar, PgCharacterClass::HUnewearl => CharacterClass::HUnewearl, PgCharacterClass::HUcast => CharacterClass::HUcast, @@ -144,9 +144,9 @@ pub enum PgSectionId { Whitill, } -impl Into for PgSectionId { - fn into(self) -> SectionID { - match self { +impl From for SectionID { + fn from(other: PgSectionId) -> SectionID { + match other { PgSectionId::Viridia => SectionID::Viridia, PgSectionId::Greenill => SectionID::Greenill, PgSectionId::Skyly => SectionID::Skyly, @@ -220,55 +220,55 @@ pub struct PgCharacter { bank_meseta: i32, } -impl Into for PgCharacter { - fn into(self) -> CharacterEntity { +impl From for CharacterEntity { + fn from(other: PgCharacter) -> CharacterEntity { CharacterEntity { - id: CharacterEntityId(self.id as u32), - user_id: UserAccountId(self.user_account as u32), - slot: self.slot as u32, - name: self.name, - exp: self.exp as u32, - char_class: self.class.parse().unwrap(), - section_id: self.section_id.parse().unwrap(), + id: CharacterEntityId(other.id as u32), + user_id: UserAccountId(other.user_account as u32), + slot: other.slot as u32, + name: other.name, + exp: other.exp as u32, + char_class: other.class.parse().unwrap(), + section_id: other.section_id.parse().unwrap(), appearance: CharacterAppearance { - costume: self.costume as u16, - skin: self.skin as u16, - face: self.face as u16, - head: self.head as u16, - hair: self.hair as u16, - hair_r: self.hair_r as u16, - hair_g: self.hair_g as u16, - hair_b: self.hair_b as u16, - prop_x: self.prop_x, - prop_y: self.prop_y, + costume: other.costume as u16, + skin: other.skin as u16, + face: other.face as u16, + head: other.head as u16, + hair: other.hair as u16, + hair_r: other.hair_r as u16, + hair_g: other.hair_g as u16, + hair_b: other.hair_b as u16, + prop_x: other.prop_x, + prop_y: other.prop_y, }, techs: CharacterTechniques { - techs: self.techs.iter().enumerate().take(19).filter(|(_, t)| **t != 0xFF).map(|(i, t)| (tech::Technique::from_value(i as u8), TechLevel(*t)) ).collect() + techs: other.techs.iter().enumerate().take(19).filter(|(_, t)| **t != 0xFF).map(|(i, t)| (tech::Technique::from_value(i as u8), TechLevel(*t)) ).collect() }, config: CharacterConfig { - raw_data: vec_to_array(self.config) + raw_data: vec_to_array(other.config) }, info_board: CharacterInfoboard { - board: libpso::utf8_to_utf16_array!(self.infoboard, 172), + board: libpso::utf8_to_utf16_array!(other.infoboard, 172), }, guildcard: CharacterGuildCard { - description: self.guildcard, + description: other.guildcard, }, - option_flags: self.option_flags as u32, + option_flags: other.option_flags as u32, materials: CharacterMaterials { - power: self.power as u32, - mind: self.mind as u32, - def: self.def as u32, - evade: self.evade as u32, - luck: self.luck as u32, - hp: self.hp as u32, - tp: self.tp as u32, + power: other.power as u32, + mind: other.mind as u32, + def: other.def as u32, + evade: other.evade as u32, + luck: other.luck as u32, + hp: other.hp as u32, + tp: other.tp as u32, }, tech_menu: CharacterTechMenu { - tech_menu: vec_to_array(self.tech_menu) + tech_menu: vec_to_array(other.tech_menu) }, - meseta: self.meseta as u32, - bank_meseta: self.bank_meseta as u32, + meseta: other.meseta as u32, + bank_meseta: other.bank_meseta as u32, } } } @@ -300,10 +300,10 @@ impl From for PgWeapon { } } -impl Into for PgWeapon { - fn into(self) -> weapon::Weapon { +impl From for weapon::Weapon { + fn from(other: PgWeapon) -> weapon::Weapon { let mut attrs: [Option; 3] = [None; 3]; - for (attr, (atype, value)) in attrs.iter_mut().zip(self.attrs.iter()) { + for (attr, (atype, value)) in attrs.iter_mut().zip(other.attrs.iter()) { *attr = Some(weapon::WeaponAttribute { attr: *atype, value: *value @@ -311,11 +311,11 @@ impl Into for PgWeapon { } weapon::Weapon { - weapon: self.weapon, - special: self.special, - grind: self.grind, + weapon: other.weapon, + special: other.special, + grind: other.grind, attrs: attrs, - tekked: self.tekked, + tekked: other.tekked, } } } @@ -345,13 +345,13 @@ impl From for PgArmor { } } -impl Into for PgArmor { - fn into(self) -> armor::Armor { +impl From for armor::Armor { + fn from(other: PgArmor) -> armor::Armor { armor::Armor { - armor: self.armor, - dfp: self.dfp, - evp: self.evp, - slots: self.slots, + armor: other.armor, + dfp: other.dfp, + evp: other.evp, + slots: other.slots, } } } @@ -373,12 +373,12 @@ impl From for PgShield { } } -impl Into for PgShield { - fn into(self) -> shield::Shield { +impl From for shield::Shield { + fn from(other: PgShield) -> shield::Shield { shield::Shield { - shield: self.shield, - dfp: self.dfp, - evp: self.evp, + shield: other.shield, + dfp: other.dfp, + evp: other.evp, } } } @@ -398,11 +398,11 @@ impl From for PgUnit { } } -impl Into for PgUnit { - fn into(self) -> unit::Unit { +impl From for unit::Unit { + fn from(other: PgUnit) -> unit::Unit { unit::Unit { - unit: self.unit, - modifier: self.modifier, + unit: other.unit, + modifier: other.modifier, } } } @@ -420,10 +420,10 @@ impl From for PgTool { } } -impl Into for PgTool { - fn into(self) -> tool::Tool { +impl From for tool::Tool { + fn from(other: PgTool) -> tool::Tool { tool::Tool { - tool: self.tool, + tool: other.tool, } } } @@ -443,11 +443,11 @@ impl From for PgTechDisk { } } -impl Into for PgTechDisk { - fn into(self) -> tech::TechniqueDisk { +impl From for tech::TechniqueDisk { + fn from(other: PgTechDisk) -> tech::TechniqueDisk { tech::TechniqueDisk { - tech: self.tech, - level: self.level + tech: other.tech, + level: other.level } } } @@ -469,8 +469,8 @@ impl From for PgMag { } } -impl Into for PgMag { - fn into(self) -> mag::Mag { +impl From for mag::Mag { + fn from(other: PgMag) -> mag::Mag { /*mag::Mag { mag: self.mag, synchro: self.synchro, @@ -484,9 +484,9 @@ impl Into for PgMag { class: CharacterClass::HUmar, id: SectionID::Viridia, }*/ - let mut mag = mag::Mag::baby_mag(self.color as u16); - mag.mag = self.mag; - mag.synchro = self.synchro; + let mut mag = mag::Mag::baby_mag(other.color as u16); + mag.mag = other.mag; + mag.synchro = other.synchro; mag } } @@ -510,13 +510,13 @@ impl From for PgESWeapon { } } -impl Into for PgESWeapon { - fn into(self) -> esweapon::ESWeapon { +impl From for esweapon::ESWeapon { + fn from(other: PgESWeapon) -> esweapon::ESWeapon { esweapon::ESWeapon { - esweapon: self.esweapon, - special: self.special, - name: self.name, - grind: self.grind, + esweapon: other.esweapon, + special: other.special, + name: other.name, + grind: other.grind, } } } @@ -548,9 +548,9 @@ impl From for PgItemDetail { } } -impl Into for PgItemDetail { - fn into(self) -> ItemDetail { - match self { +impl From for ItemDetail { + fn from(other: PgItemDetail) -> ItemDetail { + match other { PgItemDetail::Weapon(weapon) => ItemDetail::Weapon(weapon.into()), PgItemDetail::Armor(armor) => ItemDetail::Armor(armor.into()), PgItemDetail::Shield(shield) => ItemDetail::Shield(shield.into()), @@ -613,9 +613,9 @@ impl From for PgItemLocationDetail { } } -impl Into for PgItemLocationDetail { - fn into(self) -> ItemLocation { - match self { +impl From for ItemLocation { + fn from(other: PgItemLocationDetail) -> ItemLocation { + match other{ PgItemLocationDetail::Inventory{character_id} => ItemLocation::Inventory{character_id: CharacterEntityId(character_id)}, PgItemLocationDetail::Bank{character_id, name} => ItemLocation::Bank{character_id: CharacterEntityId(character_id), name: BankName(name)}, PgItemLocationDetail::LocalFloor{character_id, map_area, x,y,z} => ItemLocation::LocalFloor{character_id: CharacterEntityId(character_id), map_area, x,y,z}, @@ -655,9 +655,9 @@ impl From for PgMagModifierDetail { } } -impl Into for PgMagModifierDetail { - fn into(self) -> mag::MagModifier { - match self { +impl From for mag::MagModifier { + fn from(other: PgMagModifierDetail) -> mag::MagModifier { + match other { PgMagModifierDetail::FeedMag(food) => mag::MagModifier::FeedMag{food: ItemEntityId(food as u32)}, PgMagModifierDetail::BankMag => mag::MagModifier::BankMag, PgMagModifierDetail::MagCell(cell) => mag::MagModifier::MagCell(ItemEntityId(cell as u32)), @@ -687,12 +687,12 @@ pub struct PgItemWithLocation { pub location: sqlx::types::Json, } -impl Into for PgItemWithLocation { - fn into(self) -> ItemEntity { +impl From for ItemEntity { + fn from(other: PgItemWithLocation) -> ItemEntity { ItemEntity { - id: ItemEntityId(self.id as u32), - item: self.item.0.into(), - location: self.location.0.into(), + id: ItemEntityId(other.id as u32), + item: other.item.0.into(), + location: other.location.0.into(), } } } @@ -740,18 +740,18 @@ pub struct PgEquipped { mag: Option, } -impl Into for PgEquipped { - fn into(self) -> EquippedEntity { +impl From for EquippedEntity{ + fn from(other: PgEquipped) -> EquippedEntity { EquippedEntity { - weapon: self.weapon.map(|i| ItemEntityId(i as u32)), - armor: self.armor.map(|i| ItemEntityId(i as u32)), - shield: self.shield.map(|i| ItemEntityId(i as u32)), - unit: [self.unit0.map(|i| ItemEntityId(i as u32)), - self.unit1.map(|i| ItemEntityId(i as u32)), - self.unit2.map(|i| ItemEntityId(i as u32)), - self.unit3.map(|i| ItemEntityId(i as u32)), + weapon: other.weapon.map(|i| ItemEntityId(i as u32)), + armor: other.armor.map(|i| ItemEntityId(i as u32)), + shield: other.shield.map(|i| ItemEntityId(i as u32)), + unit: [other.unit0.map(|i| ItemEntityId(i as u32)), + other.unit1.map(|i| ItemEntityId(i as u32)), + other.unit2.map(|i| ItemEntityId(i as u32)), + other.unit3.map(|i| ItemEntityId(i as u32)), ], - mag: self.mag.map(|i| ItemEntityId(i as u32)), + mag: other.mag.map(|i| ItemEntityId(i as u32)), } } } diff --git a/src/entity/gateway/postgres/postgres.rs b/src/entity/gateway/postgres/postgres.rs index 4d7a36e..1856fda 100644 --- a/src/entity/gateway/postgres/postgres.rs +++ b/src/entity/gateway/postgres/postgres.rs @@ -25,10 +25,10 @@ pub struct PostgresGateway { impl PostgresGateway { pub fn new(host: &str, dbname: &str, username: &str, password: &str) -> PostgresGateway { let mut conn = refinery::config::Config::new(refinery::config::ConfigDbType::Postgres) - .set_db_host(&host) - .set_db_user(&username) - .set_db_pass(&password) - .set_db_name(&dbname); + .set_db_host(host) + .set_db_user(username) + .set_db_pass(password) + .set_db_name(dbname); embedded::migrations::runner().run(&mut conn).unwrap(); let pool = async_std::task::block_on(async move { diff --git a/src/login/character.rs b/src/login/character.rs index a268d1c..9e05d26 100644 --- a/src/login/character.rs +++ b/src/login/character.rs @@ -858,7 +858,7 @@ mod test { #[async_std::test] async fn test_character_create() { - let test_data = InMemoryGateway::new(); + let test_data = InMemoryGateway::default(); let mut fake_user = ClientState::new(); fake_user.user = Some(UserAccountEntity { id: UserAccountId(3), diff --git a/tests/test_bank.rs b/tests/test_bank.rs index 486e9d0..2c1be0e 100644 --- a/tests/test_bank.rs +++ b/tests/test_bank.rs @@ -13,7 +13,7 @@ use common::*; #[async_std::test] async fn test_bank_items_sent_in_character_login() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, char1) = new_user_character(&mut entity_gateway, "a1", "a").await; let (_user2, _char2) = new_user_character(&mut entity_gateway, "a2", "a").await; @@ -52,7 +52,7 @@ async fn test_bank_items_sent_in_character_login() { #[async_std::test] async fn test_request_bank_items() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, char1) = new_user_character(&mut entity_gateway, "a1", "a").await; let (_user2, _char2) = new_user_character(&mut entity_gateway, "a2", "a").await; @@ -104,7 +104,7 @@ async fn test_request_bank_items() { #[async_std::test] async fn test_request_stacked_bank_items() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, char1) = new_user_character(&mut entity_gateway, "a1", "a").await; let (_user2, _char2) = new_user_character(&mut entity_gateway, "a2", "a").await; @@ -151,7 +151,7 @@ async fn test_request_stacked_bank_items() { #[async_std::test] async fn test_request_bank_items_sorted() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, char1) = new_user_character(&mut entity_gateway, "a1", "a").await; let (_user2, _char2) = new_user_character(&mut entity_gateway, "a2", "a").await; @@ -229,7 +229,7 @@ async fn test_request_bank_items_sorted() { #[async_std::test] async fn test_deposit_individual_item() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, char1) = new_user_character(&mut entity_gateway, "a1", "a").await; let (_user2, _char2) = new_user_character(&mut entity_gateway, "a2", "a").await; @@ -308,7 +308,7 @@ async fn test_deposit_individual_item() { #[async_std::test] async fn test_deposit_stacked_item() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, char1) = new_user_character(&mut entity_gateway, "a1", "a").await; let (_user2, _char2) = new_user_character(&mut entity_gateway, "a2", "a").await; @@ -372,7 +372,7 @@ async fn test_deposit_stacked_item() { #[async_std::test] async fn test_deposit_partial_stacked_item() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, char1) = new_user_character(&mut entity_gateway, "a1", "a").await; let (_user2, _char2) = new_user_character(&mut entity_gateway, "a2", "a").await; @@ -445,7 +445,7 @@ async fn test_deposit_partial_stacked_item() { #[async_std::test] async fn test_deposit_stacked_item_with_stack_already_in_bank() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, char1) = new_user_character(&mut entity_gateway, "a1", "a").await; let (_user2, _char2) = new_user_character(&mut entity_gateway, "a2", "a").await; @@ -524,7 +524,7 @@ async fn test_deposit_stacked_item_with_stack_already_in_bank() { #[async_std::test] async fn test_deposit_stacked_item_with_full_stack_in_bank() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, char1) = new_user_character(&mut entity_gateway, "a1", "a").await; @@ -603,7 +603,7 @@ async fn test_deposit_stacked_item_with_full_stack_in_bank() { #[async_std::test] async fn test_deposit_individual_item_in_full_bank() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, char1) = new_user_character(&mut entity_gateway, "a1", "a").await; @@ -684,7 +684,7 @@ async fn test_deposit_individual_item_in_full_bank() { #[async_std::test] async fn test_deposit_stacked_item_in_full_bank() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, char1) = new_user_character(&mut entity_gateway, "a1", "a").await; @@ -764,7 +764,7 @@ async fn test_deposit_stacked_item_in_full_bank() { #[async_std::test] async fn test_deposit_stacked_item_in_full_bank_with_partial_stack() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, char1) = new_user_character(&mut entity_gateway, "a1", "a").await; @@ -858,7 +858,7 @@ async fn test_deposit_stacked_item_in_full_bank_with_partial_stack() { #[async_std::test] async fn test_deposit_meseta() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (user1, mut char1) = new_user_character(&mut entity_gateway, "a1", "a").await; char1.meseta = 300; @@ -895,7 +895,7 @@ async fn test_deposit_meseta() { #[async_std::test] async fn test_deposit_too_much_meseta() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (user1, mut char1) = new_user_character(&mut entity_gateway, "a1", "a").await; char1.meseta = 300; @@ -934,7 +934,7 @@ async fn test_deposit_too_much_meseta() { #[async_std::test] async fn test_deposit_meseta_when_bank_is_maxed() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (user1, mut char1) = new_user_character(&mut entity_gateway, "a1", "a").await; char1.meseta = 300; @@ -973,7 +973,7 @@ async fn test_deposit_meseta_when_bank_is_maxed() { #[async_std::test] async fn test_withdraw_individual_item() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, char1) = new_user_character(&mut entity_gateway, "a1", "a").await; let (_user2, _char2) = new_user_character(&mut entity_gateway, "a2", "a").await; @@ -1039,7 +1039,7 @@ async fn test_withdraw_individual_item() { #[async_std::test] async fn test_withdraw_stacked_item() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, char1) = new_user_character(&mut entity_gateway, "a1", "a").await; let (_user2, _char2) = new_user_character(&mut entity_gateway, "a2", "a").await; @@ -1103,7 +1103,7 @@ async fn test_withdraw_stacked_item() { #[async_std::test] async fn test_withdraw_partial_stacked_item() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, char1) = new_user_character(&mut entity_gateway, "a1", "a").await; let (_user2, _char2) = new_user_character(&mut entity_gateway, "a2", "a").await; @@ -1173,7 +1173,7 @@ async fn test_withdraw_partial_stacked_item() { #[async_std::test] async fn test_withdraw_stacked_item_with_stack_already_in_inventory() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, char1) = new_user_character(&mut entity_gateway, "a1", "a").await; let (_user2, _char2) = new_user_character(&mut entity_gateway, "a2", "a").await; @@ -1254,7 +1254,7 @@ async fn test_withdraw_stacked_item_with_stack_already_in_inventory() { #[async_std::test] async fn test_withdraw_stacked_item_with_full_stack_in_inventory() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, char1) = new_user_character(&mut entity_gateway, "a1", "a").await; @@ -1333,7 +1333,7 @@ async fn test_withdraw_stacked_item_with_full_stack_in_inventory() { #[async_std::test] async fn test_withdraw_individual_item_in_full_inventory() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, char1) = new_user_character(&mut entity_gateway, "a1", "a").await; @@ -1410,7 +1410,7 @@ async fn test_withdraw_individual_item_in_full_inventory() { #[async_std::test] async fn test_withdraw_stacked_item_in_full_inventory() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, char1) = new_user_character(&mut entity_gateway, "a1", "a").await; @@ -1491,7 +1491,7 @@ async fn test_withdraw_stacked_item_in_full_inventory() { #[async_std::test] async fn test_withdraw_stacked_item_in_full_inventory_with_partial_stack() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, char1) = new_user_character(&mut entity_gateway, "a1", "a").await; @@ -1587,7 +1587,7 @@ async fn test_withdraw_stacked_item_in_full_inventory_with_partial_stack() { #[async_std::test] async fn test_withdraw_meseta() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (user1, mut char1) = new_user_character(&mut entity_gateway, "a1", "a").await; char1.bank_meseta = 300; @@ -1624,7 +1624,7 @@ async fn test_withdraw_meseta() { #[async_std::test] async fn test_withdraw_too_much_meseta() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (user1, mut char1) = new_user_character(&mut entity_gateway, "a1", "a").await; char1.meseta = 999980; @@ -1662,7 +1662,7 @@ async fn test_withdraw_too_much_meseta() { #[async_std::test] async fn test_withdraw_meseta_inventory_is_maxed() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (user1, mut char1) = new_user_character(&mut entity_gateway, "a1", "a").await; char1.meseta = 999999; diff --git a/tests/test_character.rs b/tests/test_character.rs index ba35270..f46fa67 100644 --- a/tests/test_character.rs +++ b/tests/test_character.rs @@ -10,7 +10,7 @@ use common::*; #[async_std::test] async fn test_save_options() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (user1, _char1) = new_user_character(&mut entity_gateway, "a1", "a").await; diff --git a/tests/test_exp_gain.rs b/tests/test_exp_gain.rs index fde9930..6d3e8b3 100644 --- a/tests/test_exp_gain.rs +++ b/tests/test_exp_gain.rs @@ -13,7 +13,7 @@ use common::*; #[async_std::test] async fn test_character_gains_exp() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, _char1) = new_user_character(&mut entity_gateway, "a1", "a").await; @@ -50,7 +50,7 @@ async fn test_character_gains_exp() { #[async_std::test] async fn test_character_levels_up() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, mut char1) = new_user_character(&mut entity_gateway, "a1", "a").await; char1.exp = 49; @@ -90,7 +90,7 @@ async fn test_character_levels_up() { #[async_std::test] async fn test_character_levels_up_multiple_times() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, _char1) = new_user_character(&mut entity_gateway, "a1", "a").await; @@ -134,7 +134,7 @@ async fn test_character_levels_up_multiple_times() { #[async_std::test] async fn test_one_character_gets_full_exp_and_other_attacker_gets_partial() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, _char1) = new_user_character(&mut entity_gateway, "a1", "a").await; let (_user2, _char2) = new_user_character(&mut entity_gateway, "a2", "a").await; diff --git a/tests/test_item_actions.rs b/tests/test_item_actions.rs index 1cbaf6d..fa27041 100644 --- a/tests/test_item_actions.rs +++ b/tests/test_item_actions.rs @@ -12,7 +12,7 @@ use common::*; #[async_std::test] async fn test_equip_unit_from_equip_menu() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, char1) = new_user_character(&mut entity_gateway, "a1", "a").await; @@ -98,7 +98,7 @@ async fn test_equip_unit_from_equip_menu() { #[async_std::test] async fn test_unequip_armor_with_units() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, char1) = new_user_character(&mut entity_gateway, "a1", "a").await; @@ -175,7 +175,7 @@ async fn test_unequip_armor_with_units() { #[async_std::test] async fn test_sort_items() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, char1) = new_user_character(&mut entity_gateway, "a1", "a").await; diff --git a/tests/test_item_pickup.rs b/tests/test_item_pickup.rs index bfac7b9..e54f0ec 100644 --- a/tests/test_item_pickup.rs +++ b/tests/test_item_pickup.rs @@ -12,7 +12,7 @@ use common::*; #[async_std::test] async fn test_pick_up_item_stack_of_items_already_in_inventory() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, char1) = new_user_character(&mut entity_gateway, "a1", "a").await; let (_user2, char2) = new_user_character(&mut entity_gateway, "a2", "a").await; @@ -94,7 +94,7 @@ async fn test_pick_up_item_stack_of_items_already_in_inventory() { #[async_std::test] async fn test_pick_up_item_stack_of_items_not_already_held() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, char1) = new_user_character(&mut entity_gateway, "a1", "a").await; let (_user2, char2) = new_user_character(&mut entity_gateway, "a2", "a").await; @@ -156,7 +156,7 @@ async fn test_pick_up_item_stack_of_items_not_already_held() { #[async_std::test] async fn test_pick_up_meseta_when_inventory_full() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (user1, char1) = new_user_character(&mut entity_gateway, "a1", "a").await; let (user2, mut char2) = new_user_character(&mut entity_gateway, "a2", "a").await; @@ -235,7 +235,7 @@ async fn test_pick_up_meseta_when_inventory_full() { #[async_std::test] async fn test_pick_up_partial_stacked_item_when_inventory_is_otherwise_full() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, char1) = new_user_character(&mut entity_gateway, "a1", "a").await; let (_user2, char2) = new_user_character(&mut entity_gateway, "a2", "a").await; @@ -327,7 +327,7 @@ async fn test_pick_up_partial_stacked_item_when_inventory_is_otherwise_full() { #[async_std::test] async fn test_can_not_pick_up_item_when_inventory_full() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, char1) = new_user_character(&mut entity_gateway, "a1", "a").await; let (_user2, char2) = new_user_character(&mut entity_gateway, "a2", "a").await; @@ -423,7 +423,7 @@ async fn test_can_not_pick_up_item_when_inventory_full() { #[async_std::test] async fn test_can_not_drop_more_meseta_than_is_held() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (user1, mut char1) = new_user_character(&mut entity_gateway, "a1", "a").await; @@ -464,7 +464,7 @@ async fn test_can_not_drop_more_meseta_than_is_held() { #[async_std::test] async fn test_pick_up_stack_that_would_exceed_stack_limit() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, char1) = new_user_character(&mut entity_gateway, "a1", "a").await; let (_user2, char2) = new_user_character(&mut entity_gateway, "a2", "a").await; @@ -544,7 +544,7 @@ async fn test_pick_up_stack_that_would_exceed_stack_limit() { #[async_std::test] async fn test_can_not_pick_up_meseta_when_full() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (user1, mut char1) = new_user_character(&mut entity_gateway, "a1", "a").await; let (user2, mut char2) = new_user_character(&mut entity_gateway, "a2", "a").await; @@ -602,7 +602,7 @@ async fn test_can_not_pick_up_meseta_when_full() { #[async_std::test] async fn test_meseta_caps_at_999999_when_trying_to_pick_up_more() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (user1, mut char1) = new_user_character(&mut entity_gateway, "a1", "a").await; let (user2, mut char2) = new_user_character(&mut entity_gateway, "a2", "a").await; @@ -659,7 +659,7 @@ async fn test_meseta_caps_at_999999_when_trying_to_pick_up_more() { #[async_std::test] async fn test_player_drops_partial_stack_and_other_player_picks_it_up() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, char1) = new_user_character(&mut entity_gateway, "a1", "a").await; let (_user2, char2) = new_user_character(&mut entity_gateway, "a2", "a").await; diff --git a/tests/test_item_use.rs b/tests/test_item_use.rs index 03cb935..ba28e19 100644 --- a/tests/test_item_use.rs +++ b/tests/test_item_use.rs @@ -14,7 +14,7 @@ use common::*; #[async_std::test] async fn test_use_monomate() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, char1) = new_user_character(&mut entity_gateway, "a1", "a").await; @@ -64,7 +64,7 @@ async fn test_use_monomate() { #[async_std::test] async fn test_use_monomate_twice() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, char1) = new_user_character(&mut entity_gateway, "a1", "a").await; @@ -119,7 +119,7 @@ async fn test_use_monomate_twice() { #[async_std::test] async fn test_use_last_monomate() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, char1) = new_user_character(&mut entity_gateway, "a1", "a").await; @@ -164,7 +164,7 @@ async fn test_use_last_monomate() { #[async_std::test] async fn test_use_nonstackable_tool() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, char1) = new_user_character(&mut entity_gateway, "a1", "a").await; @@ -202,7 +202,7 @@ async fn test_use_nonstackable_tool() { #[async_std::test] async fn test_use_materials() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (user1, char1) = new_user_character(&mut entity_gateway, "a1", "a").await; @@ -282,4 +282,4 @@ pub async fn test_char_cannot_learn_wrong_tech() {} pub async fn test_char_cannot_learn_high_level_tech() {} #[async_std::test] -pub async fn test_android_cannot_learn_tech() {} \ No newline at end of file +pub async fn test_android_cannot_learn_tech() {} diff --git a/tests/test_mags.rs b/tests/test_mags.rs index 51675cf..268833d 100644 --- a/tests/test_mags.rs +++ b/tests/test_mags.rs @@ -13,7 +13,7 @@ use common::*; #[async_std::test] async fn test_mag_feed() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, char1) = new_user_character(&mut entity_gateway, "a1", "a").await; @@ -92,7 +92,7 @@ async fn test_mag_feed() { #[async_std::test] async fn test_mag_change_owner() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, mut char1) = new_user_character(&mut entity_gateway, "a1", "a").await; let (_user2, mut char2) = new_user_character(&mut entity_gateway, "a2", "a").await; @@ -160,7 +160,7 @@ async fn test_mag_change_owner() { #[async_std::test] async fn test_mag_cell() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, char1) = new_user_character(&mut entity_gateway, "a1", "a").await; diff --git a/tests/test_rooms.rs b/tests/test_rooms.rs index a641cbd..45f8ace 100644 --- a/tests/test_rooms.rs +++ b/tests/test_rooms.rs @@ -13,7 +13,7 @@ use common::*; #[async_std::test] async fn test_item_ids_reset_when_rejoining_rooms() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, char1) = new_user_character(&mut entity_gateway, "a1", "a").await; let (_user2, char2) = new_user_character(&mut entity_gateway, "a2", "a").await; diff --git a/tests/test_shops.rs b/tests/test_shops.rs index 79aa438..ade8ccf 100644 --- a/tests/test_shops.rs +++ b/tests/test_shops.rs @@ -13,7 +13,7 @@ use common::*; #[async_std::test] async fn test_player_opens_weapon_shop() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, mut char1) = new_user_character(&mut entity_gateway, "a1", "a").await; char1.exp = 80000000; @@ -43,7 +43,7 @@ async fn test_player_opens_weapon_shop() { #[async_std::test] async fn test_player_opens_tool_shop() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, mut char1) = new_user_character(&mut entity_gateway, "a1", "a").await; char1.exp = 80000000; @@ -73,7 +73,7 @@ async fn test_player_opens_tool_shop() { #[async_std::test] async fn test_player_opens_armor_shop() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, mut char1) = new_user_character(&mut entity_gateway, "a1", "a").await; char1.exp = 80000000; @@ -103,7 +103,7 @@ async fn test_player_opens_armor_shop() { #[async_std::test] async fn test_player_buys_from_weapon_shop() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (user1, mut char1) = new_user_character(&mut entity_gateway, "a1", "a").await; char1.exp = 80000000; @@ -142,7 +142,7 @@ async fn test_player_buys_from_weapon_shop() { #[async_std::test] async fn test_player_buys_from_tool_shop() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (user1, mut char1) = new_user_character(&mut entity_gateway, "a1", "a").await; char1.exp = 80000000; @@ -180,7 +180,7 @@ async fn test_player_buys_from_tool_shop() { #[async_std::test] async fn test_player_buys_multiple_from_tool_shop() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (user1, mut char1) = new_user_character(&mut entity_gateway, "a1", "a").await; char1.exp = 80000000; @@ -222,7 +222,7 @@ async fn test_player_buys_multiple_from_tool_shop() { #[async_std::test] async fn test_player_buys_from_armor_shop() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (user1, mut char1) = new_user_character(&mut entity_gateway, "a1", "a").await; char1.exp = 80000000; @@ -264,7 +264,7 @@ async fn test_player_sells_to_shop() { #[async_std::test] async fn test_other_clients_see_purchase() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, mut char1) = new_user_character(&mut entity_gateway, "a1", "a").await; let (_user2, _char2) = new_user_character(&mut entity_gateway, "a2", "a").await; @@ -307,7 +307,7 @@ async fn test_other_clients_see_purchase() { #[async_std::test] async fn test_other_clients_see_stacked_purchase() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, mut char1) = new_user_character(&mut entity_gateway, "a1", "a").await; let (_user2, _char2) = new_user_character(&mut entity_gateway, "a2", "a").await; @@ -361,7 +361,7 @@ async fn test_other_clients_see_stacked_purchase() { #[async_std::test] async fn test_buying_item_without_enough_mseseta() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (user1, char1) = new_user_character(&mut entity_gateway, "a1", "a").await; @@ -397,7 +397,7 @@ async fn test_buying_item_without_enough_mseseta() { #[async_std::test] async fn test_player_double_buys_from_tool_shop() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (user1, mut char1) = new_user_character(&mut entity_gateway, "a1", "a").await; char1.exp = 80000000; @@ -463,7 +463,7 @@ async fn test_player_double_buys_from_tool_shop() { #[async_std::test] async fn test_techs_disappear_from_shop_when_bought() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, mut char1) = new_user_character(&mut entity_gateway, "a1", "a").await; char1.exp = 80000000; @@ -525,7 +525,7 @@ async fn test_techs_disappear_from_shop_when_bought() { // TOOD: this is not deterministic and can randomly fail #[async_std::test] async fn test_units_disappear_from_shop_when_bought() { - let mut entity_gateway = InMemoryGateway::new(); + let mut entity_gateway = InMemoryGateway::default(); let (_user1, mut char1) = new_user_character(&mut entity_gateway, "a1", "a").await; char1.exp = 80000000; From 4ce7fb2a266f360825e4ab94802adccc2b81a619 Mon Sep 17 00:00:00 2001 From: jake Date: Fri, 18 Jun 2021 20:01:05 -0600 Subject: [PATCH 20/25] lint src/common/* --- src/common/leveltable.rs | 13 +++++++------ src/common/mainloop/client.rs | 2 +- src/common/mainloop/interserver.rs | 2 +- src/common/mainloop/mod.rs | 2 +- src/login/character.rs | 2 +- src/ship/ship.rs | 2 +- tests/test_exp_gain.rs | 2 +- 7 files changed, 13 insertions(+), 12 deletions(-) diff --git a/src/common/leveltable.rs b/src/common/leveltable.rs index 9d9f4c0..d60d1fe 100644 --- a/src/common/leveltable.rs +++ b/src/common/leveltable.rs @@ -30,9 +30,8 @@ pub struct CharacterLevelTable { table: HashMap, } - -impl CharacterLevelTable { - pub fn new() -> CharacterLevelTable { +impl Default for CharacterLevelTable { + fn default() -> CharacterLevelTable { let file = File::open("data/char_stats.json").unwrap(); let json: Value = serde_json::from_reader(file).unwrap(); let mut table = HashMap::new(); @@ -55,7 +54,7 @@ impl CharacterLevelTable { }; let mut statlist = [CharacterLevelEntry::default(); 200]; - for (i, stat) in it.1.as_array().unwrap().into_iter().enumerate() { + for (i, stat) in it.1.as_array().unwrap().iter().enumerate() { statlist[i] = CharacterLevelEntry { hp: stat["hp"].as_i64().unwrap() as u32, atp: stat["atp"].as_i64().unwrap() as u32, @@ -75,7 +74,9 @@ impl CharacterLevelTable { table: table, } } +} +impl CharacterLevelTable { pub fn get_level_from_exp(&self, ch_class: CharacterClass, exp: u32) -> u32 { if let Some(statlist) = self.table.get(&ch_class) { statlist @@ -120,14 +121,14 @@ mod test { use super::*; #[test] fn test_stat_levels() { - let table = CharacterLevelTable::new(); + let table = CharacterLevelTable::default(); assert!(table.get_stats_from_exp(CharacterClass::FOmarl, 0) == (1, CharacterStats { hp: 20, atp: 13, mst: 53, evp: 35, dfp: 10, ata: 15, lck: 10 })); assert!(table.get_stats_from_exp(CharacterClass::FOmarl, 1 << 17) == (36, CharacterStats { hp: 125, atp: 114, mst: 219, evp: 182, dfp: 42, ata: 213, lck: 10 })); } #[test] fn test_levels() { - let table = CharacterLevelTable::new(); + let table = CharacterLevelTable::default(); assert!(table.get_level_from_exp(CharacterClass::FOmarl, 0) == 1); assert!(table.get_level_from_exp(CharacterClass::FOmarl, 3000) == 8); assert!(table.get_level_from_exp(CharacterClass::FOmarl, 3200) == 9); diff --git a/src/common/mainloop/client.rs b/src/common/mainloop/client.rs index c13acbf..1bfc1ce 100644 --- a/src/common/mainloop/client.rs +++ b/src/common/mainloop/client.rs @@ -65,7 +65,7 @@ impl PacketReceiver { return Err(NetworkError::ClientDisconnected); } - self.recv_buffer.extend_from_slice(&mut data[..len]); + self.recv_buffer.extend_from_slice(&data[..len]); let mut dec_buf = { let mut cipher = self.cipher.lock().await; diff --git a/src/common/mainloop/interserver.rs b/src/common/mainloop/interserver.rs index 473abb4..cc6cce2 100644 --- a/src/common/mainloop/interserver.rs +++ b/src/common/mainloop/interserver.rs @@ -163,7 +163,7 @@ where warn!("interserver send failed: {:?}", err); break; } - if let Err(err) = socket.write_all(&payload.as_bytes()).await { + if let Err(err) = socket.write_all(payload.as_bytes()).await { warn!("intserserver send failed: {:?}", err); break; } diff --git a/src/common/mainloop/mod.rs b/src/common/mainloop/mod.rs index b0e207b..2a5b3ff 100644 --- a/src/common/mainloop/mod.rs +++ b/src/common/mainloop/mod.rs @@ -25,7 +25,7 @@ pub fn patch_mainloop(patch_state: PatchServerState, patch_port: u16) -> Pin(login_state: LoginServerState, login_port: u16) -> Pin>> { let login_state = Arc::new(Mutex::new(login_state)); - let client_mainloop = client_accept_mainloop(login_state.clone(), login_port); + let client_mainloop = client_accept_mainloop(login_state, login_port); Box::pin(client_mainloop) } diff --git a/src/login/character.rs b/src/login/character.rs index 9e05d26..6867189 100644 --- a/src/login/character.rs +++ b/src/login/character.rs @@ -306,7 +306,7 @@ impl CharacterServerState { param_data: param_data, clients: HashMap::new(), ships: BTreeMap::new(), - level_table: CharacterLevelTable::new(), + level_table: CharacterLevelTable::default(), auth_token: auth_token, authenticated_ships: BTreeSet::new(), ship_sender: BTreeMap::new(), diff --git a/src/ship/ship.rs b/src/ship/ship.rs index 6206440..8091647 100644 --- a/src/ship/ship.rs +++ b/src/ship/ship.rs @@ -367,7 +367,7 @@ impl ShipServerStateBuilder { ShipServerState { entity_gateway: self.entity_gateway.unwrap(), clients: HashMap::new(), - level_table: CharacterLevelTable::new(), + level_table: CharacterLevelTable::default(), name: self.name.unwrap_or_else(|| "NAMENOTSET".into()), item_manager: items::ItemManager::default(), quests: quests::load_quests("data/quests.toml".into()).unwrap(), diff --git a/tests/test_exp_gain.rs b/tests/test_exp_gain.rs index 6d3e8b3..2223c8e 100644 --- a/tests/test_exp_gain.rs +++ b/tests/test_exp_gain.rs @@ -83,7 +83,7 @@ async fn test_character_levels_up() { assert!(matches!(levelup_pkt[1].1, SendShipPacket::Message(Message {msg: GameMessage::PlayerLevelUp(PlayerLevelUp {lvl: 2, ..})}))); - let leveltable = CharacterLevelTable::new(); + let leveltable = CharacterLevelTable::default(); let c1 = ship.clients.get(&ClientId(1)).unwrap(); assert!(leveltable.get_level_from_exp(c1.character.char_class, c1.character.exp) == 2); } From 1b506e014f79921a8893e55b6fd2d0491ae14e5f Mon Sep 17 00:00:00 2001 From: jake Date: Fri, 18 Jun 2021 20:38:29 -0600 Subject: [PATCH 21/25] clean up last of normal warnings --- src/common/leveltable.rs | 2 +- src/common/mainloop/client.rs | 4 +-- src/common/mainloop/interserver.rs | 2 +- src/entity/account.rs | 6 ++-- src/entity/gateway/postgres/models.rs | 2 +- src/entity/gateway/postgres/postgres.rs | 11 +++--- src/entity/item/esweapon.rs | 6 ++-- src/entity/item/mag.rs | 8 ++--- src/entity/item/weapon.rs | 38 ++++++++++----------- src/login/character.rs | 14 ++++---- src/login/login.rs | 4 +-- src/patch/patch.rs | 12 +++---- src/ship/character.rs | 4 +-- src/ship/drops/generic_weapon.rs | 10 +++--- src/ship/drops/rare_drop_table.rs | 12 +++---- src/ship/items/bank.rs | 8 ++--- src/ship/items/floor.rs | 4 +-- src/ship/items/inventory.rs | 18 +++++----- src/ship/items/manager.rs | 45 ++++++++++++------------- src/ship/map/enemy.rs | 6 ++-- src/ship/map/maps.rs | 2 +- src/ship/map/object.rs | 2 +- src/ship/map/variant.rs | 16 ++++----- src/ship/packet/builder/message.rs | 12 +++---- src/ship/packet/builder/mod.rs | 4 +-- src/ship/packet/builder/quest.rs | 6 ++-- src/ship/packet/builder/room.rs | 2 +- src/ship/packet/builder/ship.rs | 9 ----- src/ship/packet/handler/auth.rs | 2 +- src/ship/packet/handler/message.rs | 3 +- src/ship/quests.rs | 16 ++++----- src/ship/room.rs | 2 +- src/ship/shops/tool.rs | 2 +- src/ship/shops/weapon.rs | 14 ++++---- 34 files changed, 146 insertions(+), 162 deletions(-) diff --git a/src/common/leveltable.rs b/src/common/leveltable.rs index d60d1fe..94ad8ae 100644 --- a/src/common/leveltable.rs +++ b/src/common/leveltable.rs @@ -71,7 +71,7 @@ impl Default for CharacterLevelTable { } CharacterLevelTable { - table: table, + table, } } } diff --git a/src/common/mainloop/client.rs b/src/common/mainloop/client.rs index 1bfc1ce..32562e9 100644 --- a/src/common/mainloop/client.rs +++ b/src/common/mainloop/client.rs @@ -49,8 +49,8 @@ struct PacketReceiver { impl PacketReceiver { fn new(socket: Arc, cipher: Arc>>) -> PacketReceiver { PacketReceiver { - socket: socket, - cipher: cipher, + socket, + cipher, recv_buffer: Vec::new(), incoming_data: Vec::new(), } diff --git a/src/common/mainloop/interserver.rs b/src/common/mainloop/interserver.rs index cc6cce2..3547f8b 100644 --- a/src/common/mainloop/interserver.rs +++ b/src/common/mainloop/interserver.rs @@ -29,7 +29,7 @@ struct MessageReceiver { impl MessageReceiver { fn new(socket: async_std::net::TcpStream) -> MessageReceiver { MessageReceiver { - socket: socket, + socket, } } diff --git a/src/entity/account.rs b/src/entity/account.rs index 0ab4452..9223797 100644 --- a/src/entity/account.rs +++ b/src/entity/account.rs @@ -75,7 +75,7 @@ pub struct NewUserSettingsEntity { impl NewUserSettingsEntity { pub fn new(user_id: UserAccountId) -> NewUserSettingsEntity { NewUserSettingsEntity { - user_id: user_id, + user_id, settings: settings::UserSettings::default(), } } @@ -98,7 +98,7 @@ pub struct NewGuildCardDataEntity { impl NewGuildCardDataEntity { pub fn new(user_id: UserAccountId) -> NewGuildCardDataEntity { NewGuildCardDataEntity { - user_id: user_id, + user_id, guildcard: guildcard::GuildCardData::default(), } } @@ -116,7 +116,7 @@ impl GuildCardDataEntity { pub fn new(user_id: UserAccountId) -> GuildCardDataEntity { GuildCardDataEntity { id: GuildCardDataId(0), - user_id: user_id, + user_id, guildcard: guildcard::GuildCardData::default(), } } diff --git a/src/entity/gateway/postgres/models.rs b/src/entity/gateway/postgres/models.rs index f33f399..02bd750 100644 --- a/src/entity/gateway/postgres/models.rs +++ b/src/entity/gateway/postgres/models.rs @@ -314,7 +314,7 @@ impl From for weapon::Weapon { weapon: other.weapon, special: other.special, grind: other.grind, - attrs: attrs, + attrs, tekked: other.tekked, } } diff --git a/src/entity/gateway/postgres/postgres.rs b/src/entity/gateway/postgres/postgres.rs index 1856fda..53609cf 100644 --- a/src/entity/gateway/postgres/postgres.rs +++ b/src/entity/gateway/postgres/postgres.rs @@ -1,5 +1,4 @@ use std::convert::{From, TryFrom, Into}; -use futures::future::join_all; use futures::TryStreamExt; use async_std::stream::StreamExt; use libpso::character::guildcard; @@ -40,7 +39,7 @@ impl PostgresGateway { }); PostgresGateway { - pool: pool, + pool, } } @@ -96,13 +95,13 @@ impl PostgresGateway { ItemDetail::Mag(mag) }, - item @ _ => item + item => item }; ItemEntity { - id: id, - item: item, - location: location + id, + item, + location } } } diff --git a/src/entity/item/esweapon.rs b/src/entity/item/esweapon.rs index 6c00e7f..908b026 100644 --- a/src/entity/item/esweapon.rs +++ b/src/entity/item/esweapon.rs @@ -247,10 +247,10 @@ impl ESWeapon { let name = ESWeapon::name_from_bytes(&bytes[6..12]); ESWeapon { - esweapon: esweapon, + esweapon, special: special.ok(), - grind: grind, - name: name, + grind, + name, } } } diff --git a/src/entity/item/mag.rs b/src/entity/item/mag.rs index 348d025..4f36983 100644 --- a/src/entity/item/mag.rs +++ b/src/entity/item/mag.rs @@ -651,12 +651,12 @@ impl Mag { Ok(Mag{ mag: m, - def: def, - pow: pow, - dex: dex, + def, + pow, + dex, mnd: mind, synchro: sync, - iq: iq, + iq, photon_blast: [None, None, None], // TODO: actually get PBs from bytes color: data[15] % 18, //modifiers: Vec::new(), diff --git a/src/entity/item/weapon.rs b/src/entity/item/weapon.rs index e18eac5..6473dd8 100644 --- a/src/entity/item/weapon.rs +++ b/src/entity/item/weapon.rs @@ -1536,25 +1536,25 @@ impl Weapon { // TODO: error handling pub fn from_bytes(data: [u8; 16]) -> Result { - let w = WeaponType::parse_type([data[0], data[1], data[2]]); - if let Ok(w) = w { - let mut s = None; - let mut t = true; - let g = data[3]; + let wep = WeaponType::parse_type([data[0], data[1], data[2]]); + if let Ok(weapon) = wep { + let mut special = None; + let mut tekked = true; + let grind = data[3]; if data[4] >= 0x81 && data[4] <= 0xA8 { - s = WeaponSpecial::from(data[4] - 0x80); - t = false; + special = WeaponSpecial::from(data[4] - 0x80); + tekked = false; } else if data[4] >= 0x01 && data[4] <= 0x28 { - s = WeaponSpecial::from(data[4]); - t = true; + special = WeaponSpecial::from(data[4]); + tekked = true; } // else { // return Err(ItemParseError::InvalidSpecial) // } - let mut a = [ + let mut attrs = [ None, None, None @@ -1562,26 +1562,22 @@ impl Weapon { for i in 0..3 { if data[2 * (3 + i)] >= 1 && data[2 * (3 + i)] <= 5 { - a[i] = Some(WeaponAttribute{ + attrs[i] = Some(WeaponAttribute{ attr: Attribute::from(data[2 * (3 + i)]).unwrap(), value: data[2 * (3 + i) + 1] as i8, }); } else { - a[i] = None; + attrs[i] = None; // return Err(ItemParseError::InvalidAttribute) } } Ok(Weapon { - weapon: w, - special: s, - grind: g, - attrs:[ - a[0], - a[1], - a[2], - ], - tekked: t, + weapon, + special, + grind, + attrs, + tekked, }) } else { diff --git a/src/login/character.rs b/src/login/character.rs index 6867189..12e874a 100644 --- a/src/login/character.rs +++ b/src/login/character.rs @@ -28,7 +28,7 @@ use crate::entity::item::tool::Tool; use crate::entity::item::mag::Mag; use crate::entity::character::{CharacterEntity, NewCharacterEntity, CharacterClass, TechLevel}; -use crate::login::login::{get_login_status, check_if_already_online}; +use crate::login::login::{get_login_status}; use crate::common::interserver::AuthToken; pub const CHARACTER_PORT: u16 = 12001; @@ -148,7 +148,7 @@ fn generate_param_data(path: &str) -> (ParamDataHeader, Vec) { } (ParamDataHeader { - files: files + files }, buffer) } @@ -301,13 +301,13 @@ impl CharacterServerState { let (param_header, param_data) = generate_param_data("data/param/"); CharacterServerState { - entity_gateway: entity_gateway, - param_header: param_header, - param_data: param_data, + entity_gateway, + param_header, + param_data, clients: HashMap::new(), ships: BTreeMap::new(), level_table: CharacterLevelTable::default(), - auth_token: auth_token, + auth_token, authenticated_ships: BTreeSet::new(), ship_sender: BTreeMap::new(), connected_clients: BTreeMap::new(), @@ -481,7 +481,7 @@ impl CharacterServerState { Ok(vec![SendCharacterPacket::ParamDataChunk( Box::new(ParamDataChunk { chunk: chunk as u32, - data: data, + data, }) )]) } diff --git a/src/login/login.rs b/src/login/login.rs index f6ef7c4..617fad2 100644 --- a/src/login/login.rs +++ b/src/login/login.rs @@ -101,8 +101,8 @@ pub struct LoginServerState { impl LoginServerState { pub fn new(entity_gateway: EG, character_server_ip: net::Ipv4Addr) -> LoginServerState { LoginServerState { - entity_gateway: entity_gateway, - character_server_ip: character_server_ip, + entity_gateway, + character_server_ip, clients: HashMap::new(), } } diff --git a/src/patch/patch.rs b/src/patch/patch.rs index 13a9928..52dd7d2 100644 --- a/src/patch/patch.rs +++ b/src/patch/patch.rs @@ -146,10 +146,10 @@ pub struct PatchServerState { impl PatchServerState { pub fn new(patch_file_tree: PatchFileTree, patch_file_lookup: HashMap, patch_motd: String) -> PatchServerState { PatchServerState { - patch_file_tree: patch_file_tree, - patch_file_lookup: patch_file_lookup, + patch_file_tree, + patch_file_lookup, patch_file_info: Vec::new(), - patch_motd: patch_motd, + patch_motd, } } } @@ -222,9 +222,9 @@ fn load_patch_dir(basedir: &str, patchbase: &str, file_ids: &mut HashMap CharacterBytesBuilder<'a> { dfp: stats.dfp + character.materials.def as u16 * 2, ata: stats.ata, lck: stats.lck + character.materials.luck as u16 * 2, - level: level, + level, section_id: character.section_id.into(), ch_class: character.char_class.into(), costume: character.appearance.costume, @@ -221,7 +221,7 @@ impl<'a> FullCharacterBytesBuilder<'a> { symbol_chats: *symbol_chat, tech_menu: *tech_menu, bank: bank.as_client_bank_items(), - option_flags: option_flags, + option_flags, ..character::FullCharacter::default() } } diff --git a/src/ship/drops/generic_weapon.rs b/src/ship/drops/generic_weapon.rs index 28a5007..d1fb2bb 100644 --- a/src/ship/drops/generic_weapon.rs +++ b/src/ship/drops/generic_weapon.rs @@ -232,9 +232,9 @@ impl AttributeTable { let area_percent_patterns: AreaPercentPatterns = load_data_file(episode, difficulty, section_id, "area_percent_pattern.toml"); AttributeTable { - attribute_rates: attribute_rates, - percent_rates: percent_rates, - area_percent_patterns: area_percent_patterns, + attribute_rates, + percent_rates, + area_percent_patterns, } } @@ -258,7 +258,7 @@ impl AttributeTable { let percent = ((value + 1) * 5) as i8; Some(WeaponAttribute { - attr: attr, + attr, value: percent }) } @@ -406,7 +406,7 @@ impl GenericWeaponTable { rank_table.insert(WeaponDropType::Wand, vec![WeaponType::Wand, WeaponType::Staff, WeaponType::Baton, WeaponType::Scepter]); GenericWeaponTable { - rank_table: rank_table, + rank_table, weapon_ratio: WeaponRatios::new(episode, difficulty, section_id), grind_rates: GrindRates::new(episode, difficulty, section_id), attribute_table: AttributeTable::new(episode, difficulty, section_id), diff --git a/src/ship/drops/rare_drop_table.rs b/src/ship/drops/rare_drop_table.rs index 0ca356c..6631654 100644 --- a/src/ship/drops/rare_drop_table.rs +++ b/src/ship/drops/rare_drop_table.rs @@ -87,7 +87,7 @@ impl RareDropTable { }).collect(); RareDropTable { - rates: rates, + rates, attribute_table: AttributeTable::new(episode, difficulty, section_id), armor_stats: GenericArmorTable::new(episode, difficulty, section_id), shield_stats: GenericShieldTable::new(episode, difficulty, section_id), @@ -98,7 +98,7 @@ impl RareDropTable { match item { RareDropItem::Weapon(weapon) => { ItemDropType::Weapon(Weapon { - weapon: weapon, + weapon, special: None, grind: 0, attrs: self.attribute_table.generate_rare_attributes(map_area, rng), @@ -108,7 +108,7 @@ impl RareDropTable { }, RareDropItem::Armor(armor) => { ItemDropType::Armor(Armor { - armor: armor, + armor, dfp: self.armor_stats.dfp_modifier(&armor, rng) as u8, evp: self.armor_stats.evp_modifier(&armor, rng) as u8, slots: self.armor_stats.slots(map_area, rng) as u8, @@ -116,20 +116,20 @@ impl RareDropTable { }, RareDropItem::Shield(shield) => { ItemDropType::Shield(Shield { - shield: shield, + shield, dfp: self.shield_stats.dfp_modifier(&shield, rng) as u8, evp: self.shield_stats.evp_modifier(&shield, rng) as u8, }) }, RareDropItem::Unit(unit) => { ItemDropType::Unit(Unit { - unit: unit, + unit, modifier: None, }) }, RareDropItem::Tool(tool) => { ItemDropType::Tool(Tool { - tool: tool, + tool, }) }, RareDropItem::Mag(_mag) => { diff --git a/src/ship/items/bank.rs b/src/ship/items/bank.rs index 44b9cd1..f3d5d10 100644 --- a/src/ship/items/bank.rs +++ b/src/ship/items/bank.rs @@ -167,7 +167,7 @@ impl CharacterBank { items.sort(); CharacterBank { item_id_counter: 0, - items: items, + items, } } @@ -186,7 +186,7 @@ impl CharacterBank { })?; Some(BankItemHandle { bank: self, - index: index, + index, }) } @@ -221,8 +221,8 @@ impl CharacterBank { }, }; character::BankItem { - data1: data1, - data2: data2, + data1, + data2, item_id: item.item_id().0, amount: amount as u16, flags: 1, diff --git a/src/ship/items/floor.rs b/src/ship/items/floor.rs index 3083271..c976048 100644 --- a/src/ship/items/floor.rs +++ b/src/ship/items/floor.rs @@ -181,7 +181,7 @@ impl RoomFloorItems { let index = self.0.iter().position(|item| item.item_id() == item_id)?; Some(FloorItemHandle { floor: self, - index: index, + index, }) } @@ -234,7 +234,7 @@ impl RoomFloorItems { self.0.push(FloorItem::Stacked(StackedFloorItem { entity_ids: consumed_item.entity_ids(), item_id: new_item_id, - tool: tool, + tool, map_area: item_drop_location.0, x: item_drop_location.1, y: item_drop_location.2, diff --git a/src/ship/items/inventory.rs b/src/ship/items/inventory.rs index bbf833c..9589849 100644 --- a/src/ship/items/inventory.rs +++ b/src/ship/items/inventory.rs @@ -339,8 +339,8 @@ impl<'a> InventoryItemHandle<'a> { }) .ok_or(InventoryItemConsumeError::InvalidAmount)?; Ok(ConsumedItem::Stacked(StackedConsumedItem { - entity_ids: entity_ids, - tool: tool, + entity_ids, + tool, })) } } @@ -365,7 +365,7 @@ impl CharacterInventory { pub fn new(items: Vec, equipped: &EquippedEntity) -> CharacterInventory { CharacterInventory{ item_id_counter: 0, - items: items, + items, equipped: equipped.clone(), } } @@ -394,7 +394,7 @@ impl CharacterInventory { inventory[slot].data1[4] = self.equipped.unit.iter() .enumerate() .find(|(_, u_id)| **u_id == Some(individual_item.entity_id)) - .map(|(a, b)| a) + .map(|(a, _)| a) .unwrap_or(0) as u8 } inventory[slot].equipped = 1; @@ -421,7 +421,7 @@ impl CharacterInventory { })?; Some(InventoryItemHandle { inventory: self, - slot: slot, + slot, }) } @@ -438,7 +438,7 @@ impl CharacterInventory { })?; Some(InventoryItemHandle { inventory: self, - slot: slot, + slot, }) } @@ -455,7 +455,7 @@ impl CharacterInventory { })?; Some(InventoryItemHandle { inventory: self, - slot: slot, + slot, }) } @@ -472,7 +472,7 @@ impl CharacterInventory { })?; Some(InventoryItemHandle { inventory: self, - slot: slot, + slot, }) } @@ -489,7 +489,7 @@ impl CharacterInventory { })?; Some(InventoryItemHandle { inventory: self, - slot: slot, + slot, }) } diff --git a/src/ship/items/manager.rs b/src/ship/items/manager.rs index b975cc0..441c85b 100644 --- a/src/ship/items/manager.rs +++ b/src/ship/items/manager.rs @@ -1,12 +1,11 @@ use crate::ship::items::ClientItemId; -use std::collections::{HashMap, BTreeMap}; +use std::collections::HashMap; use thiserror::Error; use crate::entity::gateway::EntityGateway; use crate::entity::character::{CharacterEntity, CharacterEntityId, TechLevel}; use crate::entity::item::{ItemDetail, ItemLocation, BankName}; -use crate::entity::item::{Meseta, NewItemEntity, ItemEntity, InventoryItemEntity, EquippedEntity, InventoryEntity, BankItemEntity, BankEntity}; +use crate::entity::item::{Meseta, NewItemEntity, ItemEntity, InventoryItemEntity, BankItemEntity}; use crate::entity::item::tool::{Tool, ToolType}; -use crate::entity::item::unit; use crate::entity::item::weapon; use crate::ship::map::MapArea; use crate::ship::ship::ItemDropLocation; @@ -237,7 +236,7 @@ impl ItemManager { Some(FloorItem::Individual(individual_floor_item)) => { let new_inventory_item = inventory.pick_up_individual_floor_item(individual_floor_item); match new_inventory_item { - Some((new_inventory_item, slot)) => { + Some((new_inventory_item, _slot)) => { entity_gateway.change_item_location( &new_inventory_item.entity_id, ItemLocation::Inventory { @@ -258,7 +257,7 @@ impl ItemManager { let new_inventory_item = inventory.pick_up_stacked_floor_item(stacked_floor_item); match new_inventory_item { - Some((new_inventory_item, slot)) => { + Some((new_inventory_item, _slot)) => { for entity_id in &new_inventory_item.entity_ids { entity_gateway.change_item_location( entity_id, @@ -337,7 +336,7 @@ impl ItemManager { }).await?; FloorItem::Individual(IndividualFloorItem { entity_id: entity.id, - item_id: item_id, + item_id, item: item_detail, map_area: item_drop.map_area, x: item_drop.x, @@ -358,8 +357,8 @@ impl ItemManager { }).await?; FloorItem::Stacked(StackedFloorItem { entity_ids: vec![entity.id], - item_id: item_id, - tool: tool, + item_id, + tool, map_area: item_drop.map_area, x: item_drop.x, y: item_drop.y, @@ -368,8 +367,8 @@ impl ItemManager { }, ItemOrMeseta::Meseta(meseta) => { FloorItem::Meseta(MesetaFloorItem { - item_id: item_id, - meseta: meseta, + item_id, + meseta, map_area: item_drop.map_area, x: item_drop.x, y: item_drop.y, @@ -445,7 +444,7 @@ impl ItemManager { let item_id = self.room_item_id_counter.get_mut(room_id).ok_or(ItemManagerError::NoCharacter(character.id))?(); let floor_item = FloorItem::Meseta(MesetaFloorItem { - item_id: item_id, + item_id, meseta: Meseta(amount), map_area: drop_location.map_area, x: drop_location.x, @@ -571,13 +570,13 @@ impl ItemManager { let inventory_item = inventory.withdraw_item(item_to_withdraw, amount).ok_or(ItemManagerError::Idunnoman)?; match inventory_item { - (InventoryItem::Individual(individual_inventory_item), slot) => { + (InventoryItem::Individual(individual_inventory_item), _slot) => { entity_gateway.change_item_location(&individual_inventory_item.entity_id, ItemLocation::Inventory { character_id: character.id, }).await?; }, - (InventoryItem::Stacked(stacked_inventory_item), slot) => { + (InventoryItem::Stacked(stacked_inventory_item), _slot) => { for entity_id in &stacked_inventory_item.entity_ids { entity_gateway.change_item_location(entity_id, ItemLocation::Inventory { @@ -768,8 +767,8 @@ impl ItemManager { } let floor_item = StackedFloorItem { entity_ids: item_entities.into_iter().map(|i| i.id).collect(), - item_id: item_id, - tool: tool, + item_id, + tool, // TODO: this is gonna choke if I ever require the item being near the player for pickup map_area: MapArea::Pioneer2Ep1, x: 0.0, @@ -777,7 +776,7 @@ impl ItemManager { z: 0.0, }; let item_id = { - let (picked_up_item, slot) = inventory.pick_up_stacked_floor_item(&floor_item).ok_or(ItemManagerError::CouldNotAddBoughtItemToInventory)?; + let (picked_up_item, _slot) = inventory.pick_up_stacked_floor_item(&floor_item).ok_or(ItemManagerError::CouldNotAddBoughtItemToInventory)?; for entity_id in &picked_up_item.entity_ids { entity_gateway.change_item_location(entity_id, ItemLocation::Inventory { @@ -795,7 +794,7 @@ impl ItemManager { }).await?; let floor_item = IndividualFloorItem { entity_id: item_entity.id, - item_id: item_id, + item_id, item: ItemDetail::Tool(tool), // TODO: this is gonna choke if I ever require the item being near the player for pickup map_area: MapArea::Pioneer2Ep1, @@ -804,7 +803,7 @@ impl ItemManager { z: 0.0, }; let item_id = { - let (picked_up_item, slot) = inventory.pick_up_individual_floor_item(&floor_item).ok_or(ItemManagerError::CouldNotAddBoughtItemToInventory)?; + let (picked_up_item, _slot) = inventory.pick_up_individual_floor_item(&floor_item).ok_or(ItemManagerError::CouldNotAddBoughtItemToInventory)?; entity_gateway.change_item_location(&picked_up_item.entity_id, ItemLocation::Inventory { character_id: character.id, @@ -814,14 +813,14 @@ impl ItemManager { inventory.get_item_by_id(item_id).ok_or(ItemManagerError::ItemIdNotInInventory(item_id))? } }, - item_detail @ _ => { + item_detail => { let item_entity = entity_gateway.create_item(NewItemEntity { location: ItemLocation::Shop, item: item_detail.clone(), }).await?; let floor_item = IndividualFloorItem { entity_id: item_entity.id, - item_id: item_id, + item_id, item: item_detail, // TODO: this is gonna choke if I ever require the item being near the player for pickup map_area: MapArea::Pioneer2Ep1, @@ -830,7 +829,7 @@ impl ItemManager { z: 0.0, }; let item_id = { - let (picked_up_item, slot) = inventory.pick_up_individual_floor_item(&floor_item).ok_or(ItemManagerError::CouldNotAddBoughtItemToInventory)?; + let (picked_up_item, _slot) = inventory.pick_up_individual_floor_item(&floor_item).ok_or(ItemManagerError::CouldNotAddBoughtItemToInventory)?; entity_gateway.change_item_location(&picked_up_item.entity_id, ItemLocation::Inventory { character_id: character.id, @@ -911,8 +910,8 @@ impl ItemManager { entity_gateway.add_weapon_modifier(&entity_id, tek).await?; inventory.add_item(InventoryItem::Individual(IndividualInventoryItem { - entity_id: entity_id, - item_id: item_id, + entity_id, + item_id, item: ItemDetail::Weapon(weapon.clone()), }))?; diff --git a/src/ship/map/enemy.rs b/src/ship/map/enemy.rs index a9601d2..32e53df 100644 --- a/src/ship/map/enemy.rs +++ b/src/ship/map/enemy.rs @@ -252,7 +252,7 @@ impl MapEnemy { }; Ok(MapEnemy { - monster: monster, + monster, map_area: *map_area, hp: 0, dropped_item: false, @@ -263,8 +263,8 @@ impl MapEnemy { pub fn new(monster: MonsterType, map_area: MapArea) -> MapEnemy { MapEnemy { - monster: monster, - map_area: map_area, + monster, + map_area, hp: 0, dropped_item: false, gave_exp: false, diff --git a/src/ship/map/maps.rs b/src/ship/map/maps.rs index 15e790c..e1558d8 100644 --- a/src/ship/map/maps.rs +++ b/src/ship/map/maps.rs @@ -280,7 +280,7 @@ impl Maps { object_data: map_variants.iter().map(|map_variant| { objects_from_map_data(map_variant.obj_file().into(), &room_mode.episode(), &map_variant.map) }).flatten().collect(), - map_variants: map_variants, + map_variants, }; maps } diff --git a/src/ship/map/object.rs b/src/ship/map/object.rs index e431c88..8307bf0 100644 --- a/src/ship/map/object.rs +++ b/src/ship/map/object.rs @@ -159,7 +159,7 @@ impl MapObject { }; Ok(MapObject { - object: object, + object, map: *map_area, dropped_item: false, }) diff --git a/src/ship/map/variant.rs b/src/ship/map/variant.rs index 7e85bee..819bcdb 100644 --- a/src/ship/map/variant.rs +++ b/src/ship/map/variant.rs @@ -75,10 +75,10 @@ impl MapVariant { }; MapVariant { - map: map, - mode: mode, - major: major, - minor: minor, + map, + mode, + major, + minor, } } else { @@ -136,10 +136,10 @@ impl MapVariant { }; MapVariant { - map: map, - mode: mode, - major: major, - minor: minor, + map, + mode, + major, + minor, } } } diff --git a/src/ship/packet/builder/message.rs b/src/ship/packet/builder/message.rs index dfe1ac5..b7d7f97 100644 --- a/src/ship/packet/builder/message.rs +++ b/src/ship/packet/builder/message.rs @@ -12,8 +12,8 @@ use crate::ship::shops::ShopItem; pub fn item_drop(client: u8, target: u8, item_drop: &FloorItem) -> Result { let item_bytes = item_drop.as_client_bytes(); Ok(ItemDrop { - client: client, - target: target, + client, + target, map_area: item_drop.map_area().area_value(), variety: 0, unknown: 0, @@ -101,7 +101,7 @@ pub fn character_gained_exp(area_client: AreaClient, exp: u32) -> GiveCharacterE GiveCharacterExp { client: area_client.local_client.id(), target: 0, - exp: exp, + exp, } } @@ -138,7 +138,7 @@ pub fn player_no_longer_has_item(area_client: AreaClient, item_id: ClientItemId, client: area_client.local_client.id(), target: 0, item_id: item_id.0, - amount: amount, + amount, } } @@ -157,10 +157,10 @@ pub fn shop_list(shop_type: u8, items: &[I]) -> ShopList { ShopList { client: 0, target: 0, - shop_type: shop_type, + shop_type, num_items: 0, unused: 0, - items: items, + items, } } diff --git a/src/ship/packet/builder/mod.rs b/src/ship/packet/builder/mod.rs index e0e5301..a5c30d7 100644 --- a/src/ship/packet/builder/mod.rs +++ b/src/ship/packet/builder/mod.rs @@ -14,7 +14,7 @@ use crate::ship::items::ItemManager; pub fn player_header(tag: u32, client: &ClientState, area_client: &AreaClient) -> PlayerHeader { PlayerHeader { - tag: tag, + tag, guildcard: client.user.id.0, _unknown1: [0; 5], client_id: area_client.local_client.id() as u32, @@ -40,6 +40,6 @@ pub fn player_info(tag: u32, client: &ClientState, area_client: &AreaClient, ite language: 0, // TODO: account language items: inventory.as_client_inventory_items(), }, - character: character, + character, } } diff --git a/src/ship/packet/builder/quest.rs b/src/ship/packet/builder/quest.rs index 8078517..f162269 100644 --- a/src/ship/packet/builder/quest.rs +++ b/src/ship/packet/builder/quest.rs @@ -59,9 +59,9 @@ pub fn quest_header(quest_menu_select: &QuestMenuSelect, data_blob: &[u8], suffi pub fn quest_chunk(chunk_num: u32, filename: [u8; 16], blob: [u8; 0x400], blob_length: usize) -> QuestChunk { QuestChunk { - chunk_num: chunk_num, - filename: filename, - blob: blob, + chunk_num, + filename, + blob, blob_length: blob_length as u32, unknown: 0, } diff --git a/src/ship/packet/builder/room.rs b/src/ship/packet/builder/room.rs index 2eb8fc7..1effe5d 100644 --- a/src/ship/packet/builder/room.rs +++ b/src/ship/packet/builder/room.rs @@ -30,7 +30,7 @@ pub fn join_room(id: ClientId, Ok(JoinRoom { flag: all_clients.len() as u32, maps: room.maps.map_headers(), - players: players, + players, client: area_client.local_client.id(), leader: leader.local_client.id(), one: 1, diff --git a/src/ship/packet/builder/ship.rs b/src/ship/packet/builder/ship.rs index 8b3e40f..1411f2a 100644 --- a/src/ship/packet/builder/ship.rs +++ b/src/ship/packet/builder/ship.rs @@ -1,16 +1,7 @@ use libpso::packet::login::{ShipList, ShipListEntry}; -use libpso::packet::ship::*; -use crate::common::serverstate::ClientId; -use crate::common::leveltable::CharacterLevelTable; -use crate::ship::ship::{ShipError, ClientState, Clients}; -use crate::ship::location::{ClientLocation, RoomId, AreaClient, ClientLocationError}; -use crate::ship::room::RoomState; -use crate::ship::items::ItemManager; -use crate::ship::packet::builder::{player_header, player_info}; use libpso::utf8_to_utf16_array; use crate::common::interserver::Ship; -use libpso::packet::ship::BLOCK_MENU_ID; use crate::login::character::SHIP_MENU_ID; pub fn ship_list(ships: &[Ship]) -> ShipList { diff --git a/src/ship/packet/handler/auth.rs b/src/ship/packet/handler/auth.rs index 0bf5ebe..c9e6987 100644 --- a/src/ship/packet/handler/auth.rs +++ b/src/ship/packet/handler/auth.rs @@ -2,7 +2,7 @@ use libpso::packet::login::{Login, LoginResponse, AccountStatus, Session}; use libpso::packet::ship::*; use crate::common::serverstate::ClientId; use crate::ship::ship::{SendShipPacket, ShipError, ClientState, Clients}; -use crate::login::login::{get_login_status, check_if_already_online}; +use crate::login::login::get_login_status; use crate::entity::gateway::EntityGateway; use crate::ship::items::ItemManager; use crate::common::interserver::ShipMessage; diff --git a/src/ship/packet/handler/message.rs b/src/ship/packet/handler/message.rs index 6bf2106..39d3717 100644 --- a/src/ship/packet/handler/message.rs +++ b/src/ship/packet/handler/message.rs @@ -1,12 +1,11 @@ use libpso::packet::ship::*; use libpso::packet::messages::*; use crate::entity::gateway::EntityGateway; -use crate::entity::item::{ItemType}; use crate::common::serverstate::ClientId; use crate::common::leveltable::CharacterLevelTable; use crate::ship::ship::{SendShipPacket, ShipError, Rooms, Clients, ItemDropLocation}; use crate::ship::location::{ClientLocation, ClientLocationError}; -use crate::ship::items::{ItemManager, ClientItemId, InventoryItem}; +use crate::ship::items::{ItemManager, ClientItemId}; use crate::ship::packet::builder; pub async fn request_exp(id: ClientId, diff --git a/src/ship/quests.rs b/src/ship/quests.rs index 7b1316f..3b430ba 100644 --- a/src/ship/quests.rs +++ b/src/ship/quests.rs @@ -191,16 +191,16 @@ impl Quest { prs_dat.write_all(&dat)?; Ok(Quest { - name: name, - description: description, - full_description: full_description, - id: id, - language: language, + name, + description, + full_description, + id, + language, bin_blob: prs_bin.into_inner().map_err(|_| QuestLoadError::CouldNotReadMetadata)?, dat_blob: prs_dat.into_inner().map_err(|_| QuestLoadError::CouldNotReadMetadata)?, - enemies: enemies, - objects: objects, - map_areas: map_areas, + enemies, + objects, + map_areas, }) } } diff --git a/src/ship/room.rs b/src/ship/room.rs index 5fbae80..3aae5da 100644 --- a/src/ship/room.rs +++ b/src/ship/room.rs @@ -238,7 +238,7 @@ impl RoomState { name: String::from_utf16_lossy(&create_room.name).trim_matches(char::from(0)).into(), password: create_room.password, maps: Maps::new(room_mode), - section_id: section_id, + section_id, drop_table: Box::new(DropTable::new(room_mode.episode(), room_mode.difficulty(), section_id)), bursting: false, map_areas: MapAreaLookup::new(&room_mode.episode()), diff --git a/src/ship/shops/tool.rs b/src/ship/shops/tool.rs index 66313b5..d3a8e4b 100644 --- a/src/ship/shops/tool.rs +++ b/src/ship/shops/tool.rs @@ -263,7 +263,7 @@ impl ToolShop { }; ToolShopItem::Tech(TechniqueDisk { - tech: tech, + tech, level: level as u32, }) }) diff --git a/src/ship/shops/weapon.rs b/src/ship/shops/weapon.rs index d978ad9..6818f23 100644 --- a/src/ship/shops/weapon.rs +++ b/src/ship/shops/weapon.rs @@ -329,8 +329,8 @@ pub struct WeaponShop { impl WeaponShop { pub fn new(difficulty: Difficulty, section_id: SectionID) -> WeaponShop { WeaponShop { - difficulty: difficulty, - section_id: section_id, + difficulty, + section_id, weapon: load_weapon_table(difficulty, section_id), special: load_special_table(), grind: load_grind_table(), @@ -405,7 +405,7 @@ impl WeaponShop { .choose(&mut self.rng)?; Some(WeaponAttribute { - attr: attr, + attr, value: percent as i8, }) } @@ -432,7 +432,7 @@ impl WeaponShop { .choose(&mut self.rng)?; Some(WeaponAttribute { - attr: attr, + attr, value: percent as i8, }) } @@ -512,9 +512,9 @@ impl WeaponShop { }; WeaponShopItem { - weapon: weapon, - grind: grind, - special: special, + weapon, + grind, + special, attributes: [attr1, attr2], } } From 5cf5907a86b62ad719d42536312029d979b0f061 Mon Sep 17 00:00:00 2001 From: jake Date: Fri, 18 Jun 2021 20:39:16 -0600 Subject: [PATCH 22/25] add clippy to ci --- .drone.yml | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/.drone.yml b/.drone.yml index 46e90f4..7b72752 100644 --- a/.drone.yml +++ b/.drone.yml @@ -7,7 +7,7 @@ concurrency: limit: 1 steps: -- name: cargo build +- name: build image: rustlang/rust:nightly volumes: - name: cache @@ -16,7 +16,16 @@ steps: path: /drone/src/target commands: - cargo build -- name: cargo test +- name: clippy! + image: rustlang/rust:nightly + volumes: + - name: cache + path: /usr/local/cargo + - name: target-cache + path: /drone/src/target + commands: + - cargo clippy +- name: test image: rustlang/rust:nightly volumes: - name: cache From 2213bcee640d38f9ec19f7498061a0ff61a40262 Mon Sep 17 00:00:00 2001 From: jake Date: Fri, 18 Jun 2021 22:20:43 -0600 Subject: [PATCH 23/25] fail ci on clippy warnings --- .drone.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.drone.yml b/.drone.yml index 7b72752..b794571 100644 --- a/.drone.yml +++ b/.drone.yml @@ -24,7 +24,7 @@ steps: - name: target-cache path: /drone/src/target commands: - - cargo clippy + - cargo clippy --deny warnings - name: test image: rustlang/rust:nightly volumes: From dd31769881003ef589bbe90632268571027a7e58 Mon Sep 17 00:00:00 2001 From: jake Date: Fri, 18 Jun 2021 22:27:03 -0600 Subject: [PATCH 24/25] fail ci on clippy warnings for real this time --- .drone.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.drone.yml b/.drone.yml index b794571..ae267b5 100644 --- a/.drone.yml +++ b/.drone.yml @@ -24,7 +24,7 @@ steps: - name: target-cache path: /drone/src/target commands: - - cargo clippy --deny warnings + - cargo clippy -- --deny warnings - name: test image: rustlang/rust:nightly volumes: From efe180ad31ceeb25d44ae9c2ecf9b4ad34a6bcb2 Mon Sep 17 00:00:00 2001 From: jake Date: Fri, 18 Jun 2021 23:36:52 -0600 Subject: [PATCH 25/25] allow the postgres use --- src/bin/main.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/bin/main.rs b/src/bin/main.rs index e0c7207..a9ed329 100644 --- a/src/bin/main.rs +++ b/src/bin/main.rs @@ -6,6 +6,7 @@ use elseware::login::login::LoginServerState; use elseware::login::character::CharacterServerState; use elseware::ship::ship::ShipServerStateBuilder; use elseware::entity::account::{NewUserAccountEntity, NewUserSettingsEntity}; +#[allow(unused_imports)] use elseware::entity::gateway::{EntityGateway, InMemoryGateway, PostgresGateway}; use elseware::entity::character::NewCharacterEntity; use elseware::entity::item::{NewItemEntity, ItemDetail, ItemLocation};