From 2b6dfe07cd1692ebe9fe7fe3ae924567ff5b417f Mon Sep 17 00:00:00 2001 From: Dan Goodliffe Date: Sun, 17 Jun 2018 18:11:09 +0100 Subject: Any stream type with CTF Minor alteration to allow for custom helpers. Then a unit test to demonstrate that with suitable helpers, a CTF can operate on any stream type, such as a stdio FILE. --- libadhocutil/compileTimeFormatter.h | 8 ++++++- .../unittests/testCompileTimeFormatter.cpp | 28 ++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/libadhocutil/compileTimeFormatter.h b/libadhocutil/compileTimeFormatter.h index f409b1c..fecbd91 100644 --- a/libadhocutil/compileTimeFormatter.h +++ b/libadhocutil/compileTimeFormatter.h @@ -89,6 +89,12 @@ namespace AdHoc { } }; + template + static inline void appendStream(stream & s, const char_type * p, size_t n) + { + s.write(p, n); + } + /** * Compile time string formatter. * @param S the format string. @@ -133,7 +139,7 @@ namespace AdHoc { if (pos != L) { constexpr auto ph = strchrnul(); if constexpr (ph != pos) { - s.write((S + pos), ph - pos); + appendStream(s, (S + pos), ph - pos); } if constexpr (ph != L) { packAndWrite(s, pn...); diff --git a/libadhocutil/unittests/testCompileTimeFormatter.cpp b/libadhocutil/unittests/testCompileTimeFormatter.cpp index 9d01a80..a04b92e 100644 --- a/libadhocutil/unittests/testCompileTimeFormatter.cpp +++ b/libadhocutil/unittests/testCompileTimeFormatter.cpp @@ -280,3 +280,31 @@ BOOST_AUTO_TEST_CASE( lorem_ipsum ) BOOST_CHECK_EQUAL_COLLECTIONS(s.begin(), s.end(), sv.begin(), sv.end()); } +namespace AdHoc { + template<> + inline void appendStream(FILE & strm, const char * const p, size_t n) + { + BOOST_VERIFY(fwrite(p, n, 1, &strm) == 1); + } +} + +FILE & +operator<<(FILE & strm, const char * const p) +{ + BOOST_VERIFY(fputs(p, &strm) != EOF); + return strm; +} + +BOOST_AUTO_TEST_CASE( filestar ) +{ + char * buf = NULL; + size_t len = 0; + FILE * strm = open_memstream(&buf, &len); + BOOST_REQUIRE(strm); + Formatter::write(*strm, "file", "star"); + fclose(strm); + BOOST_CHECK_EQUAL(len, 22); + BOOST_CHECK_EQUAL(buf, "First file, then star."); + free(buf); +} + -- cgit v1.2.3