Handle empty strings in serializer

This commit is contained in:
Joakim Hove 2020-09-02 07:45:17 +02:00
parent 015d8ff923
commit e99e2c5e82
2 changed files with 26 additions and 6 deletions

View File

@ -47,11 +47,16 @@ public:
this->pack(std::addressof(value), sizeof(T)); this->pack(std::addressof(value), sizeof(T));
} }
template <typename T>
void put(const T* ) {
throw std::logic_error("Serializer can not pack pointers");
}
template <typename T> template <typename T>
T get() { T get() {
T value; T value;
std::memcpy(&value, &this->buffer[pos], sizeof(T)); std::memcpy(&value, &this->buffer[this->read_pos], sizeof(T));
this->pos += sizeof(T); this->read_pos += sizeof(T);
return value; return value;
} }
@ -86,20 +91,26 @@ private:
std::memcpy(&this->buffer[write_pos], ptr, value_size); std::memcpy(&this->buffer[write_pos], ptr, value_size);
} }
std::size_t pos = 0; std::size_t read_pos = 0;
}; };
template <> template <>
void inline Serializer::put(const std::string& value) { void inline Serializer::put(const std::string& value) {
this->put<std::string::size_type>(value.size()); this->put(value.size());
if (value.empty())
return;
this->pack(value.c_str(), value.size()); this->pack(value.c_str(), value.size());
} }
template<> template<>
std::string inline Serializer::get<std::string>() { std::string inline Serializer::get<std::string>() {
std::string::size_type length = this->get<std::string::size_type>(); std::string::size_type length = this->get<std::string::size_type>();
this->pos += length; if (length == 0)
return {std::addressof(this->buffer[this->pos - length]), length}; return std::string{};
this->read_pos += length;
return {std::addressof(this->buffer[this->read_pos - length]), length};
} }
} }

View File

@ -48,3 +48,12 @@ BOOST_AUTO_TEST_CASE(SERIALIZER) {
BOOST_CHECK(m2 == m); 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<std::string>(), "");
}