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