From a95893e43b0d9b71276e26ec070e2ba368e50868 Mon Sep 17 00:00:00 2001 From: timokoesters Date: Sat, 31 Aug 2019 00:09:25 +0200 Subject: [PATCH] Remove inventory::swap and improve inventory::insert --- common/src/comp/inventory/mod.rs | 17 ++++++----------- server/src/lib.rs | 13 ++++++++----- 2 files changed, 14 insertions(+), 16 deletions(-) diff --git a/common/src/comp/inventory/mod.rs b/common/src/comp/inventory/mod.rs index 6bcf46d79e..e65b9eecd6 100644 --- a/common/src/comp/inventory/mod.rs +++ b/common/src/comp/inventory/mod.rs @@ -33,15 +33,16 @@ impl Inventory { } } - /// Replaces an item in a specific slot of the inventory. Returns the item again if that slot + /// Replaces an item in a specific slot of the inventory. Returns the old item or the same item again if that slot /// was not found. - pub fn insert(&mut self, cell: usize, item: Option) -> Option { + pub fn insert(&mut self, cell: usize, item: Item) -> Result, Item> { match self.slots.get_mut(cell) { Some(slot) => { - *slot = item; - None + let old = slot.take(); + *slot = Some(item); + Ok(old) } - None => item, + None => Err(item), } } @@ -50,12 +51,6 @@ impl Inventory { self.slots.get(cell).and_then(Option::as_ref) } - /// Insert an item into a slot if its empty - pub fn swap(&mut self, cell: usize, item: Item) -> Option { - //TODO: Check if a slot is empty first. - self.slots.get_mut(cell).and_then(|cell| cell.replace(item)) - } - /// Swap the items inside of two slots pub fn swap_slots(&mut self, a: usize, b: usize) { if a.max(b) < self.slots.len() { diff --git a/server/src/lib.rs b/server/src/lib.rs index fe8ff30ad1..0be77d38d9 100644 --- a/server/src/lib.rs +++ b/server/src/lib.rs @@ -724,11 +724,14 @@ impl Server { if let Some(stats) = state.ecs().write_storage::().get_mut(entity) { - state - .ecs() - .write_storage::() - .get_mut(entity) - .map(|inv| inv.insert(x, stats.equipment.main.take())); + // Insert old item into inventory + if let Some(old_item) = stats.equipment.main.take() { + state + .ecs() + .write_storage::() + .get_mut(entity) + .map(|inv| inv.insert(x, old_item)); + } stats.equipment.main = item; }