summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDan Goodliffe <dan@randomdan.homeip.net>2018-06-17 18:11:09 +0100
committerDan Goodliffe <dan@randomdan.homeip.net>2018-06-17 18:11:09 +0100
commit2b6dfe07cd1692ebe9fe7fe3ae924567ff5b417f (patch)
treee5544756250bef4761f22093573e1e0b74985897
parentCreate a typedef for the formatters char type (diff)
downloadlibadhocutil-2b6dfe07cd1692ebe9fe7fe3ae924567ff5b417f.tar.bz2
libadhocutil-2b6dfe07cd1692ebe9fe7fe3ae924567ff5b417f.tar.xz
libadhocutil-2b6dfe07cd1692ebe9fe7fe3ae924567ff5b417f.zip
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.
-rw-r--r--libadhocutil/compileTimeFormatter.h8
-rw-r--r--libadhocutil/unittests/testCompileTimeFormatter.cpp28
2 files changed, 35 insertions, 1 deletions
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<typename stream, typename char_type>
+ 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<S, '%', pos, L>();
if constexpr (ph != pos) {
- s.write((S + pos), ph - pos);
+ appendStream(s, (S + pos), ph - pos);
}
if constexpr (ph != L) {
packAndWrite<ph>(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<formatStringMulti>::write(*strm, "file", "star");
+ fclose(strm);
+ BOOST_CHECK_EQUAL(len, 22);
+ BOOST_CHECK_EQUAL(buf, "First file, then star.");
+ free(buf);
+}
+