v1
Brett 2023-07-26 14:03:21 -04:00
parent 5c0093e0d3
commit ff1765c52e
2 changed files with 32 additions and 8 deletions

View File

@ -319,12 +319,14 @@ namespace blt::nbt {
public: public:
tag_compound(): tag(nbt_tag::COMPOUND) {} tag_compound(): tag(nbt_tag::COMPOUND) {}
tag_compound(const std::string& name, const std::vector<tag_t*>& v): tag(nbt_tag::COMPOUND, name, _internal_::toHashmap(v)) {} tag_compound(const std::string& name, const std::vector<tag_t*>& v): tag(nbt_tag::COMPOUND, name, _internal_::toHashmap(v)) {}
tag_compound(const std::string& name, const std::initializer_list<tag_t*>& v): tag(nbt_tag::COMPOUND, name, _internal_::toHashmap(v)) {}
tag_compound(const std::string& name, const HASHMAP<std::string, tag_t*>& v): tag(nbt_tag::COMPOUND, name, v) {} tag_compound(const std::string& name, const HASHMAP<std::string, tag_t*>& v): tag(nbt_tag::COMPOUND, name, v) {}
void writePayload(blt::fs::block_writer& out) final { void writePayload(blt::fs::block_writer& out) final {
for (auto*& v : t){ for (const auto& v : t){
out.put((char) v->getType()); auto tag = v.second;
v->writeName(out); out.put((char) tag->getType());
v->writePayload(out); tag->writeName(out);
tag->writePayload(out);
} }
out.put('\0'); out.put('\0');
} }
@ -334,7 +336,7 @@ namespace blt::nbt {
auto* v = _internal_::toType(type); auto* v = _internal_::toType(type);
v->readName(in); v->readName(in);
v->readPayload(in); v->readPayload(in);
t.push_back(v); t[v->getName()] = v;
} }
} }
}; };
@ -350,19 +352,33 @@ namespace blt::nbt {
class NBTReader { class NBTReader {
private: private:
blt::fs::block_reader& reader; blt::fs::block_reader& reader;
tag_compound* root = nullptr;
public: public:
explicit NBTReader(blt::fs::block_reader& reader): reader(reader) {} explicit NBTReader(blt::fs::block_reader& reader): reader(reader) {}
void read();
template<typename T>
[[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<T*>(tag);
}
}; };
class NBTWriter { class NBTWriter {
private: private:
blt::fs::block_writer& writer; blt::fs::block_writer& writer;
tag_compound* root = nullptr;
public: public:
explicit NBTWriter(blt::fs::block_writer& writer): writer(writer) {} 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);
} }
}; };

View File

@ -31,4 +31,12 @@ namespace blt::nbt {
return strOut; 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);
}
} }