From 5166cfb9b70f21b16193315cbdee69a507371a13 Mon Sep 17 00:00:00 2001 From: ljfa-ag Date: Wed, 12 Aug 2015 14:13:22 +0200 Subject: Implement basic stream_writer methods --- include/io/stream_writer.h | 12 +++++++++--- src/io/stream_writer.cpp | 16 ++++++++++++++++ test/write_test.cpp | 1 + 3 files changed, 26 insertions(+), 3 deletions(-) diff --git a/include/io/stream_writer.h b/include/io/stream_writer.h index ea3dcd1c58..78d02cb2cc 100644 --- a/include/io/stream_writer.h +++ b/include/io/stream_writer.h @@ -42,17 +42,22 @@ class output_error : public std::runtime_error class stream_writer { public: + ///Maximum length of an NBT string (65535) + static constexpr size_t max_string_len = UINT16_MAX; + /** * @param os the stream to write to * @param e the byte order of the written data. The Java edition * of Minecraft uses Big Endian, the Pocket edition uses Little Endian */ - explicit stream_writer(std::ostream& os, endian::endian e = endian::big) noexcept; + explicit stream_writer(std::ostream& os, endian::endian e = endian::big) noexcept: + os(os), endian(e) + {} ///Returns the stream - std::ostream& get_ostr() const; + std::ostream& get_ostr() const { return os; } ///Returns the byte order - endian::endian get_endian() const; + endian::endian get_endian() const { return endian; } /** * @brief Writes a tag type to the stream @@ -70,6 +75,7 @@ public: * * An NBT string consists of two bytes indicating the length, followed by * the characters encoded in modified UTF-8. + * @throw std::length_error if the string is too long for NBT */ void write_string(const std::string& str); diff --git a/src/io/stream_writer.cpp b/src/io/stream_writer.cpp index dd90c83322..26a6a7eb65 100644 --- a/src/io/stream_writer.cpp +++ b/src/io/stream_writer.cpp @@ -18,13 +18,29 @@ * along with libnbt++. If not, see . */ #include "io/stream_writer.h" +#include namespace nbt { namespace io { +void stream_writer::write_type(tag_type tt) +{ + write_num(static_cast(tt)); +} +void stream_writer::write_string(const std::string& str) +{ + if(str.size() > max_string_len) + { + std::ostringstream sstr; + sstr << "String is too long for NBT (" << str.size() << " > " << max_string_len << ")"; + throw std::length_error(sstr.str()); + } + write_num(static_cast(str.size())); + os.write(str.data(), str.size()); +} } } diff --git a/test/write_test.cpp b/test/write_test.cpp index 5c5cab055b..3f9327b978 100644 --- a/test/write_test.cpp +++ b/test/write_test.cpp @@ -51,6 +51,7 @@ void test_stream_writer_big() 0x00, 0x06, //string length in Big Endian 'f', 'o', 'o', 'b', 'a', 'r' }; + std::string s = os.str(); ASSERT(os.str() == expected); std::clog << "test_stream_writer_big passed" << std::endl; } -- cgit 0.0.5-2-1-g0f52