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 28, 2024
1 parent 97fe5f2 commit 26cddc6
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 12 deletions.
12 changes: 6 additions & 6 deletions include/nlohmann/detail/input/binary_reader.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -2803,17 +2803,17 @@ 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);
#else
if constexpr(std::is_integral_v<NumberType>)
{
number = std::byteswap(number);
return;
}
#endif
auto* ptr = reinterpret_cast<std::uint8_t*>(&number);
for (std::size_t i = 0; i < sz / 2; ++i)
{
std::swap(ptr[i], ptr[sz - i - 1]);
}
#endif
}

/*
Expand Down
12 changes: 6 additions & 6 deletions single_include/nlohmann/json.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -12101,17 +12101,17 @@ 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);
#else
if constexpr(std::is_integral_v<NumberType>)
{
number = std::byteswap(number);
return;
}
#endif
auto* ptr = reinterpret_cast<std::uint8_t*>(&number);
for (std::size_t i = 0; i < sz / 2; ++i)
{
std::swap(ptr[i], ptr[sz - i - 1]);
}
#endif
}

/*
Expand Down

0 comments on commit 26cddc6

Please sign in to comment.