Commit 5872c80b authored by Branislav Katreniak's avatar Branislav Katreniak

kj/string: parse 0x prefixed integers in base 16, add documentation

parent 1f25659c
......@@ -102,6 +102,13 @@ TEST(String, parseAs) {
KJ_EXPECT_THROW_MESSAGE("not contain valid", StringPtr("a").parseAs<int64_t>());
KJ_EXPECT_THROW_MESSAGE("not contain valid", StringPtr("1a").parseAs<int64_t>());
KJ_EXPECT_THROW_MESSAGE("not contain valid", StringPtr("+-1").parseAs<int64_t>());
EXPECT_EQ(StringPtr("010").parseAs<int64_t>(), 10);
EXPECT_EQ(StringPtr("0010").parseAs<int64_t>(), 10);
EXPECT_EQ(StringPtr("0x10").parseAs<int64_t>(), 16);
EXPECT_EQ(StringPtr("0X10").parseAs<int64_t>(), 16);
EXPECT_EQ(StringPtr("-010").parseAs<int64_t>(), -10);
EXPECT_EQ(StringPtr("-0x10").parseAs<int64_t>(), -16);
EXPECT_EQ(StringPtr("-0X10").parseAs<int64_t>(), -16);
EXPECT_EQ(StringPtr("1").parseAs<uint64_t>(), 1);
EXPECT_EQ(StringPtr("0").parseAs<uint64_t>(), 0);
......
......@@ -34,12 +34,16 @@ namespace kj {
#endif
namespace {
bool isHex(const char *s) {
if (*s == '-') s++;
return s[0] == '0' && (s[1] == 'x' || s[1] == 'X');
}
long long parseSigned(const StringPtr& s, long long min, long long max) {
KJ_REQUIRE(s != nullptr, "String does not contain valid number", s);
char *endPtr;
errno = 0;
auto value = strtoll(s.begin(), &endPtr, 10);
auto value = strtoll(s.begin(), &endPtr, isHex(s.cStr()) ? 16 : 10);
KJ_REQUIRE(endPtr == s.end(), "String does not contain valid number", s);
KJ_REQUIRE(errno != ERANGE, "Value out-of-range", s);
KJ_REQUIRE(value >= min && value <= max, "Value out-of-range", value, min, max);
......@@ -50,7 +54,7 @@ unsigned long long parseUnsigned(const StringPtr& s, unsigned long long max) {
KJ_REQUIRE(s != nullptr, "String does not contain valid number", s);
char *endPtr;
errno = 0;
auto value = strtoull(s.begin(), &endPtr, 10);
auto value = strtoull(s.begin(), &endPtr, isHex(s.cStr()) ? 16 : 10);
KJ_REQUIRE(endPtr == s.end(), "String does not contain valid number", s);
KJ_REQUIRE(errno != ERANGE, "Value out-of-range", s);
KJ_REQUIRE(value <= max, "Value out-of-range", value, max);
......
......@@ -114,6 +114,11 @@ public:
template <typename T>
T parseAs() const;
// Parse string as template number type.
// Integer numbers prefixed by "0x" and "0X" are parsed in base 16 (like strtoi with base 0).
// Integer numbers prefixed by "0" are parsed in base 10 (unlike strtoi with base 0).
// Overflowed integer numbers throw exception.
// Overflowed floating numbers return inf.
private:
inline StringPtr(ArrayPtr<const char> content): content(content) {}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment