From b18f6ba23788f687b7c748fa4b8a3dc87875212c Mon Sep 17 00:00:00 2001 From: Scott Lamb Date: Sat, 16 Jan 2016 17:59:39 -0800 Subject: [PATCH] Add a simple Atoi64. This will be useful in parsing numeric HTTP params. --- src/string-test.cc | 10 ++++++++++ src/string.cc | 8 ++++++++ src/string.h | 7 +++++-- 3 files changed, 23 insertions(+), 2 deletions(-) diff --git a/src/string-test.cc b/src/string-test.cc index 40611ca..a781ed9 100644 --- a/src/string-test.cc +++ b/src/string-test.cc @@ -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 diff --git a/src/string.cc b/src/string.cc index 999a0c4..b468084 100644 --- a/src/string.cc +++ b/src/string.cc @@ -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(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 diff --git a/src/string.h b/src/string.h index fffd0e8..aa24423 100644 --- a/src/string.h +++ b/src/string.h @@ -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