Add a simple Atoi64.

This will be useful in parsing numeric HTTP params.
This commit is contained in:
Scott Lamb 2016-01-16 17:59:39 -08:00
parent 442b953f28
commit b18f6ba237
3 changed files with 23 additions and 2 deletions

View File

@ -112,6 +112,16 @@ TEST(HumanizeTest, Simple) {
EXPECT_EQ("1000.0 Ebps", HumanizeWithDecimalPrefix(1e21, "bps"));
}
TEST(AtoiTest, Simple) {
int64_t out;
EXPECT_TRUE(Atoi64("1234", 10, &out));
EXPECT_EQ(1234, out);
EXPECT_FALSE(Atoi64(nullptr, 10, &out));
EXPECT_FALSE(Atoi64("", 10, &out));
EXPECT_FALSE(Atoi64("asdf", 10, &out));
EXPECT_FALSE(Atoi64("1234asdf", 10, &out));
}
} // namespace
} // namespace moonfire_nvr

View File

@ -148,9 +148,17 @@ std::string HumanizeWithBinaryPrefix(float n, re2::StringPiece suffix) {
bool strto64(const char *str, int base, const char **endptr, int64_t *value) {
static_assert(sizeof(int64_t) == sizeof(long long int),
"unknown memory model");
if (str == nullptr) {
return false;
}
errno = 0;
*value = ::strtoll(str, const_cast<char **>(endptr), base);
return *endptr != str && errno == 0;
}
bool Atoi64(const char *str, int base, int64_t *value) {
const char *endptr;
return strto64(str, base, &endptr, value) && *endptr == '\0';
}
} // namespace moonfire_nvr

View File

@ -127,10 +127,13 @@ std::string ToHex(re2::StringPiece in, bool pad = false);
std::string HumanizeWithDecimalPrefix(float n, re2::StringPiece suffix);
std::string HumanizeWithBinaryPrefix(float n, re2::StringPiece suffix);
// Wrapper around ::strtol that returns true iff valid and corrects
// constness.
// Wrapper around ::strtoll that returns true iff valid and corrects
// constness. Returns false if |str| is null.
bool strto64(const char *str, int base, const char **endptr, int64_t *value);
// Simpler form that expects the entire string to be a single integer.
bool Atoi64(const char *str, int base, int64_t *value);
} // namespace moonfire_nvr
#endif // MOONFIRE_NVR_STRING_H