Skip to main content

openstranded_common_items/
item_stack.rs

1use serde::{Deserialize, Serialize};
2
3/// A stack of identical items in an inventory.
4///
5/// This is the primary ECS component for representing items in the world
6/// or in a container. It is serialised via bincode when crossing the WASM
7/// boundary (get_component / set_component).
8///
9/// # Example
10///
11/// ```rust
12/// use openstranded_common_items::ItemStack;
13///
14/// let stack = ItemStack::new(23, 1);       // one stone
15/// let tool = ItemStack::with_durability(30, 1, 100.0); // hammer at full health
16/// ```
17#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
18pub struct ItemStack {
19    /// Item type ID (matches `ItemDef.id`).
20    pub item_id: u32,
21
22    /// Number of items in this stack.
23    pub amount: u32,
24
25    /// Remaining durability for tools / weapons.
26    ///
27    /// `None` means the item doesn't have durability (non-tools).
28    /// `Some(n)` means current durability; when it reaches 0 the item breaks.
29    #[serde(default)]
30    pub durability: Option<f32>,
31}
32
33impl ItemStack {
34    /// Create a new stack of `amount` items of type `item_id`.
35    ///
36    /// Durability is set to `None` (non-relevant for non-tools).
37    #[must_use]
38    pub const fn new(item_id: u32, amount: u32) -> Self {
39        Self {
40            item_id,
41            amount,
42            durability: None,
43        }
44    }
45
46    /// Create a new stack with a specific durability value.
47    ///
48    /// Useful for tools and weapons that degrade over time.
49    #[must_use]
50    pub const fn with_durability(item_id: u32, amount: u32, durability: f32) -> Self {
51        Self {
52            item_id,
53            amount,
54            durability: Some(durability),
55        }
56    }
57
58    /// Whether this stack is empty (amount == 0).
59    #[must_use]
60    pub const fn is_empty(&self) -> bool {
61        self.amount == 0
62    }
63
64    /// Maximum amount per stack.
65    ///
66    /// This is a game-wide constant from the original game (999).
67    /// Individual item types may override this in the future.
68    pub const MAX_STACK: u32 = 999;
69
70    /// Merge another stack into this one, respecting max stack size.
71    ///
72    /// Returns the amount that could NOT be merged (overflow), or 0 if
73    /// all items fit.
74    pub fn merge(&mut self, other: &Self) -> u32 {
75        if self.item_id != other.item_id {
76            return other.amount;
77        }
78
79        let total = self.amount + other.amount;
80        if total <= Self::MAX_STACK {
81            self.amount = total;
82            0
83        } else {
84            self.amount = Self::MAX_STACK;
85            total - Self::MAX_STACK
86        }
87    }
88
89    /// Split this stack, taking `count` items.
90    ///
91    /// Returns `None` if `count` exceeds the current amount.
92    /// Otherwise decrements the stack and returns a new stack with `count` items.
93    #[must_use]
94    pub fn split(&mut self, count: u32) -> Option<Self> {
95        if count == 0 || count > self.amount {
96            return None;
97        }
98        self.amount -= count;
99        Some(Self {
100            item_id: self.item_id,
101            amount: count,
102            durability: self.durability,
103        })
104    }
105}
106
107// ── Tests ──────────────────────────────────────────────────────────
108
109#[cfg(test)]
110mod tests {
111    use super::*;
112
113    #[test]
114    fn test_new_stack() {
115        let stack = ItemStack::new(23, 5);
116        assert_eq!(stack.item_id, 23);
117        assert_eq!(stack.amount, 5);
118        assert!(stack.durability.is_none());
119    }
120
121    #[test]
122    fn test_with_durability() {
123        let stack = ItemStack::with_durability(30, 1, 100.0);
124        assert_eq!(stack.durability, Some(100.0));
125    }
126
127    #[test]
128    fn test_is_empty() {
129        assert!(ItemStack::new(1, 0).is_empty());
130        assert!(!ItemStack::new(1, 1).is_empty());
131    }
132
133    #[test]
134    fn test_merge_same_type() {
135        let mut dst = ItemStack::new(1, 500);
136        let src = ItemStack::new(1, 300);
137        let overflow = dst.merge(&src);
138        assert_eq!(dst.amount, 800);
139        assert_eq!(overflow, 0);
140    }
141
142    #[test]
143    fn test_merge_overflow() {
144        let mut dst = ItemStack::new(1, 700);
145        let src = ItemStack::new(1, 500);
146        let overflow = dst.merge(&src);
147        assert_eq!(dst.amount, ItemStack::MAX_STACK);
148        assert_eq!(overflow, 700 + 500 - ItemStack::MAX_STACK);
149    }
150
151    #[test]
152    fn test_merge_different_type() {
153        let mut dst = ItemStack::new(1, 5);
154        let src = ItemStack::new(2, 3);
155        assert_eq!(dst.merge(&src), 3);
156        assert_eq!(dst.amount, 5);
157    }
158
159    #[test]
160    fn test_split_happy() {
161        let mut stack = ItemStack::new(1, 10);
162        let part = stack.split(3).unwrap();
163        assert_eq!(part.amount, 3);
164        assert_eq!(part.item_id, 1);
165        assert_eq!(stack.amount, 7);
166    }
167
168    #[test]
169    fn test_split_all() {
170        let mut stack = ItemStack::new(1, 5);
171        let part = stack.split(5).unwrap();
172        assert_eq!(part.amount, 5);
173        assert_eq!(stack.amount, 0);
174    }
175
176    #[test]
177    fn test_split_too_many() {
178        let mut stack = ItemStack::new(1, 3);
179        assert!(stack.split(10).is_none());
180        assert_eq!(stack.amount, 3);
181    }
182
183    #[test]
184    fn test_split_zero() {
185        let mut stack = ItemStack::new(1, 3);
186        assert!(stack.split(0).is_none());
187        assert_eq!(stack.amount, 3);
188    }
189
190    #[test]
191    fn test_serde_derives_compile() {
192        // Verify that serializer/deserializer derives compile
193        let stack = ItemStack::with_durability(42, 3, 75.5);
194        assert_eq!(stack.item_id, 42);
195        assert_eq!(stack.amount, 3);
196        assert_eq!(stack.durability, Some(75.5));
197    }
198}