From ff1765c52e973b3f78680bfaf45fd1886bab75f0 Mon Sep 17 00:00:00 2001 From: Brett Date: Wed, 26 Jul 2023 14:03:21 -0400 Subject: [PATCH] reader --- include/blt/nbt/nbt.h | 32 ++++++++++++++++++++++++-------- src/blt/nbt/nbt.cpp | 8 ++++++++ 2 files changed, 32 insertions(+), 8 deletions(-) diff --git a/include/blt/nbt/nbt.h b/include/blt/nbt/nbt.h index d104913..605a9a0 100755 --- a/include/blt/nbt/nbt.h +++ b/include/blt/nbt/nbt.h @@ -319,12 +319,14 @@ namespace blt::nbt { public: tag_compound(): tag(nbt_tag::COMPOUND) {} tag_compound(const std::string& name, const std::vector& v): tag(nbt_tag::COMPOUND, name, _internal_::toHashmap(v)) {} + tag_compound(const std::string& name, const std::initializer_list& v): tag(nbt_tag::COMPOUND, name, _internal_::toHashmap(v)) {} tag_compound(const std::string& name, const HASHMAP& v): tag(nbt_tag::COMPOUND, name, v) {} void writePayload(blt::fs::block_writer& out) final { - for (auto*& v : t){ - out.put((char) v->getType()); - v->writeName(out); - v->writePayload(out); + for (const auto& v : t){ + auto tag = v.second; + out.put((char) tag->getType()); + tag->writeName(out); + tag->writePayload(out); } out.put('\0'); } @@ -334,7 +336,7 @@ namespace blt::nbt { auto* v = _internal_::toType(type); v->readName(in); v->readPayload(in); - t.push_back(v); + t[v->getName()] = v; } } }; @@ -350,19 +352,33 @@ namespace blt::nbt { class NBTReader { private: blt::fs::block_reader& reader; + tag_compound* root = nullptr; public: explicit NBTReader(blt::fs::block_reader& reader): reader(reader) {} + void read(); + + template + [[nodiscard]] T* getTag(const std::string& name){ + auto& tag = root->get()[name]; + T t; + if (tag->getType() != t.getType()) { + BLT_WARN("Expected tag of type %d but got tag of type %d", (char)t.getType(), (char)tag->getType()); + throw std::runtime_error("Requested Tag does not match stored type!"); + } + return dynamic_cast(tag); + } }; class NBTWriter { private: blt::fs::block_writer& writer; - tag_compound* root = nullptr; public: explicit NBTWriter(blt::fs::block_writer& writer): writer(writer) {} - void readFully(){ - + void write(tag_compound* root){ + writer.put((char)nbt_tag::COMPOUND); + root->writeName(writer); + root->writePayload(writer); } }; diff --git a/src/blt/nbt/nbt.cpp b/src/blt/nbt/nbt.cpp index 7c547c9..3787b39 100755 --- a/src/blt/nbt/nbt.cpp +++ b/src/blt/nbt/nbt.cpp @@ -31,4 +31,12 @@ namespace blt::nbt { return strOut; } + void NBTReader::read() { + char t = reader.get(); + if (t != (char)nbt_tag::COMPOUND) + throw std::runtime_error("Incorrectly formatted NBT data! Root tag must be a compound tag!"); + root = new tag_compound; + root->readName(reader); + root->readPayload(reader); + } } \ No newline at end of file