From bab3f580037594e9cfb8a6658c7166b0a082e812 Mon Sep 17 00:00:00 2001 From: Victor Zverovich Date: Sun, 3 May 2020 20:33:25 -0700 Subject: [PATCH] Refactor pointer formatting --- include/fmt/format.h | 27 ++++++++++++++++----------- test/format-impl-test.cc | 10 +++++----- 2 files changed, 21 insertions(+), 16 deletions(-) diff --git a/include/fmt/format.h b/include/fmt/format.h index 6da2bfba..cef92bcb 100644 --- a/include/fmt/format.h +++ b/include/fmt/format.h @@ -1577,6 +1577,21 @@ template struct int_writer { } }; +template +OutputIt write_ptr(OutputIt out, UIntPtr value, + const basic_format_specs* specs) { + int num_digits = count_digits<4>(value); + auto size = to_unsigned(num_digits) + size_t(2); + using iterator = remove_reference_t; + auto write = [=](iterator it) { + *it++ = static_cast('0'); + *it++ = static_cast('x'); + return format_uint<4, Char>(it, value, num_digits); + }; + return specs ? write_padded(out, *specs, size, write) + : base_iterator(out, write(reserve(out, size))); +} + // This template provides operations for formatting and writing data into a // character range. template class basic_writer { @@ -1742,17 +1757,7 @@ template class basic_writer { template void write_pointer(UIntPtr value, const format_specs* specs) { - int num_digits = count_digits<4>(value); - auto size = to_unsigned(num_digits) + size_t(2); - auto write = [=](reserve_iterator it) { - *it++ = static_cast('0'); - *it++ = static_cast('x'); - return format_uint<4, char_type>(it, value, num_digits); - }; - if (!specs) return void(write(reserve(size))); - format_specs specs_copy = *specs; - if (specs_copy.align == align::none) specs_copy.align = align::right; - out_ = write_padded(out_, specs_copy, size, write); + out_ = write_ptr(out_, value, specs); } }; diff --git a/test/format-impl-test.cc b/test/format-impl-test.cc index 21e91014..e40ad907 100644 --- a/test/format-impl-test.cc +++ b/test/format-impl-test.cc @@ -450,11 +450,11 @@ TEST(UtilTest, CountDigits) { test_count_digits(); } -TEST(UtilTest, WriteUIntPtr) { - fmt::memory_buffer buf; - fmt::internal::writer writer(buf); - writer.write_pointer( +TEST(UtilTest, WriteFallbackUIntPtr) { + std::string s; + fmt::internal::write_ptr( + std::back_inserter(s), fmt::internal::fallback_uintptr(reinterpret_cast(0xface)), nullptr); - EXPECT_EQ("0xface", to_string(buf)); + EXPECT_EQ(s, "0xface"); }