From d473a79581f8b1b6248771fbe4f2c83e249d3336 Mon Sep 17 00:00:00 2001 From: Victor Zverovich Date: Thu, 13 Feb 2014 09:59:49 -0800 Subject: [PATCH] Add FormatInt::size, and support for long and long long. --- format-test.cc | 6 ++++++ format.h | 15 +++++++++------ 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/format-test.cc b/format-test.cc index 3f867f0e..9142c75b 100644 --- a/format-test.cc +++ b/format-test.cc @@ -1410,7 +1410,13 @@ TEST(FormatterTest, Examples) { TEST(FormatIntTest, FormatInt) { EXPECT_EQ("42", fmt::FormatInt(42).str()); + EXPECT_EQ(2, fmt::FormatInt(42).size()); EXPECT_EQ("-42", fmt::FormatInt(-42).str()); + EXPECT_EQ(3, fmt::FormatInt(-42).size()); + EXPECT_EQ("42", fmt::FormatInt(42ul).str()); + EXPECT_EQ("-42", fmt::FormatInt(-42l).str()); + EXPECT_EQ("42", fmt::FormatInt(42ull).str()); + EXPECT_EQ("-42", fmt::FormatInt(-42ll).str()); std::ostringstream os; os << std::numeric_limits::max(); EXPECT_EQ(os.str(), fmt::FormatInt(std::numeric_limits::max()).str()); diff --git a/format.h b/format.h index eb7b5c8e..038901a6 100644 --- a/format.h +++ b/format.h @@ -1266,12 +1266,12 @@ class FormatInt { private: // Buffer should be large enough to hold all digits (digits10 + 1), // a sign and a null character. - enum {BUFFER_SIZE = std::numeric_limits::digits10 + 3}; + enum {BUFFER_SIZE = std::numeric_limits::digits10 + 3}; char buffer_[BUFFER_SIZE]; char *str_; // Formats value in reverse and returns the number of digits. - char *FormatDecimal(uint64_t value) { + char *FormatDecimal(unsigned long long value) { char *buffer_end = buffer_ + BUFFER_SIZE; *--buffer_end = '\0'; while (value >= 100) { @@ -1293,8 +1293,8 @@ class FormatInt { return buffer_end; } - void FormatSigned(int64_t value) { - uint64_t abs_value = value; + void FormatSigned(long long value) { + unsigned long long abs_value = value; bool negative = value < 0; if (negative) abs_value = 0 - value; @@ -1305,12 +1305,15 @@ class FormatInt { public: explicit FormatInt(int value) { FormatSigned(value); } - explicit FormatInt(int64_t value) { FormatSigned(value); } + explicit FormatInt(long value) { FormatSigned(value); } + explicit FormatInt(long long value) { FormatSigned(value); } explicit FormatInt(unsigned value) : str_(FormatDecimal(value)) {} - explicit FormatInt(uint64_t value) : str_(FormatDecimal(value)) {} + explicit FormatInt(unsigned long value) : str_(FormatDecimal(value)) {} + explicit FormatInt(unsigned long long value) : str_(FormatDecimal(value)) {} const char *c_str() const { return str_; } std::string str() const { return str_; } + std::size_t size() const { return buffer_ - str_ + BUFFER_SIZE - 1; } }; /**