forked from organicmaps/organicmaps
[base] Refactor to_int and to_uint. Implement tests.
This commit is contained in:
parent
de7e82024b
commit
035fab80c5
2 changed files with 51 additions and 12 deletions
|
@ -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)
|
||||
|
|
|
@ -44,29 +44,31 @@ UniChar LastUniChar(string const & s)
|
|||
|
||||
namespace
|
||||
{
|
||||
template<typename T, typename ET>
|
||||
bool IntegerCheck(T x, char const *stop, ET & out)
|
||||
template <typename T, typename TResult>
|
||||
bool IntegerCheck(char const * start, char const * stop, T x, TResult & out)
|
||||
{
|
||||
if (*stop == 0)
|
||||
if (errno != EINVAL && *stop == 0)
|
||||
{
|
||||
out = static_cast<ET>(x);
|
||||
ASSERT_EQUAL(static_cast<T>(out), x, ());
|
||||
return true;
|
||||
out = static_cast<TResult>(x);
|
||||
return static_cast<T>(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);
|
||||
}
|
||||
|
||||
|
||||
|
|
Loading…
Add table
Reference in a new issue