From 86574285ccf756417c2ce0e765c35e71c03cd5f0 Mon Sep 17 00:00:00 2001 From: Victor Zverovich Date: Thu, 20 Feb 2014 21:05:46 -0800 Subject: [PATCH] Don't use CountDigits for 1-2 digit numbers. --- format-test.cc | 2 ++ format.h | 12 +++++++++++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/format-test.cc b/format-test.cc index b44e4946..e5ee65c9 100644 --- a/format-test.cc +++ b/format-test.cc @@ -1459,6 +1459,8 @@ TEST(FormatIntTest, FormatDec) { std::ostringstream os; os << std::numeric_limits::max(); EXPECT_EQ(os.str(), FormatDec(std::numeric_limits::max())); + EXPECT_EQ("1", FormatDec(1)); + EXPECT_EQ("-1", FormatDec(-1)); EXPECT_EQ("42", FormatDec(42)); EXPECT_EQ("-42", FormatDec(-42)); EXPECT_EQ("42", FormatDec(42l)); diff --git a/format.h b/format.h index 1541417a..c4b91bc4 100644 --- a/format.h +++ b/format.h @@ -301,7 +301,7 @@ class FormatterProxy; // Formats a decimal unsigned integer value writing into buffer. template void FormatDecimal(Char *buffer, UInt value, unsigned num_digits) { - --num_digits; + --num_digits; while (value >= 100) { // Integer division is slow so do it for a group of two digits instead // of for every digit. The idea comes from the talk by Alexandrescu @@ -1407,6 +1407,16 @@ inline void FormatDec(char *&buffer, T value) { *buffer++ = '-'; abs_value = 0 - abs_value; } + if (abs_value < 100) { + if (abs_value < 10) { + *buffer++ = static_cast('0' + abs_value); + return; + } + unsigned index = static_cast(abs_value * 2); + *buffer++ = internal::DIGITS[index]; + *buffer++ = internal::DIGITS[index + 1]; + return; + } unsigned num_digits = internal::CountDigits(abs_value); internal::FormatDecimal(buffer, abs_value, num_digits); buffer += num_digits;