Skip to content

Commit

Permalink
feat: add NbtIo::readNamedTag
Browse files Browse the repository at this point in the history
  • Loading branch information
wu-vincent committed Feb 20, 2025
1 parent 6f3a2e8 commit 92cc35a
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 3 deletions.
13 changes: 11 additions & 2 deletions src/bedrock/nbt/compound_tag.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,17 @@ void CompoundTag::write(IDataOutput &output) const

Bedrock::Result<void> CompoundTag::load(IDataInput &input)
{
// TODO(nbt): fixme
throw std::runtime_error("Not implemented");
tags_.clear();
while (input.numBytesLeft()) {
std::string name;
auto tag_result = NbtIo::readNamedTag(input, name);
if (!tag_result) {
return nonstd::make_unexpected(tag_result.error());
}
put(name, std::move(tag_result.value()));
}

return {};
}

std::string CompoundTag::toString() const
Expand Down
28 changes: 27 additions & 1 deletion src/bedrock/nbt/nbt_io.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,33 @@

#include "bedrock/nbt/compound_tag.h"

Bedrock::Result<std::unique_ptr<Tag>> NbtIo::readNamedTag(IDataInput &dis, std::string &name)
{
auto type_result = dis.readByteResult();
if (!type_result) {
return nonstd::make_unexpected(type_result.error());
}

auto type = static_cast<Tag::Type>(type_result.value());
if (type == Tag::Type::End) {
return std::make_unique<EndTag>();
}

auto name_result = dis.readStringResult();
if (!name_result) {
return nonstd::make_unexpected(name_result.error());
}
name = name_result.value();

auto tag_result = Tag::newTag(type);
if (!tag_result) {
return nonstd::make_unexpected(tag_result.error());
}

tag_result.value()->load(dis);
return std::move(tag_result.value());
}

void NbtIo::writeNamedTag(const std::string &name, const Tag &tag, IDataOutput &output)
{
auto type = tag.getId();
Expand All @@ -25,4 +52,3 @@ void NbtIo::writeNamedTag(const std::string &name, const Tag &tag, IDataOutput &
tag.write(output);
}
}

2 changes: 2 additions & 0 deletions src/bedrock/nbt/nbt_io.h
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@

namespace NbtIo {

Bedrock::Result<std::unique_ptr<Tag>> readNamedTag(IDataInput &dis, std::string &name);

void writeNamedTag(const std::string &name, const Tag &tag, IDataOutput &output);

} // namespace NbtIo

0 comments on commit 92cc35a

Please sign in to comment.