use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ItemStack {
pub item_id: u32,
pub amount: u32,
#[serde(default)]
pub durability: Option<f32>,
}
impl ItemStack {
#[must_use]
pub const fn new(item_id: u32, amount: u32) -> Self {
Self {
item_id,
amount,
durability: None,
}
}
#[must_use]
pub const fn with_durability(item_id: u32, amount: u32, durability: f32) -> Self {
Self {
item_id,
amount,
durability: Some(durability),
}
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.amount == 0
}
pub const MAX_STACK: u32 = 999;
pub fn merge(&mut self, other: &Self) -> u32 {
if self.item_id != other.item_id {
return other.amount;
}
let total = self.amount + other.amount;
if total <= Self::MAX_STACK {
self.amount = total;
0
} else {
self.amount = Self::MAX_STACK;
total - Self::MAX_STACK
}
}
#[must_use]
pub fn split(&mut self, count: u32) -> Option<Self> {
if count == 0 || count > self.amount {
return None;
}
self.amount -= count;
Some(Self {
item_id: self.item_id,
amount: count,
durability: self.durability,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_new_stack() {
let stack = ItemStack::new(23, 5);
assert_eq!(stack.item_id, 23);
assert_eq!(stack.amount, 5);
assert!(stack.durability.is_none());
}
#[test]
fn test_with_durability() {
let stack = ItemStack::with_durability(30, 1, 100.0);
assert_eq!(stack.durability, Some(100.0));
}
#[test]
fn test_is_empty() {
assert!(ItemStack::new(1, 0).is_empty());
assert!(!ItemStack::new(1, 1).is_empty());
}
#[test]
fn test_merge_same_type() {
let mut dst = ItemStack::new(1, 500);
let src = ItemStack::new(1, 300);
let overflow = dst.merge(&src);
assert_eq!(dst.amount, 800);
assert_eq!(overflow, 0);
}
#[test]
fn test_merge_overflow() {
let mut dst = ItemStack::new(1, 700);
let src = ItemStack::new(1, 500);
let overflow = dst.merge(&src);
assert_eq!(dst.amount, ItemStack::MAX_STACK);
assert_eq!(overflow, 700 + 500 - ItemStack::MAX_STACK);
}
#[test]
fn test_merge_different_type() {
let mut dst = ItemStack::new(1, 5);
let src = ItemStack::new(2, 3);
assert_eq!(dst.merge(&src), 3);
assert_eq!(dst.amount, 5);
}
#[test]
fn test_split_happy() {
let mut stack = ItemStack::new(1, 10);
let part = stack.split(3).unwrap();
assert_eq!(part.amount, 3);
assert_eq!(part.item_id, 1);
assert_eq!(stack.amount, 7);
}
#[test]
fn test_split_all() {
let mut stack = ItemStack::new(1, 5);
let part = stack.split(5).unwrap();
assert_eq!(part.amount, 5);
assert_eq!(stack.amount, 0);
}
#[test]
fn test_split_too_many() {
let mut stack = ItemStack::new(1, 3);
assert!(stack.split(10).is_none());
assert_eq!(stack.amount, 3);
}
#[test]
fn test_split_zero() {
let mut stack = ItemStack::new(1, 3);
assert!(stack.split(0).is_none());
assert_eq!(stack.amount, 3);
}
#[test]
fn test_serde_derives_compile() {
let stack = ItemStack::with_durability(42, 3, 75.5);
assert_eq!(stack.item_id, 42);
assert_eq!(stack.amount, 3);
assert_eq!(stack.durability, Some(75.5));
}
}