voxel-framework 0.10.0

A reusable voxel engine framework built on Bevy
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
//! Slot-based inventory resource and the [`ItemType`] trait.
//!
//! This module is the data layer of the item system.  It defines the
//! [`ItemType`] trait that all item enums must implement, the [`Inventory`]
//! resource that stores collected items, and the [`ItemPickedUp`] message
//! emitted whenever items successfully enter the inventory.
//!
//! The design mirrors [`crate::voxel::VoxelType`]: item types are lightweight
//! value types (typically unit-variant enums) stored densely in a flat slot
//! vector.  The actual spawning, attraction, and pickup logic lives in
//! [`crate::items::drops`]; this module is concerned only with the data model.

use std::hash::Hash;

use crate::voxel::{DefaultTerrainVoxel, VoxelType};
use bevy::prelude::*;

// ─── Container trait ─────────────────────────────────────────────────────────

/// Neutral failure reasons for an atomic container exchange.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ContainerExchangeError {
    /// A positive sentinel quantity or an overflowing quantity list.
    InvalidRequest,
    /// The container's shape, live stacks, or totals are invalid.
    InvalidContainer,
    /// The container cannot supply every requested item.
    InsufficientItems,
    /// The post-consumption outputs exceed slot or numeric capacity.
    CapacityExceeded,
}

/// Normalize by item equality, retaining first-occurrence order (not byte identity).
pub(crate) fn normalize_quantities<I: ItemType>(
    quantities: &[(I, u32)],
) -> Result<Vec<(I, u32)>, ContainerExchangeError> {
    let mut normalized: Vec<(I, u32)> = Vec::new();
    for &(item, count) in quantities {
        if count == 0 {
            continue;
        }
        if item == I::default() || item.is_empty() {
            return Err(ContainerExchangeError::InvalidRequest);
        }
        if let Some((_, total)) = normalized
            .iter_mut()
            .find(|(existing, _)| *existing == item)
        {
            *total = total
                .checked_add(count)
                .ok_or(ContainerExchangeError::InvalidRequest)?;
        } else {
            normalized.push((item, count));
        }
    }
    Ok(normalized)
}

/// Abstraction over slot-based item storage.
///
/// Any type that holds items in indexed slots can implement this trait to be
/// usable with the framework's pickup, hotbar, and crafting systems.
///
/// The framework provides two built-in implementors:
/// - [`Inventory<I>`] — the standalone resource form (backward-compatible).
/// - [`ContainerComponent<I>`] — the Bevy component form used by the new
///   entity-based pipeline.
pub trait Container<I: ItemType> {
    /// Adds `count` of `item`.  Returns the number of items that could NOT be
    /// inserted due to capacity (0 = all inserted).
    fn add(&mut self, item: I, count: u32) -> u32;

    /// Removes up to `count` of `item`.  Returns the number actually removed.
    fn remove(&mut self, item: I, count: u32) -> u32;

    /// Total number of `item` across all slots.
    fn count_of(&self, item: I) -> u32;

    /// Maximum number of distinct item stacks this container can hold.
    fn capacity(&self) -> usize;

    /// Returns `true` if every slot is occupied.
    fn is_full(&self) -> bool;

    /// Iterates over all slots, yielding `Some(&InventorySlot<I>)` for occupied
    /// slots and `None` for empty ones.  Yields exactly `capacity()` items.
    fn iter_slots(&self) -> impl Iterator<Item = Option<&InventorySlot<I>>>;

    /// Returns the slot at `index`, or `None` if the index is out of bounds or
    /// the slot is empty.  Never panics.
    fn slot_at(&self, index: usize) -> Option<&InventorySlot<I>>;

    /// Optionally consume and produce a complete exchange atomically.
    ///
    /// `None` means unsupported; `None` and `Some(Err(_))` MUST leave the
    /// container unchanged. `Some(Ok(()))` means every quantity was exchanged.
    /// Normalize duplicates by equality in first-occurrence order, ignore zero
    /// quantities, allow empty lists, and reject positive default/empty sentinels
    /// and checked `u32` sums that overflow. Evaluate capacity after consumption.
    /// The default keeps existing implementors compatible; legacy crafting may
    /// partially mutate when their individual operations fail.
    fn try_exchange_atomic(
        &mut self,
        _remove: &[(I, u32)],
        _add: &[(I, u32)],
    ) -> Option<Result<(), ContainerExchangeError>> {
        None
    }
}

// ─── ItemType trait ───────────────────────────────────────────────────────────

/// Contract that all item types must satisfy to participate in the item pipeline.
///
/// Implement this trait for any `Copy + Hash + Default` enum to make it usable
/// with [`Inventory`], [`crate::items::drops::DropTable`],
/// [`crate::items::drops::DropsPlugin`], and
/// [`crate::items::persistence::save_inventory`] /
/// [`crate::items::persistence::load_inventory`].
///
/// The framework ships [`DefaultItem`] as a ready-made implementation.
/// Custom implementations should designate one variant as the *empty sentinel*
/// (returned by [`Default`]) and override [`ItemType::is_empty`] accordingly.
///
/// # Contract
///
/// * `Copy + Clone` — slots are copied freely; no heap allocation per item.
/// * `Default` — produces the empty-sentinel value.
/// * `PartialEq + Eq + Hash` — required for slot deduplication and hash-map
///   lookups in [`crate::items::drops::DropTable`].
/// * `Send + Sync + 'static` — required for use as a Bevy [`Resource`] type
///   parameter.
/// * [`to_byte`](ItemType::to_byte) / [`from_byte`](ItemType::from_byte) —
///   stable single-byte encoding used by the JSON persistence layer.  Unknown
///   bytes must round-trip to `Self::default()`.
///
/// # Examples
///
/// ```rust,no_run
/// use voxel_framework::items::ItemType;
///
/// #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
/// enum MyItem { #[default] Empty, Wood, Stone }
///
/// impl ItemType for MyItem {
///     fn name(&self) -> &'static str {
///         match self { MyItem::Empty => "Empty", MyItem::Wood => "Wood", MyItem::Stone => "Stone" }
///     }
///     fn color(&self) -> [f32; 4] {
///         match self {
///             MyItem::Empty => [0.0; 4],
///             MyItem::Wood  => [0.55, 0.35, 0.20, 1.0],
///             MyItem::Stone => [0.50, 0.50, 0.50, 1.0],
///         }
///     }
///     fn to_byte(&self) -> u8   { match self { MyItem::Empty => 0, MyItem::Wood => 1, MyItem::Stone => 2 } }
///     fn from_byte(b: u8) -> Self { match b { 1 => MyItem::Wood, 2 => MyItem::Stone, _ => MyItem::Empty } }
///     fn is_empty(&self) -> bool { matches!(self, MyItem::Empty) }
/// }
/// ```
pub trait ItemType: Copy + Clone + Default + Send + Sync + PartialEq + Eq + Hash + 'static {
    /// Human-readable display name for this item (e.g. `"Iron Ore"`).
    ///
    /// Used by UI widgets such as the pickup notification overlay.
    fn name(&self) -> &'static str;

    /// Default RGBA display colour for this item, with components in `[0.0, 1.0]`.
    ///
    /// Used by hotbar and inventory UI as a fallback when no sprite is available.
    fn color(&self) -> [f32; 4];

    /// Encodes this item variant as a single byte for JSON persistence.
    ///
    /// The mapping must be stable across game versions; changing it will
    /// corrupt existing save files.  The empty-sentinel variant should map
    /// to `0`.
    fn to_byte(&self) -> u8;

    /// Decodes a single byte back into an item variant.
    ///
    /// Unknown byte values — for example from a future game version — **must**
    /// return `Self::default()` rather than panicking so that save files from
    /// newer versions degrade gracefully.
    fn from_byte(b: u8) -> Self;

    /// Returns `true` if this variant is the empty-slot sentinel.
    ///
    /// The default implementation returns `false`; override it for the variant
    /// that represents "nothing here" (typically the `Default` variant).
    fn is_empty(&self) -> bool {
        false
    }

    /// Tool level provided when this item is the active hotbar selection.
    ///
    /// `0` = bare hands. Matched against [`crate::voxel::VoxelType::mining_level`]:
    /// if `tool_level < voxel.mining_level()`, mining makes no progress.
    ///
    /// Default: `0`.
    fn tool_level(&self) -> u8 {
        0
    }

    /// Mining speed multiplier when this item is the active tool.
    ///
    /// The effective break time is divided by this value (`2.0` = twice as fast).
    /// Default: `1.0`.
    fn tool_speed(&self) -> f32 {
        1.0
    }
}

// ─── InventorySlot ────────────────────────────────────────────────────────────

/// A single occupied inventory slot, holding a stack of one item type.
///
/// Slots are always non-empty — "no item" is represented by `None` at the
/// [`Inventory::slots`] level rather than a zero-count `InventorySlot`.
/// The `count` field is therefore always `>= 1` in practice; the drop systems
/// never produce a zero-count slot.
#[derive(Debug, Clone, PartialEq)]
pub struct InventorySlot<I: ItemType> {
    /// The item type stored in this slot.
    pub item: I,
    /// Number of items in the stack.  Always `>= 1` for a live slot.
    pub count: u32,
}

// ─── Inventory ────────────────────────────────────────────────────────────────

/// Fixed-capacity player inventory backed by a flat slot vector.
///
/// The inventory holds up to `capacity` stacks, each stored as
/// `Option<`[`InventorySlot`]`<I>>`.  `None` denotes an empty slot.
///
/// Items of the same type are automatically stacked: [`Inventory::add`]
/// fills existing stacks of the matching type before opening a new slot.
/// [`Inventory::remove`] drains stacks in order and clears slots that reach
/// zero.
///
/// The default capacity is 36 slots (4 rows × 9 columns), matching the
/// standard Minecraft-style layout expected by the built-in hotbar and
/// inventory UI widgets.
///
/// # Examples
///
/// ```rust,no_run
/// use voxel_framework::items::{Inventory, DefaultItem};
///
/// let mut inv = Inventory::<DefaultItem>::new(9);
/// inv.add(DefaultItem::IronOre, 5);
/// assert_eq!(inv.count_of(DefaultItem::IronOre), 5);
/// ```
#[derive(Resource, Debug, Clone)]
pub struct Inventory<I: ItemType> {
    /// The backing slot vector.  `None` at index `i` means slot `i` is empty.
    ///
    /// The length always equals `capacity`; slots are never removed from the
    /// vector.
    pub slots: Vec<Option<InventorySlot<I>>>,
    /// Maximum number of distinct item stacks the inventory can hold.
    ///
    /// Set at construction time; cannot be changed after the fact without
    /// rebuilding the inventory.
    pub capacity: usize,
}

impl<I: ItemType> Inventory<I> {
    /// Check publicly writable fields before transactional use or persistence.
    pub(crate) fn validate_integrity(&self) -> Result<(), ContainerExchangeError> {
        if self.capacity != self.slots.len() {
            return Err(ContainerExchangeError::InvalidContainer);
        }
        let quantities: Vec<_> = self
            .slots
            .iter()
            .flatten()
            .map(|slot| (slot.item, slot.count))
            .collect();
        if quantities.iter().any(|(_, count)| *count == 0) {
            return Err(ContainerExchangeError::InvalidContainer);
        }
        normalize_quantities(&quantities)
            .map(|_| ())
            .map_err(|_| ContainerExchangeError::InvalidContainer)
    }

    fn exchange_atomic(
        &mut self,
        remove: &[(I, u32)],
        add: &[(I, u32)],
    ) -> Result<(), ContainerExchangeError> {
        let remove = normalize_quantities(remove)?;
        let add = normalize_quantities(add)?;
        self.validate_integrity()?;
        if remove
            .iter()
            .any(|&(item, count)| self.count_of(item) < count)
        {
            return Err(ContainerExchangeError::InsufficientItems);
        }
        // Copy only private staging data: no extra Clone bound on item/container.
        let mut staged = Self {
            slots: self.slots.clone(),
            capacity: self.capacity,
        };
        for (item, count) in remove {
            if staged.remove(item, count) != count {
                return Err(ContainerExchangeError::InsufficientItems);
            }
        }
        for (item, count) in add {
            if staged.add(item, count) != 0 {
                return Err(ContainerExchangeError::CapacityExceeded);
            }
        }
        self.slots = staged.slots;
        Ok(())
    }

    /// Creates a new empty inventory with the given slot capacity.
    pub fn new(capacity: usize) -> Self {
        Self {
            slots: vec![None; capacity],
            capacity,
        }
    }

    /// Adds `count` of `item` to the inventory.
    ///
    /// Items are stacked onto existing slots of the same type first, then into
    /// empty slots. Returns the number of items that could **not** be added
    /// because slot capacity or the per-item `u32` representational ceiling is
    /// exceeded. This is not an author-configured stack limit. Invalid public
    /// fields or positive default/empty sentinels are rejected without mutation.
    pub fn add(&mut self, item: I, count: u32) -> u32 {
        if count == 0 {
            return 0;
        }
        if item == I::default() || item.is_empty() || self.validate_integrity().is_err() {
            return count;
        }
        let accepted = count.min(u32::MAX - self.count_of(item));
        let mut remaining = accepted;

        // First pass: fill existing stacks.
        for slot in self.slots.iter_mut().flatten() {
            if remaining == 0 {
                break;
            }
            if slot.item == item {
                slot.count += remaining;
                remaining = 0;
            }
        }

        // Second pass: open new slots for leftovers.
        if remaining > 0 {
            for slot in self.slots.iter_mut() {
                if remaining == 0 {
                    break;
                }
                if slot.is_none() {
                    *slot = Some(InventorySlot {
                        item,
                        count: remaining,
                    });
                    remaining = 0;
                }
            }
        }

        (count - accepted) + remaining
    }

    /// Removes up to `count` of `item` from the inventory.
    ///
    /// Returns the number of items that were actually removed (may be less than
    /// `count` if the inventory held fewer).
    pub fn remove(&mut self, item: I, count: u32) -> u32 {
        let mut to_remove = count;
        let mut removed = 0u32;

        for slot in self.slots.iter_mut() {
            if to_remove == 0 {
                break;
            }
            if let Some(s) = slot {
                if s.item == item {
                    let take = s.count.min(to_remove);
                    s.count -= take;
                    to_remove -= take;
                    removed += take;
                    if s.count == 0 {
                        *slot = None;
                    }
                }
            }
        }

        removed
    }

    /// Returns the total number of `item`, defensively saturating for invalid
    /// publicly modified fields rather than wrapping or panicking.
    pub fn count_of(&self, item: I) -> u32 {
        self.slots
            .iter()
            .flatten()
            .filter(|s| s.item == item)
            .fold(0u32, |total, slot| total.saturating_add(slot.count))
    }

    /// Returns `true` if every slot is occupied.
    pub fn is_full(&self) -> bool {
        self.slots.iter().all(|s| s.is_some())
    }
}

impl<I: ItemType> Default for Inventory<I> {
    /// Creates a default inventory with 36 slots (4 rows × 9 columns).
    fn default() -> Self {
        Self::new(36)
    }
}

// ─── Container impl for Inventory ────────────────────────────────────────────

impl<I: ItemType> Container<I> for Inventory<I> {
    fn try_exchange_atomic(
        &mut self,
        remove: &[(I, u32)],
        add: &[(I, u32)],
    ) -> Option<Result<(), ContainerExchangeError>> {
        Some(self.exchange_atomic(remove, add))
    }

    fn add(&mut self, item: I, count: u32) -> u32 {
        Inventory::add(self, item, count)
    }

    fn remove(&mut self, item: I, count: u32) -> u32 {
        Inventory::remove(self, item, count)
    }

    fn count_of(&self, item: I) -> u32 {
        Inventory::count_of(self, item)
    }

    fn capacity(&self) -> usize {
        self.capacity
    }

    fn is_full(&self) -> bool {
        Inventory::is_full(self)
    }

    fn iter_slots(&self) -> impl Iterator<Item = Option<&InventorySlot<I>>> {
        self.slots.iter().map(|s| s.as_ref())
    }

    fn slot_at(&self, index: usize) -> Option<&InventorySlot<I>> {
        self.slots.get(index).and_then(|s| s.as_ref())
    }
}

// ─── ContainerComponent ───────────────────────────────────────────────────────

/// Bevy [`Component`] newtype that wraps an [`Inventory<I>`] for use in the
/// entity-based item pipeline.
///
/// Add this alongside [`PrimaryContainer`] on the player entity so the magnet,
/// hotbar, and crafting systems can locate the player's inventory via ECS
/// queries instead of a global resource.
///
/// # Examples
///
/// ```rust,no_run
/// use bevy::prelude::*;
/// use voxel_framework::items::{ContainerComponent, PrimaryContainer, DefaultItem};
///
/// fn spawn_player(mut commands: Commands) {
///     commands.spawn((
///         ContainerComponent::<DefaultItem>::new(36),
///         PrimaryContainer,
///     ));
/// }
/// ```
#[derive(Component)]
pub struct ContainerComponent<I: ItemType>(pub Inventory<I>);

impl<I: ItemType> ContainerComponent<I> {
    /// Creates a new `ContainerComponent` wrapping a fresh [`Inventory`] with
    /// the given `capacity`.
    pub fn new(capacity: usize) -> Self {
        Self(Inventory::new(capacity))
    }
}

impl<I: ItemType> Container<I> for ContainerComponent<I> {
    fn try_exchange_atomic(
        &mut self,
        remove: &[(I, u32)],
        add: &[(I, u32)],
    ) -> Option<Result<(), ContainerExchangeError>> {
        Container::try_exchange_atomic(&mut self.0, remove, add)
    }

    fn add(&mut self, item: I, count: u32) -> u32 {
        self.0.add(item, count)
    }

    fn remove(&mut self, item: I, count: u32) -> u32 {
        self.0.remove(item, count)
    }

    fn count_of(&self, item: I) -> u32 {
        self.0.count_of(item)
    }

    fn capacity(&self) -> usize {
        self.0.capacity
    }

    fn is_full(&self) -> bool {
        self.0.is_full()
    }

    fn iter_slots(&self) -> impl Iterator<Item = Option<&InventorySlot<I>>> {
        self.0.slots.iter().map(|s| s.as_ref())
    }

    fn slot_at(&self, index: usize) -> Option<&InventorySlot<I>> {
        self.0.slots.get(index).and_then(|s| s.as_ref())
    }
}

// ─── PrimaryContainer marker ──────────────────────────────────────────────────

/// Zero-size marker component that identifies the entity whose
/// [`ContainerComponent`] is the player's primary backpack.
///
/// Exactly one entity should carry this marker at runtime.  If zero or more
/// than one exist, the pickup and hotbar systems skip silently — no panic.
#[derive(Component, Default)]
pub struct PrimaryContainer;

// ─── Messages ────────────────────────────────────────────────────────────────

/// Message emitted when one or more items are successfully added to the inventory.
///
/// The magnet system in [`crate::items::drops`] writes this message after
/// adding items to [`Inventory`].  UI systems — such as the pickup notification
/// overlay — subscribe to this message to display transient feedback.
///
/// Note: this message is only written when at least one item was actually
/// inserted (i.e. `count > 0`).  If the inventory was full the message is
/// **not** written even though a pickup was attempted.
#[derive(Message, Debug, Clone)]
pub struct ItemPickedUp<I: ItemType> {
    /// The item type that was picked up.
    pub item: I,
    /// Number of items that were successfully inserted.  Always `>= 1`.
    pub count: u32,
}

// ─── DefaultItem ─────────────────────────────────────────────────────────────

/// Built-in item type covering common mineral pickups.
///
/// `DefaultItem` is the item counterpart of [`crate::voxel::DefaultVoxel`]:
/// it implements [`ItemType`] out of the box and is wired into the default
/// [`crate::items::drops::DropTable`] entries provided by the framework.
///
/// `Empty` is the empty-slot sentinel returned by [`Default`] and by
/// [`ItemType::from_byte`] for unknown byte values.  It should never appear
/// as a real collectible.
///
/// # Examples
///
/// ```rust,no_run
/// use voxel_framework::items::{DefaultItem, Inventory};
///
/// let mut inv = Inventory::<DefaultItem>::new(9);
/// inv.add(DefaultItem::Crystal, 3);
/// ```
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, Hash, Default, serde::Serialize, serde::Deserialize,
)]
pub enum DefaultItem {
    /// Empty slot sentinel — not a real item; returned by [`Default`].
    #[default]
    Empty,
    /// Dirt block; placeable Dirt voxel item (byte 2, matches DefaultTerrainVoxel::Dirt).
    Dirt,
    /// Sand block; placeable Sand voxel item (byte 4, matches DefaultTerrainVoxel::Sand).
    Sand,
    /// Wood log block; placeable Wood voxel item (byte 5, matches DefaultTerrainVoxel::Wood).
    Wood,
    /// Gravel block; placeable Gravel voxel item (byte 7, matches DefaultTerrainVoxel::Gravel).
    Gravel,
    /// Snow block; placeable Snow voxel item (byte 8, matches DefaultTerrainVoxel::Snow).
    Snow,
    /// Coal ore block; placeable CoalOre voxel item (byte 10, matches DefaultTerrainVoxel::CoalOre).
    CoalOre,
    /// Iron ore block; placeable IronOre voxel item (byte 11, matches DefaultTerrainVoxel::IronOre).
    IronOre,
    /// Cobblestone block; placeable Cobblestone voxel item (byte 12).
    Cobblestone,
    /// Sandstone block; placeable Sandstone voxel item (byte 13).
    Sandstone,
    /// Wooden planks block; placeable Planks voxel item (byte 14).
    Planks,
    /// Fired clay brick block; placeable Brick voxel item (byte 15).
    Brick,
    /// Coal lump; dropped from CoalOre voxels (byte 16).
    Coal,
    /// Smelted iron ingot; produced from IronOre (byte 17).
    IronIngot,
    /// Wood log; dropped from Wood voxels (byte 18).
    Log,
    /// Snowball; dropped from Snow voxels (byte 19).
    Snowball,
    /// Fragment of common rock; drops from Stone voxels (byte 20).
    RockFragment,
    /// Silicon crystal shard; drops from crystal voxels (byte 21).
    Crystal,
    /// Rare mineral node; drops from high-value voxels (byte 22).
    RareMineral,
    /// Wooden pickaxe — tool level 1, normal speed. Crafted from wood (byte 23).
    WoodenPickaxe,
    /// Stone pickaxe — tool level 1, 2× speed. Crafted from rock fragments (byte 24).
    StonePickaxe,
    /// Iron pickaxe — tool level 2, 4× speed. Crafted from iron ore (byte 25).
    IronPickaxe,
    /// Deprecated alias for IronOre block — maps to byte 11 on write, never returned by from_byte.
    IronOreItem,
}

impl ItemType for DefaultItem {
    fn name(&self) -> &'static str {
        match self {
            DefaultItem::Empty => "Empty",
            DefaultItem::Dirt => "Dirt",
            DefaultItem::Sand => "Sand",
            DefaultItem::Wood => "Wood",
            DefaultItem::Gravel => "Gravel",
            DefaultItem::Snow => "Snow",
            DefaultItem::CoalOre => "Coal Ore",
            DefaultItem::IronOre => "Iron Ore",
            DefaultItem::IronOreItem => "Iron Ore",
            DefaultItem::Cobblestone => "Cobblestone",
            DefaultItem::Sandstone => "Sandstone",
            DefaultItem::Planks => "Planks",
            DefaultItem::Brick => "Brick",
            DefaultItem::Coal => "Coal",
            DefaultItem::IronIngot => "Iron Ingot",
            DefaultItem::Log => "Log",
            DefaultItem::Snowball => "Snowball",
            DefaultItem::RockFragment => "Rock Fragment",
            DefaultItem::Crystal => "Crystal",
            DefaultItem::RareMineral => "Rare Mineral",
            DefaultItem::WoodenPickaxe => "Wooden Pickaxe",
            DefaultItem::StonePickaxe => "Stone Pickaxe",
            DefaultItem::IronPickaxe => "Iron Pickaxe",
        }
    }

    fn color(&self) -> [f32; 4] {
        match self {
            DefaultItem::Empty => [0.0, 0.0, 0.0, 0.0],
            // Block-items: delegate to the matching voxel color for visual consistency.
            DefaultItem::Dirt
            | DefaultItem::Sand
            | DefaultItem::Wood
            | DefaultItem::Gravel
            | DefaultItem::Snow
            | DefaultItem::CoalOre
            | DefaultItem::IronOre
            | DefaultItem::IronOreItem
            | DefaultItem::Cobblestone
            | DefaultItem::Sandstone
            | DefaultItem::Planks
            | DefaultItem::Brick => DefaultTerrainVoxel::from_byte(self.to_byte()).color(),
            // Processed / dropped items — explicit colors.
            DefaultItem::Coal => [0.15, 0.15, 0.15, 1.0],
            DefaultItem::IronIngot => [0.75, 0.65, 0.55, 1.0],
            DefaultItem::Log => [0.40, 0.28, 0.12, 1.0],
            DefaultItem::Snowball => [0.92, 0.95, 1.00, 1.0],
            DefaultItem::RockFragment => [0.35, 0.30, 0.28, 1.0],
            DefaultItem::Crystal => [0.40, 0.50, 0.80, 1.0],
            DefaultItem::RareMineral => [0.20, 0.85, 0.60, 1.0],
            // Tools.
            DefaultItem::WoodenPickaxe => [0.55, 0.35, 0.20, 1.0],
            DefaultItem::StonePickaxe => [0.50, 0.50, 0.50, 1.0],
            DefaultItem::IronPickaxe => [0.70, 0.75, 0.80, 1.0],
        }
    }

    fn to_byte(&self) -> u8 {
        match self {
            DefaultItem::Empty => 0,
            // Block-items: bytes match DefaultTerrainVoxel::to_byte()
            DefaultItem::Dirt => 2,
            DefaultItem::Sand => 4,
            DefaultItem::Wood => 5,
            DefaultItem::Gravel => 7,
            DefaultItem::Snow => 8,
            DefaultItem::CoalOre => 10,
            DefaultItem::IronOre => 11,
            DefaultItem::IronOreItem => 11, // deprecated alias; collapses to IronOre byte
            DefaultItem::Cobblestone => 12,
            DefaultItem::Sandstone => 13,
            DefaultItem::Planks => 14,
            DefaultItem::Brick => 15,
            // Processed / dropped items
            DefaultItem::Coal => 16,
            DefaultItem::IronIngot => 17,
            DefaultItem::Log => 18,
            DefaultItem::Snowball => 19,
            DefaultItem::RockFragment => 20,
            DefaultItem::Crystal => 21,
            DefaultItem::RareMineral => 22,
            DefaultItem::WoodenPickaxe => 23,
            DefaultItem::StonePickaxe => 24,
            DefaultItem::IronPickaxe => 25,
        }
    }

    fn from_byte(b: u8) -> Self {
        match b {
            // Block-items (bytes 2–15 mirror DefaultTerrainVoxel)
            2 => DefaultItem::Dirt,
            4 => DefaultItem::Sand,
            5 => DefaultItem::Wood,
            7 => DefaultItem::Gravel,
            8 => DefaultItem::Snow,
            10 => DefaultItem::CoalOre,
            11 => DefaultItem::IronOre,
            12 => DefaultItem::Cobblestone,
            13 => DefaultItem::Sandstone,
            14 => DefaultItem::Planks,
            15 => DefaultItem::Brick,
            // Processed / dropped items
            16 => DefaultItem::Coal,
            17 => DefaultItem::IronIngot,
            18 => DefaultItem::Log,
            19 => DefaultItem::Snowball,
            20 => DefaultItem::RockFragment,
            21 => DefaultItem::Crystal,
            22 => DefaultItem::RareMineral,
            23 => DefaultItem::WoodenPickaxe,
            24 => DefaultItem::StonePickaxe,
            25 => DefaultItem::IronPickaxe,
            // Bytes 0, 1, 3, 6, 9 and anything else → Empty
            _ => DefaultItem::Empty,
        }
    }

    fn is_empty(&self) -> bool {
        matches!(self, DefaultItem::Empty)
    }

    fn tool_level(&self) -> u8 {
        match self {
            DefaultItem::WoodenPickaxe => 1,
            DefaultItem::StonePickaxe => 1,
            DefaultItem::IronPickaxe => 2,
            _ => 0,
        }
    }

    fn tool_speed(&self) -> f32 {
        match self {
            DefaultItem::WoodenPickaxe => 1.0,
            DefaultItem::StonePickaxe => 2.0,
            DefaultItem::IronPickaxe => 4.0,
            _ => 1.0,
        }
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;

    // ── add ──────────────────────────────────────────────────────────────────

    #[test]
    fn test_inventory_add_and_count() {
        let mut inv = Inventory::<DefaultItem>::new(9);
        let leftover = inv.add(DefaultItem::IronOre, 5);
        assert_eq!(leftover, 0);
        assert_eq!(inv.count_of(DefaultItem::IronOre), 5);
    }

    #[test]
    fn test_inventory_add_stacks_same_type() {
        let mut inv = Inventory::<DefaultItem>::new(9);
        inv.add(DefaultItem::Crystal, 3);
        inv.add(DefaultItem::Crystal, 7);
        assert_eq!(inv.count_of(DefaultItem::Crystal), 10);
        // Should occupy only one slot.
        let filled = inv.slots.iter().filter(|s| s.is_some()).count();
        assert_eq!(filled, 1);
    }

    // ── remove ───────────────────────────────────────────────────────────────

    #[test]
    fn test_inventory_remove() {
        let mut inv = Inventory::<DefaultItem>::new(9);
        inv.add(DefaultItem::RockFragment, 10);
        let removed = inv.remove(DefaultItem::RockFragment, 4);
        assert_eq!(removed, 4);
        assert_eq!(inv.count_of(DefaultItem::RockFragment), 6);
    }

    #[test]
    fn test_inventory_remove_more_than_held_returns_actual() {
        let mut inv = Inventory::<DefaultItem>::new(9);
        inv.add(DefaultItem::RareMineral, 3);
        let removed = inv.remove(DefaultItem::RareMineral, 10);
        assert_eq!(removed, 3);
        assert_eq!(inv.count_of(DefaultItem::RareMineral), 0);
    }

    #[test]
    fn test_inventory_remove_clears_slot() {
        let mut inv = Inventory::<DefaultItem>::new(9);
        inv.add(DefaultItem::IronOre, 2);
        inv.remove(DefaultItem::IronOre, 2);
        assert!(inv.slots[0].is_none());
    }

    // ── full ─────────────────────────────────────────────────────────────────

    #[test]
    fn test_inventory_full() {
        let mut inv = Inventory::<DefaultItem>::new(2);
        inv.add(DefaultItem::IronOre, 1);
        inv.add(DefaultItem::Crystal, 1);
        assert!(inv.is_full());

        // Adding more should return a leftover.
        let leftover = inv.add(DefaultItem::RockFragment, 5);
        assert_eq!(leftover, 5);
    }

    // ── Container trait via Inventory ─────────────────────────────────────────

    #[test]
    fn container_trait_add_and_count() {
        let mut inv = Inventory::<DefaultItem>::new(9);
        let leftover = Container::add(&mut inv, DefaultItem::IronOre, 5);
        assert_eq!(leftover, 0);
        assert_eq!(Container::count_of(&inv, DefaultItem::IronOre), 5);
    }

    #[test]
    fn container_slot_at_out_of_bounds_returns_none() {
        let inv = Inventory::<DefaultItem>::new(9);
        assert!(Container::slot_at(&inv, 100).is_none());
    }

    #[test]
    fn container_iter_slots_yields_capacity_items() {
        let inv = Inventory::<DefaultItem>::new(9);
        assert_eq!(Container::iter_slots(&inv).count(), 9);
    }

    // ── ContainerComponent ───────────────────────────────────────────────────

    #[test]
    fn container_component_delegates_correctly() {
        let mut cc = ContainerComponent::<DefaultItem>::new(9);
        cc.add(DefaultItem::Crystal, 3);
        assert_eq!(cc.count_of(DefaultItem::Crystal), 3);
        assert_eq!(cc.0.count_of(DefaultItem::Crystal), 3);
    }

    #[test]
    fn container_component_slot_at_oob_no_panic() {
        let cc = ContainerComponent::<DefaultItem>::new(9);
        assert!(cc.slot_at(100).is_none());
    }

    fn stack(item: DefaultItem, count: u32) -> Option<InventorySlot<DefaultItem>> {
        Some(InventorySlot { item, count })
    }

    #[test]
    fn exchange_normalizes_duplicates_and_uses_freed_capacity() {
        let mut inv = Inventory::new(1);
        inv.add(DefaultItem::IronOre, 4);
        assert_eq!(
            inv.try_exchange_atomic(
                &[(DefaultItem::IronOre, 2), (DefaultItem::IronOre, 2)],
                &[(DefaultItem::Crystal, 1), (DefaultItem::Crystal, 2)],
            ),
            Some(Ok(()))
        );
        assert_eq!(inv.slots, vec![stack(DefaultItem::Crystal, 3)]);
        assert_eq!(inv.capacity, 1);
    }

    #[test]
    fn exchange_failure_preserves_exact_sparse_layout() {
        let original = Inventory {
            capacity: 4,
            slots: vec![
                stack(DefaultItem::IronOre, 2),
                None,
                stack(DefaultItem::IronOre, 1),
                stack(DefaultItem::Crystal, 7),
            ],
        };
        let requests = [
            (
                vec![(DefaultItem::IronOre, 2), (DefaultItem::IronOre, 2)],
                vec![],
                ContainerExchangeError::InsufficientItems,
            ),
            (
                vec![(DefaultItem::IronOre, 1)],
                vec![(DefaultItem::Wood, 1), (DefaultItem::Sand, 1)],
                ContainerExchangeError::CapacityExceeded,
            ),
            (
                vec![(DefaultItem::IronOre, 1)],
                vec![(DefaultItem::Crystal, u32::MAX)],
                ContainerExchangeError::CapacityExceeded,
            ),
            (
                vec![(DefaultItem::IronOre, u32::MAX), (DefaultItem::IronOre, 1)],
                vec![],
                ContainerExchangeError::InvalidRequest,
            ),
            (
                vec![],
                vec![(DefaultItem::Crystal, u32::MAX), (DefaultItem::Crystal, 1)],
                ContainerExchangeError::InvalidRequest,
            ),
            (
                vec![(DefaultItem::Empty, 1)],
                vec![],
                ContainerExchangeError::InvalidRequest,
            ),
            (
                vec![],
                vec![(DefaultItem::Empty, 1)],
                ContainerExchangeError::InvalidRequest,
            ),
        ];
        for (remove, add, error) in requests {
            let mut inv = original.clone();
            assert_eq!(inv.try_exchange_atomic(&remove, &add), Some(Err(error)));
            assert_eq!(inv.slots, original.slots);
            assert_eq!(inv.capacity, original.capacity);
        }
    }

    #[test]
    fn exchange_same_input_outputs_and_existing_duplicate_stacks() {
        let mut inv = Inventory {
            capacity: 4,
            slots: vec![
                stack(DefaultItem::IronOre, 2),
                None,
                stack(DefaultItem::IronOre, 3),
                stack(DefaultItem::Crystal, 4),
            ],
        };
        assert_eq!(
            inv.try_exchange_atomic(
                &[(DefaultItem::IronOre, 4)],
                &[
                    (DefaultItem::IronOre, 2),
                    (DefaultItem::Crystal, 1),
                    (DefaultItem::IronOre, 3)
                ],
            ),
            Some(Ok(()))
        );
        assert_eq!(
            inv.slots,
            vec![
                None,
                None,
                stack(DefaultItem::IronOre, 6),
                stack(DefaultItem::Crystal, 5)
            ]
        );
    }

    #[test]
    fn add_bounds_aggregate_headroom_and_returns_every_leftover() {
        let mut inv = Inventory {
            capacity: 3,
            slots: vec![
                stack(DefaultItem::Crystal, u32::MAX - 10),
                None,
                stack(DefaultItem::Crystal, 5),
            ],
        };
        assert_eq!(inv.add(DefaultItem::Crystal, 8), 3);
        assert_eq!(inv.count_of(DefaultItem::Crystal), u32::MAX);
        assert_eq!(inv.slots[0], stack(DefaultItem::Crystal, u32::MAX - 5));
        assert_eq!(inv.slots[2], stack(DefaultItem::Crystal, 5));
        assert!(inv.slots[1].is_none());
        let before = inv.slots.clone();
        assert_eq!(inv.add(DefaultItem::Crystal, u32::MAX), u32::MAX);
        assert_eq!(inv.slots, before);
        let mut full = Inventory::new(1);
        full.add(DefaultItem::IronOre, 1);
        assert_eq!(full.add(DefaultItem::Crystal, u32::MAX), u32::MAX);
    }

    #[test]
    fn malformed_sources_reject_exchange_and_add_without_mutation() {
        let invalid = [
            Inventory {
                capacity: 2,
                slots: vec![None],
            },
            Inventory {
                capacity: 0,
                slots: vec![None],
            },
            Inventory {
                capacity: 1,
                slots: vec![stack(DefaultItem::IronOre, 0)],
            },
            Inventory {
                capacity: 1,
                slots: vec![stack(DefaultItem::Empty, 1)],
            },
            Inventory {
                capacity: 2,
                slots: vec![
                    stack(DefaultItem::IronOre, u32::MAX),
                    stack(DefaultItem::IronOre, 1),
                ],
            },
        ];
        for mut inv in invalid {
            let before = inv.slots.clone();
            let capacity = inv.capacity;
            assert_eq!(
                inv.validate_integrity(),
                Err(ContainerExchangeError::InvalidContainer)
            );
            assert_eq!(
                inv.try_exchange_atomic(&[], &[]),
                Some(Err(ContainerExchangeError::InvalidContainer))
            );
            assert_eq!(inv.add(DefaultItem::Crystal, 5), 5);
            assert_eq!(inv.slots, before);
            assert_eq!(inv.capacity, capacity);
        }
    }

    #[test]
    fn count_of_defensively_saturates_invalid_totals() {
        let inv = Inventory {
            capacity: 3,
            slots: vec![
                stack(DefaultItem::Crystal, u32::MAX),
                stack(DefaultItem::Crystal, u32::MAX),
                stack(DefaultItem::IronOre, 3),
            ],
        };
        assert_eq!(inv.count_of(DefaultItem::Crystal), u32::MAX);
        assert_eq!(inv.count_of(DefaultItem::IronOre), 3);
    }

    #[test]
    fn empty_lists_zero_quantities_and_zero_capacity_are_valid() {
        let mut inv = Inventory::<DefaultItem>::new(0);
        assert_eq!(inv.validate_integrity(), Ok(()));
        assert_eq!(inv.try_exchange_atomic(&[], &[]), Some(Ok(())));
        assert_eq!(
            inv.try_exchange_atomic(&[(DefaultItem::Empty, 0)], &[(DefaultItem::Empty, 0)]),
            Some(Ok(()))
        );
        assert_eq!(inv.add(DefaultItem::Empty, 0), 0);
        assert_eq!(inv.add(DefaultItem::Empty, 1), 1);
        assert_eq!(inv.add(DefaultItem::Crystal, 1), 1);
        assert!(inv.slots.is_empty());
    }

    #[test]
    fn normalization_uses_equality_not_serialized_bytes_and_keeps_order() {
        assert_eq!(
            DefaultItem::IronOre.to_byte(),
            DefaultItem::IronOreItem.to_byte()
        );
        assert_ne!(DefaultItem::IronOre, DefaultItem::IronOreItem);
        assert_eq!(
            normalize_quantities(&[
                (DefaultItem::Empty, 0),
                (DefaultItem::IronOreItem, 1),
                (DefaultItem::Crystal, 0),
                (DefaultItem::IronOre, 2),
                (DefaultItem::IronOreItem, 3),
                (DefaultItem::Crystal, 5),
            ]),
            Ok(vec![
                (DefaultItem::IronOreItem, 4),
                (DefaultItem::IronOre, 2),
                (DefaultItem::Crystal, 5)
            ])
        );
    }

    // Deliberately no Debug/Serialize derives and no is_empty override for Default.
    #[derive(Clone, Copy, Default, PartialEq, Eq, Hash)]
    enum MinimalItem {
        #[default]
        DefaultSentinel,
        OtherSentinel,
        Live,
    }

    impl ItemType for MinimalItem {
        fn name(&self) -> &'static str {
            "minimal"
        }
        fn color(&self) -> [f32; 4] {
            [1.0; 4]
        }
        fn to_byte(&self) -> u8 {
            1
        }
        fn from_byte(_: u8) -> Self {
            Self::default()
        }
        fn is_empty(&self) -> bool {
            *self == Self::OtherSentinel
        }
    }

    #[test]
    fn exchange_requires_no_new_item_bounds_and_rejects_both_sentinels() {
        let mut inv = Inventory::<MinimalItem>::new(1);
        assert_eq!(inv.add(MinimalItem::DefaultSentinel, 1), 1);
        assert_eq!(inv.add(MinimalItem::OtherSentinel, 1), 1);
        assert_eq!(
            inv.try_exchange_atomic(&[], &[(MinimalItem::Live, 1)]),
            Some(Ok(()))
        );
        for sentinel in [MinimalItem::DefaultSentinel, MinimalItem::OtherSentinel] {
            assert_eq!(
                inv.try_exchange_atomic(&[(sentinel, 1)], &[]),
                Some(Err(ContainerExchangeError::InvalidRequest))
            );
            assert_eq!(
                inv.try_exchange_atomic(&[], &[(sentinel, 1)]),
                Some(Err(ContainerExchangeError::InvalidRequest))
            );
            assert_eq!(
                inv.try_exchange_atomic(&[(sentinel, 0)], &[(sentinel, 0)]),
                Some(Ok(()))
            );
            let invalid = Inventory {
                capacity: 1,
                slots: vec![Some(InventorySlot {
                    item: sentinel,
                    count: 1,
                })],
            };
            assert_eq!(
                invalid.validate_integrity(),
                Err(ContainerExchangeError::InvalidContainer)
            );
        }
        assert_eq!(inv.count_of(MinimalItem::Live), 1);
    }

    #[test]
    fn component_atomic_exchange_matches_inventory_success_and_failure() {
        let mut inv = Inventory::new(1);
        inv.add(DefaultItem::IronOre, 4);
        let mut component = ContainerComponent(inv.clone());
        for (remove, add) in [
            (
                vec![(DefaultItem::IronOre, 4)],
                vec![(DefaultItem::Crystal, 3)],
            ),
            (vec![], vec![(DefaultItem::Wood, 1)]),
            (vec![(DefaultItem::Crystal, 4)], vec![]),
            (vec![], vec![(DefaultItem::Empty, 1)]),
        ] {
            assert_eq!(
                component.try_exchange_atomic(&remove, &add),
                inv.try_exchange_atomic(&remove, &add)
            );
            assert_eq!(component.0.slots, inv.slots);
            assert_eq!(component.capacity(), inv.capacity);
        }
        component.0.capacity = 2;
        let before = component.0.slots.clone();
        assert_eq!(
            component.try_exchange_atomic(&[], &[]),
            Some(Err(ContainerExchangeError::InvalidContainer))
        );
        assert_eq!(component.0.slots, before);
    }
}