1
0
mirror of https://gitlab.com/OpenMW/openmw.git synced 2025-01-07 12:54:00 +00:00
OpenMW/components/detournavigator/serialization/binaryreader.hpp
elsid a58f1a94e3
Add helpers for binary serialization
To construct serializer from given entities:
* Data source/destination - any value that has to be serialized/deserialized,
  usually already existing type.
* Format - functional object to define high level serialization logic to
  define specific format and data schema. Like order of fields, allocation.
* Visitor - functional object to define low level serialization logic to
  operator on given data part.
  * BinaryWriter - copies given value into provided buffer.
  * BinaryReader - copies value into given destination from provided buffer.
  * SizeAccumulator - calculates required buffer size for given data.
2021-10-24 14:20:44 +02:00

63 lines
1.7 KiB
C++

#ifndef OPENMW_COMPONENTS_DETOURNAVIGATOR_SERIALIZATION_BINARYREADER_H
#define OPENMW_COMPONENTS_DETOURNAVIGATOR_SERIALIZATION_BINARYREADER_H
#include <cassert>
#include <cstddef>
#include <cstring>
#include <stdexcept>
#include <type_traits>
namespace DetourNavigator::Serialization
{
class BinaryReader
{
public:
explicit BinaryReader(const std::byte* pos, const std::byte* end)
: mPos(pos), mEnd(end)
{
assert(mPos <= mEnd);
}
BinaryReader(const BinaryReader&) = delete;
template <class Format, class T>
void operator()(Format&& format, T& value)
{
if constexpr (std::is_arithmetic_v<T>)
{
if (mEnd - mPos < static_cast<std::ptrdiff_t>(sizeof(value)))
throw std::runtime_error("Not enough data");
std::memcpy(&value, mPos, sizeof(value));
mPos += sizeof(value);
}
else
{
format(*this, value);
}
}
template <class Format, class T>
auto operator()(Format&& format, T* data, std::size_t count)
{
if constexpr (std::is_arithmetic_v<T>)
{
if (mEnd - mPos < static_cast<std::ptrdiff_t>(count * sizeof(T)))
throw std::runtime_error("Not enough data");
const std::size_t size = sizeof(T) * count;
std::memcpy(data, mPos, size);
mPos += size;
}
else
{
format(*this, data, count);
}
}
private:
const std::byte* mPos;
const std::byte* const mEnd;
};
}
#endif