Serialize arithmetic and enum types in little endian encoding

pull/3225/head
elsid 3 years ago
parent 23ad1b2b9f
commit b5c689976e
No known key found for this signature in database
GPG Key ID: D27B8E8D10A2896B

@ -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
{

@ -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);
}
};
}

Loading…
Cancel
Save