Serializing strings works with nullbytes instead of size+data

This commit is contained in:
Sebastian Messmer 2015-10-27 20:59:23 +01:00
parent 9e67e52dc8
commit eac8d44b41
2 changed files with 11 additions and 9 deletions

View File

@ -91,12 +91,14 @@ namespace cpputils {
} }
inline std::string Deserializer::readString() { inline std::string Deserializer::readString() {
uint64_t size = readUint64(); //TODO Test whether that works when string ends (a) at beginning (b) in middle (c) at end of data region
if (_pos + size > _source->size()) { const void *nullbytepos = std::memchr(_source->dataOffset(_pos), '\0', _source->size()-_pos);
throw std::runtime_error("Deserialization failed - size overflow"); if (nullbytepos == nullptr) {
throw std::runtime_error("Deserialization failed - missing nullbyte for string termination");
} }
uint64_t size = static_cast<const uint8_t*>(nullbytepos) - static_cast<const uint8_t*>(_source->dataOffset(_pos));
std::string result(reinterpret_cast<const char*>(_source->dataOffset(_pos)), size); std::string result(reinterpret_cast<const char*>(_source->dataOffset(_pos)), size);
_pos += size; _pos += size + 1;
return result; return result;
} }

View File

@ -97,16 +97,16 @@ namespace cpputils {
} }
inline void Serializer::writeString(const std::string &value) { inline void Serializer::writeString(const std::string &value) {
writeUint64(value.size()); size_t size = value.size() + 1; // +1 for the nullbyte
if (_pos + value.size() > _result.size()) { if (_pos + size > _result.size()) {
throw std::runtime_error("Serialization failed - size overflow"); throw std::runtime_error("Serialization failed - size overflow");
} }
std::memcpy(static_cast<char*>(_result.dataOffset(_pos)), value.c_str(), value.size()); std::memcpy(static_cast<char*>(_result.dataOffset(_pos)), value.c_str(), size);
_pos += value.size(); _pos += size;
} }
inline size_t Serializer::StringSize(const std::string &value) { inline size_t Serializer::StringSize(const std::string &value) {
return sizeof(uint64_t) + value.size(); return value.size() + 1; // +1 for nullbyte
} }
inline Data Serializer::finished() { inline Data Serializer::finished() {