1
0
Fork 0
mirror of https://github.com/OpenMW/openmw.git synced 2025-03-03 07:09:40 +00:00

Serialize arithmetic and enum types in little endian encoding

This commit is contained in:
elsid 2021-11-08 19:28:04 +01:00
parent 23ad1b2b9f
commit b5c689976e
No known key found for this signature in database
GPG key ID: D27B8E8D10A2896B
2 changed files with 25 additions and 4 deletions

View file

@ -1,6 +1,9 @@
#ifndef OPENMW_COMPONENTS_SERIALIZATION_BINARYREADER_H
#define OPENMW_COMPONENTS_SERIALIZATION_BINARYREADER_H
#include <components/misc/endianness.hpp>
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstring>
@ -31,6 +34,7 @@ namespace Serialization
throw std::runtime_error("Not enough data");
std::memcpy(&value, mPos, sizeof(T));
mPos += sizeof(T);
value = Misc::toLittleEndian(value);
}
else
{
@ -50,6 +54,8 @@ namespace Serialization
throw std::runtime_error("Not enough data");
std::memcpy(data, mPos, size);
mPos += size;
if constexpr (!Misc::IS_LITTLE_ENDIAN)
std::for_each(data, data + count, [&] (T& v) { v = Misc::fromLittleEndian(v); });
}
else
{

View file

@ -1,6 +1,9 @@
#ifndef OPENMW_COMPONENTS_SERIALIZATION_BINARYWRITER_H
#define OPENMW_COMPONENTS_SERIALIZATION_BINARYWRITER_H
#include <components/misc/endianness.hpp>
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstring>
@ -29,8 +32,7 @@ namespace Serialization
{
if (mEnd - mDest < static_cast<std::ptrdiff_t>(sizeof(T)))
throw std::runtime_error("Not enough space");
std::memcpy(mDest, &value, sizeof(T));
mDest += sizeof(T);
writeValue(value);
}
else
{
@ -48,8 +50,13 @@ namespace Serialization
const std::size_t size = sizeof(T) * count;
if (mEnd - mDest < static_cast<std::ptrdiff_t>(size))
throw std::runtime_error("Not enough space");
std::memcpy(mDest, data, size);
mDest += size;
if constexpr (Misc::IS_LITTLE_ENDIAN)
{
std::memcpy(mDest, data, size);
mDest += size;
}
else
std::for_each(data, data + count, [&] (const T& v) { writeValue(v); });
}
else
{
@ -60,6 +67,14 @@ namespace Serialization
private:
std::byte* mDest;
const std::byte* const mEnd;
template <class T>
void writeValue(const T& value) noexcept
{
T coverted = Misc::toLittleEndian(value);
std::memcpy(mDest, &coverted, sizeof(T));
mDest += sizeof(T);
}
};
}