From c5569265973805166b220b3218e4fd11e474d619 Mon Sep 17 00:00:00 2001 From: Victor Zverovich Date: Fri, 20 Jun 2014 07:59:23 -0700 Subject: [PATCH] Implement precision + fill. --- format.h | 25 ++++++++++++++++++------- test/printf-test.cc | 14 +++++++++++++- 2 files changed, 31 insertions(+), 8 deletions(-) diff --git a/format.h b/format.h index 88120bdb..654f0f06 100644 --- a/format.h +++ b/format.h @@ -1306,16 +1306,27 @@ typename BasicWriter::CharPtr BasicWriter::FormatString( template template typename fmt::BasicWriter::CharPtr -fmt::BasicWriter::PrepareFilledBuffer(unsigned num_digits, - const Spec &spec, const char *prefix, unsigned prefix_size) { - if (spec.precision() >= 0) { - // TODO: fill up to width if necessary + fmt::BasicWriter::PrepareFilledBuffer( + unsigned num_digits, const Spec &spec, + const char *prefix, unsigned prefix_size) { + unsigned width = spec.width(); + if (spec.precision() > static_cast(num_digits)) { + // Octal prefix '0' is counted as a digit, so ignore it if precision + // is specified. + if (prefix_size == 1) + prefix_size = 0; + unsigned number_size = prefix_size + spec.precision(); + if (number_size < width) { + buffer_.reserve(width); + unsigned size = width - number_size; + CharPtr p = GrowBuffer(size); + std::fill(p, p + size, spec.fill()); + // TODO: take alignment into account + } return PrepareFilledBuffer(num_digits, - AlignSpec(spec.precision() + prefix_size, '0', ALIGN_NUMERIC), - prefix, prefix_size); + AlignSpec(number_size, '0', ALIGN_NUMERIC), prefix, prefix_size); } unsigned size = prefix_size + num_digits; - unsigned width = spec.width(); if (width <= size) { CharPtr p = GrowBuffer(size); std::copy(prefix, prefix + prefix_size, p); diff --git a/test/printf-test.cc b/test/printf-test.cc index 8655af98..4ae45964 100644 --- a/test/printf-test.cc +++ b/test/printf-test.cc @@ -229,8 +229,20 @@ TEST(PrintfTest, DynamicWidth) { TEST(PrintfTest, Precision) { EXPECT_PRINTF("00042", "%.5d", 42); + EXPECT_PRINTF("00042", "%.5x", 0x42); + EXPECT_PRINTF("0x00042", "%#.5x", 0x42); + EXPECT_PRINTF("00042", "%.5o", 042); + EXPECT_PRINTF("00042", "%#.5o", 042); + + EXPECT_PRINTF(" 00042", "%7.5d", 42); + EXPECT_PRINTF(" 00042", "%7.5x", 0x42); + EXPECT_PRINTF(" 0x00042", "%#10.5x", 0x42); + EXPECT_PRINTF(" 00042", "%7.5o", 042); + EXPECT_PRINTF(" 00042", "%#10.5o", 042); + + // TODO: test left alignment } -// TODO: test precision, length and type specifier +// TODO: test length and type specifier #endif