owengage / fastnbt

Fast serde serializer and deserializer for Minecraft's NBT and Anvil formats
MIT License
186 stars 34 forks source link

Add `nbt!` macro #52

Closed RubixDev closed 2 years ago

RubixDev commented 2 years ago

This adds a nbt! macro similar to the json! macro from serde_json. The code is actually mostly copied from there, but modified for NBT.

An example usage might look like this:

nbt!({
    "Items": [
        {
            "tag": {},
            "id": "minecraft:axolotl_bucket",
            "Count": 1_u8,
            "Slot": 0_u8,
        },
        {
            "id": "minecraft:stick",
            "Count": 42_u8,
            "Slot": 1_u8,
        },
        {
            "id": "minecraft:stone",
            "Count": 64_u8,
            "Slot": 11_u8,
        },
    ]
})

I have taken the simple approach of turning expressions into fastnbt::Values and implemented the From<T> trait for a few types (all number types, String, &str, ByteArray, IntArray, LongArray, and all their referenced versions). If you would like me to do it the serde_json way and implement a Serializer with fastnbt::Value as the target type, I can do that too. That would allow any type with the Serialize trait to be turned into a value.

I also added one simple test, but no documentation. You are free to do that in the way you like

RubixDev commented 2 years ago

I now also added a few things from the sNBT syntax like booleans mapping to 0 and 1 as bytes and the special array syntax for Byte/Int/Long Arrays. I do not allow identifiers as keys in compunds, only quoted strings, because one might want to use the value of a variable as a key

owengage commented 2 years ago

This looks awesome. I will have a closer look soon.

owengage commented 2 years ago

Merging this, thank you for your contribution! I'll have a deeper look and make a 2.1 release.