Skip to content

Repository files navigation

cpp-nbt

license

This is a C++23 header-only library for reading/writing Minecraft NBT data:

  • Single header file
  • Requires C++23 (GCC 13, Clang 14, MSVC 19.latest)
  • Reads from istreams, writes to ostreams
  • Supports pretty printing

This is mostly for me to play with bleeding edge C++ stuff. Don't expect this to compile on anything but trunk.

Quickstart

std::map doesn't work with incomplete types portably, so you need to provide your own (std::map may work depending on your platform and stdlib). By default cpp-nbt uses boost::container::map. You can do this by defining NBT_MAP_TYPE to whatever type you want to use, so long it has a vaguely std::map-ish API.

Include nbt.hpp, munch some data.

#defineNBT_MAP_TYPE myFavoriteMap
#include"nbt.hpp"
nbt::NBT root {std::ifstream {"hello_world.nbt"}};
std::cout << root;

Tags

All PC-edition NBT tags are supported, Bedrock is not currently supported.

Most tags map directly to primitive types, the remainder map to STL containers.

Tag TypeDescription
TagEndstd::nullptr_t
TagBytestd::int8_t
TagShortstd::int16_t
TagIntstd::int32_t
TagLongstd::int64_t
TagFloatfloat
TagDoubledouble
TagByteArraystd::vector<TagByte>
TagIntArraystd::vector<TagInt>
TagLongArraystd::vector<TagLong>
TagStringstd::string
TagListstd::variant<std::vectors<TagEnd>, std::vector<TagByte>, and all other tags>
Tagstd::variant<TagEnd, TagByte, and all other tags>
TagCompoundstd::map<TagString, Tag>
NBTDatastruct { TagString name; TagCompound tags; }
NBTstruct {std::optional<NBTData> data; }

Constructing and Destructing Tags

Java edition NBT root nodes are always either a TagEnd, or a named TagCompound. These two root nodes are encapsulated by the NBT type, which has an encode() and decode() methods to serialize and deserialize NBT. When the TagCompound is present the data field will be present, otherwise it will be absent. If absent, the NBT container will serialize to a single TagEnd.

Example Usage:

nbt::NBT root;
root.decode(std::ifstream {"hello_world.nbt"});
// Optionally, use the constructor// nbt::NBT root {ifs};
root.encode(std::ofstream {"out.nbt"});

Manipulating Tags

Tags must exist inside a container type, and manipulating NBT containers involves standard usage of the STL.

nbt::NBT root {"LyricalNBT", {
{"Hello", "World"},
{"Lyrics", nbt::TagList {
"There's", "a", "song", "that", "we're", "singing",
}},
}};
root["LuckyNumbers"] = nbt::TagByteArray {1, 3, 7, 9, 13, 15};
std::get<nbt::TagByteArray>(root["LuckyNumbers"]).push_back(21);
std::cout << root["Hello"] << std::endl;
std::cout << root << std::endl;

Issues

Please open an issue or better yet, a pull request, for any bugs or other problems.

Releases

Packages

Contributors

Languages