Added (De)Serializer::write/readString

This commit is contained in:
Sebastian Messmer 2015-10-25 13:02:28 +01:00
parent 7abbb33654
commit a33df2e292
2 changed files with 31 additions and 3 deletions

View File

@ -21,6 +21,7 @@ namespace cpputils {
uint64_t readUint64();
int64_t readInt64();
Data readData();
std::string readString();
void finished();
@ -97,6 +98,17 @@ namespace cpputils {
return result;
}
inline std::string Deserializer::readString() {
uint64_t size = readUint64();
if (_pos + size > _source->size()) {
_finishedCalled = true; // We don't want the destructor assertion to fail when destructor is called because of the exception
throw std::runtime_error("Deserialization failed - size overflow");
}
std::string result(reinterpret_cast<const char*>(_source->dataOffset(_pos)), size);
_pos += size;
return result;
}
inline void Deserializer::finished() {
_finishedCalled = true;
if (_pos != _source->size()) {

View File

@ -4,6 +4,7 @@
#include "Data.h"
#include "../macros.h"
#include <string>
namespace cpputils {
//TODO Test Serializer/Deserializer
@ -20,9 +21,11 @@ namespace cpputils {
void writeInt32(int32_t value);
void writeUint64(uint64_t value);
void writeInt64(int64_t value);
void writeData(const Data &data);
void writeData(const Data &value);
void writeString(const std::string &value);
static size_t DataSize(const Data &data);
static size_t DataSize(const Data &value);
static size_t StringSize(const std::string &value);
Data finished();
@ -93,7 +96,20 @@ namespace cpputils {
return sizeof(uint64_t) + data.size();
}
Data Serializer::finished() {
inline void Serializer::writeString(const std::string &value) {
writeUint64(value.size());
if (_pos + value.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();
}
inline size_t Serializer::StringSize(const std::string &value) {
return sizeof(uint64_t) + value.size();
}
inline Data Serializer::finished() {
if (_pos != _result.size()) {
throw std::runtime_error("Serialization failed - size not fully used.");
}