ghast-inventory 0.4.6

Inventory and container windows for the ghast Minecraft Java Edition client library: vanilla client-side click prediction, the window confirm protocol, hashed 26.1 clicks and lazy NBT / data-component item stacks (1.8.9, 1.12.2, 1.16.5, 26.1 and 26.2)
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
//! 26.1 (protocol 775) items: default components of every item (Mojang's `--reports` component
//! dump, see `examples/gen_items_26_1.rs`), readers for the components the click rules and the
//! item accessors use, the window types, and the hashed stacks a 26.1 client sends with every
//! click (vanilla `HashedStack` / `HashedPatchMap` over `HashOps.CRC32C_INSTANCE`).

use bytes::Bytes;
use ghast_protocol::codec::Reader;
use ghast_protocol::nbt::{AnonNbt, Tag};

use crate::stack::{ItemData, Stack};
use crate::window::WindowKind;

#[path = "item26_hash.rs"]
mod hash;
pub use hash::HashRegistries;
pub(crate) use hash::{component_hash, hash_covers};

pub(crate) use crate::tables::{
    BANNER, BEACON_PAYMENT, BREWING_FUEL, BREWING_INGREDIENT, FITS_CONTAINER, FUEL, HAS_DYE,
    HAS_PATTERNS, LOOM_DYE_TAG, LOOM_PATTERN_TAG,
};
use crate::tables::{Mv, Names, kind as component};

/// Name `i` of a generated text table (`*_TEXT` + `*_ENDS`).
pub(crate) fn nth(text: &'static str, ends: &[u32], i: usize) -> Option<&'static str> {
    let end = *ends.get(i)? as usize;
    let start = if i == 0 { 0 } else { ends[i - 1] as usize };
    text.get(start..end)
}

/// The id of `name` in a generated text table.
pub(crate) fn position(text: &'static str, ends: &[u32], name: &str) -> Option<usize> {
    (0..ends.len()).find(|&i| nth(text, ends, i) == Some(name))
}

/// The registry id of an entity type name (without `minecraft:`).
pub(crate) fn entity_type_id(mv: Mv, name: &str) -> Option<i32> {
    mv.position(Names::EntityType, name).map(|i| i as i32)
}

/// The menu slot facts of item `id` (bits of the `menus` table; 0 for unknown ids).
pub(crate) fn menu_facts(mv: Mv, id: i32) -> u16 {
    usize::try_from(id)
        .ok()
        .and_then(|i| mv.menu_facts().get(i))
        .copied()
        .unwrap_or(0)
}

/// `Item.getCraftingRemainder()` as a stack.
pub(crate) fn crafting_remainder(mv: Mv, id: i32) -> Option<Stack> {
    let r = mv.remainders();
    r.binary_search_by_key(&id, |r| r.0)
        .ok()
        .map(|i| Stack::new(r[i].1, r[i].2, 0))
}

/// `(name, Some((max_level, anvil_cost, supported_items, exclusive_set)))` of the entries of a
/// `minecraft:enchantment` `registry_data` body (code generation; holder sets as `#tag` or
/// comma-separated names).
#[doc(hidden)]
#[must_use]
pub fn enchantment_specs(body: &[u8]) -> Option<Vec<crate::data26::EnchantmentSpec>> {
    crate::data26::enchantment_specs(body)
}

/// The equipment slot of an item's `equippable` component.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Equip {
    /// Not equippable.
    None,
    /// Head.
    Head,
    /// Chest.
    Chest,
    /// Legs.
    Legs,
    /// Feet.
    Feet,
    /// Offhand (the shield).
    Offhand,
    /// Main hand.
    MainHand,
    /// Animal body armor.
    Body,
    /// Saddle.
    Saddle,
}

impl Equip {
    /// The player armor slot index (0 head … 3 feet) of a humanoid armor slot.
    #[must_use]
    pub fn armor_index(self) -> Option<u8> {
        match self {
            Equip::Head => Some(0),
            Equip::Chest => Some(1),
            Equip::Legs => Some(2),
            Equip::Feet => Some(3),
            _ => None,
        }
    }
}

/// The default components of one item that ghast reads (from Mojang's report).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct ItemDefaults {
    /// Registry name without `minecraft:`.
    pub name: &'static str,
    /// `max_stack_size`.
    pub max_stack_size: u8,
    /// `max_damage` (0 = absent).
    pub max_damage: u16,
    /// Has a default `damage` component.
    pub damage: bool,
    /// Has a default `unbreakable` component.
    pub unbreakable: bool,
    /// `equippable.slot`.
    pub equip: Equip,
    /// `equippable.allowed_entities` is set (not wearable by players).
    pub equip_restricted: bool,
    /// Has `bundle_contents` (a bundle: clicks with it run the bundle's own rules).
    pub bundle: bool,
    /// `rarity` (0 common, 1 uncommon, 2 rare, 3 epic).
    pub rarity: u8,
}

/// One item's default components as ghast stores them: plain data, strings as spans of the
/// generated `ITEM_TEXT` (no pointers: the table needs no load-time relocation).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Row {
    pub(crate) name_s: (u32, u16),
    pub(crate) max_stack_size: u8,
    pub(crate) max_damage: u16,
    pub(crate) damage: bool,
    pub(crate) unbreakable: bool,
    pub(crate) equip: Equip,
    pub(crate) equip_restricted: bool,
    pub(crate) bundle: bool,
    pub(crate) rarity: u8,
    /// `use_effects`: can sprint, interact vibrations, speed multiplier (`f32` bits).
    pub(crate) use_effects: (bool, bool, u32),
    /// `consumable`: consume seconds (`f32` bits), animation id.
    pub(crate) consumable: Option<(u32, u8)>,
    /// `food`: nutrition, saturation (`f32` bits), can always eat.
    pub(crate) food: Option<(i32, u32, bool)>,
    /// Has `blocks_attacks` (a shield).
    pub(crate) blocks_attacks: bool,
    /// Has `kinetic_weapon` (a spear).
    pub(crate) kinetic_weapon: bool,
    /// `repairable.items` (`#tag` or an item name; empty when absent).
    pub(crate) repairable_s: (u32, u16),
    /// `provides_banner_patterns` (`#tag` or a pattern name; empty when absent).
    pub(crate) patterns_s: (u32, u16),
    /// `dye` color id (255 when absent).
    pub(crate) dye: u8,
    /// `equippable.allowed_entities` (`#tag` or entity type names; empty when absent).
    pub(crate) allowed_s: (u32, u16),
    /// `glider` present (the elytra).
    pub(crate) glider: bool,
}

impl Row {
    fn text(mv: Mv, (o, l): (u32, u16)) -> &'static str {
        let o = o as usize;
        mv.item_text().get(o..o + usize::from(l)).unwrap_or("")
    }

    /// Registry name without `minecraft:`.
    pub(crate) fn name(&self, mv: Mv) -> &'static str {
        Self::text(mv, self.name_s)
    }

    /// `repairable.items` (`#tag` or an item name; empty when absent).
    pub(crate) fn repairable(&self, mv: Mv) -> &'static str {
        Self::text(mv, self.repairable_s)
    }

    /// `provides_banner_patterns` (`#tag` or a pattern name; empty when absent).
    pub(crate) fn patterns(&self, mv: Mv) -> &'static str {
        Self::text(mv, self.patterns_s)
    }

    /// `equippable.allowed_entities` (`#tag` or entity type names; empty when absent).
    pub(crate) fn allowed(&self, mv: Mv) -> &'static str {
        Self::text(mv, self.allowed_s)
    }
}

/// The stored defaults of item `id`.
pub(crate) fn row(mv: Mv, id: i32) -> Option<&'static Row> {
    mv.item_rows().get(usize::try_from(id).ok()?)
}

/// Registry name of item `id` without `minecraft:` (`"diamond_sword"`).
#[must_use]
pub(crate) fn item_name(mv: Mv, id: i32) -> Option<&'static str> {
    row(mv, id).map(|r| r.name(mv))
}

/// Default components of item `id`.
#[must_use]
///
/// The table of these is built on the first call (ghast itself reads its compact,
/// relocation-free table; see [`item_name`] for the name alone).
pub(crate) fn defaults(mv: Mv, id: i32) -> Option<&'static ItemDefaults> {
    static TABLES: [std::sync::OnceLock<Box<[ItemDefaults]>>; 2] =
        [const { std::sync::OnceLock::new() }; 2];
    let table = TABLES[mv as usize].get_or_init(|| {
        mv.item_rows()
            .iter()
            .map(|r| ItemDefaults {
                name: r.name(mv),
                max_stack_size: r.max_stack_size,
                max_damage: r.max_damage,
                damage: r.damage,
                unbreakable: r.unbreakable,
                equip: r.equip,
                equip_restricted: r.equip_restricted,
                bundle: r.bundle,
                rarity: r.rarity,
            })
            .collect()
    });
    table.get(usize::try_from(id).ok()?)
}

/// Item registry id of a name (`"diamond_sword"` or `"minecraft:diamond_sword"`).
#[must_use]
pub(crate) fn item_id(mv: Mv, name: &str) -> Option<i32> {
    let name = name.strip_prefix("minecraft:").unwrap_or(name);
    mv.item_rows()
        .iter()
        .position(|d| d.name(mv) == name)
        .map(|i| i as i32)
}

/// Component type id of a name (`"damage"` or `"minecraft:damage"`).
#[must_use]
pub(crate) fn component_id(mv: Mv, name: &str) -> Option<i32> {
    let name = name.strip_prefix("minecraft:").unwrap_or(name);
    mv.position(Names::Component, name).map(|i| i as i32)
}

/// The window type of a 26.1 `open_screen` (`minecraft:menu` registry id).
#[must_use]
pub(crate) fn window_kind(mv: Mv, menu: i32) -> Option<WindowKind> {
    let name = mv.name(Names::Menu, usize::try_from(menu).ok()?)?;
    Some(match name {
        "generic_9x1" => WindowKind::Chest { rows: 1 },
        "generic_9x2" => WindowKind::Chest { rows: 2 },
        "generic_9x3" => WindowKind::Chest { rows: 3 },
        "generic_9x4" => WindowKind::Chest { rows: 4 },
        "generic_9x5" => WindowKind::Chest { rows: 5 },
        "generic_9x6" => WindowKind::Chest { rows: 6 },
        "generic_3x3" => WindowKind::Generic3x3,
        "anvil" => WindowKind::Anvil,
        "beacon" => WindowKind::Beacon,
        "blast_furnace" | "furnace" | "smoker" => WindowKind::Furnace,
        "brewing_stand" => WindowKind::BrewingStand,
        "crafting" => WindowKind::Crafting,
        "enchantment" => WindowKind::Enchanting,
        "grindstone" => WindowKind::Grindstone,
        "hopper" => WindowKind::Hopper,
        "lectern" => WindowKind::Lectern,
        "loom" => WindowKind::Loom,
        "merchant" => WindowKind::Merchant,
        "shulker_box" => WindowKind::ShulkerBox,
        "smithing" => WindowKind::Smithing,
        "cartography_table" => WindowKind::Cartography,
        "stonecutter" => WindowKind::Stonecutter,
        "crafter_3x3" => WindowKind::Crafter,
        _ => return None,
    })
}

// ---------------------------------------------------------------------- component values

#[cfg(all(test, feature = "v26_1"))]
fn patch(s: &Stack) -> Option<&ghast_protocol::types::slot::v775::ComponentPatch> {
    s.components()
}

/// The patch's verdict on component `ty`: `Some(Some(bytes))` set, `Some(None)` removed, `None`
/// not in the patch (the item's default applies).
pub(crate) fn patched(mv: Mv, s: &Stack, ty: i32) -> Option<Option<Bytes>> {
    let ItemData::Components(p) = &s.data else {
        return None;
    };
    if let Some(b) = mv.get(p, ty) {
        return Some(Some(b));
    }
    p.removes(mv.wire(ty)).then_some(None)
}

fn varint(b: &Bytes) -> Option<i32> {
    Reader::new(b).read_varint().ok()
}

fn int_component(mv: Mv, s: &Stack, ty: i32, default: Option<i32>) -> Option<i32> {
    match patched(mv, s, ty) {
        Some(Some(b)) => varint(&b),
        Some(None) => None,
        None => default,
    }
}

fn has_component(mv: Mv, s: &Stack, ty: i32, default: bool) -> bool {
    match patched(mv, s, ty) {
        Some(v) => v.is_some(),
        None => default,
    }
}

/// `ItemStack.getMaxStackSize()`: the `max_stack_size` component (default 1 when absent).
pub(crate) fn max_stack_size(mv: Mv, s: &Stack) -> i32 {
    let d = row(mv, s.id).map(|d| i32::from(d.max_stack_size));
    int_component(mv, s, component::MAX_STACK_SIZE, d).unwrap_or(1)
}

/// `max_damage` (`None` when absent).
pub(crate) fn max_damage(mv: Mv, s: &Stack) -> Option<i32> {
    let d = row(mv, s.id).and_then(|d| (d.max_damage > 0).then_some(i32::from(d.max_damage)));
    int_component(mv, s, component::MAX_DAMAGE, d)
}

/// `ItemStack.isDamageableItem()`: `max_damage` and `damage` present, `unbreakable` absent.
pub(crate) fn is_damageable(mv: Mv, s: &Stack) -> bool {
    let d = row(mv, s.id);
    max_damage(mv, s).is_some()
        && !unbreakable(mv, s)
        && has_component(mv, s, component::DAMAGE, d.is_some_and(|d| d.damage))
}

/// `ItemStack.getDamageValue()`: `damage` clamped to `0..=max_damage`.
pub(crate) fn damage_value(mv: Mv, s: &Stack) -> i32 {
    let d = row(mv, s.id).and_then(|d| d.damage.then_some(0));
    let v = int_component(mv, s, component::DAMAGE, d).unwrap_or(0);
    v.clamp(0, max_damage(mv, s).unwrap_or(0))
}

/// `unbreakable` present.
pub(crate) fn unbreakable(mv: Mv, s: &Stack) -> bool {
    has_component(
        mv,
        s,
        component::UNBREAKABLE,
        row(mv, s.id).is_some_and(|d| d.unbreakable),
    )
}

/// The equipment slot of `equippable`: the item default, or the patched value's slot
/// (`Err` when a patch sets `allowed_entities`: whether a player may wear it is not modelled).
pub(crate) fn equip(mv: Mv, s: &Stack) -> Result<Equip, ()> {
    match patched(mv, s, component::EQUIPPABLE) {
        Some(Some(b)) => patched_equip(&b).ok_or(()),
        Some(None) => Ok(Equip::None),
        None => Ok(row(mv, s.id).map_or(Equip::None, |d| {
            if d.equip_restricted {
                Equip::None
            } else {
                d.equip
            }
        })),
    }
}

/// The equipment slot a stack's `equippable` component names (the item default or the patched
/// value; `allowed_entities` is not looked at), `None` without the component.
fn equippable_slot(mv: Mv, s: &Stack) -> Option<Equip> {
    match patched(mv, s, component::EQUIPPABLE) {
        Some(Some(b)) => equip_of_slot(Reader::new(&b).read_varint().ok()?),
        Some(None) => None,
        None => row(mv, s.id).map(|d| d.equip).filter(|e| *e != Equip::None),
    }
}

fn equip_of_slot(slot: i32) -> Option<Equip> {
    Some(match slot {
        0 => Equip::MainHand,
        1 => Equip::Feet,
        2 => Equip::Legs,
        3 => Equip::Chest,
        4 => Equip::Head,
        5 => Equip::Offhand,
        6 => Equip::Body,
        7 => Equip::Saddle,
        _ => return None,
    })
}

/// The slot a glider works from: `Some(slot)` when the stack has the `glider` component (the
/// item default or patched in, not patched out) and an `equippable` component naming `slot`;
/// `None` otherwise. Durability is not looked at: see [`can_glide_using`].
#[must_use]
pub(crate) fn glider(mv: Mv, s: &Stack) -> Option<Equip> {
    let d = row(mv, s.id);
    if !has_component(mv, s, component::GLIDER, d.is_some_and(|d| d.glider)) {
        return None;
    }
    equippable_slot(mv, s)
}

/// `ItemStack.nextDamageWillBreak()`: damageable (`max_damage` and `damage` present, not
/// `unbreakable`) and `damage >= max_damage - 1`.
#[must_use]
pub(crate) fn next_damage_will_break(mv: Mv, s: &Stack) -> bool {
    is_damageable(mv, s) && damage_value(mv, s) >= max_damage(mv, s).unwrap_or(0) - 1
}

/// `LivingEntity.canGlideUsing(stack, slot)`: the stack is a glider equipped in `slot` (see
/// [`glider`]) and its next damage will not break it.
#[must_use]
pub(crate) fn can_glide_using(mv: Mv, s: &Stack, slot: Equip) -> bool {
    glider(mv, s) == Some(slot) && !next_damage_will_break(mv, s)
}

/// The slot of a patched `equippable` (`Equippable.STREAM_CODEC`: slot, equip sound, asset id,
/// camera overlay, allowed entities, ...); `None` when `allowed_entities` is set or the bytes
/// do not read.
fn patched_equip(b: &Bytes) -> Option<Equip> {
    let mut r = Reader::new(b);
    let slot = r.read_varint().ok()?;
    // equip_sound: a registry id + 1, or 0 and an inline `SoundEvent` (id, optional range)
    if r.read_varint().ok()? == 0 {
        r.read_string().ok()?;
        if r.read_bool().ok()? {
            r.read_f32().ok()?;
        }
    }
    for _ in 0..2 {
        // asset_id, camera_overlay
        if r.read_bool().ok()? {
            r.read_string().ok()?;
        }
    }
    if r.read_bool().ok()? {
        return None;
    }
    equip_of_slot(slot)
}

/// Whether the stack has the `bundle_contents` component (a bundle: some clicks with it run
/// the bundle's own rules, `BundleItem.overrideStackedOnOther` / `overrideOtherStackedOnMe`).
pub(crate) fn overrides_clicks(mv: Mv, s: &Stack) -> bool {
    has_component(
        mv,
        s,
        component::BUNDLE_CONTENTS,
        row(mv, s.id).is_some_and(|d| d.bundle),
    )
}

/// `(enchantment registry id, level)` of the `enchantments` (`stored = false`) or
/// `stored_enchantments` component, in wire order. `None` when the component is absent.
pub(crate) fn enchantments(mv: Mv, s: &Stack, stored: bool) -> Option<Vec<(i32, i32)>> {
    let ty = if stored {
        component::STORED_ENCHANTMENTS
    } else {
        component::ENCHANTMENTS
    };
    let b = patched(mv, s, ty)??;
    let mut r = Reader::new(&b);
    let n = r.read_varint().ok()?;
    let n = usize::try_from(n).ok()?;
    let mut v = Vec::with_capacity(n.min(64));
    for _ in 0..n {
        v.push((r.read_varint().ok()?, r.read_varint().ok()?));
    }
    Some(v)
}

/// A text component (`custom_name`, `item_name`) as NBT.
pub(crate) fn text(mv: Mv, s: &Stack, ty: i32) -> Option<AnonNbt> {
    let b = patched(mv, s, ty)??;
    AnonNbt::read(&mut Reader::new(&b)).ok()
}

/// The `lore` lines as NBT text components.
pub(crate) fn lore(mv: Mv, s: &Stack) -> Vec<AnonNbt> {
    let Some(Some(b)) = patched(mv, s, component::LORE) else {
        return Vec::new();
    };
    let mut r = Reader::new(&b);
    let Ok(n) = r.read_varint() else {
        return Vec::new();
    };
    (0..n.max(0))
        .map_while(|_| AnonNbt::read(&mut r).ok())
        .collect()
}

/// The `potion_contents` potion (registry name), if it names one.
pub(crate) fn potion(mv: Mv, s: &Stack) -> Option<&'static str> {
    let b = patched(mv, s, component::POTION_CONTENTS)??;
    let mut r = Reader::new(&b);
    if !r.read_bool().ok()? {
        return None;
    }
    let id = r.read_varint().ok()?;
    mv.name(Names::Potion, usize::try_from(id).ok()?)
}

// ---------------------------------------------------------------------- item use

/// How an item in use animates (`ItemUseAnimation`, by its network id).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum UseAnimation {
    /// `none`.
    None,
    /// `eat`.
    Eat,
    /// `drink`.
    Drink,
    /// `block` (shields: `blocks_attacks`).
    Block,
    /// `bow`.
    Bow,
    /// `trident`.
    Trident,
    /// `crossbow`.
    Crossbow,
    /// `spyglass`.
    Spyglass,
    /// `toot_horn` (goat horns).
    TootHorn,
    /// `brush`.
    Brush,
    /// `bundle`.
    Bundle,
    /// `spear` (`kinetic_weapon`).
    Spear,
}

impl UseAnimation {
    fn from_id(id: i32) -> Option<UseAnimation> {
        Some(match id {
            0 => UseAnimation::None,
            1 => UseAnimation::Eat,
            2 => UseAnimation::Drink,
            3 => UseAnimation::Block,
            4 => UseAnimation::Bow,
            5 => UseAnimation::Trident,
            6 => UseAnimation::Crossbow,
            7 => UseAnimation::Spyglass,
            8 => UseAnimation::TootHorn,
            9 => UseAnimation::Brush,
            10 => UseAnimation::Bundle,
            11 => UseAnimation::Spear,
            _ => return None,
        })
    }
}

/// `food` component: what eating the item restores.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct Food {
    /// `nutrition`.
    pub nutrition: i32,
    /// `saturation`.
    pub saturation: f32,
    /// `can_always_eat` (eaten with a full hunger bar).
    pub can_always_eat: bool,
}

/// What using (right-click holding) a 26.1 item does, from its components (the patch over the
/// item's defaults) and its item class, as `Item.getUseAnimation` / `getUseDuration` and
/// `LocalPlayer`'s movement read them.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct ItemUse {
    /// `getUseAnimation`.
    pub animation: UseAnimation,
    /// `getUseDuration` in ticks: 0 = the use does not last (no use state), 72000 = until
    /// released (bows, shields, spears, tridents, crossbow charging); `None` when it depends on
    /// data ghast does not have (a goat horn's instrument).
    pub duration: Option<i32>,
    /// `use_effects.speed_multiplier`: movement input factor while using (vanilla default
    /// 0.2; the physics input of `ghast_physics::modern`).
    pub speed_multiplier: f32,
    /// `use_effects.can_sprint`: sprinting continues while using.
    pub can_sprint: bool,
    /// `use_effects.interact_vibrations`.
    pub interact_vibrations: bool,
    /// The stack has a `consumable` component (eaten / drunk over `duration` ticks).
    pub consumable: bool,
    /// The `food` component.
    pub food: Option<Food>,
}

/// [`ItemUse`] of a 26.1 stack (`None` for an id outside the item registry). Components the
/// stack patches but that do not read give the item defaults' values.
#[must_use]
pub(crate) fn item_use(mv: Mv, s: &Stack) -> Option<ItemUse> {
    let d = row(mv, s.id)?;
    let (mut can_sprint, mut vibrations, mut speed) = (
        d.use_effects.0,
        d.use_effects.1,
        f32::from_bits(d.use_effects.2),
    );
    match patched(mv, s, component::USE_EFFECTS) {
        Some(Some(b)) => {
            let mut r = Reader::new(&b);
            if let (Ok(a), Ok(v), Ok(f)) = (r.read_bool(), r.read_bool(), r.read_f32()) {
                (can_sprint, vibrations, speed) = (a, v, f);
            }
        }
        // removed: `getOrDefault(USE_EFFECTS, DEFAULT)`
        Some(None) => (can_sprint, vibrations, speed) = (false, true, 0.2),
        None => {}
    }
    let consumable = match patched(mv, s, component::CONSUMABLE) {
        Some(Some(b)) => {
            let mut r = Reader::new(&b);
            match (r.read_f32(), r.read_varint()) {
                (Ok(secs), Ok(anim)) => Some((secs, UseAnimation::from_id(anim))),
                _ => d
                    .consumable
                    .map(|(b, a)| (f32::from_bits(b), UseAnimation::from_id(i32::from(a)))),
            }
        }
        Some(None) => None,
        None => d
            .consumable
            .map(|(b, a)| (f32::from_bits(b), UseAnimation::from_id(i32::from(a)))),
    };
    let food = match patched(mv, s, component::FOOD) {
        Some(Some(b)) => {
            let mut r = Reader::new(&b);
            match (r.read_varint(), r.read_f32(), r.read_bool()) {
                (Ok(n), Ok(sat), Ok(a)) => Some(Food {
                    nutrition: n,
                    saturation: sat,
                    can_always_eat: a,
                }),
                _ => None,
            }
        }
        Some(None) => None,
        None => d.food.map(|(n, sat, a)| Food {
            nutrition: n,
            saturation: f32::from_bits(sat),
            can_always_eat: a,
        }),
    };
    let blocks = has_component(mv, s, component::BLOCKS_ATTACKS, d.blocks_attacks);
    let kinetic = has_component(mv, s, component::KINETIC_WEAPON, d.kinetic_weapon);
    // Item.getUseAnimation / getUseDuration, then the item classes that override them
    let (mut animation, mut duration) = match consumable {
        Some((secs, anim)) => (
            anim.unwrap_or(UseAnimation::Eat),
            Some((secs * 20.0) as i32),
        ),
        None if blocks => (UseAnimation::Block, Some(72000)),
        None if kinetic => (UseAnimation::Spear, Some(72000)),
        None => (UseAnimation::None, Some(0)),
    };
    match d.name(mv) {
        "bow" => (animation, duration) = (UseAnimation::Bow, Some(72000)),
        "crossbow" => (animation, duration) = (UseAnimation::Crossbow, Some(72000)),
        "trident" => (animation, duration) = (UseAnimation::Trident, Some(72000)),
        "spyglass" => (animation, duration) = (UseAnimation::Spyglass, Some(1200)),
        "brush" => (animation, duration) = (UseAnimation::Brush, Some(200)),
        "goat_horn" => (animation, duration) = (UseAnimation::TootHorn, None),
        "ender_eye" => duration = Some(0),
        _ if d.bundle => (animation, duration) = (UseAnimation::Bundle, Some(200)),
        _ => {}
    }
    Some(ItemUse {
        animation,
        duration,
        speed_multiplier: speed,
        can_sprint,
        interact_vibrations: vibrations,
        consumable: consumable.is_some(),
        food,
    })
}

// ---------------------------------------------------------------------- hashed stacks

/// Hash put into a click for a component ghast cannot hash: certainly not the real one, so the
/// server answers with the slot's true contents (the click itself is applied either way).
pub const UNKNOWN_HASH: i32 = 0;

/// Guava `Hashing.crc32c()`.
struct Crc32c(u32);

const fn crc_table() -> [u32; 256] {
    let mut t = [0u32; 256];
    let mut i = 0;
    while i < 256 {
        let mut c = i as u32;
        let mut k = 0;
        while k < 8 {
            c = if c & 1 != 0 {
                (c >> 1) ^ 0x82F6_3B78
            } else {
                c >> 1
            };
            k += 1;
        }
        t[i] = c;
        i += 1;
    }
    t
}

static CRC_TABLE: [u32; 256] = crc_table();

impl Crc32c {
    fn new() -> Self {
        Crc32c(!0)
    }
    fn put(&mut self, b: &[u8]) -> &mut Self {
        let mut c = self.0;
        for &x in b {
            c = CRC_TABLE[((c ^ u32::from(x)) & 0xFF) as usize] ^ (c >> 8);
        }
        self.0 = c;
        self
    }
    fn byte(&mut self, b: u8) -> &mut Self {
        self.put(&[b])
    }
    fn finish(&self) -> u32 {
        !self.0
    }
}

fn hash_of(bytes: &[u8]) -> u32 {
    Crc32c::new().put(bytes).finish()
}

/// `HashOps` values (Guava hashers write little-endian).
mod ops {
    use super::{Crc32c, hash_of};

    pub fn int(v: i32) -> u32 {
        Crc32c::new().byte(8).put(&v.to_le_bytes()).finish()
    }
    pub fn byte(v: i8) -> u32 {
        Crc32c::new().byte(6).byte(v as u8).finish()
    }
    pub fn short(v: i16) -> u32 {
        Crc32c::new().byte(7).put(&v.to_le_bytes()).finish()
    }
    pub fn long(v: i64) -> u32 {
        Crc32c::new().byte(9).put(&v.to_le_bytes()).finish()
    }
    pub fn float(v: f32) -> u32 {
        Crc32c::new()
            .byte(10)
            .put(&v.to_bits().to_le_bytes())
            .finish()
    }
    pub fn double(v: f64) -> u32 {
        Crc32c::new()
            .byte(11)
            .put(&v.to_bits().to_le_bytes())
            .finish()
    }
    pub fn string(s: &str) -> u32 {
        let units: Vec<u16> = s.encode_utf16().collect();
        let mut h = Crc32c::new();
        h.byte(12).put(&(units.len() as i32).to_le_bytes());
        for u in units {
            h.put(&u.to_le_bytes());
        }
        h.finish()
    }
    pub fn boolean(b: bool) -> u32 {
        hash_of(&[13, u8::from(b)])
    }
    pub fn empty_map() -> u32 {
        hash_of(&[2, 3])
    }
    /// Entries sorted by key hash, then value hash (unsigned), as `HashOps.hashMap` does.
    pub fn map(mut entries: Vec<(u32, u32)>) -> u32 {
        entries.sort_unstable();
        let mut h = Crc32c::new();
        h.byte(2);
        for (k, v) in entries {
            h.put(&k.to_le_bytes()).put(&v.to_le_bytes());
        }
        h.byte(3).finish()
    }
    pub fn list(items: impl IntoIterator<Item = u32>) -> u32 {
        let mut h = Crc32c::new();
        h.byte(4);
        for v in items {
            h.put(&v.to_le_bytes());
        }
        h.byte(5).finish()
    }
    pub fn byte_list(b: &[u8]) -> u32 {
        Crc32c::new().byte(14).put(b).byte(15).finish()
    }
    pub fn int_list(v: &[i32]) -> u32 {
        let mut h = Crc32c::new();
        h.byte(16);
        for x in v {
            h.put(&x.to_le_bytes());
        }
        h.byte(17).finish()
    }
    pub fn long_list(v: &[i64]) -> u32 {
        let mut h = Crc32c::new();
        h.byte(18);
        for x in v {
            h.put(&x.to_le_bytes());
        }
        h.byte(19).finish()
    }
}

/// NBT converted into `HashOps` (vanilla `NbtOps.convertTo`); `text = true` reads the byte
/// fields a text component's codec writes as booleans (`bold`, `italic`, …) as booleans, which
/// is what encoding the component itself to `HashOps` produces.
fn nbt_hash(t: &Tag, text: bool) -> u32 {
    const BOOL_KEYS: &[&str] = &[
        "bold",
        "italic",
        "underlined",
        "strikethrough",
        "obfuscated",
        "interpret",
    ];
    match t {
        Tag::Byte(v) => ops::byte(*v),
        Tag::Short(v) => ops::short(*v),
        Tag::Int(v) => ops::int(*v),
        Tag::Long(v) => ops::long(*v),
        Tag::Float(v) => ops::float(*v),
        Tag::Double(v) => ops::double(*v),
        Tag::String(s) => ops::string(s),
        Tag::ByteArray(b) => ops::byte_list(b),
        Tag::IntArray(v) => ops::int_list(v),
        Tag::LongArray(v) => ops::long_list(v),
        Tag::List(l) => ops::list(l.items.iter().map(|e| match e {
            // ListTag unwraps the `{"": value}` wrappers of mixed lists when it is read.
            Tag::Compound(c) if c.0.len() == 1 && c.0[0].0.is_empty() => nbt_hash(&c.0[0].1, text),
            e => nbt_hash(e, text),
        })),
        Tag::Compound(c) => {
            let mut seen: Vec<&str> = Vec::new();
            let mut entries = Vec::with_capacity(c.0.len());
            // Java maps keep the last duplicate.
            for (k, v) in c.0.iter().rev() {
                if seen.contains(&k.as_str()) {
                    continue;
                }
                seen.push(k);
                let vh = match v {
                    Tag::Byte(b)
                        if text && BOOL_KEYS.contains(&k.as_str()) && (*b == 0 || *b == 1) =>
                    {
                        ops::boolean(*b != 0)
                    }
                    v => nbt_hash(v, text),
                };
                entries.push((ops::string(k), vh));
            }
            ops::map(entries)
        }
    }
}

/// `TypedEntityData.codec`: the compound without its `id`, then `id` = the type's name.
fn typed_nbt_hash(n: &AnonNbt, type_name: &str) -> Option<u32> {
    let Tag::Compound(mut c) = n.parse().ok()?? else {
        return None;
    };
    c.0.retain(|(k, _)| k != "id");
    c.0.push(("id".into(), Tag::String(type_name.into())));
    Some(nbt_hash(&Tag::Compound(c), false))
}

fn anon_hash(n: &AnonNbt, text: bool) -> Option<u32> {
    if n.is_end() {
        return None;
    }
    Some(nbt_hash(&n.parse().ok()??, text))
}

/// One slot as a modern click sends it (vanilla `HashedStack.create`), in wire terms.
pub(crate) fn hashed(mv: Mv, s: Option<&Stack>, reg: &HashRegistries) -> (Option<Hashed>, bool) {
    let Some(s) = s.filter(|s| s.count > 0 && s.id != 0) else {
        return (None, true);
    };
    let mut exact = true;
    let mut components: Vec<(i32, i32)> = Vec::new();
    let mut removed: Vec<i32> = Vec::new();
    if let ItemData::Components(p) = &s.data {
        // DataComponentPatch is a map: the last value of a type wins.
        let all: Vec<(i32, Bytes)> = p.iter().collect();
        for (t, b) in all.iter().rev() {
            if components.iter().any(|c| c.0 == *t) {
                continue;
            }
            let h = hash::component_hash(*t, b, mv, reg).unwrap_or_else(|| {
                exact = false;
                UNKNOWN_HASH
            });
            components.push((*t, h));
        }
        for t in p.removed() {
            if !removed.contains(&t) {
                removed.push(t);
            }
        }
        // a map and a set in vanilla: written here in type id order
        components.sort_by_key(|c| c.0);
        removed.sort_unstable();
    }
    (
        Some(Hashed {
            item_id: s.id,
            item_count: s.count,
            components,
            removed,
        }),
        exact,
    )
}

/// A hashed stack in wire terms: component type ids (sorted) with their hashes, removed types.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Hashed {
    pub(crate) item_id: i32,
    pub(crate) item_count: i32,
    pub(crate) components: Vec<(i32, i32)>,
    pub(crate) removed: Vec<i32>,
}

#[cfg(all(test, feature = "v26_1"))]
mod tests {
    use super::*;
    use crate::v26_1::{
        ITEM_COUNT, can_glide_using, component_hash, component_id, glider, hashed_slot, item_id,
        next_damage_will_break, window_kind,
    };
    use ghast_protocol::types::slot::v775::ComponentPatch;

    const M: Mv = Mv::V26_1;
    fn max_stack_size(s: &Stack) -> i32 {
        super::max_stack_size(M, s)
    }
    fn max_damage(s: &Stack) -> Option<i32> {
        super::max_damage(M, s)
    }
    fn is_damageable(s: &Stack) -> bool {
        super::is_damageable(M, s)
    }
    fn damage_value(s: &Stack) -> i32 {
        super::damage_value(M, s)
    }
    fn equip(s: &Stack) -> Result<Equip, ()> {
        super::equip(M, s)
    }
    fn overrides_clicks(s: &Stack) -> bool {
        super::overrides_clicks(M, s)
    }

    /// Known answers computed with the 26.1 jar's `HashOps.CRC32C_INSTANCE` (Guava crc32c):
    /// `createInt(5)`, `createString("minecraft:sharpness")`, `emptyMap()`,
    /// `createBoolean(true)`, `createMap({"a": 1})`, `createList([int 1, int 2])`.
    #[test]
    fn hash_ops_known_answers() {
        // crc32c("123456789") = 0xE3069283 (the standard check value).
        assert_eq!(hash_of(b"123456789"), 0xE306_9283);
        for (got, want) in KNOWN.iter() {
            assert_eq!(got(), *want);
        }
    }

    type Known = (fn() -> u32, u32);
    const KNOWN: &[Known] = &[
        (|| ops::int(5), 645_064_431),
        (
            || ops::string("minecraft:sharpness"),
            -1_560_913_390i32 as u32,
        ),
        (ops::empty_map, -982_207_288i32 as u32),
        (|| ops::boolean(true), -1_019_818_302i32 as u32),
        (
            || ops::map(vec![(ops::string("a"), ops::int(1))]),
            -108_872_706i32 as u32,
        ),
        (
            || ops::list([ops::int(1), ops::int(2)]),
            -1_373_960_668i32 as u32,
        ),
        (|| ops::byte(-3), -722_991_802i32 as u32),
        (|| ops::double(1.5), -1_387_852_210i32 as u32),
        (
            || {
                ops::map(vec![
                    (ops::string("minecraft:sharpness"), ops::int(5)),
                    (ops::string("minecraft:unbreaking"), ops::int(3)),
                ])
            },
            1_231_404_551,
        ),
    ];

    fn unhex(s: &str) -> Bytes {
        Bytes::from(
            (0..s.len())
                .step_by(2)
                .map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap())
                .collect::<Vec<u8>>(),
        )
    }

    /// Text components: the jar's `ComponentSerialization.CODEC` encoded once to `HashOps`
    /// (the hash) and once to `NbtOps` (the bytes a server sends); ghast hashes the NBT.
    #[test]
    fn text_hashes_match_the_codec() {
        let cases: &[(&str, i32, &str)] = &[
            ("plain", 815_466_656, "08000548656c6c6f"),
            (
                "bold",
                -608_560_159,
                "0a080005636f6c6f720004676f6c6408000474657874000453686f70010004626f6c640100",
            ),
            (
                "notitalic",
                185_662_785,
                "0a080005636f6c6f720004677261790800047465787400044c696e650100066974616c69630000",
            ),
            (
                "mixed",
                -198_755_598,
                "0a09000565787472610a0000000208000000016200080005636f6c6f72000372656408000474657874000163000800047465787400016100",
            ),
            (
                "translate",
                1_855_830_573,
                "0a0800097472616e736c617465001c6974656d2e6d696e6563726166742e6469616d6f6e645f73776f726400",
            ),
            ("unicode", -45_199_928, "08000ac39cc3a9eda0bdedb880"),
        ];
        for (label, hash, hex) in cases {
            let nbt = AnonNbt::from_bytes(unhex(hex)).unwrap();
            assert_eq!(
                anon_hash(&nbt, true).map(|h| h as i32),
                Some(*hash),
                "{label}"
            );
            // the component value on the wire is the NBT itself
            let v = nbt.as_bytes().clone();
            let reg = HashRegistries::default();
            assert_eq!(
                component_hash(component::CUSTOM_NAME, &v, &reg),
                Some(*hash),
                "{label}"
            );
        }
    }

    #[test]
    fn defaults_table() {
        assert_eq!(ITEM_COUNT, 1506);
        let sword = item_id("diamond_sword").unwrap();
        let st = Stack::new(sword, 1, 0);
        assert_eq!(max_stack_size(&st), 1);
        assert_eq!(max_damage(&st), Some(1561));
        assert!(is_damageable(&st));
        assert_eq!(
            equip(&Stack::new(item_id("elytra").unwrap(), 1, 0)),
            Ok(Equip::Chest)
        );
        assert_eq!(
            equip(&Stack::new(item_id("shield").unwrap(), 1, 0)),
            Ok(Equip::Offhand)
        );
        assert_eq!(
            equip(&Stack::new(item_id("diamond_horse_armor").unwrap(), 1, 0)),
            Ok(Equip::None)
        );
        assert!(overrides_clicks(&Stack::new(
            item_id("red_bundle").unwrap(),
            1,
            0
        )));
        assert_eq!(
            max_stack_size(&Stack::new(item_id("ender_pearl").unwrap(), 1, 0)),
            16
        );
        assert_eq!(component_id("damage"), Some(component::DAMAGE));
        assert_eq!(window_kind(2), Some(WindowKind::Chest { rows: 3 }));
        assert_eq!(window_kind(7), Some(WindowKind::Crafter));
        assert_eq!(window_kind(20), Some(WindowKind::ShulkerBox));
    }

    #[test]
    fn gliders() {
        let with = |name: &str, added: &[(i32, &[u8])], removed: &[i32]| {
            let mut st = Stack::new(item_id(name).unwrap(), 1, 0);
            if !added.is_empty() || !removed.is_empty() {
                let p = ComponentPatch::from_parts(added, removed);
                st.data = ItemData::Components(Box::new(p));
            }
            st
        };
        let elytra = with("elytra", &[], &[]);
        assert_eq!(glider(&elytra), Some(Equip::Chest));
        assert!(can_glide_using(&elytra, Equip::Chest));
        assert!(!can_glide_using(&elytra, Equip::Head));
        // 432 durability: damage 430 still glides, 431 (next damage breaks it) does not
        let worn = with("elytra", &[(component::DAMAGE, &[0xae, 0x03])], &[]);
        assert_eq!(damage_value(&worn), 430);
        assert!(can_glide_using(&worn, Equip::Chest));
        let broken = with("elytra", &[(component::DAMAGE, &[0xaf, 0x03])], &[]);
        assert!(next_damage_will_break(&broken));
        assert!(!can_glide_using(&broken, Equip::Chest));
        let unbreakable = with(
            "elytra",
            &[
                (component::DAMAGE, &[0xaf, 0x03]),
                (component::UNBREAKABLE, &[]),
            ],
            &[],
        );
        assert!(can_glide_using(&unbreakable, Equip::Chest));
        // glider patched out / in; no equippable, no glider slot
        assert_eq!(glider(&with("elytra", &[], &[component::GLIDER])), None);
        assert_eq!(glider(&with("elytra", &[], &[component::EQUIPPABLE])), None);
        let chestplate = with("diamond_chestplate", &[(component::GLIDER, &[])], &[]);
        assert_eq!(glider(&chestplate), Some(Equip::Chest));
        assert_eq!(glider(&with("diamond_chestplate", &[], &[])), None);
        assert_eq!(
            glider(&with("stone", &[(component::GLIDER, &[])], &[])),
            None
        );
    }

    #[test]
    fn patched_components() {
        let sword = item_id("diamond_sword").unwrap();
        let mut st = Stack::new(sword, 1, 0);
        // damage 37, max_stack_size 4 (wire: varints), unbreakable removed? no: added
        let p = ComponentPatch::from_parts(
            &[
                (component::DAMAGE, &[37]),
                (component::MAX_STACK_SIZE, &[4]),
            ],
            &[component::MAX_DAMAGE],
        );
        st.data = ItemData::Components(Box::new(p));
        assert_eq!(patch(&st).unwrap().added_len(), 2);
        assert_eq!(max_stack_size(&st), 4);
        assert_eq!(max_damage(&st), None);
        assert!(!is_damageable(&st));
        assert_eq!(damage_value(&st), 0); // clamped to max_damage 0
        let (h, exact) = hashed_slot(Some(&st), &HashRegistries::default());
        let h = h.unwrap();
        assert!(exact);
        assert_eq!(h.components.len(), 2);
        assert_eq!(h.remove_components.len(), 1);
        assert_eq!(
            h.components
                .iter()
                .find(|c| c.r#type.0 == component::DAMAGE)
                .unwrap()
                .hash,
            ops::int(37) as i32
        );
    }
}