diff --git a/components/serialization/binaryreader.hpp b/components/serialization/binaryreader.hpp index c1a9031676..66e09f6ffb 100644 --- a/components/serialization/binaryreader.hpp +++ b/components/serialization/binaryreader.hpp @@ -1,6 +1,9 @@ #ifndef OPENMW_COMPONENTS_SERIALIZATION_BINARYREADER_H #define OPENMW_COMPONENTS_SERIALIZATION_BINARYREADER_H +#include + +#include #include #include #include @@ -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 { diff --git a/components/serialization/binarywriter.hpp b/components/serialization/binarywriter.hpp index 5250bcfdf2..199f208da9 100644 --- a/components/serialization/binarywriter.hpp +++ b/components/serialization/binarywriter.hpp @@ -1,6 +1,9 @@ #ifndef OPENMW_COMPONENTS_SERIALIZATION_BINARYWRITER_H #define OPENMW_COMPONENTS_SERIALIZATION_BINARYWRITER_H +#include + +#include #include #include #include @@ -29,8 +32,7 @@ namespace Serialization { if (mEnd - mDest < static_cast(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(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 + void writeValue(const T& value) noexcept + { + T coverted = Misc::toLittleEndian(value); + std::memcpy(mDest, &coverted, sizeof(T)); + mDest += sizeof(T); + } }; }