diff --git a/base/base_tests/string_utils_test.cpp b/base/base_tests/string_utils_test.cpp index f1e2dff2cc..684a33a527 100644 --- a/base/base_tests/string_utils_test.cpp +++ b/base/base_tests/string_utils_test.cpp @@ -176,6 +176,10 @@ UNIT_TEST(to_int) int i; string s; + s = "AF"; + TEST(strings::to_int(s, i, 16), ()); + TEST_EQUAL(175, i, ()); + s = "-2"; TEST(strings::to_int(s, i), ()); TEST_EQUAL(-2, i, ()); @@ -190,10 +194,43 @@ UNIT_TEST(to_int) s = "labuda"; TEST(!strings::to_int(s, i), ()); +} +UNIT_TEST(to_uint) +{ + unsigned int i; + string s; + + s = ""; + TEST(!strings::to_uint(s, i), ()); + + s = "-2"; + TEST(!strings::to_uint(s, i), ()); + + s = "0"; + TEST(strings::to_uint(s, i), ()); + TEST_EQUAL(0, i, ()); + + s = "123456789123456789123456789"; + TEST(!strings::to_uint(s, i), ()); + + s = "labuda"; + TEST(!strings::to_uint(s, i), ()); + s = "AF"; - TEST(strings::to_int(s, i, 16), ()); + TEST(strings::to_uint(s, i, 16), ()); TEST_EQUAL(175, i, ()); + + s = "100"; + TEST(strings::to_uint(s, i), ()); + TEST_EQUAL(100, i, ()); + + s = "4294967295"; + TEST(strings::to_uint(s, i), ()); + TEST_EQUAL(0xFFFFFFFF, i, ()); + + s = "4294967296"; + TEST(!strings::to_uint(s, i), ()); } UNIT_TEST(to_uint64) diff --git a/base/string_utils.cpp b/base/string_utils.cpp index d91dc5bb0d..22dfad3030 100644 --- a/base/string_utils.cpp +++ b/base/string_utils.cpp @@ -44,29 +44,31 @@ UniChar LastUniChar(string const & s) namespace { -template -bool IntegerCheck(T x, char const *stop, ET & out) +template +bool IntegerCheck(char const * start, char const * stop, T x, TResult & out) { - if (*stop == 0) + if (errno != EINVAL && *stop == 0) { - out = static_cast(x); - ASSERT_EQUAL(static_cast(out), x, ()); - return true; + out = static_cast(x); + return static_cast(out) == x; } + errno = 0; return false; } } // namespace - -bool to_int(char const * s, int & i, int base /*= 10*/) + +bool to_int(char const * start, int & i, int base /*= 10*/) { char * stop; - return IntegerCheck(strtol(s, &stop, base), stop, i); + long const v = strtol(start, &stop, base); + return IntegerCheck(start, stop, v, i); } -bool to_uint(char const * s, unsigned int & i, int base /*= 10*/) +bool to_uint(char const * start, unsigned int & i, int base /*= 10*/) { char * stop; - return IntegerCheck(strtoul(s, &stop, base), stop, i); + unsigned long const v = strtoul(start, &stop, base); + return IntegerCheck(start, stop, v, i); }