openstranded-common-items 0.1.1

OpenStranded item domain types: ItemDef, ItemGroup, Material, ItemStack
Documentation
use serde::{Deserialize, Serialize};

/// A stack of identical items in an inventory.
///
/// This is the primary ECS component for representing items in the world
/// or in a container. It is serialised via bincode when crossing the WASM
/// boundary (get_component / set_component).
///
/// # Example
///
/// ```rust
/// use openstranded_common_items::ItemStack;
///
/// let stack = ItemStack::new(23, 1);       // one stone
/// let tool = ItemStack::with_durability(30, 1, 100.0); // hammer at full health
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ItemStack {
    /// Item type ID (matches `ItemDef.id`).
    pub item_id: u32,

    /// Number of items in this stack.
    pub amount: u32,

    /// Remaining durability for tools / weapons.
    ///
    /// `None` means the item doesn't have durability (non-tools).
    /// `Some(n)` means current durability; when it reaches 0 the item breaks.
    #[serde(default)]
    pub durability: Option<f32>,
}

impl ItemStack {
    /// Create a new stack of `amount` items of type `item_id`.
    ///
    /// Durability is set to `None` (non-relevant for non-tools).
    #[must_use]
    pub const fn new(item_id: u32, amount: u32) -> Self {
        Self {
            item_id,
            amount,
            durability: None,
        }
    }

    /// Create a new stack with a specific durability value.
    ///
    /// Useful for tools and weapons that degrade over time.
    #[must_use]
    pub const fn with_durability(item_id: u32, amount: u32, durability: f32) -> Self {
        Self {
            item_id,
            amount,
            durability: Some(durability),
        }
    }

    /// Whether this stack is empty (amount == 0).
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.amount == 0
    }

    /// Maximum amount per stack.
    ///
    /// This is a game-wide constant from the original game (999).
    /// Individual item types may override this in the future.
    pub const MAX_STACK: u32 = 999;

    /// Merge another stack into this one, respecting max stack size.
    ///
    /// Returns the amount that could NOT be merged (overflow), or 0 if
    /// all items fit.
    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
        }
    }

    /// Split this stack, taking `count` items.
    ///
    /// Returns `None` if `count` exceeds the current amount.
    /// Otherwise decrements the stack and returns a new stack with `count` items.
    #[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,
        })
    }
}

// ── Tests ──────────────────────────────────────────────────────────

#[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() {
        // Verify that serializer/deserializer 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));
    }
}