diff --git a/opm/common/utility/Serializer.hpp b/opm/common/utility/Serializer.hpp index 342b53ecb..d4ec057cb 100644 --- a/opm/common/utility/Serializer.hpp +++ b/opm/common/utility/Serializer.hpp @@ -47,11 +47,16 @@ public: this->pack(std::addressof(value), sizeof(T)); } + template + void put(const T* ) { + throw std::logic_error("Serializer can not pack pointers"); + } + template T get() { T value; - std::memcpy(&value, &this->buffer[pos], sizeof(T)); - this->pos += sizeof(T); + std::memcpy(&value, &this->buffer[this->read_pos], sizeof(T)); + this->read_pos += sizeof(T); return value; } @@ -86,20 +91,26 @@ private: std::memcpy(&this->buffer[write_pos], ptr, value_size); } - std::size_t pos = 0; + std::size_t read_pos = 0; }; template <> void inline Serializer::put(const std::string& value) { - this->put(value.size()); + this->put(value.size()); + if (value.empty()) + return; + this->pack(value.c_str(), value.size()); } template<> std::string inline Serializer::get() { std::string::size_type length = this->get(); - this->pos += length; - return {std::addressof(this->buffer[this->pos - length]), length}; + if (length == 0) + return std::string{}; + + this->read_pos += length; + return {std::addressof(this->buffer[this->read_pos - length]), length}; } } diff --git a/tests/test_Serializer.cpp b/tests/test_Serializer.cpp index 518b06263..6bfb1038d 100644 --- a/tests/test_Serializer.cpp +++ b/tests/test_Serializer.cpp @@ -48,3 +48,12 @@ BOOST_AUTO_TEST_CASE(SERIALIZER) { BOOST_CHECK(m2 == m); } +BOOST_AUTO_TEST_CASE(EMPTY_STRING) { + Opm::Serializer ser; + ser.put(std::string{}); + BOOST_CHECK_THROW( ser.put(""), std::logic_error); + + Opm::Serializer ser2(ser.buffer); + BOOST_CHECK_EQUAL(ser2.get(), ""); +} +