From 02f4420399a388f4c7cca0e9ab87ecf8e4286e08 Mon Sep 17 00:00:00 2001 From: Dan Goodliffe Date: Fri, 9 Dec 2016 16:28:48 +0000 Subject: Provide a way of formatting a literal percent sign --- libadhocutil/compileTimeFormatter.h | 11 +++++++ .../unittests/testCompileTimeFormatter.cpp | 34 +++++++++++++++++++++- 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/libadhocutil/compileTimeFormatter.h b/libadhocutil/compileTimeFormatter.h index d9349dc..e17270a 100644 --- a/libadhocutil/compileTimeFormatter.h +++ b/libadhocutil/compileTimeFormatter.h @@ -80,6 +80,17 @@ namespace AdHoc { } }; + // Escaped % stream writer formatter + template + struct StreamWriter { + template + static void write(stream & s, const Pn & ... pn) + { + s << '%'; + StreamWriter::write(s, pn...); + } + }; + // Unknown stream writer formatter template struct StreamWriter { diff --git a/libadhocutil/unittests/testCompileTimeFormatter.cpp b/libadhocutil/unittests/testCompileTimeFormatter.cpp index ffb528b..b3e3dac 100644 --- a/libadhocutil/unittests/testCompileTimeFormatter.cpp +++ b/libadhocutil/unittests/testCompileTimeFormatter.cpp @@ -16,6 +16,10 @@ extern constexpr const char * formatEdgeCaseFormatLonely = "%?"; extern constexpr const char * formatStringLiteral = "literal"; extern constexpr const char * formatStringSingle = "single %?."; extern constexpr const char * formatStringMulti = "First %?, then %?."; +extern constexpr const char * formatStringEscape1 = "literal %% percentage."; +extern constexpr const char * formatStringEscape2 = "literal %%? percentage."; +extern constexpr const char * formatStringEscape3 = "literal %%%? percentage."; +extern constexpr const char * formatStringEscape4 = "literal %%%?%% percentage."; BOOST_AUTO_TEST_CASE ( empty ) { @@ -84,10 +88,38 @@ BOOST_AUTO_TEST_CASE ( singlePath ) BOOST_AUTO_TEST_CASE ( multi ) { std::stringstream buf; - Formatter::write(buf, "one", "two"); + Formatter::write(buf, "one", "two"); BOOST_REQUIRE_EQUAL(buf.str(), "First one, then two."); } +BOOST_AUTO_TEST_CASE ( escape1 ) +{ + std::stringstream buf; + Formatter::write(buf); + BOOST_REQUIRE_EQUAL(buf.str(), "literal % percentage."); +} + +BOOST_AUTO_TEST_CASE ( escape2 ) +{ + std::stringstream buf; + Formatter::write(buf); + BOOST_REQUIRE_EQUAL(buf.str(), "literal %? percentage."); +} + +BOOST_AUTO_TEST_CASE ( escape3 ) +{ + std::stringstream buf; + Formatter::write(buf, 3); + BOOST_REQUIRE_EQUAL(buf.str(), "literal %3 percentage."); +} + +BOOST_AUTO_TEST_CASE ( escape4 ) +{ + std::stringstream buf; + Formatter::write(buf, 3); + BOOST_REQUIRE_EQUAL(buf.str(), "literal %3% percentage."); +} + namespace AdHoc { // Custom stream writer formatter, formats as (bracketed expression) template -- cgit v1.2.3