Serializing strings works with nullbytes instead of size+data
This commit is contained in:
parent
9e67e52dc8
commit
eac8d44b41
@ -91,12 +91,14 @@ namespace cpputils {
|
||||
}
|
||||
|
||||
inline std::string Deserializer::readString() {
|
||||
uint64_t size = readUint64();
|
||||
if (_pos + size > _source->size()) {
|
||||
throw std::runtime_error("Deserialization failed - size overflow");
|
||||
//TODO Test whether that works when string ends (a) at beginning (b) in middle (c) at end of data region
|
||||
const void *nullbytepos = std::memchr(_source->dataOffset(_pos), '\0', _source->size()-_pos);
|
||||
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);
|
||||
_pos += size;
|
||||
_pos += size + 1;
|
||||
return result;
|
||||
}
|
||||
|
||||
|
@ -97,16 +97,16 @@ namespace cpputils {
|
||||
}
|
||||
|
||||
inline void Serializer::writeString(const std::string &value) {
|
||||
writeUint64(value.size());
|
||||
if (_pos + value.size() > _result.size()) {
|
||||
size_t size = value.size() + 1; // +1 for the nullbyte
|
||||
if (_pos + size > _result.size()) {
|
||||
throw std::runtime_error("Serialization failed - size overflow");
|
||||
}
|
||||
std::memcpy(static_cast<char*>(_result.dataOffset(_pos)), value.c_str(), value.size());
|
||||
_pos += value.size();
|
||||
std::memcpy(static_cast<char*>(_result.dataOffset(_pos)), value.c_str(), size);
|
||||
_pos += size;
|
||||
}
|
||||
|
||||
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() {
|
||||
|
Loading…
x
Reference in New Issue
Block a user