From b5fda1c90d94aeaf96081477c9bfe13789c00e03 Mon Sep 17 00:00:00 2001 From: vitaut Date: Wed, 11 Nov 2015 07:57:19 -0800 Subject: [PATCH] Format null pointer as (nil) and null string as (null) in printf (#226) --- format.cc | 14 ++++++++++++++ test/printf-test.cc | 4 ++++ 2 files changed, 18 insertions(+) diff --git a/format.cc b/format.cc index 2168ce6f..336d91b9 100644 --- a/format.cc +++ b/format.cc @@ -540,6 +540,20 @@ class PrintfArgFormatter : *out = static_cast(value); } + void visit_cstring(const char *value) { + if (value) + BasicArgFormatter, Char>::visit_cstring(value); + else + this->writer() << "(null)"; + } + + void visit_pointer(const void *value) { + if (value) + BasicArgFormatter, Char>::visit_pointer(value); + else + this->writer() << "(nil)"; + } + void visit_custom(Arg::CustomValue c) { BasicFormatter formatter(ArgList(), this->writer()); const Char format_str[] = {'}', 0}; diff --git a/test/printf-test.cc b/test/printf-test.cc index 8f8647f0..f4faaf1c 100644 --- a/test/printf-test.cc +++ b/test/printf-test.cc @@ -418,6 +418,8 @@ TEST(PrintfTest, Char) { TEST(PrintfTest, String) { EXPECT_PRINTF("abc", "%s", "abc"); + const char *null_str = 0; + EXPECT_PRINTF("(null)", "%s", null_str); // TODO: wide string } @@ -425,6 +427,8 @@ TEST(PrintfTest, Pointer) { int n; void *p = &n; EXPECT_PRINTF(fmt::format("{}", p), "%p", p); + p = 0; + EXPECT_PRINTF("(nil)", "%p", p); const char *s = "test"; EXPECT_PRINTF(fmt::format("{:p}", s), "%p", s); }