ghast-inventory 0.5.2

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, 26.2 and 26.3)
Documentation
//! `Stack::attack` on the legacy versions: the jar's main-hand modifiers (the tables are checked
//! item by item against the oracle in `ghast-data/tests/oracle_attack.rs`), and the
//! `AttributeModifiers` tag that replaces them.
#![cfg(all(feature = "v1_8", feature = "v1_12", feature = "v1_16_5"))]

use ghast_inventory::{Stack, Version};
use ghast_protocol::nbt::{Compound, List, NamedTag, RawNbt, Tag};

fn id(v: Version, name: &str) -> i32 {
    (0..2000i32)
        .find(|&i| Stack::new(i, 1, 0).item_name(v) == Some(name))
        .unwrap_or_else(|| panic!("{name} on {v:?}"))
}

fn with_tag(s: Stack, key: &str, tag: Tag) -> Stack {
    let nbt = RawNbt::from_named(&NamedTag {
        name: String::new(),
        tag: Tag::Compound(Compound(vec![(key.into(), tag)])),
    })
    .unwrap();
    s.with_nbt(Some(nbt))
}

#[test]
fn held_attack_attributes_legacy() {
    let f = |x: f32| f64::from(x);
    for (v, sword, axe, speed) in [
        (Version::V1_8, 8.0, 7.0, None),
        (Version::V1_12, 7.0, 9.0, Some((4.0 + f(-2.4), 4.0 - 3.0))),
        (Version::V1_16_5, 7.0, 9.0, Some((4.0 + f(-2.4), 4.0 - 3.0))),
    ] {
        let s = Stack::new(id(v, "diamond_sword"), 1, 0).attack(v).unwrap();
        let a = Stack::new(id(v, "diamond_axe"), 1, 0).attack(v).unwrap();
        assert_eq!(s.attack_damage(), sword, "{v:?}");
        assert_eq!(a.attack_damage(), axe, "{v:?}");
        assert_eq!(s.attack_speed().zip(a.attack_speed()), speed, "{v:?}");
        // items without modifiers: the bare-hand values
        let stone = Stack::new(1, 64, 0).attack(v).unwrap();
        assert_eq!(stone.attack_damage(), 1.0);
        assert_eq!(stone.attack_speed(), speed.map(|_| 4.0));
        // a damaged sword is the same sword
        let worn = Stack::new(id(v, "diamond_sword"), 1, 100)
            .attack(v)
            .unwrap();
        assert_eq!(worn, s);
        // an `AttributeModifiers` list replaces the item's modifiers: not modelled
        let list = Tag::List(List {
            elem_type: 10,
            items: vec![],
        });
        let custom = with_tag(
            Stack::new(id(v, "diamond_sword"), 1, 0),
            "AttributeModifiers",
            list,
        );
        assert_eq!(custom.attack(v), None, "{v:?}");
        // a tag of that name that is not a list is ignored, as in vanilla
        let odd = with_tag(
            Stack::new(id(v, "diamond_sword"), 1, 0),
            "AttributeModifiers",
            Tag::Int(1),
        );
        assert_eq!(odd.attack(v), Some(s), "{v:?}");
    }
    assert_eq!(Stack::new(1, 1, 0).attack(Version::V26_1), None);
}