Fix two ParseInt edge cases
1) ParseInt and ParseUint accept strings that have spaces followed by
a valid number, however the base check for determining hex numbers
does not take this into account currently, but now does this this
change.
2) ParseUint rejects negative numbers except in the case that the
template argument is unsigned long long. That is a mistake; it
should reject negative numbers in all cases and this change does
that by rejecting any string with a - prefix.
Bug: 112668205
Test: new (and old) unit tests
Change-Id: I0179b42e50adc1b169cf0e6d830283b71210a029
diff --git a/parseint_test.cpp b/parseint_test.cpp
index 8f9ed77..4afa32e 100644
--- a/parseint_test.cpp
+++ b/parseint_test.cpp
@@ -25,8 +25,14 @@
ASSERT_TRUE(android::base::ParseInt("123", &i));
ASSERT_EQ(123, i);
+ i = 0;
+ EXPECT_TRUE(android::base::ParseInt(" 123", &i));
+ EXPECT_EQ(123, i);
ASSERT_TRUE(android::base::ParseInt("-123", &i));
ASSERT_EQ(-123, i);
+ i = 0;
+ EXPECT_TRUE(android::base::ParseInt(" -123", &i));
+ EXPECT_EQ(-123, i);
short s = 0;
ASSERT_TRUE(android::base::ParseInt("1234", &s));
@@ -49,7 +55,11 @@
ASSERT_TRUE(android::base::ParseUint("123", &i));
ASSERT_EQ(123u, i);
+ i = 0u;
+ EXPECT_TRUE(android::base::ParseUint(" 123", &i));
+ EXPECT_EQ(123u, i);
ASSERT_FALSE(android::base::ParseUint("-123", &i));
+ EXPECT_FALSE(android::base::ParseUint(" -123", &i));
unsigned short s = 0u;
ASSERT_TRUE(android::base::ParseUint("1234", &s));
@@ -63,6 +73,10 @@
ASSERT_FALSE(android::base::ParseUint<unsigned short>("x", nullptr));
ASSERT_FALSE(android::base::ParseUint<unsigned short>("123x", nullptr));
ASSERT_TRUE(android::base::ParseUint<unsigned short>("1234", nullptr));
+
+ unsigned long long int lli;
+ EXPECT_FALSE(android::base::ParseUint("-123", &lli));
+ EXPECT_FALSE(android::base::ParseUint(" -123", &lli));
}
TEST(parseint, no_implicit_octal) {
@@ -79,10 +93,16 @@
int i = 0;
ASSERT_TRUE(android::base::ParseInt("0x123", &i));
ASSERT_EQ(0x123, i);
+ i = 0;
+ EXPECT_TRUE(android::base::ParseInt(" 0x123", &i));
+ EXPECT_EQ(0x123, i);
unsigned int u = 0u;
ASSERT_TRUE(android::base::ParseUint("0x123", &u));
ASSERT_EQ(0x123u, u);
+ u = 0u;
+ EXPECT_TRUE(android::base::ParseUint(" 0x123", &u));
+ EXPECT_EQ(0x123u, u);
}
TEST(parseint, string) {