From bb22b1003ffcf5f5a34036acca90bda3a6608bde Mon Sep 17 00:00:00 2001 From: Andreas Schwab Date: Thu, 21 Feb 2019 11:55:21 +0100 Subject: [PATCH] Do proper endian conversions This fixes all testsuite failures on big endian hosts. --- include/nlohmann/detail/input/binary_reader.hpp | 2 +- include/nlohmann/detail/output/binary_writer.hpp | 2 +- single_include/nlohmann/json.hpp | 4 ++-- test/src/unit-udt.cpp | 5 ++--- 4 files changed, 6 insertions(+), 7 deletions(-) diff --git a/include/nlohmann/detail/input/binary_reader.hpp b/include/nlohmann/detail/input/binary_reader.hpp index d20522341..3f173a6a7 100644 --- a/include/nlohmann/detail/input/binary_reader.hpp +++ b/include/nlohmann/detail/input/binary_reader.hpp @@ -1853,7 +1853,7 @@ class binary_reader } // reverse byte order prior to conversion if necessary - if (is_little_endian && !InputIsLittleEndian) + if (is_little_endian != InputIsLittleEndian) { vec[sizeof(NumberType) - i - 1] = static_cast(current); } diff --git a/include/nlohmann/detail/output/binary_writer.hpp b/include/nlohmann/detail/output/binary_writer.hpp index 2f1eed4b3..f191ca127 100644 --- a/include/nlohmann/detail/output/binary_writer.hpp +++ b/include/nlohmann/detail/output/binary_writer.hpp @@ -1278,7 +1278,7 @@ class binary_writer std::memcpy(vec.data(), &n, sizeof(NumberType)); // step 2: write array to output (with possible reordering) - if (is_little_endian and not OutputIsLittleEndian) + if (is_little_endian != OutputIsLittleEndian) { // reverse byte order prior to conversion if necessary std::reverse(vec.begin(), vec.end()); diff --git a/single_include/nlohmann/json.hpp b/single_include/nlohmann/json.hpp index 1b83be0b3..a6a7752f3 100644 --- a/single_include/nlohmann/json.hpp +++ b/single_include/nlohmann/json.hpp @@ -8333,7 +8333,7 @@ class binary_reader } // reverse byte order prior to conversion if necessary - if (is_little_endian && !InputIsLittleEndian) + if (is_little_endian != InputIsLittleEndian) { vec[sizeof(NumberType) - i - 1] = static_cast(current); } @@ -9746,7 +9746,7 @@ class binary_writer std::memcpy(vec.data(), &n, sizeof(NumberType)); // step 2: write array to output (with possible reordering) - if (is_little_endian and not OutputIsLittleEndian) + if (is_little_endian != OutputIsLittleEndian) { // reverse byte order prior to conversion if necessary std::reverse(vec.begin(), vec.end()); diff --git a/test/src/unit-udt.cpp b/test/src/unit-udt.cpp index 833a4c71d..0659745c4 100644 --- a/test/src/unit-udt.cpp +++ b/test/src/unit-udt.cpp @@ -599,9 +599,8 @@ struct pod_serializer static void to_json(BasicJsonType& j, const T& t) noexcept { auto bytes = static_cast< const unsigned char*>(static_cast(&t)); - std::uint64_t value = bytes[0]; - for (auto i = 1; i < 8; ++i) - value |= std::uint64_t{bytes[i]} << 8 * i; + std::uint64_t value; + std::memcpy(&value, bytes, sizeof(value)); nlohmann::to_json(j, value); } };