Skip to content

Commit 7acebd4

Browse files
committed
Not casting float to int, it violates strict aliasing rule
1 parent 97fe5f2 commit 7acebd4

File tree

2 files changed

+10
-8
lines changed

2 files changed

+10
-8
lines changed

include/nlohmann/detail/input/binary_reader.hpp

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2803,10 +2803,11 @@ class binary_reader
28032803
{
28042804
return;
28052805
}
2806-
// convert float types to int types of the same size
2807-
using swap_t = std::conditional<sz == 2, std::uint16_t, typename std::conditional<sz == 4, std::uint32_t, std::uint64_t>::type>::type;
2808-
swap_t& number_ref = reinterpret_cast<swap_t&>(number);
2809-
number_ref = std::byteswap(number_ref);
2806+
if constexpr(std::is_integral_v<NumberType>)
2807+
{
2808+
number = std::byteswap(number);
2809+
return;
2810+
}
28102811
#else
28112812
auto* ptr = reinterpret_cast<std::uint8_t*>(&number);
28122813
for (std::size_t i = 0; i < sz / 2; ++i)

single_include/nlohmann/json.hpp

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12101,10 +12101,11 @@ class binary_reader
1210112101
{
1210212102
return;
1210312103
}
12104-
// convert float types to int types of the same size
12105-
using swap_t = std::conditional<sz == 2, std::uint16_t, typename std::conditional<sz == 4, std::uint32_t, std::uint64_t>::type>::type;
12106-
swap_t& number_ref = reinterpret_cast<swap_t&>(number);
12107-
number_ref = std::byteswap(number_ref);
12104+
if constexpr(std::is_integral_v<NumberType>)
12105+
{
12106+
number = std::byteswap(number);
12107+
return;
12108+
}
1210812109
#else
1210912110
auto* ptr = reinterpret_cast<std::uint8_t*>(&number);
1211012111
for (std::size_t i = 0; i < sz / 2; ++i)

0 commit comments

Comments
 (0)