Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions include/intx/intx.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -840,9 +840,11 @@ constexpr Int from_string(const char* str)
throw_<std::out_of_range>(str);

const auto d = from_dec_digit(c);
x = x * Int{10} + d;
if (x < d)
// Check for overflow before multiplying, since checking after could be fooled by
// wraparound.
if (x > (std::numeric_limits<Int>::max() - d) / Int{10})
throw_<std::out_of_range>(str);
x = x * Int{10} + d;
}
return x;
}
Expand Down
9 changes: 9 additions & 0 deletions test/unittests/test_intx.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,15 @@ TYPED_TEST(uint_test, string_conversions)
}
}

TYPED_TEST(uint_test, from_string_decimal_overflow)
{
// A decimal string with as many digits as TypeParam::max() but consisting of all 9s
// is always greater than max() and must be rejected, not silently wrapped around.
const auto digits = to_string(std::numeric_limits<TypeParam>::max()).size();
const auto s = std::string(digits, '9');
EXPECT_THROW_MESSAGE(from_string<TypeParam>(s), std::out_of_range, s.c_str());
}

TYPED_TEST(uint_test, to_string_base)
{
auto x = TypeParam{1024};
Expand Down