1use std::hash::Hash;
14
15use crate::voxel::{DefaultTerrainVoxel, VoxelType};
16use bevy::prelude::*;
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22#[non_exhaustive]
23pub enum ContainerExchangeError {
24 InvalidRequest,
26 InvalidContainer,
28 InsufficientItems,
30 CapacityExceeded,
32}
33
34pub(crate) fn normalize_quantities<I: ItemType>(
36 quantities: &[(I, u32)],
37) -> Result<Vec<(I, u32)>, ContainerExchangeError> {
38 let mut normalized: Vec<(I, u32)> = Vec::new();
39 for &(item, count) in quantities {
40 if count == 0 {
41 continue;
42 }
43 if item == I::default() || item.is_empty() {
44 return Err(ContainerExchangeError::InvalidRequest);
45 }
46 if let Some((_, total)) = normalized
47 .iter_mut()
48 .find(|(existing, _)| *existing == item)
49 {
50 *total = total
51 .checked_add(count)
52 .ok_or(ContainerExchangeError::InvalidRequest)?;
53 } else {
54 normalized.push((item, count));
55 }
56 }
57 Ok(normalized)
58}
59
60pub trait Container<I: ItemType> {
70 fn add(&mut self, item: I, count: u32) -> u32;
73
74 fn remove(&mut self, item: I, count: u32) -> u32;
76
77 fn count_of(&self, item: I) -> u32;
79
80 fn capacity(&self) -> usize;
82
83 fn is_full(&self) -> bool;
85
86 fn iter_slots(&self) -> impl Iterator<Item = Option<&InventorySlot<I>>>;
89
90 fn slot_at(&self, index: usize) -> Option<&InventorySlot<I>>;
93
94 fn try_exchange_atomic(
104 &mut self,
105 _remove: &[(I, u32)],
106 _add: &[(I, u32)],
107 ) -> Option<Result<(), ContainerExchangeError>> {
108 None
109 }
110}
111
112pub trait ItemType: Copy + Clone + Default + Send + Sync + PartialEq + Eq + Hash + 'static {
163 fn name(&self) -> &'static str;
167
168 fn color(&self) -> [f32; 4];
173
174 fn to_byte(&self) -> u8;
180
181 fn from_byte(b: u8) -> Self;
187
188 fn is_empty(&self) -> bool {
193 false
194 }
195
196 fn tool_level(&self) -> u8 {
203 0
204 }
205
206 fn tool_speed(&self) -> f32 {
211 1.0
212 }
213}
214
215#[derive(Debug, Clone, PartialEq)]
224pub struct InventorySlot<I: ItemType> {
225 pub item: I,
227 pub count: u32,
229}
230
231#[derive(Resource, Debug, Clone)]
257pub struct Inventory<I: ItemType> {
258 pub slots: Vec<Option<InventorySlot<I>>>,
263 pub capacity: usize,
268}
269
270impl<I: ItemType> Inventory<I> {
271 pub(crate) fn validate_integrity(&self) -> Result<(), ContainerExchangeError> {
273 if self.capacity != self.slots.len() {
274 return Err(ContainerExchangeError::InvalidContainer);
275 }
276 let quantities: Vec<_> = self
277 .slots
278 .iter()
279 .flatten()
280 .map(|slot| (slot.item, slot.count))
281 .collect();
282 if quantities.iter().any(|(_, count)| *count == 0) {
283 return Err(ContainerExchangeError::InvalidContainer);
284 }
285 normalize_quantities(&quantities)
286 .map(|_| ())
287 .map_err(|_| ContainerExchangeError::InvalidContainer)
288 }
289
290 fn exchange_atomic(
291 &mut self,
292 remove: &[(I, u32)],
293 add: &[(I, u32)],
294 ) -> Result<(), ContainerExchangeError> {
295 let remove = normalize_quantities(remove)?;
296 let add = normalize_quantities(add)?;
297 self.validate_integrity()?;
298 if remove
299 .iter()
300 .any(|&(item, count)| self.count_of(item) < count)
301 {
302 return Err(ContainerExchangeError::InsufficientItems);
303 }
304 let mut staged = Self {
306 slots: self.slots.clone(),
307 capacity: self.capacity,
308 };
309 for (item, count) in remove {
310 if staged.remove(item, count) != count {
311 return Err(ContainerExchangeError::InsufficientItems);
312 }
313 }
314 for (item, count) in add {
315 if staged.add(item, count) != 0 {
316 return Err(ContainerExchangeError::CapacityExceeded);
317 }
318 }
319 self.slots = staged.slots;
320 Ok(())
321 }
322
323 pub fn new(capacity: usize) -> Self {
325 Self {
326 slots: vec![None; capacity],
327 capacity,
328 }
329 }
330
331 pub fn add(&mut self, item: I, count: u32) -> u32 {
339 if count == 0 {
340 return 0;
341 }
342 if item == I::default() || item.is_empty() || self.validate_integrity().is_err() {
343 return count;
344 }
345 let accepted = count.min(u32::MAX - self.count_of(item));
346 let mut remaining = accepted;
347
348 for slot in self.slots.iter_mut().flatten() {
350 if remaining == 0 {
351 break;
352 }
353 if slot.item == item {
354 slot.count += remaining;
355 remaining = 0;
356 }
357 }
358
359 if remaining > 0 {
361 for slot in self.slots.iter_mut() {
362 if remaining == 0 {
363 break;
364 }
365 if slot.is_none() {
366 *slot = Some(InventorySlot {
367 item,
368 count: remaining,
369 });
370 remaining = 0;
371 }
372 }
373 }
374
375 (count - accepted) + remaining
376 }
377
378 pub fn remove(&mut self, item: I, count: u32) -> u32 {
383 let mut to_remove = count;
384 let mut removed = 0u32;
385
386 for slot in self.slots.iter_mut() {
387 if to_remove == 0 {
388 break;
389 }
390 if let Some(s) = slot {
391 if s.item == item {
392 let take = s.count.min(to_remove);
393 s.count -= take;
394 to_remove -= take;
395 removed += take;
396 if s.count == 0 {
397 *slot = None;
398 }
399 }
400 }
401 }
402
403 removed
404 }
405
406 pub fn count_of(&self, item: I) -> u32 {
409 self.slots
410 .iter()
411 .flatten()
412 .filter(|s| s.item == item)
413 .fold(0u32, |total, slot| total.saturating_add(slot.count))
414 }
415
416 pub fn is_full(&self) -> bool {
418 self.slots.iter().all(|s| s.is_some())
419 }
420}
421
422impl<I: ItemType> Default for Inventory<I> {
423 fn default() -> Self {
425 Self::new(36)
426 }
427}
428
429impl<I: ItemType> Container<I> for Inventory<I> {
432 fn try_exchange_atomic(
433 &mut self,
434 remove: &[(I, u32)],
435 add: &[(I, u32)],
436 ) -> Option<Result<(), ContainerExchangeError>> {
437 Some(self.exchange_atomic(remove, add))
438 }
439
440 fn add(&mut self, item: I, count: u32) -> u32 {
441 Inventory::add(self, item, count)
442 }
443
444 fn remove(&mut self, item: I, count: u32) -> u32 {
445 Inventory::remove(self, item, count)
446 }
447
448 fn count_of(&self, item: I) -> u32 {
449 Inventory::count_of(self, item)
450 }
451
452 fn capacity(&self) -> usize {
453 self.capacity
454 }
455
456 fn is_full(&self) -> bool {
457 Inventory::is_full(self)
458 }
459
460 fn iter_slots(&self) -> impl Iterator<Item = Option<&InventorySlot<I>>> {
461 self.slots.iter().map(|s| s.as_ref())
462 }
463
464 fn slot_at(&self, index: usize) -> Option<&InventorySlot<I>> {
465 self.slots.get(index).and_then(|s| s.as_ref())
466 }
467}
468
469#[derive(Component)]
492pub struct ContainerComponent<I: ItemType>(pub Inventory<I>);
493
494impl<I: ItemType> ContainerComponent<I> {
495 pub fn new(capacity: usize) -> Self {
498 Self(Inventory::new(capacity))
499 }
500}
501
502impl<I: ItemType> Container<I> for ContainerComponent<I> {
503 fn try_exchange_atomic(
504 &mut self,
505 remove: &[(I, u32)],
506 add: &[(I, u32)],
507 ) -> Option<Result<(), ContainerExchangeError>> {
508 Container::try_exchange_atomic(&mut self.0, remove, add)
509 }
510
511 fn add(&mut self, item: I, count: u32) -> u32 {
512 self.0.add(item, count)
513 }
514
515 fn remove(&mut self, item: I, count: u32) -> u32 {
516 self.0.remove(item, count)
517 }
518
519 fn count_of(&self, item: I) -> u32 {
520 self.0.count_of(item)
521 }
522
523 fn capacity(&self) -> usize {
524 self.0.capacity
525 }
526
527 fn is_full(&self) -> bool {
528 self.0.is_full()
529 }
530
531 fn iter_slots(&self) -> impl Iterator<Item = Option<&InventorySlot<I>>> {
532 self.0.slots.iter().map(|s| s.as_ref())
533 }
534
535 fn slot_at(&self, index: usize) -> Option<&InventorySlot<I>> {
536 self.0.slots.get(index).and_then(|s| s.as_ref())
537 }
538}
539
540#[derive(Component, Default)]
548pub struct PrimaryContainer;
549
550#[derive(Message, Debug, Clone)]
562pub struct ItemPickedUp<I: ItemType> {
563 pub item: I,
565 pub count: u32,
567}
568
569#[derive(
590 Debug, Clone, Copy, PartialEq, Eq, Hash, Default, serde::Serialize, serde::Deserialize,
591)]
592pub enum DefaultItem {
593 #[default]
595 Empty,
596 Dirt,
598 Sand,
600 Wood,
602 Gravel,
604 Snow,
606 CoalOre,
608 IronOre,
610 Cobblestone,
612 Sandstone,
614 Planks,
616 Brick,
618 Coal,
620 IronIngot,
622 Log,
624 Snowball,
626 RockFragment,
628 Crystal,
630 RareMineral,
632 WoodenPickaxe,
634 StonePickaxe,
636 IronPickaxe,
638 IronOreItem,
640}
641
642impl ItemType for DefaultItem {
643 fn name(&self) -> &'static str {
644 match self {
645 DefaultItem::Empty => "Empty",
646 DefaultItem::Dirt => "Dirt",
647 DefaultItem::Sand => "Sand",
648 DefaultItem::Wood => "Wood",
649 DefaultItem::Gravel => "Gravel",
650 DefaultItem::Snow => "Snow",
651 DefaultItem::CoalOre => "Coal Ore",
652 DefaultItem::IronOre => "Iron Ore",
653 DefaultItem::IronOreItem => "Iron Ore",
654 DefaultItem::Cobblestone => "Cobblestone",
655 DefaultItem::Sandstone => "Sandstone",
656 DefaultItem::Planks => "Planks",
657 DefaultItem::Brick => "Brick",
658 DefaultItem::Coal => "Coal",
659 DefaultItem::IronIngot => "Iron Ingot",
660 DefaultItem::Log => "Log",
661 DefaultItem::Snowball => "Snowball",
662 DefaultItem::RockFragment => "Rock Fragment",
663 DefaultItem::Crystal => "Crystal",
664 DefaultItem::RareMineral => "Rare Mineral",
665 DefaultItem::WoodenPickaxe => "Wooden Pickaxe",
666 DefaultItem::StonePickaxe => "Stone Pickaxe",
667 DefaultItem::IronPickaxe => "Iron Pickaxe",
668 }
669 }
670
671 fn color(&self) -> [f32; 4] {
672 match self {
673 DefaultItem::Empty => [0.0, 0.0, 0.0, 0.0],
674 DefaultItem::Dirt
676 | DefaultItem::Sand
677 | DefaultItem::Wood
678 | DefaultItem::Gravel
679 | DefaultItem::Snow
680 | DefaultItem::CoalOre
681 | DefaultItem::IronOre
682 | DefaultItem::IronOreItem
683 | DefaultItem::Cobblestone
684 | DefaultItem::Sandstone
685 | DefaultItem::Planks
686 | DefaultItem::Brick => DefaultTerrainVoxel::from_byte(self.to_byte()).color(),
687 DefaultItem::Coal => [0.15, 0.15, 0.15, 1.0],
689 DefaultItem::IronIngot => [0.75, 0.65, 0.55, 1.0],
690 DefaultItem::Log => [0.40, 0.28, 0.12, 1.0],
691 DefaultItem::Snowball => [0.92, 0.95, 1.00, 1.0],
692 DefaultItem::RockFragment => [0.35, 0.30, 0.28, 1.0],
693 DefaultItem::Crystal => [0.40, 0.50, 0.80, 1.0],
694 DefaultItem::RareMineral => [0.20, 0.85, 0.60, 1.0],
695 DefaultItem::WoodenPickaxe => [0.55, 0.35, 0.20, 1.0],
697 DefaultItem::StonePickaxe => [0.50, 0.50, 0.50, 1.0],
698 DefaultItem::IronPickaxe => [0.70, 0.75, 0.80, 1.0],
699 }
700 }
701
702 fn to_byte(&self) -> u8 {
703 match self {
704 DefaultItem::Empty => 0,
705 DefaultItem::Dirt => 2,
707 DefaultItem::Sand => 4,
708 DefaultItem::Wood => 5,
709 DefaultItem::Gravel => 7,
710 DefaultItem::Snow => 8,
711 DefaultItem::CoalOre => 10,
712 DefaultItem::IronOre => 11,
713 DefaultItem::IronOreItem => 11, DefaultItem::Cobblestone => 12,
715 DefaultItem::Sandstone => 13,
716 DefaultItem::Planks => 14,
717 DefaultItem::Brick => 15,
718 DefaultItem::Coal => 16,
720 DefaultItem::IronIngot => 17,
721 DefaultItem::Log => 18,
722 DefaultItem::Snowball => 19,
723 DefaultItem::RockFragment => 20,
724 DefaultItem::Crystal => 21,
725 DefaultItem::RareMineral => 22,
726 DefaultItem::WoodenPickaxe => 23,
727 DefaultItem::StonePickaxe => 24,
728 DefaultItem::IronPickaxe => 25,
729 }
730 }
731
732 fn from_byte(b: u8) -> Self {
733 match b {
734 2 => DefaultItem::Dirt,
736 4 => DefaultItem::Sand,
737 5 => DefaultItem::Wood,
738 7 => DefaultItem::Gravel,
739 8 => DefaultItem::Snow,
740 10 => DefaultItem::CoalOre,
741 11 => DefaultItem::IronOre,
742 12 => DefaultItem::Cobblestone,
743 13 => DefaultItem::Sandstone,
744 14 => DefaultItem::Planks,
745 15 => DefaultItem::Brick,
746 16 => DefaultItem::Coal,
748 17 => DefaultItem::IronIngot,
749 18 => DefaultItem::Log,
750 19 => DefaultItem::Snowball,
751 20 => DefaultItem::RockFragment,
752 21 => DefaultItem::Crystal,
753 22 => DefaultItem::RareMineral,
754 23 => DefaultItem::WoodenPickaxe,
755 24 => DefaultItem::StonePickaxe,
756 25 => DefaultItem::IronPickaxe,
757 _ => DefaultItem::Empty,
759 }
760 }
761
762 fn is_empty(&self) -> bool {
763 matches!(self, DefaultItem::Empty)
764 }
765
766 fn tool_level(&self) -> u8 {
767 match self {
768 DefaultItem::WoodenPickaxe => 1,
769 DefaultItem::StonePickaxe => 1,
770 DefaultItem::IronPickaxe => 2,
771 _ => 0,
772 }
773 }
774
775 fn tool_speed(&self) -> f32 {
776 match self {
777 DefaultItem::WoodenPickaxe => 1.0,
778 DefaultItem::StonePickaxe => 2.0,
779 DefaultItem::IronPickaxe => 4.0,
780 _ => 1.0,
781 }
782 }
783}
784
785#[cfg(test)]
788mod tests {
789 use super::*;
790
791 #[test]
794 fn test_inventory_add_and_count() {
795 let mut inv = Inventory::<DefaultItem>::new(9);
796 let leftover = inv.add(DefaultItem::IronOre, 5);
797 assert_eq!(leftover, 0);
798 assert_eq!(inv.count_of(DefaultItem::IronOre), 5);
799 }
800
801 #[test]
802 fn test_inventory_add_stacks_same_type() {
803 let mut inv = Inventory::<DefaultItem>::new(9);
804 inv.add(DefaultItem::Crystal, 3);
805 inv.add(DefaultItem::Crystal, 7);
806 assert_eq!(inv.count_of(DefaultItem::Crystal), 10);
807 let filled = inv.slots.iter().filter(|s| s.is_some()).count();
809 assert_eq!(filled, 1);
810 }
811
812 #[test]
815 fn test_inventory_remove() {
816 let mut inv = Inventory::<DefaultItem>::new(9);
817 inv.add(DefaultItem::RockFragment, 10);
818 let removed = inv.remove(DefaultItem::RockFragment, 4);
819 assert_eq!(removed, 4);
820 assert_eq!(inv.count_of(DefaultItem::RockFragment), 6);
821 }
822
823 #[test]
824 fn test_inventory_remove_more_than_held_returns_actual() {
825 let mut inv = Inventory::<DefaultItem>::new(9);
826 inv.add(DefaultItem::RareMineral, 3);
827 let removed = inv.remove(DefaultItem::RareMineral, 10);
828 assert_eq!(removed, 3);
829 assert_eq!(inv.count_of(DefaultItem::RareMineral), 0);
830 }
831
832 #[test]
833 fn test_inventory_remove_clears_slot() {
834 let mut inv = Inventory::<DefaultItem>::new(9);
835 inv.add(DefaultItem::IronOre, 2);
836 inv.remove(DefaultItem::IronOre, 2);
837 assert!(inv.slots[0].is_none());
838 }
839
840 #[test]
843 fn test_inventory_full() {
844 let mut inv = Inventory::<DefaultItem>::new(2);
845 inv.add(DefaultItem::IronOre, 1);
846 inv.add(DefaultItem::Crystal, 1);
847 assert!(inv.is_full());
848
849 let leftover = inv.add(DefaultItem::RockFragment, 5);
851 assert_eq!(leftover, 5);
852 }
853
854 #[test]
857 fn container_trait_add_and_count() {
858 let mut inv = Inventory::<DefaultItem>::new(9);
859 let leftover = Container::add(&mut inv, DefaultItem::IronOre, 5);
860 assert_eq!(leftover, 0);
861 assert_eq!(Container::count_of(&inv, DefaultItem::IronOre), 5);
862 }
863
864 #[test]
865 fn container_slot_at_out_of_bounds_returns_none() {
866 let inv = Inventory::<DefaultItem>::new(9);
867 assert!(Container::slot_at(&inv, 100).is_none());
868 }
869
870 #[test]
871 fn container_iter_slots_yields_capacity_items() {
872 let inv = Inventory::<DefaultItem>::new(9);
873 assert_eq!(Container::iter_slots(&inv).count(), 9);
874 }
875
876 #[test]
879 fn container_component_delegates_correctly() {
880 let mut cc = ContainerComponent::<DefaultItem>::new(9);
881 cc.add(DefaultItem::Crystal, 3);
882 assert_eq!(cc.count_of(DefaultItem::Crystal), 3);
883 assert_eq!(cc.0.count_of(DefaultItem::Crystal), 3);
884 }
885
886 #[test]
887 fn container_component_slot_at_oob_no_panic() {
888 let cc = ContainerComponent::<DefaultItem>::new(9);
889 assert!(cc.slot_at(100).is_none());
890 }
891
892 fn stack(item: DefaultItem, count: u32) -> Option<InventorySlot<DefaultItem>> {
893 Some(InventorySlot { item, count })
894 }
895
896 #[test]
897 fn exchange_normalizes_duplicates_and_uses_freed_capacity() {
898 let mut inv = Inventory::new(1);
899 inv.add(DefaultItem::IronOre, 4);
900 assert_eq!(
901 inv.try_exchange_atomic(
902 &[(DefaultItem::IronOre, 2), (DefaultItem::IronOre, 2)],
903 &[(DefaultItem::Crystal, 1), (DefaultItem::Crystal, 2)],
904 ),
905 Some(Ok(()))
906 );
907 assert_eq!(inv.slots, vec![stack(DefaultItem::Crystal, 3)]);
908 assert_eq!(inv.capacity, 1);
909 }
910
911 #[test]
912 fn exchange_failure_preserves_exact_sparse_layout() {
913 let original = Inventory {
914 capacity: 4,
915 slots: vec![
916 stack(DefaultItem::IronOre, 2),
917 None,
918 stack(DefaultItem::IronOre, 1),
919 stack(DefaultItem::Crystal, 7),
920 ],
921 };
922 let requests = [
923 (
924 vec![(DefaultItem::IronOre, 2), (DefaultItem::IronOre, 2)],
925 vec![],
926 ContainerExchangeError::InsufficientItems,
927 ),
928 (
929 vec![(DefaultItem::IronOre, 1)],
930 vec![(DefaultItem::Wood, 1), (DefaultItem::Sand, 1)],
931 ContainerExchangeError::CapacityExceeded,
932 ),
933 (
934 vec![(DefaultItem::IronOre, 1)],
935 vec![(DefaultItem::Crystal, u32::MAX)],
936 ContainerExchangeError::CapacityExceeded,
937 ),
938 (
939 vec![(DefaultItem::IronOre, u32::MAX), (DefaultItem::IronOre, 1)],
940 vec![],
941 ContainerExchangeError::InvalidRequest,
942 ),
943 (
944 vec![],
945 vec![(DefaultItem::Crystal, u32::MAX), (DefaultItem::Crystal, 1)],
946 ContainerExchangeError::InvalidRequest,
947 ),
948 (
949 vec![(DefaultItem::Empty, 1)],
950 vec![],
951 ContainerExchangeError::InvalidRequest,
952 ),
953 (
954 vec![],
955 vec![(DefaultItem::Empty, 1)],
956 ContainerExchangeError::InvalidRequest,
957 ),
958 ];
959 for (remove, add, error) in requests {
960 let mut inv = original.clone();
961 assert_eq!(inv.try_exchange_atomic(&remove, &add), Some(Err(error)));
962 assert_eq!(inv.slots, original.slots);
963 assert_eq!(inv.capacity, original.capacity);
964 }
965 }
966
967 #[test]
968 fn exchange_same_input_outputs_and_existing_duplicate_stacks() {
969 let mut inv = Inventory {
970 capacity: 4,
971 slots: vec![
972 stack(DefaultItem::IronOre, 2),
973 None,
974 stack(DefaultItem::IronOre, 3),
975 stack(DefaultItem::Crystal, 4),
976 ],
977 };
978 assert_eq!(
979 inv.try_exchange_atomic(
980 &[(DefaultItem::IronOre, 4)],
981 &[
982 (DefaultItem::IronOre, 2),
983 (DefaultItem::Crystal, 1),
984 (DefaultItem::IronOre, 3)
985 ],
986 ),
987 Some(Ok(()))
988 );
989 assert_eq!(
990 inv.slots,
991 vec![
992 None,
993 None,
994 stack(DefaultItem::IronOre, 6),
995 stack(DefaultItem::Crystal, 5)
996 ]
997 );
998 }
999
1000 #[test]
1001 fn add_bounds_aggregate_headroom_and_returns_every_leftover() {
1002 let mut inv = Inventory {
1003 capacity: 3,
1004 slots: vec![
1005 stack(DefaultItem::Crystal, u32::MAX - 10),
1006 None,
1007 stack(DefaultItem::Crystal, 5),
1008 ],
1009 };
1010 assert_eq!(inv.add(DefaultItem::Crystal, 8), 3);
1011 assert_eq!(inv.count_of(DefaultItem::Crystal), u32::MAX);
1012 assert_eq!(inv.slots[0], stack(DefaultItem::Crystal, u32::MAX - 5));
1013 assert_eq!(inv.slots[2], stack(DefaultItem::Crystal, 5));
1014 assert!(inv.slots[1].is_none());
1015 let before = inv.slots.clone();
1016 assert_eq!(inv.add(DefaultItem::Crystal, u32::MAX), u32::MAX);
1017 assert_eq!(inv.slots, before);
1018 let mut full = Inventory::new(1);
1019 full.add(DefaultItem::IronOre, 1);
1020 assert_eq!(full.add(DefaultItem::Crystal, u32::MAX), u32::MAX);
1021 }
1022
1023 #[test]
1024 fn malformed_sources_reject_exchange_and_add_without_mutation() {
1025 let invalid = [
1026 Inventory {
1027 capacity: 2,
1028 slots: vec![None],
1029 },
1030 Inventory {
1031 capacity: 0,
1032 slots: vec![None],
1033 },
1034 Inventory {
1035 capacity: 1,
1036 slots: vec![stack(DefaultItem::IronOre, 0)],
1037 },
1038 Inventory {
1039 capacity: 1,
1040 slots: vec![stack(DefaultItem::Empty, 1)],
1041 },
1042 Inventory {
1043 capacity: 2,
1044 slots: vec![
1045 stack(DefaultItem::IronOre, u32::MAX),
1046 stack(DefaultItem::IronOre, 1),
1047 ],
1048 },
1049 ];
1050 for mut inv in invalid {
1051 let before = inv.slots.clone();
1052 let capacity = inv.capacity;
1053 assert_eq!(
1054 inv.validate_integrity(),
1055 Err(ContainerExchangeError::InvalidContainer)
1056 );
1057 assert_eq!(
1058 inv.try_exchange_atomic(&[], &[]),
1059 Some(Err(ContainerExchangeError::InvalidContainer))
1060 );
1061 assert_eq!(inv.add(DefaultItem::Crystal, 5), 5);
1062 assert_eq!(inv.slots, before);
1063 assert_eq!(inv.capacity, capacity);
1064 }
1065 }
1066
1067 #[test]
1068 fn count_of_defensively_saturates_invalid_totals() {
1069 let inv = Inventory {
1070 capacity: 3,
1071 slots: vec![
1072 stack(DefaultItem::Crystal, u32::MAX),
1073 stack(DefaultItem::Crystal, u32::MAX),
1074 stack(DefaultItem::IronOre, 3),
1075 ],
1076 };
1077 assert_eq!(inv.count_of(DefaultItem::Crystal), u32::MAX);
1078 assert_eq!(inv.count_of(DefaultItem::IronOre), 3);
1079 }
1080
1081 #[test]
1082 fn empty_lists_zero_quantities_and_zero_capacity_are_valid() {
1083 let mut inv = Inventory::<DefaultItem>::new(0);
1084 assert_eq!(inv.validate_integrity(), Ok(()));
1085 assert_eq!(inv.try_exchange_atomic(&[], &[]), Some(Ok(())));
1086 assert_eq!(
1087 inv.try_exchange_atomic(&[(DefaultItem::Empty, 0)], &[(DefaultItem::Empty, 0)]),
1088 Some(Ok(()))
1089 );
1090 assert_eq!(inv.add(DefaultItem::Empty, 0), 0);
1091 assert_eq!(inv.add(DefaultItem::Empty, 1), 1);
1092 assert_eq!(inv.add(DefaultItem::Crystal, 1), 1);
1093 assert!(inv.slots.is_empty());
1094 }
1095
1096 #[test]
1097 fn normalization_uses_equality_not_serialized_bytes_and_keeps_order() {
1098 assert_eq!(
1099 DefaultItem::IronOre.to_byte(),
1100 DefaultItem::IronOreItem.to_byte()
1101 );
1102 assert_ne!(DefaultItem::IronOre, DefaultItem::IronOreItem);
1103 assert_eq!(
1104 normalize_quantities(&[
1105 (DefaultItem::Empty, 0),
1106 (DefaultItem::IronOreItem, 1),
1107 (DefaultItem::Crystal, 0),
1108 (DefaultItem::IronOre, 2),
1109 (DefaultItem::IronOreItem, 3),
1110 (DefaultItem::Crystal, 5),
1111 ]),
1112 Ok(vec![
1113 (DefaultItem::IronOreItem, 4),
1114 (DefaultItem::IronOre, 2),
1115 (DefaultItem::Crystal, 5)
1116 ])
1117 );
1118 }
1119
1120 #[derive(Clone, Copy, Default, PartialEq, Eq, Hash)]
1122 enum MinimalItem {
1123 #[default]
1124 DefaultSentinel,
1125 OtherSentinel,
1126 Live,
1127 }
1128
1129 impl ItemType for MinimalItem {
1130 fn name(&self) -> &'static str {
1131 "minimal"
1132 }
1133 fn color(&self) -> [f32; 4] {
1134 [1.0; 4]
1135 }
1136 fn to_byte(&self) -> u8 {
1137 1
1138 }
1139 fn from_byte(_: u8) -> Self {
1140 Self::default()
1141 }
1142 fn is_empty(&self) -> bool {
1143 *self == Self::OtherSentinel
1144 }
1145 }
1146
1147 #[test]
1148 fn exchange_requires_no_new_item_bounds_and_rejects_both_sentinels() {
1149 let mut inv = Inventory::<MinimalItem>::new(1);
1150 assert_eq!(inv.add(MinimalItem::DefaultSentinel, 1), 1);
1151 assert_eq!(inv.add(MinimalItem::OtherSentinel, 1), 1);
1152 assert_eq!(
1153 inv.try_exchange_atomic(&[], &[(MinimalItem::Live, 1)]),
1154 Some(Ok(()))
1155 );
1156 for sentinel in [MinimalItem::DefaultSentinel, MinimalItem::OtherSentinel] {
1157 assert_eq!(
1158 inv.try_exchange_atomic(&[(sentinel, 1)], &[]),
1159 Some(Err(ContainerExchangeError::InvalidRequest))
1160 );
1161 assert_eq!(
1162 inv.try_exchange_atomic(&[], &[(sentinel, 1)]),
1163 Some(Err(ContainerExchangeError::InvalidRequest))
1164 );
1165 assert_eq!(
1166 inv.try_exchange_atomic(&[(sentinel, 0)], &[(sentinel, 0)]),
1167 Some(Ok(()))
1168 );
1169 let invalid = Inventory {
1170 capacity: 1,
1171 slots: vec![Some(InventorySlot {
1172 item: sentinel,
1173 count: 1,
1174 })],
1175 };
1176 assert_eq!(
1177 invalid.validate_integrity(),
1178 Err(ContainerExchangeError::InvalidContainer)
1179 );
1180 }
1181 assert_eq!(inv.count_of(MinimalItem::Live), 1);
1182 }
1183
1184 #[test]
1185 fn component_atomic_exchange_matches_inventory_success_and_failure() {
1186 let mut inv = Inventory::new(1);
1187 inv.add(DefaultItem::IronOre, 4);
1188 let mut component = ContainerComponent(inv.clone());
1189 for (remove, add) in [
1190 (
1191 vec![(DefaultItem::IronOre, 4)],
1192 vec![(DefaultItem::Crystal, 3)],
1193 ),
1194 (vec![], vec![(DefaultItem::Wood, 1)]),
1195 (vec![(DefaultItem::Crystal, 4)], vec![]),
1196 (vec![], vec![(DefaultItem::Empty, 1)]),
1197 ] {
1198 assert_eq!(
1199 component.try_exchange_atomic(&remove, &add),
1200 inv.try_exchange_atomic(&remove, &add)
1201 );
1202 assert_eq!(component.0.slots, inv.slots);
1203 assert_eq!(component.capacity(), inv.capacity);
1204 }
1205 component.0.capacity = 2;
1206 let before = component.0.slots.clone();
1207 assert_eq!(
1208 component.try_exchange_atomic(&[], &[]),
1209 Some(Err(ContainerExchangeError::InvalidContainer))
1210 );
1211 assert_eq!(component.0.slots, before);
1212 }
1213}