Skip to content

Commit

Permalink
Not casting float to int, it violates strict aliasing rule
Browse files Browse the repository at this point in the history
  • Loading branch information
TianyiChen committed Nov 27, 2024
1 parent 97fe5f2 commit 7acebd4
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 8 deletions.
9 changes: 5 additions & 4 deletions include/nlohmann/detail/input/binary_reader.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -2803,10 +2803,11 @@ class binary_reader
{
return;
}
// convert float types to int types of the same size
using swap_t = std::conditional<sz == 2, std::uint16_t, typename std::conditional<sz == 4, std::uint32_t, std::uint64_t>::type>::type;
swap_t& number_ref = reinterpret_cast<swap_t&>(number);
number_ref = std::byteswap(number_ref);
if constexpr(std::is_integral_v<NumberType>)
{
number = std::byteswap(number);
return;
}
#else
auto* ptr = reinterpret_cast<std::uint8_t*>(&number);
for (std::size_t i = 0; i < sz / 2; ++i)
Expand Down
9 changes: 5 additions & 4 deletions single_include/nlohmann/json.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -12101,10 +12101,11 @@ class binary_reader
{
return;
}
// convert float types to int types of the same size
using swap_t = std::conditional<sz == 2, std::uint16_t, typename std::conditional<sz == 4, std::uint32_t, std::uint64_t>::type>::type;
swap_t& number_ref = reinterpret_cast<swap_t&>(number);
number_ref = std::byteswap(number_ref);
if constexpr(std::is_integral_v<NumberType>)
{
number = std::byteswap(number);
return;
}
#else
auto* ptr = reinterpret_cast<std::uint8_t*>(&number);
for (std::size_t i = 0; i < sz / 2; ++i)
Expand Down

0 comments on commit 7acebd4

Please sign in to comment.