Нужно сделать для каждого класса 3 функции:
- уникальный ид типа
- сериализация
- десериализация
Соответственно в файл писать блоки вида:
<ид_типа><данные_типа>
Делается такое примерно так:
#include <iostream>
#include <string>
#include <array>
#include <utility>
#include <vector>
#include <algorithm>
#include <cstdint>
#include <chrono>
#include <random>
#include <numeric>
#include <unordered_map>
#include <typeindex>
#include <functional>
#include <any>
#include <span>
#include <unordered_set>
#include <optional>
#include <cassert>
using namespace std;
// Basics
template<typename T>
void SerializeRawSimple(T const& val, vector<byte>& data)
{
union U
{
T val;
array<byte, sizeof T> b;
};
U u{ .val = val };
data.insert(data.end(), u.b.begin(), u.b.end());
}
void SerializeRaw(int32_t const& val, vector<byte>& data)
{
SerializeRawSimple(val, data);
}
void SerializeRaw(int64_t const& val, vector<byte>& data)
{
SerializeRawSimple(val, data);
}
void SerializeRaw(string const& val, vector<byte>& data)
{
SerializeRawSimple((int64_t)val.size(), data);
for (auto& c : val)
{
data.push_back((byte)c);
}
}
template<typename T>
T DeserializeRawSimple(span<const byte>const& data, int64_t& type_data_size)
{
union U
{
array<byte, sizeof T> b;
T val;
};
if (data.size() < sizeof T)
throw "Deserialize error";
U u;
copy(data.begin(), data.begin() + sizeof T, u.b.begin());
type_data_size = sizeof T;
return u.val;
}
template<typename T>
T DeserializeRaw(span<const byte>const& data, int64_t& type_data_size)
{
static_assert(false && "Need implement");
return T();
}
template<>
int32_t DeserializeRaw<int32_t>(span<const byte> const& data, int64_t& type_data_size)
{
return DeserializeRawSimple<int32_t>(data, type_data_size);
}
template<>
int64_t DeserializeRaw<int64_t>(span<const byte>const& data, int64_t& type_data_size)
{
return DeserializeRawSimple<int64_t>(data, type_data_size);
}
template<>
string DeserializeRaw<string>(std::span<const byte>const& data, int64_t& type_data_size)
{
auto data_span = data;
int64_t tmp_size;
type_data_size = 0;
string res;
auto str_len = DeserializeRaw<int64_t>(data_span, tmp_size);
data_span = data_span.subspan(tmp_size);
type_data_size += tmp_size;
if (data_span.size() < str_len)
throw "Deserialize error";
res.resize(str_len);
for (size_t i = 0; i < str_len; i++)
res[i] = (char)data_span[i];
type_data_size += str_len;
return res;
}
// Types
struct A
{
int32_t x = 8;
int32_t y = 9;
string z = "12345";
};
void SerializeRaw(A const& val, vector<byte>& data)
{
SerializeRaw(val.x, data);
SerializeRaw(val.y, data);
SerializeRaw(val.z, data);
}
template<>
A DeserializeRaw<A>(std::span<const byte>const& data, int64_t& type_data_size)
{
auto data_span = data;
int64_t tmp_size;
type_data_size = 0;
A res;
res.x = DeserializeRaw<int32_t>(data_span, tmp_size);
data_span = data_span.subspan(tmp_size);
type_data_size += tmp_size;
res.y = DeserializeRaw<int32_t>(data_span, tmp_size);
data_span = data_span.subspan(tmp_size);
type_data_size += tmp_size;
res.z = DeserializeRaw<string>(data_span, tmp_size);
data_span = data_span.subspan(tmp_size);
type_data_size += tmp_size;
return res;
}
struct B
{
int32_t x = -1;
A y;
};
void SerializeRaw(B const& val, vector<byte>& data)
{
SerializeRaw(val.x, data);
SerializeRaw(val.y, data);
}
template<>
B DeserializeRaw<B>(std::span<const byte>const& data, int64_t& type_data_size)
{
auto data_span = data;
int64_t tmp_size;
type_data_size = 0;
B res;
res.x = DeserializeRaw<int32_t>(data_span, tmp_size);
data_span = data_span.subspan(tmp_size);
type_data_size += tmp_size;
res.y = DeserializeRaw<A>(data_span, tmp_size);
data_span = data_span.subspan(tmp_size);
type_data_size += tmp_size;
return res;
}
// Serializer
class EpicSerializer
{
public:
EpicSerializer()
{
RegisterType<A>();
RegisterType<B>();
}
static auto Get()
{
static EpicSerializer i;
return &i;
}
template<typename T>
int32_t GetTypeId()
{
if (auto it = _types_map.find(typeid(T)); it != _types_map.end())
return it->second.id;
return 0;
}
template<typename T>
void Serialize(T const& val, vector<byte>& data)
{
auto it = _types_map.find(typeid(T));
if (it == _types_map.end())
throw "Unknown type serialize";
SerializeRaw(it->second.id, data);
it->second.serialize((void*)&val, data);
}
vector<any> Deserialize(vector<byte> const& data)
{
vector<any> res;
size_t pos = 0;
while (pos < data.size())
{
if (pos + sizeof(uint32_t) > data.size())
throw "Deserialize wrong";
span<const byte> uid_data(data.data() + pos, sizeof(uint32_t));
int64_t data_type_size;
auto uid = DeserializeRaw<int32_t>(uid_data, data_type_size);
pos += data_type_size;
auto it = _types_uid_map.find(uid);
if (it == _types_uid_map.end())
throw "Deserialize wrong";
span<const byte> t1{ data.data() + pos, data.size() - pos };
auto& cell = _types_map[it->second];
res.push_back(cell.deserialize(t1, data_type_size));
pos += data_type_size;
}
return res;
}
private:
struct Cell
{
int32_t id = 0;
function<void(void* val, vector<byte>& data)> serialize;
function<any(std::span<const byte>const& data, int64_t& type_data_size)> deserialize;
};
template<typename T>
static void InternalSerialize(void* val, vector<byte>& data)
{
SerializeRaw(*(T*)val, data);
}
template<typename T>
static any InternalDeserialize(std::span<const byte>const& data, int64_t& type_data_size)
{
return DeserializeRaw<T>(data, type_data_size);
}
template<typename T>
void RegisterType()
{
int32_t uid = _types_map.size() + 1;
Cell cell{
.id = uid,
.serialize = &InternalSerialize<T>,
.deserialize = &InternalDeserialize<T> };
assert(_types_map.find(typeid(T)) == _types_map.end());
_types_map.insert({ typeid(T), cell });
_types_uid_map.insert({ uid, typeid(T) });
}
unordered_map<type_index, Cell> _types_map;
unordered_map<int32_t, type_index> _types_uid_map;
};
int main()
{
A a;
B b;
vector<byte> data;
EpicSerializer::Get()->Serialize(a, data);
EpicSerializer::Get()->Serialize(b, data);
auto vec = EpicSerializer::Get()->Deserialize(data);
A a1 = any_cast<A>(vec[0]);
B b1 = any_cast<B>(vec[1]);
return 0;
}
В данном варианте не учитывается много чего. Например изменение полей типов, big-little endian итд. Реальное решение задачи сереализации гораздо сложнее(пока в C++ не завезли рефлексию).
fout.write(reinterpret_cast<char*>(mas), 8 * sizeof(const char*));
– можете объяснить нам (и себе заодно), почему в этой строчке делается именно так? Зачем эти касты и всё прочее? Что Вы хотели этим сделать? Чем это лучшеfout.write(mas[i], strlen(mas[i]));
в цикле по строкам?string
, но это не меняет дела. И - да, вы правильно поняли причину. Вам надо хранить структуру по полям. Как хранить строку - в ответе по тому же адресу приведен способ: сохраняете длину,, содержимое. Когда читаете - читаете длину, выделяете память, считываете содержимое...