Skip to content

Commit 8d91876

Browse files
committed
Fix possible undefined behavior when n_digits is 0.
1 parent 365f486 commit 8d91876

1 file changed

Lines changed: 3 additions & 0 deletions

File tree

include/bencode/detail/parser/from_chars.hpp

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ inline constexpr auto power_of_10_lookup = std::array {
3535

3636
constexpr std::uint64_t byteswap(std::uint64_t data, std::size_t n_digits = 8)
3737
{
38+
if (n_digits == 0) [[unlikely]] return 0;
3839
std::uint64_t swapped = __builtin_bswap64(data);
3940
std::uint64_t n_shifts = (8 * (8-n_digits));
4041
std::uint64_t out = swapped >> n_shifts;
@@ -43,6 +44,7 @@ constexpr std::uint64_t byteswap(std::uint64_t data, std::size_t n_digits = 8)
4344

4445
constexpr std::uint32_t byteswap(std::uint32_t data, std::size_t n_digits = 4)
4546
{
47+
if (n_digits == 0) [[unlikely]] return 0;
4648
std::uint32_t swapped = __builtin_bswap32(data);
4749
std::uint32_t n_shifts = (8 * (4-n_digits));
4850
std::uint32_t out = swapped >> n_shifts;
@@ -51,6 +53,7 @@ constexpr std::uint32_t byteswap(std::uint32_t data, std::size_t n_digits = 4)
5153

5254
constexpr std::uint16_t byteswap(std::uint16_t data, std::size_t n_digits = 2)
5355
{
56+
if (n_digits == 0) [[unlikely]] return 0;
5457
std::uint16_t swapped = __builtin_bswap16(data);
5558
std::uint16_t n_shifts = (8 * (2-n_digits));
5659
std::uint16_t out = swapped >> n_shifts;

0 commit comments

Comments
 (0)