From 6504434262ec98c603f4ba25ed86d6a5a3a1b96a Mon Sep 17 00:00:00 2001 From: Dan Goodliffe Date: Sun, 31 May 2020 16:40:20 +0100 Subject: Clang-format --- libadhocutil/buffer.cpp | 485 ++++++++++----------- libadhocutil/buffer.h | 95 ++-- libadhocutil/c++11Helpers.h | 1 - libadhocutil/cache.h | 60 ++- libadhocutil/cache.impl.h | 293 ++++++------- libadhocutil/compileTimeFormatter.h | 326 +++++++------- libadhocutil/ctf-impl/printf-compat.h | 98 +++-- libadhocutil/curlHandle.cpp | 215 +++++---- libadhocutil/curlHandle.h | 114 +++-- libadhocutil/curlMultiHandle.cpp | 125 +++--- libadhocutil/curlMultiHandle.h | 57 ++- libadhocutil/curlStream.cpp | 84 ++-- libadhocutil/curlStream.h | 72 +-- libadhocutil/definedDirs.h | 3 +- libadhocutil/exception.h | 38 +- libadhocutil/factory.h | 69 ++- libadhocutil/factory.impl.h | 7 +- libadhocutil/fileUtils.cpp | 42 +- libadhocutil/fileUtils.h | 287 ++++++------ libadhocutil/fprintbf.cpp | 1 - libadhocutil/fprintbf.h | 10 +- libadhocutil/globalStatic.h | 26 +- libadhocutil/globalStatic.impl.h | 13 +- libadhocutil/handle.h | 144 +++--- libadhocutil/lazyPointer.h | 80 ++-- libadhocutil/lexer-regex.cpp | 111 +++-- libadhocutil/lexer-regex.h | 4 +- libadhocutil/lexer.cpp | 5 +- libadhocutil/lexer.h | 145 +++--- libadhocutil/lockHelpers.h | 9 +- libadhocutil/memstream.cpp | 31 +- libadhocutil/memstream.h | 73 ++-- libadhocutil/nagios.cpp | 11 +- libadhocutil/nagios.h | 9 +- libadhocutil/nvpParse.h | 87 ++-- libadhocutil/optionalUtils.h | 20 +- libadhocutil/plugins.cpp | 60 ++- libadhocutil/plugins.h | 361 +++++++-------- libadhocutil/plugins.impl.h | 50 ++- libadhocutil/processPipes.cpp | 234 +++++----- libadhocutil/processPipes.h | 101 +++-- libadhocutil/resourcePool.cpp | 12 +- libadhocutil/resourcePool.h | 228 +++++----- libadhocutil/resourcePool.impl.h | 82 ++-- libadhocutil/runtimeContext.cpp | 64 ++- libadhocutil/runtimeContext.h | 77 ++-- libadhocutil/safeMapFind.h | 92 ++-- libadhocutil/scopeExit.cpp | 60 +-- libadhocutil/scopeExit.h | 14 +- libadhocutil/semaphore.cpp | 5 +- libadhocutil/semaphore.h | 35 +- libadhocutil/sysImpl.cpp | 8 +- libadhocutil/unique.h | 1 - libadhocutil/unittests/testBuffer.cpp | 27 +- libadhocutil/unittests/testCache.cpp | 56 ++- .../unittests/testCompileTimeFormatter.cpp | 101 +++-- libadhocutil/unittests/testContext.cpp | 43 +- libadhocutil/unittests/testCurl.cpp | 42 +- libadhocutil/unittests/testDirs.cpp | 3 +- libadhocutil/unittests/testException.cpp | 80 ++-- libadhocutil/unittests/testFactory.cpp | 50 +-- libadhocutil/unittests/testFileUtils.cpp | 76 ++-- libadhocutil/unittests/testFprintbf.cpp | 17 +- libadhocutil/unittests/testHandle.cpp | 9 +- libadhocutil/unittests/testLazyPointer.cpp | 50 ++- libadhocutil/unittests/testLexer.cpp | 101 ++--- libadhocutil/unittests/testLocks.cpp | 9 +- libadhocutil/unittests/testMapFinds.cpp | 28 +- libadhocutil/unittests/testMemStream.cpp | 7 +- libadhocutil/unittests/testNagios.cpp | 3 +- libadhocutil/unittests/testNvpParse.cpp | 27 +- libadhocutil/unittests/testOptionals.cpp | 11 +- libadhocutil/unittests/testPlugins.cpp | 28 +- libadhocutil/unittests/testPluginsRuntime.cpp | 15 +- libadhocutil/unittests/testProcessPipes.cpp | 13 +- libadhocutil/unittests/testResourcePool.cpp | 150 ++++--- libadhocutil/unittests/testScopeExit.cpp | 49 ++- libadhocutil/unittests/testSemaphore.cpp | 18 +- libadhocutil/unittests/testUriParse.cpp | 37 +- libadhocutil/unittests/utilTestClasses.cpp | 1 - libadhocutil/unittests/utilTestClasses.h | 1 - libadhocutil/uriParse.cpp | 29 +- libadhocutil/uriParse.h | 65 ++- libadhocutil/visibility.h | 5 +- 84 files changed, 2934 insertions(+), 2951 deletions(-) diff --git a/libadhocutil/buffer.cpp b/libadhocutil/buffer.cpp index 00c2b45..07a57ea 100644 --- a/libadhocutil/buffer.cpp +++ b/libadhocutil/buffer.cpp @@ -1,315 +1,295 @@ #include "buffer.h" -#include #include +#include namespace AdHoc { -// -// CString Fragment -// + // + // CString Fragment + // -Buffer::CStringFragment::CStringFragment(const char * b, CStringHandling h) : - len(strlen(b)), - buf(b), - handling(h) -{ -} + Buffer::CStringFragment::CStringFragment(const char * b, CStringHandling h) : + len(strlen(b)), buf(b), handling(h) { } -Buffer::CStringFragment::CStringFragment(const char * b, CStringHandling h, size_t l) : - len(l), - buf(b), - handling(h) -{ -} + Buffer::CStringFragment::CStringFragment(const char * b, CStringHandling h, size_t l) : len(l), buf(b), handling(h) + { + } -Buffer::CStringFragment::CStringFragment(char * b, CStringHandling h) : - len(strlen(b)), - buf(b), - handling(h) -{ -} + Buffer::CStringFragment::CStringFragment(char * b, CStringHandling h) : len(strlen(b)), buf(b), handling(h) { } -Buffer::CStringFragment::CStringFragment(char * b, CStringHandling h, size_t l) : - len(l), - buf(b), - handling(h) -{ -} + Buffer::CStringFragment::CStringFragment(char * b, CStringHandling h, size_t l) : len(l), buf(b), handling(h) { } -Buffer::CStringFragment::~CStringFragment() -{ - if (handling != Use) { // Copy or Free - // NOLINTNEXTLINE(hicpp-no-malloc) - free(const_cast(buf)); + Buffer::CStringFragment::~CStringFragment() + { + if (handling != Use) { // Copy or Free + // NOLINTNEXTLINE(hicpp-no-malloc) + free(const_cast(buf)); + } } -} -char -Buffer::CStringFragment::operator[](size_t x) const -{ - return buf[x]; -} + char + Buffer::CStringFragment::operator[](size_t x) const + { + return buf[x]; + } -size_t -Buffer::CStringFragment::length() const -{ - return len; -} + size_t + Buffer::CStringFragment::length() const + { + return len; + } -const char * -Buffer::CStringFragment::c_str() const -{ - return buf; -} + const char * + Buffer::CStringFragment::c_str() const + { + return buf; + } -std::string -Buffer::CStringFragment::str() const -{ - return buf; -} + std::string + Buffer::CStringFragment::str() const + { + return buf; + } -// -// Std::String Fragment -// + // + // Std::String Fragment + // -Buffer::StringFragment::StringFragment(std::string str) : - buf(std::move(str)) -{ -} + Buffer::StringFragment::StringFragment(std::string str) : buf(std::move(str)) { } -size_t -Buffer::StringFragment::length() const -{ - return buf.length(); -} + size_t + Buffer::StringFragment::length() const + { + return buf.length(); + } -const char * -Buffer::StringFragment::c_str() const -{ - return buf.c_str(); -} + const char * + Buffer::StringFragment::c_str() const + { + return buf.c_str(); + } -std::string -Buffer::StringFragment::str() const -{ - return buf; -} + std::string + Buffer::StringFragment::str() const + { + return buf; + } -char -Buffer::StringFragment::operator[](size_t x) const -{ - return buf[x]; -} + char + Buffer::StringFragment::operator[](size_t x) const + { + return buf[x]; + } -// -// Buffer :) -// + // + // Buffer :) + // -Buffer::Buffer(const char * src, CStringHandling h) -{ - append(src, h); -} + Buffer::Buffer(const char * src, CStringHandling h) + { + append(src, h); + } -Buffer::Buffer(char * src, CStringHandling h) -{ - append(src, h); -} + Buffer::Buffer(char * src, CStringHandling h) + { + append(src, h); + } -Buffer::Buffer(const std::string & str) -{ - append(str); -} + Buffer::Buffer(const std::string & str) + { + append(str); + } -Buffer & -Buffer::append(const char * str, CStringHandling h) -{ - if (str && *str) { - if (h == Copy) { - content.push_back(std::make_shared(str)); + Buffer & + Buffer::append(const char * str, CStringHandling h) + { + if (str && *str) { + if (h == Copy) { + content.push_back(std::make_shared(str)); + } + else { + content.push_back(std::make_shared(str, h)); + } } - else { - content.push_back(std::make_shared(str, h)); + return *this; + } + + Buffer & + Buffer::append(char * str, CStringHandling h) + { + if (str && *str) { + if (h == Copy) { + content.push_back(std::make_shared(str)); + } + else { + content.push_back(std::make_shared(str, h)); + } } + return *this; } - return *this; -} -Buffer & -Buffer::append(char * str, CStringHandling h) -{ - if (str && *str) { - if (h == Copy) { + Buffer & + Buffer::append(const std::string & str) + { + if (!str.empty()) { content.push_back(std::make_shared(str)); } - else { - content.push_back(std::make_shared(str, h)); - } + return *this; } - return *this; -} -Buffer & -Buffer::append(const std::string & str) -{ - if (!str.empty()) { - content.push_back(std::make_shared(str)); + Buffer & + Buffer::appendf(const char * fmt, ...) + { + va_list v; + va_start(v, fmt); + vappendf(fmt, v); + va_end(v); + return *this; } - return *this; -} - -Buffer & -Buffer::appendf(const char * fmt, ...) -{ - va_list v; - va_start(v, fmt); - vappendf(fmt, v); - va_end(v); - return *this; -} -Buffer & -Buffer::vappendf(const char * fmt, va_list args) -{ - char * frag; - size_t len = vasprintf(&frag, fmt, args); - if (len > 0) { - content.push_back(std::make_shared(frag, Free, len)); - } - else { - // NOLINTNEXTLINE(hicpp-no-malloc) - free(frag); + Buffer & + Buffer::vappendf(const char * fmt, va_list args) + { + char * frag; + size_t len = vasprintf(&frag, fmt, args); + if (len > 0) { + content.push_back(std::make_shared(frag, Free, len)); + } + else { + // NOLINTNEXTLINE(hicpp-no-malloc) + free(frag); + } + return *this; } - return *this; -} -Buffer & -Buffer::appendbf(boost::format & fmt) -{ - append(fmt.str()); - return *this; -} + Buffer & + Buffer::appendbf(boost::format & fmt) + { + append(fmt.str()); + return *this; + } -Buffer & -Buffer::clear() -{ - content.clear(); - return *this; -} + Buffer & + Buffer::clear() + { + content.clear(); + return *this; + } -boost::format -Buffer::getFormat(const std::string & msgfmt) -{ - return boost::format(msgfmt); -} + boost::format + Buffer::getFormat(const std::string & msgfmt) + { + return boost::format(msgfmt); + } -void -Buffer::writeto(char * buf, size_t bufSize, size_t off) const -{ - auto f = content.begin(); - while (f != content.end() && (*f)->length() < off) { - off -= (*f)->length(); - ++f; - } - while (f != content.end() && bufSize) { - for (size_t c = 0; bufSize && c < (*f)->length(); bufSize--) { - *buf++ = (**f)[c++]; + void + Buffer::writeto(char * buf, size_t bufSize, size_t off) const + { + auto f = content.begin(); + while (f != content.end() && (*f)->length() < off) { + off -= (*f)->length(); + ++f; + } + while (f != content.end() && bufSize) { + for (size_t c = 0; bufSize && c < (*f)->length(); bufSize--) { + *buf++ = (**f)[c++]; + } + ++f; } - ++f; + *buf = '\0'; } - *buf = '\0'; -} -Buffer::operator std::string() const -{ - if (content.size() > 1) { - std::string res; - res.reserve(length()); - for (const auto & f : content) { - res.append(f->str()); + Buffer::operator std::string() const + { + if (content.size() > 1) { + std::string res; + res.reserve(length()); + for (const auto & f : content) { + res.append(f->str()); + } + return res; } - return res; - } - else if (content.size() == 1) { - return std::string(content.front()->str()); + else if (content.size() == 1) { + return std::string(content.front()->str()); + } + return std::string(); } - return std::string(); -} -Buffer::operator const char *() const -{ - if (content.empty()) { - return ""; + Buffer::operator const char *() const + { + if (content.empty()) { + return ""; + } + flatten(); + return content.front()->c_str(); } - flatten(); - return content.front()->c_str(); -} -void -Buffer::flatten() const -{ - if (content.size() > 1) { - content = { std::make_shared(str()) }; + void + Buffer::flatten() const + { + if (content.size() > 1) { + content = {std::make_shared(str())}; + } } -} -std::string -Buffer::str() const -{ - return *this; -} + std::string + Buffer::str() const + { + return *this; + } -size_t -Buffer::length() const -{ - size_t len = 0; - for (const Content::value_type & c : content) { - len += c->length(); + size_t + Buffer::length() const + { + size_t len = 0; + for (const Content::value_type & c : content) { + len += c->length(); + } + return len; } - return len; -} -Buffer & -Buffer::operator=(const char * str) -{ - content = { std::make_shared(str) }; - return *this; -} + Buffer & + Buffer::operator=(const char * str) + { + content = {std::make_shared(str)}; + return *this; + } -Buffer & -Buffer::operator=(const std::string & str) -{ - content = { std::make_shared(str) }; - return *this; -} + Buffer & + Buffer::operator=(const std::string & str) + { + content = {std::make_shared(str)}; + return *this; + } -Buffer::operator bool() const -{ - return !content.empty(); -} + Buffer::operator bool() const + { + return !content.empty(); + } -bool -Buffer::operator!() const -{ - return content.empty(); -} + bool + Buffer::operator!() const + { + return content.empty(); + } -bool -Buffer::empty() const -{ - return content.empty(); -} + bool + Buffer::empty() const + { + return content.empty(); + } -Buffer & -Buffer::operator+=(const char * str) -{ - return append(str); -} + Buffer & + Buffer::operator+=(const char * str) + { + return append(str); + } -Buffer & -Buffer::operator+=(const std::string & str) -{ - return append(str); -} + Buffer & + Buffer::operator+=(const std::string & str) + { + return append(str); + } } @@ -321,4 +301,3 @@ std::operator<<(std::ostream & os, const AdHoc::Buffer & b) } return os; } - diff --git a/libadhocutil/buffer.h b/libadhocutil/buffer.h index 62c8e38..373e799 100644 --- a/libadhocutil/buffer.h +++ b/libadhocutil/buffer.h @@ -1,12 +1,12 @@ #ifndef ADHOCUTIL_BUFFER_H #define ADHOCUTIL_BUFFER_H +#include "c++11Helpers.h" +#include "visibility.h" +#include +#include #include #include -#include -#include -#include "visibility.h" -#include "c++11Helpers.h" namespace AdHoc { class DLL_PUBLIC Buffer; @@ -18,8 +18,8 @@ namespace std { namespace AdHoc { -/// High-speed text buffer for easy creation of programatically created strings. -class DLL_PUBLIC Buffer { + /// High-speed text buffer for easy creation of programatically created strings. + class DLL_PUBLIC Buffer { public: /** How should Buffer handle char * arguments? */ enum CStringHandling { @@ -85,19 +85,21 @@ class DLL_PUBLIC Buffer { /** Append the given std::string to the end of the buffer. */ Buffer & append(const std::string & str); /** Append the given printf style format string and arguments to the buffer. */ - Buffer & appendf(const char * fmt, ...) __attribute__((format (printf, 2, 3))); + Buffer & appendf(const char * fmt, ...) __attribute__((format(printf, 2, 3))); /** Append the given printf style format string and va_list to the buffer. */ Buffer & vappendf(const char * fmt, va_list args); /** Append the given boost::format style format string and arguments to the buffer. */ - template - Buffer & appendbf(const std::string & fmtstr, const Params & ... params) + template + Buffer & + appendbf(const std::string & fmtstr, const Params &... params) { auto bf = getFormat(fmtstr); return appendbf(bf, params...); } /** Append the given boost::format and arguments to the buffer. */ - template - Buffer & appendbf(boost::format & fmt, const Param & param, const Params & ... params) + template + Buffer & + appendbf(boost::format & fmt, const Param & param, const Params &... params) { fmt % param; return appendbf(fmt, params...); @@ -119,54 +121,54 @@ class DLL_PUBLIC Buffer { void DLL_PRIVATE flatten() const; class DLL_PRIVATE FragmentBase { - public: - FragmentBase() = default; - virtual ~FragmentBase() = default; - SPECIAL_MEMBERS_DEFAULT(FragmentBase); - - [[nodiscard]] virtual size_t length() const = 0; - [[nodiscard]] virtual char operator[](size_t) const = 0; - [[nodiscard]] virtual const char * c_str() const = 0; - [[nodiscard]] virtual std::string str() const = 0; + public: + FragmentBase() = default; + virtual ~FragmentBase() = default; + SPECIAL_MEMBERS_DEFAULT(FragmentBase); + + [[nodiscard]] virtual size_t length() const = 0; + [[nodiscard]] virtual char operator[](size_t) const = 0; + [[nodiscard]] virtual const char * c_str() const = 0; + [[nodiscard]] virtual std::string str() const = 0; }; class DLL_PRIVATE CStringFragment : public FragmentBase { - public: - CStringFragment(const char *, CStringHandling); - CStringFragment(const char *, CStringHandling, size_t); - CStringFragment(char *, CStringHandling); - CStringFragment(char *, CStringHandling, size_t); - SPECIAL_MEMBERS_DELETE(CStringFragment); - ~CStringFragment() override; - - [[nodiscard]] size_t length() const override; - [[nodiscard]] char operator[](size_t) const override; - [[nodiscard]] const char * c_str() const override; - [[nodiscard]] std::string str() const override; - - private: - const size_t len; // Excluding NULL term - const char * buf; - const CStringHandling handling; + public: + CStringFragment(const char *, CStringHandling); + CStringFragment(const char *, CStringHandling, size_t); + CStringFragment(char *, CStringHandling); + CStringFragment(char *, CStringHandling, size_t); + SPECIAL_MEMBERS_DELETE(CStringFragment); + ~CStringFragment() override; + + [[nodiscard]] size_t length() const override; + [[nodiscard]] char operator[](size_t) const override; + [[nodiscard]] const char * c_str() const override; + [[nodiscard]] std::string str() const override; + + private: + const size_t len; // Excluding NULL term + const char * buf; + const CStringHandling handling; }; class DLL_PRIVATE StringFragment : public FragmentBase { - public: - explicit StringFragment(std::string); + public: + explicit StringFragment(std::string); - [[nodiscard]] size_t length() const override; - [[nodiscard]] char operator[](size_t) const override; - [[nodiscard]] const char * c_str() const override; - [[nodiscard]] std::string str() const override; + [[nodiscard]] size_t length() const override; + [[nodiscard]] char operator[](size_t) const override; + [[nodiscard]] const char * c_str() const override; + [[nodiscard]] std::string str() const override; - private: - const std::string buf; + private: + const std::string buf; }; using FragmentPtr = std::shared_ptr; using Content = std::vector; mutable Content content; -}; + }; } @@ -176,4 +178,3 @@ class DLL_PUBLIC Buffer { #define stringbf(...) AdHoc::Buffer().appendbf(__VA_ARGS__).str() #endif - diff --git a/libadhocutil/c++11Helpers.h b/libadhocutil/c++11Helpers.h index 9826189..74f0987 100644 --- a/libadhocutil/c++11Helpers.h +++ b/libadhocutil/c++11Helpers.h @@ -31,4 +31,3 @@ SPECIAL_MEMBERS_MOVE(T, default) #endif - diff --git a/libadhocutil/cache.h b/libadhocutil/cache.h index 20ef52e..5f606c2 100644 --- a/libadhocutil/cache.h +++ b/libadhocutil/cache.h @@ -1,22 +1,21 @@ #ifndef ADHOCUTIL_CACHE_H #define ADHOCUTIL_CACHE_H -#include -#include -#include -#include +#include "c++11Helpers.h" +#include "visibility.h" #include #include +#include +#include +#include +#include #include #include -#include "visibility.h" -#include "c++11Helpers.h" namespace AdHoc { -/// @cond -template -class DLL_PUBLIC Cacheable { + /// @cond + template class DLL_PUBLIC Cacheable { public: using Value = const std::shared_ptr; Cacheable(K k, time_t validUntil); @@ -28,10 +27,9 @@ class DLL_PUBLIC Cacheable { const time_t validUntil; [[nodiscard]] virtual Value item() const = 0; -}; + }; -template -class DLL_PUBLIC ObjectCacheable : public Cacheable { + template class DLL_PUBLIC ObjectCacheable : public Cacheable { public: ObjectCacheable(const T & t, const K & k, time_t validUtil); ObjectCacheable(typename Cacheable::Value t, const K & k, time_t validUtil); @@ -40,10 +38,9 @@ class DLL_PUBLIC ObjectCacheable : public Cacheable { private: typename Cacheable::Value value; -}; + }; -template -class DLL_PUBLIC CallCacheable : public Cacheable { + template class DLL_PUBLIC CallCacheable : public Cacheable { public: using Factory = std::function; CallCacheable(const Factory & t, const K & k, time_t validUtil); @@ -53,10 +50,9 @@ class DLL_PUBLIC CallCacheable : public Cacheable { private: mutable std::variant, Factory> value; mutable std::shared_mutex lock; -}; + }; -template -class DLL_PUBLIC PointerCallCacheable : public Cacheable { + template class DLL_PUBLIC PointerCallCacheable : public Cacheable { public: using Factory = std::function::Value()>; PointerCallCacheable(const Factory & t, const K & k, time_t validUtil); @@ -66,15 +62,16 @@ class DLL_PUBLIC PointerCallCacheable : public Cacheable { private: mutable std::variant, Factory> value; mutable std::shared_mutex lock; -}; + }; -struct byValidity {}; -struct byKey {}; -/// @endcond + struct byValidity { + }; + struct byKey { + }; + /// @endcond -/// In-memory cache of T, keyed by K. -template -class DLL_PUBLIC Cache { + /// In-memory cache of T, keyed by K. + template class DLL_PUBLIC Cache { public: /// @cond using Key = K; @@ -140,16 +137,13 @@ class DLL_PUBLIC Cache { mutable std::shared_mutex lock; using Cached = boost::multi_index::multi_index_container, BOOST_MULTI_INDEX_MEMBER(Item, const K, key)>, - boost::multi_index::ordered_non_unique< - boost::multi_index::tag, BOOST_MULTI_INDEX_MEMBER(Item, const time_t, validUntil)> - > >; + boost::multi_index::indexed_by, + BOOST_MULTI_INDEX_MEMBER(Item, const K, key)>, + boost::multi_index::ordered_non_unique, + BOOST_MULTI_INDEX_MEMBER(Item, const time_t, validUntil)>>>; mutable Cached cached; -}; + }; } #endif - diff --git a/libadhocutil/cache.impl.h b/libadhocutil/cache.impl.h index 10c66a3..5200bce 100644 --- a/libadhocutil/cache.impl.h +++ b/libadhocutil/cache.impl.h @@ -2,190 +2,173 @@ #define ADHOCUTIL_CACHE_IMPL_H #include "cache.h" -#include #include "lockHelpers.h" +#include #include namespace AdHoc { -/// @cond -template -Cacheable::Cacheable(K k, time_t vu) : - key(std::move(k)), - validUntil(vu) -{ -} - -template -ObjectCacheable::ObjectCacheable(const T & t, const K & k, time_t vu) : - Cacheable(k, vu), - value(std::make_shared(t)) -{ -} + /// @cond + template Cacheable::Cacheable(K k, time_t vu) : key(std::move(k)), validUntil(vu) { } -template -ObjectCacheable::ObjectCacheable(typename Cacheable::Value t, const K & k, time_t vu) : - Cacheable(k, vu), - value(std::move(t)) -{ -} - -template -typename Cacheable::Value -ObjectCacheable::item() const -{ - return value; -} + template + ObjectCacheable::ObjectCacheable(const T & t, const K & k, time_t vu) : + Cacheable(k, vu), value(std::make_shared(t)) + { + } -template -CallCacheable::CallCacheable(const Factory & t, const K & k, time_t vu) : - Cacheable(k, vu), - value(t) -{ -} + template + ObjectCacheable::ObjectCacheable(typename Cacheable::Value t, const K & k, time_t vu) : + Cacheable(k, vu), value(std::move(t)) + { + } -template -typename Cacheable::Value -CallCacheable::item() const -{ - Lock(lock); - if (auto t = std::get_if<0>(&value)) { - return *t; - } - const Factory & f = std::get(value); - value = std::make_shared(f()); - return std::get<0>(value); -} + template + typename Cacheable::Value + ObjectCacheable::item() const + { + return value; + } + template + CallCacheable::CallCacheable(const Factory & t, const K & k, time_t vu) : Cacheable(k, vu), value(t) + { + } -template -PointerCallCacheable::PointerCallCacheable(const Factory & t, const K & k, time_t vu) : - Cacheable(k, vu), - value(t) -{ -} + template + typename Cacheable::Value + CallCacheable::item() const + { + Lock(lock); + if (auto t = std::get_if<0>(&value)) { + return *t; + } + const Factory & f = std::get(value); + value = std::make_shared(f()); + return std::get<0>(value); + } -template -typename Cacheable::Value -PointerCallCacheable::item() const -{ - Lock(lock); - if (auto t = std::get_if<0>(&value)) { - return *t; - } - const Factory & f = std::get(value); - value = f(); - return std::get<0>(value); -} + template + PointerCallCacheable::PointerCallCacheable(const Factory & t, const K & k, time_t vu) : + Cacheable(k, vu), value(t) + { + } + template + typename Cacheable::Value + PointerCallCacheable::item() const + { + Lock(lock); + if (auto t = std::get_if<0>(&value)) { + return *t; + } + const Factory & f = std::get(value); + value = f(); + return std::get<0>(value); + } -template -Cache::Cache() : - lastPruneTime(time(nullptr)) -{ -} + template Cache::Cache() : lastPruneTime(time(nullptr)) { } -template -void -Cache::add(const K & k, const T & t, time_t validUntil) -{ - Lock(lock); - cached.insert(std::make_shared>(t, k, validUntil)); -} + template + void + Cache::add(const K & k, const T & t, time_t validUntil) + { + Lock(lock); + cached.insert(std::make_shared>(t, k, validUntil)); + } -template -void -Cache::addPointer(const K & k, Value & t, time_t validUntil) -{ - Lock(lock); - cached.insert(std::make_shared>(t, k, validUntil)); -} + template + void + Cache::addPointer(const K & k, Value & t, time_t validUntil) + { + Lock(lock); + cached.insert(std::make_shared>(t, k, validUntil)); + } -template -void -Cache::addFactory(const K & k, const Factory & tf, time_t validUntil) -{ - Lock(lock); - cached.insert(std::make_shared>(tf, k, validUntil)); -} + template + void + Cache::addFactory(const K & k, const Factory & tf, time_t validUntil) + { + Lock(lock); + cached.insert(std::make_shared>(tf, k, validUntil)); + } -template -void -Cache::addPointerFactory(const K & k, const PointerFactory & tf, time_t validUntil) -{ - Lock(lock); - cached.insert(std::make_shared>(tf, k, validUntil)); -} + template + void + Cache::addPointerFactory(const K & k, const PointerFactory & tf, time_t validUntil) + { + Lock(lock); + cached.insert(std::make_shared>(tf, k, validUntil)); + } -template -typename Cache::Element -Cache::getItem(const K & k) const -{ + template + typename Cache::Element + Cache::getItem(const K & k) const { - SharedLock(lock); - auto & collection = cached.template get(); - auto i = collection.find(k); - if (i == collection.end()) { - return Element(); - } - if ((*i)->validUntil > time(nullptr)) { - return (*i); + { + SharedLock(lock); + auto & collection = cached.template get(); + auto i = collection.find(k); + if (i == collection.end()) { + return Element(); + } + if ((*i)->validUntil > time(nullptr)) { + return (*i); + } } + prune(); + return Element(); } - prune(); - return Element(); -} -template -typename Cache::Value -Cache::get(const K & k) const -{ - auto i = getItem(k); - if (i) { - return i->item(); + template + typename Cache::Value + Cache::get(const K & k) const + { + auto i = getItem(k); + if (i) { + return i->item(); + } + return nullptr; } - return nullptr; -} - -template -size_t -Cache::size() const -{ - return cached.size(); -} -template -void -Cache::remove(const K & k) -{ - Lock(lock); - cached.template get().erase(k); -} + template + size_t + Cache::size() const + { + return cached.size(); + } -template -void -Cache::clear() -{ - Lock(lock); - cached.clear(); -} + template + void + Cache::remove(const K & k) + { + Lock(lock); + cached.template get().erase(k); + } -template -void -Cache::prune() const -{ - auto now = time(nullptr); - if (lastPruneTime < now) { + template + void + Cache::clear() + { Lock(lock); - auto & collection = cached.template get(); - auto range = collection.range(boost::multi_index::unbounded, boost::lambda::_1 < now); - collection.erase(range.first, range.second); - lastPruneTime = now; + cached.clear(); } -} -/// @endcond + + template + void + Cache::prune() const + { + auto now = time(nullptr); + if (lastPruneTime < now) { + Lock(lock); + auto & collection = cached.template get(); + auto range = collection.range(boost::multi_index::unbounded, boost::lambda::_1 < now); + collection.erase(range.first, range.second); + lastPruneTime = now; + } + } + /// @endcond } #endif - diff --git a/libadhocutil/compileTimeFormatter.h b/libadhocutil/compileTimeFormatter.h index 5b39167..7e4eef1 100644 --- a/libadhocutil/compileTimeFormatter.h +++ b/libadhocutil/compileTimeFormatter.h @@ -1,59 +1,70 @@ #ifndef ADHOCUTIL_COMPILE_TIME_FORMATTER_H #define ADHOCUTIL_COMPILE_TIME_FORMATTER_H -#include -#include -#include -#include #include #include +#include +#include +#include +#include namespace AdHoc { #ifdef __cpp_nontype_template_parameter_class -#define USE_FIXED_STRING +# define USE_FIXED_STRING #endif #ifdef USE_FIXED_STRING -#define CtfString const auto +# define CtfString const auto #else -#define CtfString const auto & +# define CtfString const auto & #endif // Template char utils template - constexpr bool isdigit(const char_type & ch) + constexpr bool + isdigit(const char_type & ch) { return (ch >= '0' && ch <= '9'); } template - constexpr bool ispositivedigit(const char_type & ch) + constexpr bool + ispositivedigit(const char_type & ch) { return (ch >= '1' && ch <= '9'); } // Template string utils template - static constexpr auto strlen() + static constexpr auto + strlen() { auto off = 0U; - while (S[off]) { ++off; } + while (S[off]) { + ++off; + } return off; } template - static constexpr auto strlen(const char_type * S) + static constexpr auto + strlen(const char_type * S) { auto off = 0U; - while (S[off]) { ++off; } + while (S[off]) { + ++off; + } return off; } template()> - static constexpr std::optional strchr() + static constexpr std::optional + strchr() { static_assert(start <= L); decltype(start) off = start; - while (off < L && S[off] != n) { ++off; } + while (off < L && S[off] != n) { + ++off; + } if (off == L) { return {}; } @@ -61,51 +72,55 @@ namespace AdHoc { } template()> - static constexpr decltype(L) strchrnul() + static constexpr decltype(L) + strchrnul() { decltype(start) off = start; - while (off < L && S[off] != n) { ++off; } + while (off < L && S[off] != n) { + ++off; + } return off; } template class FormatterDetail; /// Template used to apply parameters to a stream. - template - struct StreamWriter { + template struct StreamWriter { /// Write parameters to stream. - template - static void write(stream &, const Pn & ...) + template + static void + write(stream &, const Pn &...) { static_assert(!L, "invalid format string/arguments"); } }; /// Helper to simplify implementations of StreamWriter. - template - struct StreamWriterBase { + template struct StreamWriterBase { /// Continue processing parameters. - template - static inline void next(stream & s, const Pn & ... pn) + template + static inline void + next(stream & s, const Pn &... pn) { FormatterDetail::template Parser::run(s, pn...); } }; #define StreamWriterT(C...) \ - template \ + template \ struct StreamWriter : \ public StreamWriterBase #define StreamWriterTP(P, C...) \ - template \ + template \ struct StreamWriter : \ public StreamWriterBase // Default stream writer formatter StreamWriterT('?') { - template - static inline void write(stream & s, const P & p, const Pn & ... pn) + template + static inline void + write(stream & s, const P & p, const Pn &... pn) { s << p; StreamWriter::next(s, pn...); @@ -114,8 +129,9 @@ namespace AdHoc { // Escaped % stream writer formatter StreamWriterT('%') { - template - static inline void write(stream & s, const Pn & ... pn) + template + static inline void + write(stream & s, const Pn &... pn) { s << '%'; StreamWriter::next(s, pn...); @@ -123,13 +139,15 @@ namespace AdHoc { }; template - static inline void appendStream(stream & s, const char_type * p, size_t n) + static inline void + appendStream(stream & s, const char_type * p, size_t n) { s.write(p, n); } template - static inline auto streamLength(stream & s) + static inline auto + streamLength(stream & s) { return s.tellp(); } @@ -138,186 +156,186 @@ namespace AdHoc { * Compile time string formatter. * @param S the format string. */ - template - class FormatterDetail { - private: - using strlen_t = decltype(strlen()); - template friend struct StreamWriterBase; + template class FormatterDetail { + private: + using strlen_t = decltype(strlen()); + template friend struct StreamWriterBase; + + public: + /// The derived charater type of the format string. + using char_type = typename std::decay::type; + /** + * Get a string containing the result of formatting. + * @param pn the format arguments. + * @return the formatted string. + */ + template + static inline auto + get(const Pn &... pn) + { + std::basic_stringstream s; + return write(s, pn...).str(); + } + /** + * Get a string containing the result of formatting. + * @param pn the format arguments. + * @return the formatted string. + */ + template + inline auto + operator()(const Pn &... pn) const + { + return get(pn...); + } - public: - /// The derived charater type of the format string. - using char_type = typename std::decay::type; - /** - * Get a string containing the result of formatting. - * @param pn the format arguments. - * @return the formatted string. - */ - template - static inline auto get(const Pn & ... pn) - { - std::basic_stringstream s; - return write(s, pn...).str(); - } - /** - * Get a string containing the result of formatting. - * @param pn the format arguments. - * @return the formatted string. - */ - template - inline auto operator()(const Pn & ... pn) const - { - return get(pn...); - } + /** + * Write the result of formatting to the given stream. + * @param s the stream to write to. + * @param pn the format arguments. + * @return the stream. + */ + template + static inline stream & + write(stream & s, const Pn &... pn) + { + return Parser::run(s, pn...); + } + /** + * Write the result of formatting to the given stream. + * @param s the stream to write to. + * @param pn the format arguments. + * @return the stream. + */ + template + inline typename std::enable_if<(bool)&stream::write, stream>::type & + operator()(stream & s, const Pn &... pn) const + { + return write(s, pn...); + } - /** - * Write the result of formatting to the given stream. - * @param s the stream to write to. - * @param pn the format arguments. - * @return the stream. - */ - template - static inline stream & write(stream & s, const Pn & ... pn) + private: + template struct Parser { + static inline stream & + run(stream & s, const Pn &... pn) { - return Parser::run(s, pn...); + if (pos != L) { + constexpr auto ph = strchrnul(); + if constexpr (ph != pos) { + appendStream(s, &S[pos], ph - pos); + } + if constexpr (ph != L) { + packAndWrite(s, pn...); + } + } + return s; } - /** - * Write the result of formatting to the given stream. - * @param s the stream to write to. - * @param pn the format arguments. - * @return the stream. - */ - template - inline typename std::enable_if<(bool)&stream::write, stream>::type & - operator()(stream & s, const Pn & ... pn) const + template + static inline void + packAndWrite(stream & s, const Pn &... pn) { - return write(s, pn...); - } - - private: - template - struct Parser { - static inline stream & - run(stream & s, const Pn & ... pn) - { - if (pos != L) { - constexpr auto ph = strchrnul(); - if constexpr (ph != pos) { - appendStream(s, &S[pos], ph - pos); - } - if constexpr (ph != L) { - packAndWrite(s, pn...); - } - } - return s; + if constexpr (ph + off == L || sizeof...(Pck) == 32) { + StreamWriter::write(s, pn...); } - template - static inline void packAndWrite(stream & s, const Pn & ... pn) - { - if constexpr (ph + off == L || sizeof...(Pck) == 32) { - StreamWriter::write(s, pn...); - } - else if constexpr (ph + off < L) { - packAndWrite(s, pn...); - } + else if constexpr (ph + off < L) { + packAndWrite(s, pn...); } - }; + } + }; }; #ifdef USE_FIXED_STRING // New C++20 implementation namespace support { - template - class basic_fixed_string : public std::array { - public: - constexpr basic_fixed_string(const CharT (&str)[N + 1]) - { - for (decltype(N) x = 0; x < N; x++) { - this->at(x) = str[x]; - } + template class basic_fixed_string : public std::array { + public: + constexpr basic_fixed_string(const CharT (&str)[N + 1]) + { + for (decltype(N) x = 0; x < N; x++) { + this->at(x) = str[x]; } - constexpr basic_fixed_string(const CharT * str, decltype(N) len) - { - for (decltype(N) x = 0; x < len; x++) { - this->at(x) = str[x]; - } + } + constexpr basic_fixed_string(const CharT * str, decltype(N) len) + { + for (decltype(N) x = 0; x < len; x++) { + this->at(x) = str[x]; } + } }; template basic_fixed_string(const CharT (&str)[N]) -> basic_fixed_string; } - template - class LiteralFormatter : public FormatterDetail { }; + template class LiteralFormatter : public FormatterDetail { + }; - template - class Formatter : public FormatterDetail::type, L>(S, L), L> { }; + template + class Formatter : + public FormatterDetail::type, L>(S, L), L> { + }; -#define AdHocFormatter(name, str) \ - using name = ::AdHoc::LiteralFormatter +# define AdHocFormatter(name, str) using name = ::AdHoc::LiteralFormatter - template - inline auto scprintf(const Pn & ... pn) + template + inline auto + scprintf(const Pn &... pn) { return FormatterDetail::get(pn...); } - template - inline auto & scprintf(stream & strm, const Pn & ... pn) + template + inline auto & + scprintf(stream & strm, const Pn &... pn) { return FormatterDetail::write(strm, pn...); } - template - inline auto & cprintf(const Pn & ... pn) + template + inline auto & + cprintf(const Pn &... pn) { return scprintf(std::cout, pn...); } #else // Classic pre-C++20 implementation -#include "unique.h" - template ()) L = strlen()> - class Formatter : public FormatterDetail { }; +# include "unique.h" + template()) L = strlen()> class Formatter : public FormatterDetail { + }; -#define AdHocFormatterTypedef(name, str, id) \ - inline constexpr auto id = str; \ - using name = ::AdHoc::Formatter -#define AdHocFormatter(name, str) \ - AdHocFormatterTypedef(name, str, MAKE_UNIQUE(name)) +# define AdHocFormatterTypedef(name, str, id) \ + inline constexpr auto id = str; \ + using name = ::AdHoc::Formatter +# define AdHocFormatter(name, str) AdHocFormatterTypedef(name, str, MAKE_UNIQUE(name)) #endif namespace literals { #ifdef USE_FIXED_STRING - template - constexpr inline auto operator""_fmt() noexcept + template constexpr inline auto operator""_fmt() noexcept { return AdHoc::FormatterDetail(); } #else -#ifdef __clang__ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wgnu-string-literal-operator-template" -#endif +# ifdef __clang__ +# pragma clang diagnostic push +# pragma clang diagnostic ignored "-Wgnu-string-literal-operator-template" +# endif /// CTF format string holder - template struct FMT - { + template struct FMT { /// CTF format string // NOLINTNEXTLINE(hicpp-avoid-c-arrays,modernize-avoid-c-arrays) static constexpr char __FMT[] = {t...}; }; - template inline auto operator""_fmt() noexcept + template inline auto operator""_fmt() noexcept { return AdHoc::FormatterDetail::__FMT, sizeof...(t)>(); } #endif #ifdef __clang__ -#pragma clang diagnostic pop +# pragma clang diagnostic pop #endif } } #endif - diff --git a/libadhocutil/ctf-impl/printf-compat.h b/libadhocutil/ctf-impl/printf-compat.h index 4f93d4f..33223bf 100644 --- a/libadhocutil/ctf-impl/printf-compat.h +++ b/libadhocutil/ctf-impl/printf-compat.h @@ -3,19 +3,20 @@ #include "../compileTimeFormatter.h" #include -#include +#include #include -#include #include -#include +#include +#include #include #include namespace AdHoc { #define BASICCONV(PARAMTYPE, OP, ...) \ StreamWriterT(__VA_ARGS__) { \ - template \ - static inline void write(stream & s, const PARAMTYPE & p, const Pn & ... pn) \ + template \ + static inline void \ + write(stream & s, const PARAMTYPE & p, const Pn &... pn) \ { \ OP; \ s.copyfmt(std::ios(nullptr)); \ @@ -68,23 +69,26 @@ namespace AdHoc { BASICCONV(wchar_t, s << p, 'l', 'c'); #undef BASICCONV StreamWriterT('p') { - template - static inline void write(stream & s, Obj * const ptr, const Pn & ... pn) + template + static inline void + write(stream & s, Obj * const ptr, const Pn &... pn) { s << std::showbase << std::hex << (long unsigned int)ptr; s.copyfmt(std::ios(nullptr)); StreamWriter::next(s, pn...); } - template - static inline void write(stream & s, const Ptr & ptr, const Pn & ... pn) + template + static inline void + write(stream & s, const Ptr & ptr, const Pn &... pn) { write(s, ptr.get(), pn...); } }; StreamWriterT('m') { - template - static inline void write(stream & s, const Pn & ... pn) + template + static inline void + write(stream & s, const Pn &... pn) { s << strerror(errno); s.copyfmt(std::ios(nullptr)); @@ -92,8 +96,9 @@ namespace AdHoc { } }; StreamWriterT('n') { - template - static inline void write(stream & s, int * n, const Pn & ... pn) + template + static inline void + write(stream & s, int * n, const Pn &... pn) { BOOST_ASSERT_MSG(n, "%n conversion requires non-null parameter"); *n = streamLength(s); @@ -104,24 +109,36 @@ namespace AdHoc { //// // Width/precision embedded in format string - template - constexpr auto decdigits() + template + constexpr auto + decdigits() { static_assert((isdigit(chs) && ... && true)); int n = 0; - ([&n](auto ch) { - n = (n * 10) + (ch - '0'); - }(chs), ...); + ( + [&n](auto ch) { + n = (n * 10) + (ch - '0'); + }(chs), + ...); return n; } -#define AUTON(z, n, data) BOOST_PP_COMMA_IF(n) auto BOOST_PP_CAT(data, n) -#define NS(z, n, data) BOOST_PP_COMMA_IF(n) BOOST_PP_CAT(data, n) -#define ISDIGIT(z, n, data) && isdigit(BOOST_PP_CAT(data, BOOST_PP_ADD(n, 1))) +#define AUTON(z, n, data) \ + BOOST_PP_COMMA_IF(n) \ + auto BOOST_PP_CAT(data, n) +#define NS(z, n, data) \ + BOOST_PP_COMMA_IF(n) \ + BOOST_PP_CAT(data, n) +#define ISDIGIT(z, n, data) &&isdigit(BOOST_PP_CAT(data, BOOST_PP_ADD(n, 1))) #define FMTWIDTH(unused, d, data) \ - template \ - struct StreamWriter::type, '%', BOOST_PP_REPEAT(BOOST_PP_ADD(d, 1), NS, n), nn, sn...> { \ - template \ - static inline void write(stream & s, const Pn & ... pn) { \ + template \ + struct StreamWriter::type, '%', \ + BOOST_PP_REPEAT(BOOST_PP_ADD(d, 1), NS, n), nn, sn...> { \ + template \ + static inline void \ + write(stream & s, const Pn &... pn) \ + { \ constexpr auto p = decdigits(); \ s << std::setw(p); \ StreamWriter::write(s, pn...); \ @@ -129,10 +146,15 @@ namespace AdHoc { }; BOOST_PP_REPEAT(6, FMTWIDTH, void); #define FMTPRECISION(unused, d, data) \ - template \ - struct StreamWriter::type, '%', '.', BOOST_PP_REPEAT(BOOST_PP_ADD(d, 1), NS, n), nn, sn...> { \ - template \ - static inline void write(stream & s, const Pn & ... pn) { \ + template \ + struct StreamWriter::type, '%', '.', \ + BOOST_PP_REPEAT(BOOST_PP_ADD(d, 1), NS, n), nn, sn...> { \ + template \ + static inline void \ + write(stream & s, const Pn &... pn) \ + { \ constexpr auto p = decdigits(); \ s << std::setprecision(p); \ StreamWriter::write(s, pn...); \ @@ -145,16 +167,18 @@ namespace AdHoc { #undef FMTWIDTH StreamWriterT('.', '*') { - template - static inline void write(stream & s, int l, const Pn & ... pn) + template + static inline void + write(stream & s, int l, const Pn &... pn) { s << std::setw(l); StreamWriter::write(s, pn...); } }; StreamWriterT('.', '*', 's') { - template - static inline void write(stream & s, int l, const std::string_view & p, const Pn & ... pn) + template + static inline void + write(stream & s, int l, const std::string_view & p, const Pn &... pn) { s << p.substr(0, l); s.copyfmt(std::ios(nullptr)); @@ -162,10 +186,13 @@ namespace AdHoc { } }; - // Flags + // Flags #define FLAGCONV(OP, ...) \ StreamWriterT(__VA_ARGS__) { \ - template static inline void write(stream & s, const Pn & ... pn) { \ + template \ + static inline void \ + write(stream & s, const Pn &... pn) \ + { \ OP; \ StreamWriter::write(s, pn...); \ } \ @@ -179,4 +206,3 @@ namespace AdHoc { } #endif - diff --git a/libadhocutil/curlHandle.cpp b/libadhocutil/curlHandle.cpp index a976410..3974f34 100644 --- a/libadhocutil/curlHandle.cpp +++ b/libadhocutil/curlHandle.cpp @@ -1,137 +1,136 @@ #include "curlHandle.h" -#include -#include #include "compileTimeFormatter.h" +#include +#include namespace AdHoc::Net { -static void cleanup() __attribute__((destructor)); -static void cleanup() -{ - curl_global_cleanup(); -} - -CurlHandle::CurlHandle(const std::string & url) : - curl_handle(curl_easy_init()), - curl_headers(nullptr), - postS(nullptr), postE(nullptr) -{ - curl_easy_setopt(curl_handle, CURLOPT_URL, url.c_str()); - curl_easy_setopt(curl_handle, CURLOPT_FAILONERROR, 1); -} + static void cleanup() __attribute__((destructor)); + static void + cleanup() + { + curl_global_cleanup(); + } -CurlHandle::~CurlHandle() -{ - if (curl_headers) { - curl_slist_free_all(curl_headers); + CurlHandle::CurlHandle(const std::string & url) : + curl_handle(curl_easy_init()), curl_headers(nullptr), postS(nullptr), postE(nullptr) + { + curl_easy_setopt(curl_handle, CURLOPT_URL, url.c_str()); + curl_easy_setopt(curl_handle, CURLOPT_FAILONERROR, 1); } - if (postS) { - curl_formfree(postS); + + CurlHandle::~CurlHandle() + { + if (curl_headers) { + curl_slist_free_all(curl_headers); + } + if (postS) { + curl_formfree(postS); + } + curl_easy_cleanup(curl_handle); } - curl_easy_cleanup(curl_handle); -} -template <> -void -CurlHandle::setopt(CURLoption opt, const void * val) -{ - curl_easy_setopt(curl_handle, opt, val); -} + template<> + void + CurlHandle::setopt(CURLoption opt, const void * val) + { + curl_easy_setopt(curl_handle, opt, val); + } -template <> -void -CurlHandle::setopt(CURLoption opt, int val) -{ - curl_easy_setopt(curl_handle, opt, val); -} + template<> + void + CurlHandle::setopt(CURLoption opt, int val) + { + curl_easy_setopt(curl_handle, opt, val); + } -template <> -void -CurlHandle::setopt(CURLoption opt, long val) -{ - curl_easy_setopt(curl_handle, opt, val); -} + template<> + void + CurlHandle::setopt(CURLoption opt, long val) + { + curl_easy_setopt(curl_handle, opt, val); + } -void -CurlHandle::getinfo(CURLINFO info, long & val) const -{ - curl_easy_getinfo(curl_handle, info, &val); -} + void + CurlHandle::getinfo(CURLINFO info, long & val) const + { + curl_easy_getinfo(curl_handle, info, &val); + } -void -CurlHandle::getinfo(CURLINFO info, int & ival) const -{ - long val; - curl_easy_getinfo(curl_handle, info, &val); - ival = boost::numeric_cast(val); -} + void + CurlHandle::getinfo(CURLINFO info, int & ival) const + { + long val; + curl_easy_getinfo(curl_handle, info, &val); + ival = boost::numeric_cast(val); + } -void -CurlHandle::getinfo(CURLINFO info, double & val) const -{ - curl_easy_getinfo(curl_handle, info, &val); -} + void + CurlHandle::getinfo(CURLINFO info, double & val) const + { + curl_easy_getinfo(curl_handle, info, &val); + } -void -CurlHandle::getinfo(CURLINFO info, char * & val) const -{ - curl_easy_getinfo(curl_handle, info, &val); -} + void + CurlHandle::getinfo(CURLINFO info, char *& val) const + { + curl_easy_getinfo(curl_handle, info, &val); + } -void -CurlHandle::appendHeader(const char * header) -{ - curl_headers = curl_slist_append(curl_headers, header); -} + void + CurlHandle::appendHeader(const char * header) + { + curl_headers = curl_slist_append(curl_headers, header); + } -void -CurlHandle::appendPost(const char * name, const char * value) -{ - CURLFORMcode r = curl_formadd(&postS, &postE, CURLFORM_PTRNAME, name, CURLFORM_PTRCONTENTS, value, CURLFORM_END); - if (r == 0) { - curl_easy_setopt(curl_handle, CURLOPT_HTTPPOST, postS); + void + CurlHandle::appendPost(const char * name, const char * value) + { + CURLFORMcode r + = curl_formadd(&postS, &postE, CURLFORM_PTRNAME, name, CURLFORM_PTRCONTENTS, value, CURLFORM_END); + if (r == 0) { + curl_easy_setopt(curl_handle, CURLOPT_HTTPPOST, postS); + } } -} -void -CurlHandle::perform() -{ - if (curl_headers) { - curl_easy_setopt(curl_handle, CURLOPT_HTTPHEADER, curl_headers); + void + CurlHandle::perform() + { + if (curl_headers) { + curl_easy_setopt(curl_handle, CURLOPT_HTTPHEADER, curl_headers); + } + checkCurlCode(curl_easy_perform(curl_handle)); } - checkCurlCode(curl_easy_perform(curl_handle)); -} -CurlHandle::operator CURL *() const -{ - return curl_handle; -} + CurlHandle::operator CURL *() const + { + return curl_handle; + } -void -CurlHandle::checkCurlCode(CURLcode res) const -{ - if (res != CURLE_OK) { - long http_code = 0; - if (curl_easy_getinfo(curl_handle, CURLINFO_RESPONSE_CODE, &http_code) == CURLE_OK) { - throw AdHoc::Net::CurlException(res, curl_easy_strerror(res), http_code); + void + CurlHandle::checkCurlCode(CURLcode res) const + { + if (res != CURLE_OK) { + long http_code = 0; + if (curl_easy_getinfo(curl_handle, CURLINFO_RESPONSE_CODE, &http_code) == CURLE_OK) { + throw AdHoc::Net::CurlException(res, curl_easy_strerror(res), http_code); + } + throw AdHoc::Net::CurlException(res, curl_easy_strerror(res), IceUtil::None); } - throw AdHoc::Net::CurlException(res, curl_easy_strerror(res), IceUtil::None); } -} -AdHocFormatter(CurlExceptionMsg, "Network operation failed: %? (%?)"); -AdHocFormatter(CurlExceptionMsgHttp, "HTTP operation failed: %?: %? (%?)"); + AdHocFormatter(CurlExceptionMsg, "Network operation failed: %? (%?)"); + AdHocFormatter(CurlExceptionMsgHttp, "HTTP operation failed: %?: %? (%?)"); -void -CurlException::ice_print(std::ostream & s) const -{ - if (httpcode) { - CurlExceptionMsgHttp::write(s, *httpcode, message, resultcode); - } - else { - CurlExceptionMsg::write(s, message, resultcode); + void + CurlException::ice_print(std::ostream & s) const + { + if (httpcode) { + CurlExceptionMsgHttp::write(s, *httpcode, message, resultcode); + } + else { + CurlExceptionMsg::write(s, message, resultcode); + } } -} } - diff --git a/libadhocutil/curlHandle.h b/libadhocutil/curlHandle.h index c9e8f58..dd8e595 100644 --- a/libadhocutil/curlHandle.h +++ b/libadhocutil/curlHandle.h @@ -1,76 +1,72 @@ #ifndef ADHOCUTIL_CURLHANDLE_H #define ADHOCUTIL_CURLHANDLE_H +#include "c++11Helpers.h" +#include "visibility.h" #include #include -#include "visibility.h" -#include "c++11Helpers.h" namespace AdHoc { -namespace Net { + namespace Net { -/// libcurl handle wrapper. -/** Wraps a libcurl CURL * object in a C++ friendly manner. */ -class DLL_PUBLIC CurlHandle { - public: - /** - * Create a new CurlHandle. - * @param url Set the required CURLOPT_URL property to the given url. - */ - explicit CurlHandle(const std::string & url); - /// Standard move/copy support - SPECIAL_MEMBERS_DEFAULT_MOVE_NO_COPY(CurlHandle); - virtual ~CurlHandle(); + /// libcurl handle wrapper. + /** Wraps a libcurl CURL * object in a C++ friendly manner. */ + class DLL_PUBLIC CurlHandle { + public: + /** + * Create a new CurlHandle. + * @param url Set the required CURLOPT_URL property to the given url. + */ + explicit CurlHandle(const std::string & url); + /// Standard move/copy support + SPECIAL_MEMBERS_DEFAULT_MOVE_NO_COPY(CurlHandle); + virtual ~CurlHandle(); - /** Set option wrapper. */ - template - void setopt(CURLoption opt, const T val); - /** Get info for long values */ - void getinfo(CURLINFO info, long & val) const; - /** Get info for int values (avoids ambiguous call errors for ease of use) */ - void getinfo(CURLINFO info, int & val) const; - /** Get info for double values */ - void getinfo(CURLINFO info, double & val) const; - /** Get info for char * values */ - void getinfo(CURLINFO info, char * & val) const; - /** Append the given HTTP header */ - void appendHeader(const char *); - /** Append the given HTTP post content */ - void appendPost(const char *, const char *); - /** Perform the CURL transfer. */ - void perform(); + /** Set option wrapper. */ + template void setopt(CURLoption opt, const T val); + /** Get info for long values */ + void getinfo(CURLINFO info, long & val) const; + /** Get info for int values (avoids ambiguous call errors for ease of use) */ + void getinfo(CURLINFO info, int & val) const; + /** Get info for double values */ + void getinfo(CURLINFO info, double & val) const; + /** Get info for char * values */ + void getinfo(CURLINFO info, char *& val) const; + /** Append the given HTTP header */ + void appendHeader(const char *); + /** Append the given HTTP post content */ + void appendPost(const char *, const char *); + /** Perform the CURL transfer. */ + void perform(); - /** Get the underlying CURL * handle. @warning Make changes at your own risk. */ - // NOLINTNEXTLINE(hicpp-explicit-conversions) - operator CURL *() const; + /** Get the underlying CURL * handle. @warning Make changes at your own risk. */ + // NOLINTNEXTLINE(hicpp-explicit-conversions) + operator CURL *() const; - protected: - /// @cond - void checkCurlCode(CURLcode res) const; + protected: + /// @cond + void checkCurlCode(CURLcode res) const; - CURL * curl_handle; - curl_slist * curl_headers; - curl_httppost * postS, * postE; - /// @endcond -}; -using CurlHandlePtr = std::shared_ptr; + CURL * curl_handle; + curl_slist * curl_headers; + curl_httppost *postS, *postE; + /// @endcond + }; + using CurlHandlePtr = std::shared_ptr; -/// @cond -template <> -void CurlHandle::setopt(CURLoption opt, const void * val); -template <> -void CurlHandle::setopt(CURLoption opt, int val); -template <> -void CurlHandle::setopt(CURLoption opt, long val); -template -void CurlHandle::setopt(CURLoption opt, const T val) -{ - setopt(opt, (const void *)val); -} -/// @endcond + /// @cond + template<> void CurlHandle::setopt(CURLoption opt, const void * val); + template<> void CurlHandle::setopt(CURLoption opt, int val); + template<> void CurlHandle::setopt(CURLoption opt, long val); + template + void + CurlHandle::setopt(CURLoption opt, const T val) + { + setopt(opt, (const void *)val); + } + /// @endcond -} + } } #endif - diff --git a/libadhocutil/curlMultiHandle.cpp b/libadhocutil/curlMultiHandle.cpp index 5db8c3f..a4a3c0c 100644 --- a/libadhocutil/curlMultiHandle.cpp +++ b/libadhocutil/curlMultiHandle.cpp @@ -1,20 +1,20 @@ #include "curlMultiHandle.h" +#include "curlStream.h" +#include "runtimeContext.h" #include #include -#include "runtimeContext.h" -#include "curlStream.h" namespace AdHoc::Net { -class RunningCurl : public CurlStreamSource { + class RunningCurl : public CurlStreamSource { public: RunningCurl(const std::string & url, std::function c) : - CurlStreamSource(url), - consumer(std::move(c)) + CurlStreamSource(url), consumer(std::move(c)) { } - void callback() override + void + callback() override { using rc_ref = boost::reference_wrapper; boost::iostreams::stream curlstrm(std::ref(*this)); @@ -23,73 +23,72 @@ class RunningCurl : public CurlStreamSource { private: const std::function consumer; -}; + }; -CurlMultiHandle::CurlMultiHandle() = default; + CurlMultiHandle::CurlMultiHandle() = default; -CurlMultiHandle::~CurlMultiHandle() = default; + CurlMultiHandle::~CurlMultiHandle() = default; -CurlHandlePtr -CurlMultiHandle::addCurl(const std::string & url, const std::function & c) -{ - return *curls.insert(std::make_shared(url, c)).first; -} + CurlHandlePtr + CurlMultiHandle::addCurl(const std::string & url, const std::function & c) + { + return *curls.insert(std::make_shared(url, c)).first; + } -void -CurlMultiHandle::addRunner(CURLM * curlm, Running & running, CurlMultiHandle::CURLs & curls) -{ - auto runner = *curls.begin(); - curl_multi_add_handle(curlm, *runner); - running[*runner] = runner; - runner->swapContext(); - curls.erase(runner); -} + void + CurlMultiHandle::addRunner(CURLM * curlm, Running & running, CurlMultiHandle::CURLs & curls) + { + auto runner = *curls.begin(); + curl_multi_add_handle(curlm, *runner); + running[*runner] = runner; + runner->swapContext(); + curls.erase(runner); + } -void -CurlMultiHandle::performAll() -{ - if (!curls.empty()) { - Running running; - CURLM * curlm = curl_multi_init(); + void + CurlMultiHandle::performAll() + { + if (!curls.empty()) { + Running running; + CURLM * curlm = curl_multi_init(); - while (!curls.empty() && running.size() < 5) { - addRunner(curlm, running, curls); - } - int act = running.size(); - while (act) { - while (curl_multi_perform(curlm, &act) == CURLM_CALL_MULTI_PERFORM) {} - // Has anything finished - CURLMsg * msg; - int msgs = 0; - while ((msg = curl_multi_info_read(curlm, &msgs))) { - if (msg->msg == CURLMSG_DONE) { - curl_multi_remove_handle(curlm, msg->easy_handle); - auto ri = running.find(msg->easy_handle); - ri->second->res = msg->data.result; - ri->second->swapContext(); - running.erase(ri); - if (!curls.empty()) { - addRunner(curlm, running, curls); - act += 1; + while (!curls.empty() && running.size() < 5) { + addRunner(curlm, running, curls); + } + int act = running.size(); + while (act) { + while (curl_multi_perform(curlm, &act) == CURLM_CALL_MULTI_PERFORM) { } + // Has anything finished + CURLMsg * msg; + int msgs = 0; + while ((msg = curl_multi_info_read(curlm, &msgs))) { + if (msg->msg == CURLMSG_DONE) { + curl_multi_remove_handle(curlm, msg->easy_handle); + auto ri = running.find(msg->easy_handle); + ri->second->res = msg->data.result; + ri->second->swapContext(); + running.erase(ri); + if (!curls.empty()) { + addRunner(curlm, running, curls); + act += 1; + } } } + // Wait for something to happen + fd_set r, w, e; + int maxfd = 0; + struct timeval to = {0, 100000}; + // NOLINTNEXTLINE(hicpp-no-assembler) + FD_ZERO(&r); + // NOLINTNEXTLINE(hicpp-no-assembler) + FD_ZERO(&w); + // NOLINTNEXTLINE(hicpp-no-assembler) + FD_ZERO(&e); + curl_multi_fdset(curlm, &r, &w, &e, &maxfd); + select(act, &r, &w, &e, &to); } - // Wait for something to happen - fd_set r, w, e; - int maxfd = 0; - struct timeval to = { 0, 100000 }; - // NOLINTNEXTLINE(hicpp-no-assembler) - FD_ZERO(&r); - // NOLINTNEXTLINE(hicpp-no-assembler) - FD_ZERO(&w); - // NOLINTNEXTLINE(hicpp-no-assembler) - FD_ZERO(&e); - curl_multi_fdset(curlm, &r, &w, &e, &maxfd); - select(act, &r, &w, &e, &to); + curl_multi_cleanup(curlm); } - curl_multi_cleanup(curlm); } -} } - diff --git a/libadhocutil/curlMultiHandle.h b/libadhocutil/curlMultiHandle.h index 5308fb3..2116565 100644 --- a/libadhocutil/curlMultiHandle.h +++ b/libadhocutil/curlMultiHandle.h @@ -1,49 +1,48 @@ #ifndef ADHOCUTIL_CURLMULTIHANDLE_H #define ADHOCUTIL_CURLMULTIHANDLE_H +#include "c++11Helpers.h" +#include "curlHandle.h" +#include "visibility.h" #include -#include #include #include -#include "visibility.h" -#include "curlHandle.h" -#include "c++11Helpers.h" +#include namespace AdHoc { -namespace Net { + namespace Net { -class RunningCurl; -using RunningCurlPtr = std::shared_ptr; + class RunningCurl; + using RunningCurlPtr = std::shared_ptr; -/// Perform multiple CURL operations at once. -class DLL_PUBLIC CurlMultiHandle { - public: - /** A function that should consume the inbound byte stream. */ - using Consumer = std::function; + /// Perform multiple CURL operations at once. + class DLL_PUBLIC CurlMultiHandle { + public: + /** A function that should consume the inbound byte stream. */ + using Consumer = std::function; - CurlMultiHandle(); - ~CurlMultiHandle(); + CurlMultiHandle(); + ~CurlMultiHandle(); - /// Standard move/copy support - SPECIAL_MEMBERS_DEFAULT_MOVE_NO_COPY(CurlMultiHandle); + /// Standard move/copy support + SPECIAL_MEMBERS_DEFAULT_MOVE_NO_COPY(CurlMultiHandle); - /** Adds a new consumer for the given URL to the set of operations to perform. */ - CurlHandlePtr addCurl(const std::string &, const Consumer &); - /** Perform all queued operations. */ - void performAll(); + /** Adds a new consumer for the given URL to the set of operations to perform. */ + CurlHandlePtr addCurl(const std::string &, const Consumer &); + /** Perform all queued operations. */ + void performAll(); - private: - using CURLs = std::set; - using Running = std::map; + private: + using CURLs = std::set; + using Running = std::map; - DLL_PRIVATE void addRunner(CURLM * curlm, Running & running, CURLs & curls); + DLL_PRIVATE void addRunner(CURLM * curlm, Running & running, CURLs & curls); - CURLs curls; -}; -using CurlMultiHandlePtr = std::shared_ptr; + CURLs curls; + }; + using CurlMultiHandlePtr = std::shared_ptr; -} + } } #endif - diff --git a/libadhocutil/curlStream.cpp b/libadhocutil/curlStream.cpp index 6784675..8f129d7 100644 --- a/libadhocutil/curlStream.cpp +++ b/libadhocutil/curlStream.cpp @@ -2,58 +2,54 @@ namespace AdHoc::Net { -CurlStreamSource::CurlStreamSource(const std::string & url) : - CurlHandle(url), - buflen(0), - buf(nullptr), - res(CURLE_OK) -{ - curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, &CurlStreamSource::recvWrapper); - curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, this); -} + CurlStreamSource::CurlStreamSource(const std::string & url) : + CurlHandle(url), buflen(0), buf(nullptr), res(CURLE_OK) + { + curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, &CurlStreamSource::recvWrapper); + curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, this); + } -AdHoc::Net::CurlStreamSource::~CurlStreamSource() = default; + AdHoc::Net::CurlStreamSource::~CurlStreamSource() = default; -std::streamsize -CurlStreamSource::read(char * target, std::streamsize targetSize) -{ - if (!buflen) { - swapContext(); - checkCurlCode(res); + std::streamsize + CurlStreamSource::read(char * target, std::streamsize targetSize) + { if (!buflen) { - return 0; + swapContext(); + checkCurlCode(res); + if (!buflen) { + return 0; + } } + size_t bytes = std::min(buflen, targetSize); + memcpy(target, buf, bytes); + buflen -= bytes; + buf += bytes; + return bytes; } - size_t bytes = std::min(buflen, targetSize); - memcpy(target, buf, bytes); - buflen -= bytes; - buf += bytes; - return bytes; -} -void -CurlStreamSource::callback() -{ - if (curl_headers) { - curl_easy_setopt(curl_handle, CURLOPT_HTTPHEADER, curl_headers); + void + CurlStreamSource::callback() + { + if (curl_headers) { + curl_easy_setopt(curl_handle, CURLOPT_HTTPHEADER, curl_headers); + } + res = curl_easy_perform(curl_handle); } - res = curl_easy_perform(curl_handle); -} -size_t -CurlStreamSource::recvWrapper(void * data, size_t sz, size_t nm, void * css) -{ - return static_cast(css)->recv(data, sz * nm); -} + size_t + CurlStreamSource::recvWrapper(void * data, size_t sz, size_t nm, void * css) + { + return static_cast(css)->recv(data, sz * nm); + } -size_t -CurlStreamSource::recv(void * data, size_t datalen) -{ - buf = (char *)data; - buflen = datalen; - swapContext(); - return datalen; -} + size_t + CurlStreamSource::recv(void * data, size_t datalen) + { + buf = (char *)data; + buflen = datalen; + swapContext(); + return datalen; + } } - diff --git a/libadhocutil/curlStream.h b/libadhocutil/curlStream.h index 9361fd8..64fb38e 100644 --- a/libadhocutil/curlStream.h +++ b/libadhocutil/curlStream.h @@ -1,45 +1,47 @@ #ifndef ADHOCUTIL_CURLSTREAM_H #define ADHOCUTIL_CURLSTREAM_H -#include +#include "c++11Helpers.h" +#include "curlHandle.h" #include "runtimeContext.h" -#include -#include #include "visibility.h" -#include "curlHandle.h" -#include "c++11Helpers.h" +#include +#include +#include namespace AdHoc { -namespace Net { - -/// boost::iostreams::source implementation for CURL downloads. -class DLL_PUBLIC CurlStreamSource : public boost::iostreams::source, public CurlHandle, ::AdHoc::System::RuntimeContext { - public: - /** Construct a new stream source for the given URL. */ - explicit CurlStreamSource(const std::string & url); - /// Standard move/copy support - SPECIAL_MEMBERS_DEFAULT_MOVE_NO_COPY(CurlStreamSource); - ~CurlStreamSource() override; - - /** Required member function for reading of the stream source by boost::iostreams::stream. */ - std::streamsize read(char * target, std::streamsize targetSize); - - private: - friend class CurlMultiHandle; - DLL_PRIVATE void callback() override; - - DLL_PRIVATE static size_t recvWrapper(void * data, size_t sz, size_t nm, void * css); - DLL_PRIVATE size_t recv(void * data, size_t datalen); - - size_t buflen; - char * buf; - CURLcode res; -}; - -using CurlStream = boost::iostreams::stream>; - -} + namespace Net { + + /// boost::iostreams::source implementation for CURL downloads. + class DLL_PUBLIC CurlStreamSource : + public boost::iostreams::source, + public CurlHandle, + ::AdHoc::System::RuntimeContext { + public: + /** Construct a new stream source for the given URL. */ + explicit CurlStreamSource(const std::string & url); + /// Standard move/copy support + SPECIAL_MEMBERS_DEFAULT_MOVE_NO_COPY(CurlStreamSource); + ~CurlStreamSource() override; + + /** Required member function for reading of the stream source by boost::iostreams::stream. */ + std::streamsize read(char * target, std::streamsize targetSize); + + private: + friend class CurlMultiHandle; + DLL_PRIVATE void callback() override; + + DLL_PRIVATE static size_t recvWrapper(void * data, size_t sz, size_t nm, void * css); + DLL_PRIVATE size_t recv(void * data, size_t datalen); + + size_t buflen; + char * buf; + CURLcode res; + }; + + using CurlStream = boost::iostreams::stream>; + + } } #endif - diff --git a/libadhocutil/definedDirs.h b/libadhocutil/definedDirs.h index accb663..d746891 100644 --- a/libadhocutil/definedDirs.h +++ b/libadhocutil/definedDirs.h @@ -4,7 +4,7 @@ #include #ifndef ROOT -#error "ROOT needs to be defined at compilation time" +# error "ROOT needs to be defined at compilation time" #endif #define XSTR(s) STR(s) @@ -14,4 +14,3 @@ const std::filesystem::path binDir = selfExe.parent_path(); const std::filesystem::path rootDir(XSTR(ROOT)); #endif - diff --git a/libadhocutil/exception.h b/libadhocutil/exception.h index 2152446..e41796c 100644 --- a/libadhocutil/exception.h +++ b/libadhocutil/exception.h @@ -2,35 +2,33 @@ #define ADHOCUTIL_EXCEPTION_H #include -#include #include +#include namespace AdHoc { /// Helper class for lazy creation of exception message text. - template - class Exception : public BaseException { - public: - /// Wrapper constructor to pass to BaseException - //@param t parameters to pass. - template - explicit Exception(const T & ... t) : BaseException(t...) { } + template class Exception : public BaseException { + public: + /// Wrapper constructor to pass to BaseException + //@param t parameters to pass. + template explicit Exception(const T &... t) : BaseException(t...) { } - /// Override of std::exception::what() to create text as required. - inline const char * what() const noexcept override - { - if (!msg) { - msg = message(); - } - return msg->c_str(); + /// Override of std::exception::what() to create text as required. + inline const char * + what() const noexcept override + { + if (!msg) { + msg = message(); } + return msg->c_str(); + } - private: - /// Message text provider. - virtual std::string message() const noexcept = 0; - mutable std::optional msg; + private: + /// Message text provider. + virtual std::string message() const noexcept = 0; + mutable std::optional msg; }; using StdException = Exception; } #endif - diff --git a/libadhocutil/factory.h b/libadhocutil/factory.h index 3bd3f19..a2a49ed 100644 --- a/libadhocutil/factory.h +++ b/libadhocutil/factory.h @@ -8,51 +8,46 @@ namespace AdHoc { /** * Base class for factories creating instances of Base. */ - template - class DLL_PUBLIC Factory : public virtual AbstractPluginImplementation { + template class DLL_PUBLIC Factory : public virtual AbstractPluginImplementation { + public: + /** + * Create a new instance of Base, overridden in a subclass to construct a new specific class. + * @param p The parameters passed to Impl constructor. + */ + [[nodiscard]] virtual std::shared_ptr create(const Params &... p) const = 0; + + /** + * A factory for a concrete implementation of Base + */ + template> class DLL_PUBLIC For : public _ { public: /** - * Create a new instance of Base, overridden in a subclass to construct a new specific class. + * Create a new instance of Base implemented in Impl. * @param p The parameters passed to Impl constructor. */ - [[nodiscard]] virtual std::shared_ptr create(const Params & ... p) const = 0; - - /** - * A factory for a concrete implementation of Base - */ - template > - class DLL_PUBLIC For : public _ + [[nodiscard]] std::shared_ptr + create(const Params &... p) const override { - public: - /** - * Create a new instance of Base implemented in Impl. - * @param p The parameters passed to Impl constructor. - */ - [[nodiscard]] std::shared_ptr create(const Params & ... p) const override - { - return std::make_shared(p...); - } - }; - - /** - * Helper to get the factory for a specific implementation. - * @param name The name of the implementation. - */ - [[nodiscard]] static std::shared_ptr get(const std::string_view & name); - /** - * Helper to create a new instance from a specific factory. - * @param name The name of the implementation. - * @param p The parameters to pass to the constructor. - */ - [[nodiscard]] static std::shared_ptr createNew(const std::string_view & name, const Params & ... p); + return std::make_shared(p...); + } + }; + + /** + * Helper to get the factory for a specific implementation. + * @param name The name of the implementation. + */ + [[nodiscard]] static std::shared_ptr get(const std::string_view & name); + /** + * Helper to create a new instance from a specific factory. + * @param name The name of the implementation. + * @param p The parameters to pass to the constructor. + */ + [[nodiscard]] static std::shared_ptr createNew(const std::string_view & name, const Params &... p); }; } -#define NAMEDFACTORY(Name, Implementation, BaseFactory) \ - NAMEDPLUGIN(Name, BaseFactory::For, BaseFactory) +#define NAMEDFACTORY(Name, Implementation, BaseFactory) NAMEDPLUGIN(Name, BaseFactory::For, BaseFactory) -#define FACTORY(Implementation, BaseFactory) \ - NAMEDFACTORY(#Implementation, Implementation, BaseFactory) +#define FACTORY(Implementation, BaseFactory) NAMEDFACTORY(#Implementation, Implementation, BaseFactory) #endif - diff --git a/libadhocutil/factory.impl.h b/libadhocutil/factory.impl.h index 6f3cb5a..2010836 100644 --- a/libadhocutil/factory.impl.h +++ b/libadhocutil/factory.impl.h @@ -5,16 +5,16 @@ #include "plugins.impl.h" namespace AdHoc { - template + template std::shared_ptr> Factory::get(const std::string_view & name) { return PluginManager::getDefault()->get(name)->implementation(); } - template + template std::shared_ptr - Factory::createNew(const std::string_view & name, const Params & ... p) + Factory::createNew(const std::string_view & name, const Params &... p) { return get(name)->create(p...); } @@ -29,4 +29,3 @@ namespace AdHoc { INSTANTIATEPLUGINOF(AdHoc::Factory) #endif - diff --git a/libadhocutil/fileUtils.cpp b/libadhocutil/fileUtils.cpp index b4d39b4..2d815a5 100644 --- a/libadhocutil/fileUtils.cpp +++ b/libadhocutil/fileUtils.cpp @@ -1,14 +1,15 @@ #include "fileUtils.h" #include "compileTimeFormatter.h" -#include +#include #include #include -#include +#include namespace AdHoc::FileUtils { AdHocFormatter(FD, "FD %?"); - std::filesystem::path operator/(const std::filesystem::path & p, unsigned int n) + std::filesystem::path + operator/(const std::filesystem::path & p, unsigned int n) { auto pp = p.begin(); while (n--) { @@ -17,13 +18,9 @@ namespace AdHoc::FileUtils { return *pp; } - FileHandle::FileHandle(int d) noexcept : - fh(d) - { - } + FileHandle::FileHandle(int d) noexcept : fh(d) { } - FileHandle::FileHandle(FileHandle && o) noexcept : - fh(o.fh) + FileHandle::FileHandle(FileHandle && o) noexcept : fh(o.fh) { const_cast(o.fh) = -1; } @@ -36,8 +33,7 @@ namespace AdHoc::FileUtils { return *this; } - FileHandle::FileHandle(const std::filesystem::path & path, int flags) : - fh(open(path.c_str(), flags)) + FileHandle::FileHandle(const std::filesystem::path & path, int flags) : fh(open(path.c_str(), flags)) { if (fh < 0) { throw SystemExceptionOn("open(2) failed", strerror(errno), errno, path); @@ -64,23 +60,18 @@ namespace AdHoc::FileUtils { return fh; } - FileHandleStat::FileHandleStat(int fd) : - FileHandle(fd), - st({}) + FileHandleStat::FileHandleStat(int fd) : FileHandle(fd), st({}) { refreshStat(); } - FileHandleStat::FileHandleStat(const std::filesystem::path & path, int flags) : - FileHandle(path, flags), - st({}) + FileHandleStat::FileHandleStat(const std::filesystem::path & path, int flags) : FileHandle(path, flags), st({}) { refreshStat(path); } FileHandleStat::FileHandleStat(const std::filesystem::path & path, int flags, int mode) : - FileHandle(path, flags, mode), - st({}) + FileHandle(path, flags, mode), st({}) { refreshStat(path); } @@ -112,21 +103,15 @@ namespace AdHoc::FileUtils { } } - MemMap::MemMap(int d, int flags) : - FileHandleStat(d), - data(setupMap(flags)) - { - } + MemMap::MemMap(int d, int flags) : FileHandleStat(d), data(setupMap(flags)) { } MemMap::MemMap(const std::filesystem::path & path, int flags) : - FileHandleStat(path, flags), - data(setupMap(path, flags)) + FileHandleStat(path, flags), data(setupMap(path, flags)) { } MemMap::MemMap(const std::filesystem::path & path, int flags, int mode) : - FileHandleStat(path, flags, mode), - data(setupMap(path, flags)) + FileHandleStat(path, flags, mode), data(setupMap(path, flags)) { } @@ -161,4 +146,3 @@ namespace AdHoc::FileUtils { return data; } } - diff --git a/libadhocutil/fileUtils.h b/libadhocutil/fileUtils.h index 26093e5..c162677 100644 --- a/libadhocutil/fileUtils.h +++ b/libadhocutil/fileUtils.h @@ -1,12 +1,12 @@ #ifndef ADHOCUTIL_FILEUTILS_H #define ADHOCUTIL_FILEUTILS_H -#include -#include +#include "c++11Helpers.h" +#include "visibility.h" #include +#include #include -#include "visibility.h" -#include "c++11Helpers.h" +#include namespace AdHoc { namespace FileUtils { @@ -22,164 +22,163 @@ namespace AdHoc { * File handle wrapper to ensure closure on scope exit */ class DLL_PUBLIC FileHandle { - public: - /** - * Move constructor. - */ - FileHandle(FileHandle &&) noexcept; - - /** - * Construct from an existing file descriptor. - * @param fd An open file descriptor. - */ - explicit FileHandle(int fd) noexcept; - - /** - * Open a new file handle. - * @param path Path of file to open. - * @param flags File handle flags - */ - explicit FileHandle(const std::filesystem::path & path, int flags = O_RDONLY); - - /** - * Open a new file handle. - * @param path Path of file to open. - * @param flags File handle flags - * @param mode File handle mode - */ - FileHandle(const std::filesystem::path & path, int flags, int mode); - - virtual ~FileHandle() noexcept; - - /// Standard move/copy support - SPECIAL_MEMBERS_COPY(FileHandle, delete); - - /// Standard move/copy support - FileHandle & operator=(FileHandle &&) noexcept; - - /** - * Implicit conversion back to raw Unix file descriptor. - * @return The container file descriptor. - */ - // NOLINTNEXTLINE(hicpp-explicit-conversions) - operator int() const noexcept; - - /// The file handle. - const int fh; + public: + /** + * Move constructor. + */ + FileHandle(FileHandle &&) noexcept; + + /** + * Construct from an existing file descriptor. + * @param fd An open file descriptor. + */ + explicit FileHandle(int fd) noexcept; + + /** + * Open a new file handle. + * @param path Path of file to open. + * @param flags File handle flags + */ + explicit FileHandle(const std::filesystem::path & path, int flags = O_RDONLY); + + /** + * Open a new file handle. + * @param path Path of file to open. + * @param flags File handle flags + * @param mode File handle mode + */ + FileHandle(const std::filesystem::path & path, int flags, int mode); + + virtual ~FileHandle() noexcept; + + /// Standard move/copy support + SPECIAL_MEMBERS_COPY(FileHandle, delete); + + /// Standard move/copy support + FileHandle & operator=(FileHandle &&) noexcept; + + /** + * Implicit conversion back to raw Unix file descriptor. + * @return The container file descriptor. + */ + // NOLINTNEXTLINE(hicpp-explicit-conversions) + operator int() const noexcept; + + /// The file handle. + const int fh; }; /** * An extension to FileHandle that automatically calls fstat on the opened handle. */ class DLL_PUBLIC FileHandleStat : public FileHandle { - public: - ~FileHandleStat() override = default; - - /** - * Construct from an existing file descriptor. - * @param fd An open file descriptor. - */ - explicit FileHandleStat(int fd); - - /** - * Open a new file handle (with the default flags). - * @param path Path of file to open. - * @param flags File handle flags - */ - explicit FileHandleStat(const std::filesystem::path & path, int flags = O_RDONLY); - - /** - * Open a new file handle. - * @param path Path of file to open. - * @param flags File handle flags - * @param mode File handle mode - */ - FileHandleStat(const std::filesystem::path & path, int flags, int mode); - - /// Standard move/copy support - SPECIAL_MEMBERS_DEFAULT_MOVE_NO_COPY(FileHandleStat); - - /** - * Get the stat structure. - * @return The stat structure. - */ - [[nodiscard]] const struct stat & getStat() const noexcept; - - /** - * Refresh and return the stat structure. - * @return The stat structure. - */ - const struct stat & refreshStat(); - - protected: - /// The stat structure. - struct stat st; - - private: - DLL_PRIVATE void refreshStat(const std::filesystem::path & path); + public: + ~FileHandleStat() override = default; + + /** + * Construct from an existing file descriptor. + * @param fd An open file descriptor. + */ + explicit FileHandleStat(int fd); + + /** + * Open a new file handle (with the default flags). + * @param path Path of file to open. + * @param flags File handle flags + */ + explicit FileHandleStat(const std::filesystem::path & path, int flags = O_RDONLY); + + /** + * Open a new file handle. + * @param path Path of file to open. + * @param flags File handle flags + * @param mode File handle mode + */ + FileHandleStat(const std::filesystem::path & path, int flags, int mode); + + /// Standard move/copy support + SPECIAL_MEMBERS_DEFAULT_MOVE_NO_COPY(FileHandleStat); + + /** + * Get the stat structure. + * @return The stat structure. + */ + [[nodiscard]] const struct stat & getStat() const noexcept; + + /** + * Refresh and return the stat structure. + * @return The stat structure. + */ + const struct stat & refreshStat(); + + protected: + /// The stat structure. + struct stat st; + + private: + DLL_PRIVATE void refreshStat(const std::filesystem::path & path); }; /** * Extension to FileHandle to automatically memmaps the file. */ class DLL_PUBLIC MemMap : public FileHandleStat { - public: - /** - * Move constructor. - */ - MemMap(MemMap &&) noexcept = default; - - /** - * Construct from an existing file descriptor. - * @param fd An open file descriptor. - * @param flags File handle flags - */ - explicit MemMap(int fd, int flags = O_RDONLY); - - /** - * Open a new file handle (with the default flags). - * @param path Path of file to open. - * @param flags File handle flags - */ - explicit MemMap(const std::filesystem::path & path, int flags = O_RDONLY); - - /** - * Open a new file handle. - * @param path Path of file to open. - * @param flags File handle flags - * @param mode File handle mode - */ - MemMap(const std::filesystem::path & path, int flags, int mode); - - ~MemMap() override; - - /// Standard move/copy support - SPECIAL_MEMBERS_COPY(MemMap, delete); - - MemMap & operator=(MemMap &&) = delete; - - /// The file data. - const void * const data; + public: + /** + * Move constructor. + */ + MemMap(MemMap &&) noexcept = default; + + /** + * Construct from an existing file descriptor. + * @param fd An open file descriptor. + * @param flags File handle flags + */ + explicit MemMap(int fd, int flags = O_RDONLY); + + /** + * Open a new file handle (with the default flags). + * @param path Path of file to open. + * @param flags File handle flags + */ + explicit MemMap(const std::filesystem::path & path, int flags = O_RDONLY); + + /** + * Open a new file handle. + * @param path Path of file to open. + * @param flags File handle flags + * @param mode File handle mode + */ + MemMap(const std::filesystem::path & path, int flags, int mode); + + ~MemMap() override; + + /// Standard move/copy support + SPECIAL_MEMBERS_COPY(MemMap, delete); + + MemMap & operator=(MemMap &&) = delete; + + /// The file data. + const void * const data; #ifdef __cpp_lib_string_view - /** - * Create a std::string_view of the mapped data. - */ - template - [[nodiscard]] auto sv() const - { - return std::basic_string_view((const T *)data, st.st_size / sizeof(T)); - } + /** + * Create a std::string_view of the mapped data. + */ + template + [[nodiscard]] auto + sv() const + { + return std::basic_string_view((const T *)data, st.st_size / sizeof(T)); + } #endif - private: - [[nodiscard]] DLL_PRIVATE void * setupMapInt(int flags) const; - [[nodiscard]] DLL_PRIVATE void * setupMap(int flags) const; - [[nodiscard]] DLL_PRIVATE void * setupMap(const std::filesystem::path & path, int flags) const; + private: + [[nodiscard]] DLL_PRIVATE void * setupMapInt(int flags) const; + [[nodiscard]] DLL_PRIVATE void * setupMap(int flags) const; + [[nodiscard]] DLL_PRIVATE void * setupMap(const std::filesystem::path & path, int flags) const; }; } } #endif - - diff --git a/libadhocutil/fprintbf.cpp b/libadhocutil/fprintbf.cpp index d46b211..db907bd 100644 --- a/libadhocutil/fprintbf.cpp +++ b/libadhocutil/fprintbf.cpp @@ -31,4 +31,3 @@ fopen(const std::filesystem::path & path, const char * mode) } return f; } - diff --git a/libadhocutil/fprintbf.h b/libadhocutil/fprintbf.h index 15366d2..63cba62 100644 --- a/libadhocutil/fprintbf.h +++ b/libadhocutil/fprintbf.h @@ -1,8 +1,8 @@ #ifndef ADHOCUTIL_FPRINTBF_H #define ADHOCUTIL_FPRINTBF_H -#include "visibility.h" #include "buffer.h" +#include "visibility.h" #include #include @@ -12,19 +12,17 @@ DLL_PUBLIC size_t fprintbf(FILE *, const boost::format &); DLL_PUBLIC FILE * fopen(const std::filesystem::path & path, const char * mode); -template -size_t inline fprintbf(FILE * f, const std::string & fmt, const Params & ... p) +template size_t inline fprintbf(FILE * f, const std::string & fmt, const Params &... p) { auto bf = AdHoc::Buffer::getFormat(fmt); return fprintbf(f, bf, p...); } -template -size_t inline fprintbf(FILE * f, boost::format & fmt, const Param & p, const Params & ... ps) +template +size_t inline fprintbf(FILE * f, boost::format & fmt, const Param & p, const Params &... ps) { fmt % p; return fprintbf(f, fmt, ps...); } #endif - diff --git a/libadhocutil/globalStatic.h b/libadhocutil/globalStatic.h index 3639237..f2443cb 100644 --- a/libadhocutil/globalStatic.h +++ b/libadhocutil/globalStatic.h @@ -8,23 +8,21 @@ namespace AdHoc { * Wrapper class for initialising/destroying a global static object via * __attribute__ constructor/destructor. */ - template - class GlobalStatic { - public: - /** - * Get the contained object. - * @return The object. - */ - static Object * get(); + template class GlobalStatic { + public: + /** + * Get the contained object. + * @return The object. + */ + static Object * get(); - private: - using Ptr = Object *; - static void createObject() __attribute__((constructor(101))); - static void deleteObject() __attribute__((destructor(101))); + private: + using Ptr = Object *; + static void createObject() __attribute__((constructor(101))); + static void deleteObject() __attribute__((destructor(101))); - inline static Ptr & instance(); + inline static Ptr & instance(); }; } #endif - diff --git a/libadhocutil/globalStatic.impl.h b/libadhocutil/globalStatic.impl.h index 13f2f72..ba121d1 100644 --- a/libadhocutil/globalStatic.impl.h +++ b/libadhocutil/globalStatic.impl.h @@ -5,26 +5,30 @@ namespace AdHoc { template - Object * GlobalStatic::get() + Object * + GlobalStatic::get() { return instance(); } template - void GlobalStatic::createObject() + void + GlobalStatic::createObject() { instance() = new Object(); } template - void GlobalStatic::deleteObject() + void + GlobalStatic::deleteObject() { delete instance(); instance() = nullptr; } template - typename GlobalStatic::Ptr & GlobalStatic::instance() + typename GlobalStatic::Ptr & + GlobalStatic::instance() { static Ptr _instance; return _instance; @@ -32,4 +36,3 @@ namespace AdHoc { }; #endif - diff --git a/libadhocutil/handle.h b/libadhocutil/handle.h index 7363183..a71859d 100644 --- a/libadhocutil/handle.h +++ b/libadhocutil/handle.h @@ -1,88 +1,110 @@ #ifndef ADHOCUTIL_HANDLE_H #define ADHOCUTIL_HANDLE_H -#include #include "c++11Helpers.h" +#include namespace AdHoc { /// A unique_ptr like construct for non-pointer objects. /// Implements RAII. - template - class Handle { - public: - /// Constructs a Handle that owns t, to be tidied with d - Handle(T t, D d) noexcept : - inst(std::move(t)), - deleter(std::move(d)), - owning(true) - { - } + template class Handle { + public: + /// Constructs a Handle that owns t, to be tidied with d + Handle(T t, D d) noexcept : inst(std::move(t)), deleter(std::move(d)), owning(true) { } - /// Constructs a Handle that takes over ownership of h - Handle(Handle && h) noexcept : - inst(std::move(h.inst)), - deleter(std::move(h.deleter)), - owning(h.owning) - { - h.owning = false; - } + /// Constructs a Handle that takes over ownership of h + Handle(Handle && h) noexcept : inst(std::move(h.inst)), deleter(std::move(h.deleter)), owning(h.owning) + { + h.owning = false; + } - ~Handle() - { - if (owning) { - deleter(inst); - } + ~Handle() + { + if (owning) { + deleter(inst); } + } - /// Standard special members - SPECIAL_MEMBERS_COPY(Handle, delete); + /// Standard special members + SPECIAL_MEMBERS_COPY(Handle, delete); - /// Takes over ownership of h - Handle & operator=(Handle && h) noexcept - { - if (owning) { - deleter(inst); - } - inst = std::move(h.inst); - deleter = std::move(h.deleter); - owning = h.owning; - h.owning = false; + /// Takes over ownership of h + Handle & + operator=(Handle && h) noexcept + { + if (owning) { + deleter(inst); } + inst = std::move(h.inst); + deleter = std::move(h.deleter); + owning = h.owning; + h.owning = false; + } - /// Returns a reference to the managed object. - [[nodiscard]] T & get() noexcept { return inst; } - /// Returns a const reference to the managed object. - [[nodiscard]] const T & get() const noexcept { return inst; } + /// Returns a reference to the managed object. + [[nodiscard]] T & + get() noexcept + { + return inst; + } + /// Returns a const reference to the managed object. + [[nodiscard]] const T & + get() const noexcept + { + return inst; + } - /// Returns a pointer to the managed object. - [[nodiscard]] T * operator->() noexcept { return inst; } - /// Returns a const pointer to the managed object. - [[nodiscard]] const T * operator->() const noexcept { return inst; } + /// Returns a pointer to the managed object. + [[nodiscard]] T * + operator->() noexcept + { + return inst; + } + /// Returns a const pointer to the managed object. + [[nodiscard]] const T * + operator->() const noexcept + { + return inst; + } - /// Returns a reference to the managed object. - [[nodiscard]] T & operator*() noexcept { return inst; } - /// Returns a const reference to the managed object. - [[nodiscard]] const T & operator*() const noexcept { return inst; } + /// Returns a reference to the managed object. + [[nodiscard]] T & + operator*() noexcept + { + return inst; + } + /// Returns a const reference to the managed object. + [[nodiscard]] const T & + operator*() const noexcept + { + return inst; + } - /// Returns a reference to the managed object. - // NOLINTNEXTLINE(hicpp-explicit-conversions) - operator T &() noexcept { return inst; } - /// Returns a const reference to the managed object. - // NOLINTNEXTLINE(hicpp-explicit-conversions) - operator const T &() const noexcept { return inst; } + /// Returns a reference to the managed object. + // NOLINTNEXTLINE(hicpp-explicit-conversions) + operator T &() noexcept + { + return inst; + } + /// Returns a const reference to the managed object. + // NOLINTNEXTLINE(hicpp-explicit-conversions) + operator const T &() const noexcept + { + return inst; + } - private: - T inst; - D deleter; - bool owning; + private: + T inst; + D deleter; + bool owning; }; template - Handle make_handle(D && d, Args && ... args) + Handle + make_handle(D && d, Args &&... args) { - return { T(std::forward(args)...), std::forward(d) }; + return {T(std::forward(args)...), std::forward(d)}; } } #endif - diff --git a/libadhocutil/lazyPointer.h b/libadhocutil/lazyPointer.h index 9188d24..667d321 100644 --- a/libadhocutil/lazyPointer.h +++ b/libadhocutil/lazyPointer.h @@ -2,21 +2,20 @@ #define ADHOCUTIL_LAZYPOINTER_H #include -#include #include #include +#include namespace AdHoc { -/// Smart pointer that initializes itself only if it has to. -/** - * LazyPointer behaves like a normal smarter for the most part. It's benefit - * is that it can be assigned a factory function which is only called on - * an attempt to dereference the pointer. All such operations will call - * this factory function as required prior to evaluating the pointer's value. - */ -template > -class LazyPointer { + /// Smart pointer that initializes itself only if it has to. + /** + * LazyPointer behaves like a normal smarter for the most part. It's benefit + * is that it can be assigned a factory function which is only called on + * an attempt to dereference the pointer. All such operations will call + * this factory function as required prior to evaluating the pointer's value. + */ + template> class LazyPointer { public: /// @cond using element_type = T; @@ -27,23 +26,14 @@ class LazyPointer { /** Construct pointer with a factory function. */ // NOLINTNEXTLINE(hicpp-explicit-conversions) - LazyPointer(Factory f) : - source(f) - { - } + LazyPointer(Factory f) : source(f) { } /** Construct pointer with an instance value. */ // NOLINTNEXTLINE(hicpp-explicit-conversions) - LazyPointer(P p) : - source(p) - { - } + LazyPointer(P p) : source(p) { } /** Construct pointer with no factory or value. */ - LazyPointer() : - source(P(NULL)) - { - } + LazyPointer() : source(P(NULL)) { } // Getters /// @cond @@ -52,17 +42,20 @@ class LazyPointer { return deref(); } - [[nodiscard]] T * operator->() const + [[nodiscard]] T * + operator->() const { return get(); } - [[nodiscard]] T & operator*() const + [[nodiscard]] T & + operator*() const { return *get(); } - [[nodiscard]] T * get() const + [[nodiscard]] T * + get() const { if constexpr (std::is_pointer

::value) { return deref(); @@ -72,7 +65,8 @@ class LazyPointer { } } - [[nodiscard]] P deref() const + [[nodiscard]] P + deref() const { if (Factory * f = std::get_if(&source)) { P p = (*f)(); @@ -84,7 +78,8 @@ class LazyPointer { } } - bool operator!() const + bool + operator!() const { return get() == nullptr; } @@ -94,30 +89,35 @@ class LazyPointer { return get() != nullptr; } - bool operator==(const P & o) const + bool + operator==(const P & o) const { return (deref() == o); } - bool operator==(const T * o) const + bool + operator==(const T * o) const { return (deref().get() == o); } // Setters - LazyPointer & operator=(const P & p) + LazyPointer & + operator=(const P & p) { source = p; return *this; } - LazyPointer & operator=(T * t) + LazyPointer & + operator=(T * t) { source = P(t); return *this; } - LazyPointer & operator=(const Factory & f) + LazyPointer & + operator=(const Factory & f) { source = f; return *this; @@ -125,22 +125,24 @@ class LazyPointer { /// @endcond /** Does the lazy pointer have a value? (as opposed to a factory). */ - bool hasValue() const + bool + hasValue() const { return std::get_if

(&source); } private: mutable Source source; -}; + }; } namespace boost { - template - R * dynamic_pointer_cast(const AdHoc::LazyPointer & p) { - return dynamic_cast(p.get()); - } + template + R * + dynamic_pointer_cast(const AdHoc::LazyPointer & p) + { + return dynamic_cast(p.get()); + } } #endif - diff --git a/libadhocutil/lexer-regex.cpp b/libadhocutil/lexer-regex.cpp index 669bd16..7a490c5 100644 --- a/libadhocutil/lexer-regex.cpp +++ b/libadhocutil/lexer-regex.cpp @@ -2,72 +2,72 @@ namespace AdHoc::LexerMatchers { class Regex : public Lexer::Pattern { - public: - Regex(const Glib::ustring & pattern, GRegexCompileFlags compile, GRegexMatchFlags match) : - err(nullptr), - regex(g_regex_new(pattern.c_str(), compile, match, &err)), - info(nullptr), - str(nullptr) - { - if (!regex) { - auto msg = std::string("Failed to create GRegex: ") + err->message; - g_error_free(err); - throw std::runtime_error(msg); - } + public: + Regex(const Glib::ustring & pattern, GRegexCompileFlags compile, GRegexMatchFlags match) : + err(nullptr), regex(g_regex_new(pattern.c_str(), compile, match, &err)), info(nullptr), str(nullptr) + { + if (!regex) { + auto msg = std::string("Failed to create GRegex: ") + err->message; + g_error_free(err); + throw std::runtime_error(msg); } + } - SPECIAL_MEMBERS_DELETE(Regex); + SPECIAL_MEMBERS_DELETE(Regex); - ~Regex() override - { - if (err) { - g_error_free(err); - } - if (info) { - g_match_info_free(info); - } - g_regex_unref(regex); + ~Regex() override + { + if (err) { + g_error_free(err); } - - bool matches(const gchar * string, size_t length, size_t position) const override - { - if (info) { - g_match_info_free(info); - } - g_regex_match_full(regex, string, length, position, G_REGEX_MATCH_ANCHORED, &info, &err); - if (err) { - auto msg = std::string("Failed to create GRegex: ") + err->message; - g_error_free(err); - throw std::runtime_error(msg); - } - str = string; - return g_match_info_matches(info); + if (info) { + g_match_info_free(info); } + g_regex_unref(regex); + } - size_t matchedLength() const override - { - gint start, end; - g_match_info_fetch_pos(info, 0, &start, &end); - return end - start; + bool + matches(const gchar * string, size_t length, size_t position) const override + { + if (info) { + g_match_info_free(info); + } + g_regex_match_full(regex, string, length, position, G_REGEX_MATCH_ANCHORED, &info, &err); + if (err) { + auto msg = std::string("Failed to create GRegex: ") + err->message; + g_error_free(err); + throw std::runtime_error(msg); } + str = string; + return g_match_info_matches(info); + } - std::optional match(int n) const override - { - gint start, end; - if (g_match_info_fetch_pos(info, n, &start, &end)) { - if (start == -1 && end == -1) { - return {}; - } - return Glib::ustring(str + start, str + end); + size_t + matchedLength() const override + { + gint start, end; + g_match_info_fetch_pos(info, 0, &start, &end); + return end - start; + } + + std::optional + match(int n) const override + { + gint start, end; + if (g_match_info_fetch_pos(info, n, &start, &end)) { + if (start == -1 && end == -1) { + return {}; } - return {}; + return Glib::ustring(str + start, str + end); } + return {}; + } - private: - mutable GError * err; - GRegex * regex; - mutable GMatchInfo * info; - mutable const gchar * str; + private: + mutable GError * err; + GRegex * regex; + mutable GMatchInfo * info; + mutable const gchar * str; }; Lexer::PatternPtr @@ -76,4 +76,3 @@ namespace AdHoc::LexerMatchers { return std::make_shared(pattern, compile, match); } } - diff --git a/libadhocutil/lexer-regex.h b/libadhocutil/lexer-regex.h index 5a141b9..8777418 100644 --- a/libadhocutil/lexer-regex.h +++ b/libadhocutil/lexer-regex.h @@ -12,9 +12,9 @@ namespace AdHoc { * @param match The regex match flags. * @return Pointer to the newly created pattern matcher. */ - DLL_PUBLIC Lexer::PatternPtr regex(const Glib::ustring & regex, GRegexCompileFlags compile = (GRegexCompileFlags)0, GRegexMatchFlags match = (GRegexMatchFlags)0); + DLL_PUBLIC Lexer::PatternPtr regex(const Glib::ustring & regex, + GRegexCompileFlags compile = (GRegexCompileFlags)0, GRegexMatchFlags match = (GRegexMatchFlags)0); } }; #endif - diff --git a/libadhocutil/lexer.cpp b/libadhocutil/lexer.cpp index 542a55f..6d16a46 100644 --- a/libadhocutil/lexer.cpp +++ b/libadhocutil/lexer.cpp @@ -6,9 +6,7 @@ namespace AdHoc { Lexer::Lexer() = default; - Lexer::Lexer(Rules r) : rules(std::move(r)) - { - } + Lexer::Lexer(Rules r) : rules(std::move(r)) { } AdHocFormatter(UnexpectedInputState, "Unexpected input in state (%?) at %?"); void @@ -85,4 +83,3 @@ namespace AdHoc { return pat; } } - diff --git a/libadhocutil/lexer.h b/libadhocutil/lexer.h index a32f3b1..5545525 100644 --- a/libadhocutil/lexer.h +++ b/libadhocutil/lexer.h @@ -1,95 +1,94 @@ #ifndef ADHOCUTIL_LEXER_H #define ADHOCUTIL_LEXER_H -#include -#include -#include -#include +#include "c++11Helpers.h" +#include "visibility.h" #include +#include #include #include -#include "visibility.h" -#include "c++11Helpers.h" +#include +#include +#include namespace AdHoc { /// An extensible lexer. class DLL_PUBLIC Lexer { + public: + /// Pattern matcher interface. + class Pattern { public: - /// Pattern matcher interface. - class Pattern { - public: - Pattern() = default; - virtual ~Pattern() = default; - /// Standard move/copy support - SPECIAL_MEMBERS_DEFAULT(Pattern); + Pattern() = default; + virtual ~Pattern() = default; + /// Standard move/copy support + SPECIAL_MEMBERS_DEFAULT(Pattern); - /// Test the pattern against the given input. - [[nodiscard]] virtual bool matches(const gchar *, size_t, size_t) const = 0; - /// Get the total amount of input matched. - [[nodiscard]] virtual size_t matchedLength() const = 0; - /// Get an extracted value from the pattern. - [[nodiscard]] virtual std::optional match(int) const = 0; - }; - /// Smart pointer to Pattern. - using PatternPtr = std::shared_ptr; - /// Lexer state identifiers. - using State = std::string; - /// Collection of States. - using States = std::set; + /// Test the pattern against the given input. + [[nodiscard]] virtual bool matches(const gchar *, size_t, size_t) const = 0; + /// Get the total amount of input matched. + [[nodiscard]] virtual size_t matchedLength() const = 0; + /// Get an extracted value from the pattern. + [[nodiscard]] virtual std::optional match(int) const = 0; + }; + /// Smart pointer to Pattern. + using PatternPtr = std::shared_ptr; + /// Lexer state identifiers. + using State = std::string; + /// Collection of States. + using States = std::set; - /// Class representing the runtime execution of the lexer. - class ExecuteState { - public: - /// Default constructor. - ExecuteState(); + /// Class representing the runtime execution of the lexer. + class ExecuteState { + public: + /// Default constructor. + ExecuteState(); - /// Push a new state to the stack. - void pushState(const State &); - /// Pop the top of the state stack off. - void popState(); - /// Replace the current top of the state stack. - void setState(const State &); - /// Get the current state. - [[nodiscard]] const State & getState() const; - /// Get the state stack depth. - [[nodiscard]] size_t depth() const; - /// Get the current position. - [[nodiscard]] size_t position() const; - /// Get the currently matched pattern. - [[nodiscard]] PatternPtr pattern() const; + /// Push a new state to the stack. + void pushState(const State &); + /// Pop the top of the state stack off. + void popState(); + /// Replace the current top of the state stack. + void setState(const State &); + /// Get the current state. + [[nodiscard]] const State & getState() const; + /// Get the state stack depth. + [[nodiscard]] size_t depth() const; + /// Get the current position. + [[nodiscard]] size_t position() const; + /// Get the currently matched pattern. + [[nodiscard]] PatternPtr pattern() const; - private: - friend class Lexer; - size_t pos { 0 }; - PatternPtr pat; + private: + friend class Lexer; + size_t pos {0}; + PatternPtr pat; - std::vector stateStack; - }; + std::vector stateStack; + }; - /// Callback for handling matched patterns. - using Handler = std::function; - /** - * Rule definition: - * States: in which states should the rule be considered? - * Pattern: the pattern matcher to test against the input. - * Handler: the callback to execute when a match succeeds. - */ - using Rule = std::tuple; - /// Collection of Rules that make up the lexer configuration. - using Rules = std::vector; - /// The initial state of applied to the lexer. - static const State InitialState; - /// Default constructor (empty rule set) - Lexer(); - /// Construct with an initial set of rules. - explicit Lexer(Rules); - /// The lexer's current rule set. - Rules rules; + /// Callback for handling matched patterns. + using Handler = std::function; + /** + * Rule definition: + * States: in which states should the rule be considered? + * Pattern: the pattern matcher to test against the input. + * Handler: the callback to execute when a match succeeds. + */ + using Rule = std::tuple; + /// Collection of Rules that make up the lexer configuration. + using Rules = std::vector; + /// The initial state of applied to the lexer. + static const State InitialState; + /// Default constructor (empty rule set) + Lexer(); + /// Construct with an initial set of rules. + explicit Lexer(Rules); + /// The lexer's current rule set. + Rules rules; - /// Execute the lexer to extract matches for the current rules. - void extract(const gchar * string, size_t length) const; + /// Execute the lexer to extract matches for the current rules. + void extract(const gchar * string, size_t length) const; }; } #endif - diff --git a/libadhocutil/lockHelpers.h b/libadhocutil/lockHelpers.h index 3e2a208..4bb285b 100644 --- a/libadhocutil/lockHelpers.h +++ b/libadhocutil/lockHelpers.h @@ -1,12 +1,12 @@ #ifndef ADHOCUTIL_LOCKHELPERS_H #define ADHOCUTIL_LOCKHELPERS_H -#define LIBADHOC_LOCK_CONCAT2(a, b) a ## b +#define LIBADHOC_LOCK_CONCAT2(a, b) a##b #define LIBADHOC_LOCK_CONCAT(a, b) LIBADHOC_LOCK_CONCAT2(a, b) -#define LIBADHOC_LOCK_WITHLINE(a) LIBADHOC_LOCK_CONCAT(a, __LINE__) +#define LIBADHOC_LOCK_WITHLINE(a) LIBADHOC_LOCK_CONCAT(a, __LINE__) -#define BaseLock(l,lt) lt LIBADHOC_LOCK_WITHLINE(_lck)(l) -#define BaseScopeLock(l,lt) if (auto LIBADHOC_LOCK_WITHLINE(_lck) = lt(l)) +#define BaseLock(l, lt) lt LIBADHOC_LOCK_WITHLINE(_lck)(l) +#define BaseScopeLock(l, lt) if (auto LIBADHOC_LOCK_WITHLINE(_lck) = lt(l)) #define Lock(l) BaseLock(l, std::unique_lock) #define SharedLock(l) BaseLock(l, std::shared_lock) @@ -15,4 +15,3 @@ #define SharedScopeLock(l) BaseScopeLock(l, std::shared_lock) #endif - diff --git a/libadhocutil/memstream.cpp b/libadhocutil/memstream.cpp index 4c83c14..282c5f7 100644 --- a/libadhocutil/memstream.cpp +++ b/libadhocutil/memstream.cpp @@ -1,12 +1,11 @@ #include "memstream.h" -#include #include +#include #include #include namespace AdHoc { - MemStream::MemStream() : - strm(open_memstream(&buf, &len)) + MemStream::MemStream() : strm(open_memstream(&buf, &len)) { if (!strm) { // LCOV_EXCL_START no sensible way to make open_memstream fail @@ -15,10 +14,7 @@ namespace AdHoc { } } - MemStream::MemStream(MemStream && o) noexcept : - buf(o.buf), - len(o.len), - strm(o.strm) + MemStream::MemStream(MemStream && o) noexcept : buf(o.buf), len(o.len), strm(o.strm) { o.buf = nullptr; o.len = 0; @@ -34,7 +30,8 @@ namespace AdHoc { free(buf); } - MemStream & MemStream::operator=(MemStream && o) noexcept + MemStream & + MemStream::operator=(MemStream && o) noexcept { if (strm) { fclose(strm); @@ -53,36 +50,38 @@ namespace AdHoc { return *this; } - MemStream::operator FILE * () noexcept + MemStream::operator FILE *() noexcept { return strm; } - MemStream::operator const char * () const noexcept + MemStream::operator const char *() const noexcept { return buffer(); } MemStream::operator std::string_view() const noexcept { - return { buffer(), len }; + return {buffer(), len}; } - const char * MemStream::buffer() const noexcept + const char * + MemStream::buffer() const noexcept { fflush(strm); return buf; } - std::string_view MemStream::sv() const noexcept + std::string_view + MemStream::sv() const noexcept { - return { buffer(), len }; + return {buffer(), len}; } - size_t MemStream::length() const noexcept + size_t + MemStream::length() const noexcept { fflush(strm); return len; } } - diff --git a/libadhocutil/memstream.h b/libadhocutil/memstream.h index 4f9d280..43a06fb 100644 --- a/libadhocutil/memstream.h +++ b/libadhocutil/memstream.h @@ -1,52 +1,51 @@ #ifndef LIBADHOC_MEMSTREAM_H #define LIBADHOC_MEMSTREAM_H -#include +#include "c++11Helpers.h" #include #include -#include "c++11Helpers.h" +#include namespace AdHoc { /** * Wrapper around open_memstream(3) */ class DLL_PUBLIC MemStream { - public: - MemStream(); - ~MemStream(); - - /// Standard move/copy support - SPECIAL_MEMBERS_COPY(MemStream, delete); - - /// Standard move constructor - MemStream(MemStream &&) noexcept; - - /// Standard move assignment - MemStream & operator=(MemStream &&) noexcept; - - /// Implicit conversion to use as FILE* for writes - // NOLINTNEXTLINE(hicpp-explicit-conversions) - operator FILE * () noexcept; - /// Implicit conversion to use as const char * for reads - // NOLINTNEXTLINE(hicpp-explicit-conversions) - operator const char * () const noexcept; - /// Implicit conversion to use as std::string_view for reads - // NOLINTNEXTLINE(hicpp-explicit-conversions) - operator std::string_view () const noexcept; - - /// Get buffer contents - [[nodiscard]] const char * buffer() const noexcept; - /// Get buffer contents view - [[nodiscard]] std::string_view sv() const noexcept; - /// Get buffer length - [[nodiscard]] size_t length() const noexcept; - - private: - char * buf { nullptr }; - size_t len { 0 }; - FILE * strm; + public: + MemStream(); + ~MemStream(); + + /// Standard move/copy support + SPECIAL_MEMBERS_COPY(MemStream, delete); + + /// Standard move constructor + MemStream(MemStream &&) noexcept; + + /// Standard move assignment + MemStream & operator=(MemStream &&) noexcept; + + /// Implicit conversion to use as FILE* for writes + // NOLINTNEXTLINE(hicpp-explicit-conversions) + operator FILE *() noexcept; + /// Implicit conversion to use as const char * for reads + // NOLINTNEXTLINE(hicpp-explicit-conversions) + operator const char *() const noexcept; + /// Implicit conversion to use as std::string_view for reads + // NOLINTNEXTLINE(hicpp-explicit-conversions) + operator std::string_view() const noexcept; + + /// Get buffer contents + [[nodiscard]] const char * buffer() const noexcept; + /// Get buffer contents view + [[nodiscard]] std::string_view sv() const noexcept; + /// Get buffer length + [[nodiscard]] size_t length() const noexcept; + + private: + char * buf {nullptr}; + size_t len {0}; + FILE * strm; }; } #endif - diff --git a/libadhocutil/nagios.cpp b/libadhocutil/nagios.cpp index 749e118..2007e7f 100644 --- a/libadhocutil/nagios.cpp +++ b/libadhocutil/nagios.cpp @@ -9,7 +9,8 @@ namespace AdHoc { /// LCOV_EXCL_START (calls real Nagios) bool - submitNagiosPassiveServiceCheck(const std::string_view & svc, NagiosStatusCode code, const std::string_view & output) + submitNagiosPassiveServiceCheck( + const std::string_view & svc, NagiosStatusCode code, const std::string_view & output) { std::ofstream command_file("/var/nagios/rw/nagios.cmd"); return submitNagiosPassiveServiceCheck(command_file, svc, code, output); @@ -17,11 +18,12 @@ namespace AdHoc { /// LCOV_EXCL_STOP bool - submitNagiosPassiveServiceCheck(std::ostream & command_file, const std::string_view & svc, - NagiosStatusCode code, const std::string_view & output) + submitNagiosPassiveServiceCheck(std::ostream & command_file, const std::string_view & svc, NagiosStatusCode code, + const std::string_view & output) { if (command_file.good()) { - struct utsname buf {}; + struct utsname buf { + }; uname(&buf); NagiosPassiveServiceCheck::write(command_file, time(nullptr), buf.nodename, svc, (uint8_t)code, output); command_file.flush(); @@ -29,4 +31,3 @@ namespace AdHoc { return command_file.good(); } } - diff --git a/libadhocutil/nagios.h b/libadhocutil/nagios.h index 144c27a..b6b140b 100644 --- a/libadhocutil/nagios.h +++ b/libadhocutil/nagios.h @@ -13,11 +13,10 @@ namespace AdHoc { Unknown = 3, }; - DLL_PUBLIC bool submitNagiosPassiveServiceCheck(const std::string_view &, - NagiosStatusCode, const std::string_view &); - DLL_PUBLIC bool submitNagiosPassiveServiceCheck(std::ostream &, const std::string_view &, - NagiosStatusCode, const std::string_view &); + DLL_PUBLIC bool submitNagiosPassiveServiceCheck( + const std::string_view &, NagiosStatusCode, const std::string_view &); + DLL_PUBLIC bool submitNagiosPassiveServiceCheck( + std::ostream &, const std::string_view &, NagiosStatusCode, const std::string_view &); } #endif - diff --git a/libadhocutil/nvpParse.h b/libadhocutil/nvpParse.h index bc06fbe..fe943dc 100644 --- a/libadhocutil/nvpParse.h +++ b/libadhocutil/nvpParse.h @@ -1,77 +1,77 @@ #ifndef ADHOCUTIL_REFLECTION_H #define ADHOCUTIL_REFLECTION_H -#include -#include -#include +#include #include +#include +#include #include -#include +#include #ifndef yyFlexLexer -#define yyFlexLexer nvpBaseFlexLexer -#include +# define yyFlexLexer nvpBaseFlexLexer +# include #endif -#include "visibility.h" #include "c++11Helpers.h" +#include "visibility.h" namespace AdHoc { -/// Name=Value parser. -/** - * Parses an input stream of the format Name=Value;Name2=Value2;... into a predefined object - * structure. - */ -class NvpParse : public yyFlexLexer { + /// Name=Value parser. + /** + * Parses an input stream of the format Name=Value;Name2=Value2;... into a predefined object + * structure. + */ + class NvpParse : public yyFlexLexer { public: /// @cond /// Thrown in the event of the input referring to a member that doesn't exist. class ValueNotFound : public std::runtime_error { - public: - explicit ValueNotFound(const std::string &); + public: + explicit ValueNotFound(const std::string &); }; using AssignFunc = std::function; using AssignMap = std::map; - template - class TargetBase { - public: - TargetBase() = default; - virtual ~TargetBase() = default; - virtual AssignFunc assign(T *) const = 0; - SPECIAL_MEMBERS_DEFAULT(TargetBase); + template class TargetBase { + public: + TargetBase() = default; + virtual ~TargetBase() = default; + virtual AssignFunc assign(T *) const = 0; + SPECIAL_MEMBERS_DEFAULT(TargetBase); }; - template - class Target : public TargetBase { - public: - explicit Target(V T::*t) : - target(t) - { - } - - AssignFunc assign(T * t) const override - { - return [t,this](const std::string & value) { - t->*target = boost::lexical_cast(value); - }; - } - - private: - V T::*target; + template class Target : public TargetBase { + public: + explicit Target(V T::*t) : target(t) { } + + AssignFunc + assign(T * t) const override + { + return [t, this](const std::string & value) { + t->*target = boost::lexical_cast(value); + }; + } + + private: + V T::*target; }; /// @endcond #define NvpTarget(T) std::map>> -#define NvpValue(c, m) { #m, std::make_shared<::AdHoc::NvpParse::Target>(&c::m) } +#define NvpValue(c, m) \ + { \ +# m, std::make_shared < ::AdHoc::NvpParse::Target < c, decltype(c::m)>>(&c::m) \ + } /** Parse an input stream into the given object. * @param in The input stream. * @param tm The Target Map for the object. * @param t The target instance to populate. */ - template - static void parse(std::istream & in, const NvpTarget(T) & tm, T & t) + template + static void + parse(std::istream & in, const NvpTarget(T) & tm, T & t) { NvpParse::AssignMap am; for (const auto & v : tm) { @@ -94,9 +94,8 @@ class NvpParse : public yyFlexLexer { void process(const std::string & value) const; std::string name; const AssignMap values; -}; + }; } #endif - diff --git a/libadhocutil/optionalUtils.h b/libadhocutil/optionalUtils.h index f4d6b1a..0ba3cb7 100644 --- a/libadhocutil/optionalUtils.h +++ b/libadhocutil/optionalUtils.h @@ -4,27 +4,23 @@ #include namespace AdHoc { - template + template auto - operator/(const A & a, const B & b) -> typename std::enable_if< - std::is_constructible::value && - !std::is_pointer::value && - std::is_convertible::value, - decltype(a ? *a : b)>::type + operator/(const A & a, const B & b) -> typename std::enable_if::value + && !std::is_pointer::value && std::is_convertible::value, + decltype(a ? *a : b)>::type { return (a ? *a : b); } - template + template auto - operator/(const A & a, const B & b) -> typename std::enable_if< - std::is_constructible::value && - std::is_pointer::value, - decltype(a ? &*a : b)>::type + operator/(const A & a, const B & b) -> + typename std::enable_if::value && std::is_pointer::value, + decltype(a ? &*a : b)>::type { return (a ? &*a : b); } } #endif - diff --git a/libadhocutil/plugins.cpp b/libadhocutil/plugins.cpp index 86dc2c5..8c8f1b5 100644 --- a/libadhocutil/plugins.cpp +++ b/libadhocutil/plugins.cpp @@ -1,14 +1,14 @@ #include "plugins.h" -#include -#include -#include -#include -#include -#include -#include #include "compileTimeFormatter.h" #include "globalStatic.impl.h" +#include +#include +#include +#include +#include +#include #include +#include namespace std { bool @@ -20,7 +20,8 @@ namespace std { std::ostream & operator<<(std::ostream & s, const std::type_info & t) { - auto buf = std::unique_ptr(__cxxabiv1::__cxa_demangle(t.name(), nullptr, nullptr, nullptr), std::free); + auto buf = std::unique_ptr( + __cxxabiv1::__cxa_demangle(t.name(), nullptr, nullptr, nullptr), std::free); s << buf.get(); return s; } @@ -31,12 +32,7 @@ namespace AdHoc { AbstractPluginImplementation::~AbstractPluginImplementation() = default; - Plugin::Plugin(const std::string_view & n, const std::string_view & f, int l) : - name(n), - filename(f), - lineno(l) - { - } + Plugin::Plugin(const std::string_view & n, const std::string_view & f, int l) : name(n), filename(f), lineno(l) { } AdHocFormatter(NoSuchPluginExceptionMsg, "No such plugin: %? of type %?"); NoSuchPluginException::NoSuchPluginException(const std::string_view & n, const std::type_info & t) : @@ -47,7 +43,7 @@ namespace AdHoc { AdHocFormatter(DuplicatePluginExceptionMsg, "Duplicate plugin %? for type %? at %?:%?, originally from %?:%?"); DuplicatePluginException::DuplicatePluginException(const PluginPtr & p1, const PluginPtr & p2) : std::runtime_error(DuplicatePluginExceptionMsg::get( - p1->name, p1->type(), p2->filename, p2->lineno, p1->filename, p1->lineno)) + p1->name, p1->type(), p2->filename, p2->lineno, p1->filename, p1->lineno)) { } @@ -63,25 +59,26 @@ namespace AdHoc { { } - class PluginManager::PluginStore : public boost::multi_index_container, std::less<>>, - boost::multi_index::ordered_non_unique>, + class PluginManager::PluginStore : + public boost::multi_index_container, std::less<>>, + boost::multi_index::ordered_non_unique< + boost::multi_index::const_mem_fun>, boost::multi_index::ordered_unique< - boost::multi_index::composite_key< - Plugin, - boost::multi_index::member, - boost::multi_index::const_mem_fun - >, std::less<>> - >> - { + boost::multi_index::composite_key, + boost::multi_index::const_mem_fun>, + std::less<>>>> { }; - class PluginManager::TypePluginResolvers : public std::map { }; + class PluginManager::TypePluginResolvers : public std::map { + }; PluginManager::PluginManager() : - plugins(std::make_unique()), - resolvers(std::make_unique()) + plugins(std::make_unique()), resolvers(std::make_unique()) { } @@ -140,14 +137,14 @@ namespace AdHoc { std::set PluginManager::getAll() const { - return { plugins->begin(), plugins->end() }; + return {plugins->begin(), plugins->end()}; } std::set PluginManager::getAll(const std::type_info & t) const { auto r = plugins->get<1>().equal_range(t); - return { r.first, r.second }; + return {r.first, r.second}; } size_t @@ -177,4 +174,3 @@ namespace AdHoc { return resolvers->size(); } } - diff --git a/libadhocutil/plugins.h b/libadhocutil/plugins.h index f8b1e8c..3502051 100644 --- a/libadhocutil/plugins.h +++ b/libadhocutil/plugins.h @@ -1,237 +1,242 @@ #ifndef ADHOCUTIL_PLUGINS_H #define ADHOCUTIL_PLUGINS_H -#include +#include "c++11Helpers.h" +#include "unique.h" +#include "visibility.h" +#include #include +#include +#include #include -#include #include -#include -#include #include -#include "visibility.h" -#include "unique.h" -#include "c++11Helpers.h" +#include namespace std { DLL_PUBLIC - std::ostream & - operator<<(std::ostream & s, const std::type_info & t); + std::ostream & operator<<(std::ostream & s, const std::type_info & t); } namespace AdHoc { /// Thrown when no matching plugin can be found. class NoSuchPluginException : public std::runtime_error { - public: - /// Constructor taking name and type of plugin requested. - NoSuchPluginException(const std::string_view &, const std::type_info &); + public: + /// Constructor taking name and type of plugin requested. + NoSuchPluginException(const std::string_view &, const std::type_info &); }; /// Base class for all plugin implementations. class DLL_PUBLIC AbstractPluginImplementation { - public: - AbstractPluginImplementation() = default; - virtual ~AbstractPluginImplementation() = 0; - /// Standard move/copy support - SPECIAL_MEMBERS_DEFAULT(AbstractPluginImplementation); + public: + AbstractPluginImplementation() = default; + virtual ~AbstractPluginImplementation() = 0; + /// Standard move/copy support + SPECIAL_MEMBERS_DEFAULT(AbstractPluginImplementation); }; /// Base class for untyped plugins. class DLL_PUBLIC Plugin { - public: - /// Constructor taking name, filename and line of install. - Plugin(const std::string_view &, const std::string_view &, int); - /// Standard move/copy support - SPECIAL_MEMBERS_DELETE(Plugin); - virtual ~Plugin() = default; - - /// Get the plugin type from the subclass. - [[nodiscard]] virtual const std::type_info & type() const = 0; - - /// Get the abstract base plugin implementation. - [[nodiscard]] virtual std::shared_ptr instance() const = 0; - - /// The name the plugin was installed with. - const std::string name; - /// The filename the plugin was installed in. - const std::string filename; - /// The line of file the plugin was installed in. - const int lineno; + public: + /// Constructor taking name, filename and line of install. + Plugin(const std::string_view &, const std::string_view &, int); + /// Standard move/copy support + SPECIAL_MEMBERS_DELETE(Plugin); + virtual ~Plugin() = default; + + /// Get the plugin type from the subclass. + [[nodiscard]] virtual const std::type_info & type() const = 0; + + /// Get the abstract base plugin implementation. + [[nodiscard]] virtual std::shared_ptr instance() const = 0; + + /// The name the plugin was installed with. + const std::string name; + /// The filename the plugin was installed in. + const std::string filename; + /// The line of file the plugin was installed in. + const int lineno; }; using PluginPtr = std::shared_ptr; /// Thrown when a plugin with the same name and base is loaded into a manager. class DuplicatePluginException : public std::runtime_error { - public: - /// Constructor taking the original and offending plugin. - DuplicatePluginException(const PluginPtr & p1, const PluginPtr & p2); + public: + /// Constructor taking the original and offending plugin. + DuplicatePluginException(const PluginPtr & p1, const PluginPtr & p2); }; /// Thrown when a resolver function is added a second time. class DuplicateResolverException : public std::runtime_error { - public: - /// Constuctor taking resolver type. - explicit DuplicateResolverException(const std::type_info &); + public: + /// Constuctor taking resolver type. + explicit DuplicateResolverException(const std::type_info &); }; /// Thrown when an attempt to load a library fails. class LoadLibraryException : public std::runtime_error { - public: - /// Constuctor taking syscall error details. - LoadLibraryException(const std::string_view & f, const std::string_view & msg); + public: + /// Constuctor taking syscall error details. + LoadLibraryException(const std::string_view & f, const std::string_view & msg); }; - template + template /// Typed plugin and handle to implementation. class DLL_PUBLIC PluginOf : public Plugin { - public: - /// Constructor taking an instance and name, filename and line of install for Plugin. - PluginOf(std::shared_ptr t, const std::string_view & n, const std::string_view & f, int l); + public: + /// Constructor taking an instance and name, filename and line of install for Plugin. + PluginOf(std::shared_ptr t, const std::string_view & n, const std::string_view & f, int l); - /// Get the type of this plugin. - [[nodiscard]] const std::type_info & type() const override; - /// Get the implementation of this plugin. - [[nodiscard]] std::shared_ptr implementation() const; + /// Get the type of this plugin. + [[nodiscard]] const std::type_info & type() const override; + /// Get the implementation of this plugin. + [[nodiscard]] std::shared_ptr implementation() const; - [[nodiscard]] std::shared_ptr instance() const override; + [[nodiscard]] std::shared_ptr instance() const override; - private: - const std::shared_ptr impl; + private: + const std::shared_ptr impl; }; /// Container for loaded plugins. class DLL_PUBLIC PluginManager { - public: - /// Callback definition to resolve a plugin type and name to a potential library - /// containing an implementation. - using PluginResolver = std::function (const std::type_info &, const std::string_view &)>; - - PluginManager(); - virtual ~PluginManager(); - - /// Standard move/copy support - SPECIAL_MEMBERS_DELETE(PluginManager); - - /// Install a plugin. - void add(const PluginPtr &); - /// Uninstall a plugin. - void remove(const std::string_view &, const std::type_info &); - /// Get a specific plugin. - [[nodiscard]] PluginPtr get(const std::string_view &, const std::type_info &) const; - /// Get all plugins. - [[nodiscard]] std::set getAll() const; - /// Get all plugins of a specific type. - [[nodiscard]] std::set getAll(const std::type_info &) const; - - /** - * Install a plugin. - * @param i Implementation instance. - * @param n Name of plugin. - * @param f Filename of plugin. - * @param l Line number. - */ - template void add(const std::shared_ptr & i, const std::string_view & n, const std::string_view & f, int l); - - /** - * Create and install a plugin - * @tparam T Base type of plugin - * @tparam I Implementation type of plugin - * @tparam Args Constructor arguments types - * @param n Name of plugin. - * @param f Filename of plugin. - * @param l Line number. - * @param args Arguments to construct an instance of I with. - */ - template void create(const std::string_view & n, const std::string_view & f, int l, const Args & ... args) - { - add(std::make_shared(args...), n, f, l); - } - - /** - * Uninstall a plugin. - * @param n Name of plugin. - */ - template void remove(const std::string_view & n); - - /** - * Get a specific plugin. - * @param n Name of plugin. - */ - template [[nodiscard]] std::shared_ptr> get(const std::string_view & n) const; - - /** - * Get the implementation from specific plugin. - * @param n Name of plugin. - */ - template [[nodiscard]] std::shared_ptr getImplementation(const std::string_view & n) const; - - /** - * Get all plugins of a given time. - */ - template [[nodiscard]] std::set>> getAll() const; - - /** - * The number of installed plugins. - */ - [[nodiscard]] size_t count() const; - - /** - * Add a type plugin resolver function. - * @param t The resolver type. - * @param f The resolver function. - */ - void addResolver(const std::type_info & t, const PluginResolver & f); - - /** - * Add a type plugin resolver function. - * @param f The resolver function. - */ - template void addResolver(const PluginResolver & f); - - /** - * Remove a type plugin resolver function. - * @param t The resolver type. - */ - void removeResolver(const std::type_info & t); - - /** - * Remove a type plugin resolver function. - */ - template void removeResolver(); - - /** - * The number of installed plugins. - */ - [[nodiscard]] size_t countResolvers() const; - - /** - * Get the default plugin manager instance. - */ - static PluginManager * getDefault(); - - private: - static void loadLibrary(const std::string &); - - class PluginStore; - std::unique_ptr plugins; - class TypePluginResolvers; - std::unique_ptr resolvers; + public: + /// Callback definition to resolve a plugin type and name to a potential library + /// containing an implementation. + using PluginResolver + = std::function(const std::type_info &, const std::string_view &)>; + + PluginManager(); + virtual ~PluginManager(); + + /// Standard move/copy support + SPECIAL_MEMBERS_DELETE(PluginManager); + + /// Install a plugin. + void add(const PluginPtr &); + /// Uninstall a plugin. + void remove(const std::string_view &, const std::type_info &); + /// Get a specific plugin. + [[nodiscard]] PluginPtr get(const std::string_view &, const std::type_info &) const; + /// Get all plugins. + [[nodiscard]] std::set getAll() const; + /// Get all plugins of a specific type. + [[nodiscard]] std::set getAll(const std::type_info &) const; + + /** + * Install a plugin. + * @param i Implementation instance. + * @param n Name of plugin. + * @param f Filename of plugin. + * @param l Line number. + */ + template + void add(const std::shared_ptr & i, const std::string_view & n, const std::string_view & f, int l); + + /** + * Create and install a plugin + * @tparam T Base type of plugin + * @tparam I Implementation type of plugin + * @tparam Args Constructor arguments types + * @param n Name of plugin. + * @param f Filename of plugin. + * @param l Line number. + * @param args Arguments to construct an instance of I with. + */ + template + void + create(const std::string_view & n, const std::string_view & f, int l, const Args &... args) + { + add(std::make_shared(args...), n, f, l); + } + + /** + * Uninstall a plugin. + * @param n Name of plugin. + */ + template void remove(const std::string_view & n); + + /** + * Get a specific plugin. + * @param n Name of plugin. + */ + template[[nodiscard]] std::shared_ptr> get(const std::string_view & n) const; + + /** + * Get the implementation from specific plugin. + * @param n Name of plugin. + */ + template[[nodiscard]] std::shared_ptr getImplementation(const std::string_view & n) const; + + /** + * Get all plugins of a given time. + */ + template[[nodiscard]] std::set>> getAll() const; + + /** + * The number of installed plugins. + */ + [[nodiscard]] size_t count() const; + + /** + * Add a type plugin resolver function. + * @param t The resolver type. + * @param f The resolver function. + */ + void addResolver(const std::type_info & t, const PluginResolver & f); + + /** + * Add a type plugin resolver function. + * @param f The resolver function. + */ + template void addResolver(const PluginResolver & f); + + /** + * Remove a type plugin resolver function. + * @param t The resolver type. + */ + void removeResolver(const std::type_info & t); + + /** + * Remove a type plugin resolver function. + */ + template void removeResolver(); + + /** + * The number of installed plugins. + */ + [[nodiscard]] size_t countResolvers() const; + + /** + * Get the default plugin manager instance. + */ + static PluginManager * getDefault(); + + private: + static void loadLibrary(const std::string &); + + class PluginStore; + std::unique_ptr plugins; + class TypePluginResolvers; + std::unique_ptr resolvers; }; } #define NAMEDPLUGIN(Name, Implementation, Base) \ - namespace MAKE_UNIQUE(__plugin__) { \ + namespace MAKE_UNIQUE(__plugin__) \ + { \ static void InstallPlugin() __attribute__((constructor(102))); \ - void InstallPlugin() { \ - ::AdHoc::PluginManager::getDefault()->add(std::make_shared(), Name, __FILE__, __LINE__); \ + void InstallPlugin() \ + { \ + ::AdHoc::PluginManager::getDefault()->add( \ + std::make_shared(), Name, __FILE__, __LINE__); \ } \ static void UninstallPlugin() __attribute__((destructor(102))); \ - void UninstallPlugin() { \ + void UninstallPlugin() \ + { \ ::AdHoc::PluginManager::getDefault()->remove(Name); \ } \ } -#define PLUGIN(Implementation, Base) \ - NAMEDPLUGIN(#Implementation, Implementation, Base) +#define PLUGIN(Implementation, Base) NAMEDPLUGIN(#Implementation, Implementation, Base) #endif - diff --git a/libadhocutil/plugins.impl.h b/libadhocutil/plugins.impl.h index e4b48d1..7757ea5 100644 --- a/libadhocutil/plugins.impl.h +++ b/libadhocutil/plugins.impl.h @@ -4,15 +4,14 @@ #include "plugins.h" namespace AdHoc { - template + template PluginOf::PluginOf(std::shared_ptr t, const std::string_view & n, const std::string_view & f, int l) : - Plugin(n, f, l), - impl(std::move(t)) + Plugin(n, f, l), impl(std::move(t)) { } /// Get the type of this plugin. - template + template const std::type_info & PluginOf::type() const { @@ -20,54 +19,54 @@ namespace AdHoc { } /// Get the implementation of this plugin. - template + template std::shared_ptr PluginOf::implementation() const { return impl; } - template + template std::shared_ptr PluginOf::instance() const { return impl; } - template + template void PluginManager::add(const std::shared_ptr & i, const std::string_view & n, const std::string_view & f, int l) { add(std::make_shared>(i, n, f, l)); } - template + template void PluginManager::remove(const std::string_view & n) { remove(n, typeid(T)); } - template + template std::shared_ptr> PluginManager::get(const std::string_view & n) const { return std::dynamic_pointer_cast>(get(n, typeid(T))); } - template + template std::shared_ptr PluginManager::getImplementation(const std::string_view & n) const { return std::static_pointer_cast(get(n)->implementation()); } - template + template std::set>> PluginManager::getAll() const { std::set>> all; - for(const auto & p : getAll(typeid(T))) { + for (const auto & p : getAll(typeid(T))) { if (auto tp = std::dynamic_pointer_cast>(p)) { all.insert(tp); } @@ -92,25 +91,32 @@ namespace AdHoc { #define INSTANTIATEPLUGINOF(...) \ template class AdHoc::PluginOf<__VA_ARGS__>; \ - template DLL_PUBLIC void AdHoc::PluginManager::add<__VA_ARGS__>(const std::shared_ptr<__VA_ARGS__> &, const std::string_view &, const std::string_view &, int); \ + template DLL_PUBLIC void AdHoc::PluginManager::add<__VA_ARGS__>( \ + const std::shared_ptr<__VA_ARGS__> &, const std::string_view &, const std::string_view &, int); \ template DLL_PUBLIC void AdHoc::PluginManager::remove<__VA_ARGS__>(const std::string_view &); \ - template DLL_PUBLIC std::shared_ptr> AdHoc::PluginManager::get<__VA_ARGS__>(const std::string_view &) const; \ - template DLL_PUBLIC std::shared_ptr<__VA_ARGS__> AdHoc::PluginManager::getImplementation<__VA_ARGS__>(const std::string_view &) const; \ - template DLL_PUBLIC std::set>> AdHoc::PluginManager::getAll<__VA_ARGS__>() const; \ - template DLL_PUBLIC void AdHoc::PluginManager::addResolver<__VA_ARGS__>(const AdHoc::PluginManager::PluginResolver & f); \ - template DLL_PUBLIC void AdHoc::PluginManager::removeResolver<__VA_ARGS__>(); \ + template DLL_PUBLIC std::shared_ptr> AdHoc::PluginManager::get<__VA_ARGS__>( \ + const std::string_view &) const; \ + template DLL_PUBLIC std::shared_ptr<__VA_ARGS__> AdHoc::PluginManager::getImplementation<__VA_ARGS__>( \ + const std::string_view &) const; \ + template DLL_PUBLIC std::set>> \ + AdHoc::PluginManager::getAll<__VA_ARGS__>() const; \ + template DLL_PUBLIC void AdHoc::PluginManager::addResolver<__VA_ARGS__>( \ + const AdHoc::PluginManager::PluginResolver & f); \ + template DLL_PUBLIC void AdHoc::PluginManager::removeResolver<__VA_ARGS__>(); #define PLUGINRESOLVER(T, F) \ - namespace MAKE_UNIQUE(__plugin__) { \ + namespace MAKE_UNIQUE(__plugin__) \ + { \ static void InstallResolver() __attribute__((constructor(102))); \ - void InstallResolver() { \ + void InstallResolver() \ + { \ ::AdHoc::PluginManager::getDefault()->addResolver(F); \ } \ static void UninstallResolver() __attribute__((destructor(102))); \ - void UninstallResolver() { \ + void UninstallResolver() \ + { \ ::AdHoc::PluginManager::getDefault()->removeResolver(); \ } \ } #endif - diff --git a/libadhocutil/processPipes.cpp b/libadhocutil/processPipes.cpp index efdcc88..59253bc 100644 --- a/libadhocutil/processPipes.cpp +++ b/libadhocutil/processPipes.cpp @@ -1,142 +1,146 @@ #include "processPipes.h" -#include -#include +#include "c++11Helpers.h" #include -#include +#include #include #include -#include "c++11Helpers.h" +#include +#include namespace AdHoc::System { -ProcessPipes::InitPipe -ProcessPipes::pipeSetup(bool setup, bool swap) -{ - if (setup) { - PipePair pair; - if (::pipe(&pair.first)) { - throw SystemException("pipe(2) failed", strerror(errno), errno); + ProcessPipes::InitPipe + ProcessPipes::pipeSetup(bool setup, bool swap) + { + if (setup) { + PipePair pair; + if (::pipe(&pair.first)) { + throw SystemException("pipe(2) failed", strerror(errno), errno); + } + if (swap) { + std::swap(pair.first, pair.second); + } + return pair; } - if (swap) { - std::swap(pair.first, pair.second); + return {}; + } + + void + ProcessPipes::closeChild(const InitPipe & pipe) noexcept + { + if (pipe) { + close(pipe->second); } - return pair; } - return {}; -} -void ProcessPipes::closeChild(const InitPipe & pipe) noexcept -{ - if (pipe) { - close(pipe->second); + void + ProcessPipes::dupChild(int fd, const InitPipe & pipe) noexcept + { + if (pipe) { + close(pipe->first); + dup2(pipe->second, fd); + } } -} -void ProcessPipes::dupChild(int fd, const InitPipe & pipe) noexcept -{ - if (pipe) { - close(pipe->first); - dup2(pipe->second, fd); + ProcessPipes::ProcessPipes(const std::vector & args, bool i, bool o, bool e) : + ProcessPipes( + [&args]() { + if (args.empty()) { + throw std::invalid_argument("args is empty"); + } + return args; + }(), + pipeSetup(i, true), pipeSetup(o, false), pipeSetup(e, false)) + { } -} -ProcessPipes::ProcessPipes(const std::vector & args, bool i, bool o, bool e) : - ProcessPipes([&args](){ - if (args.empty()) { - throw std::invalid_argument("args is empty"); + ProcessPipes::ProcessPipes( + const std::vector & args, InitPipe && ipp, InitPipe && opp, InitPipe && epp) : + child([]() { + if (pid_t p = fork(); p != -1) { + return p; + } + /// LCOV_EXCL_START (fork won't fail) + throw SystemException("fork(2) failed", strerror(errno), errno); + /// LCOV_EXCL_STOP + }()), + in(ipp ? std::make_optional(ipp->first, &close) : OFHandle()), + out(opp ? std::make_optional(opp->first, &close) : OFHandle()), + error(epp ? std::make_optional(epp->first, &close) : OFHandle()) + { + switch (child) { + default: // parent + closeChild(ipp); + closeChild(opp); + closeChild(epp); + break; + case 0: // in child + dupChild(STDIN_FILENO, ipp); + dupChild(STDOUT_FILENO, opp); + dupChild(STDERR_FILENO, epp); + closeAllOpenFiles(); + std::vector buf(args.size() + 1); + auto w = buf.begin(); + for (const auto & p : args) { + *w++ = strdup(p.c_str()); + } + *w = nullptr; + if (buf[0]) { + execv(buf[0], buf.data()); + } + abort(); + break; } - return args; - }(), pipeSetup(i, true), pipeSetup(o, false), pipeSetup(e, false)) -{ -} + } -ProcessPipes::ProcessPipes(const std::vector & args, InitPipe && ipp, InitPipe && opp, InitPipe && epp) : - child([]() { - if (pid_t p = fork(); p != -1) { - return p; + int + ProcessPipes::closeIn() + { + if (in) { + in.reset(); + return 0; } - /// LCOV_EXCL_START (fork won't fail) - throw SystemException("fork(2) failed", strerror(errno), errno); - /// LCOV_EXCL_STOP - }()), - in(ipp ? std::make_optional(ipp->first, &close) : OFHandle()), - out(opp ? std::make_optional(opp->first, &close) : OFHandle()), - error(epp ? std::make_optional(epp->first, &close) : OFHandle()) -{ - switch (child) { - default: // parent - closeChild(ipp); - closeChild(opp); - closeChild(epp); - break; - case 0: // in child - dupChild(STDIN_FILENO, ipp); - dupChild(STDOUT_FILENO, opp); - dupChild(STDERR_FILENO, epp); - closeAllOpenFiles(); - std::vector buf(args.size() + 1); - auto w = buf.begin(); - for (const auto & p : args) { - *w++ = strdup(p.c_str()); - } - *w = nullptr; - if (buf[0]) { - execv(buf[0], buf.data()); - } - abort(); - break; + return EBADF; } -} -int -ProcessPipes::closeIn() -{ - if (in) { - in.reset(); - return 0; + int + ProcessPipes::fdIn() const noexcept + { + return in ? *in : -1; } - return EBADF; -} - -int -ProcessPipes::fdIn() const noexcept -{ - return in ? *in : -1; -} - -int -ProcessPipes::fdOut() const noexcept -{ - return out ? *out : -1; -} -int -ProcessPipes::fdError() const noexcept -{ - return error ? *error : -1; -} + int + ProcessPipes::fdOut() const noexcept + { + return out ? *out : -1; + } -pid_t -ProcessPipes::pid() const noexcept -{ - return child; -} + int + ProcessPipes::fdError() const noexcept + { + return error ? *error : -1; + } -void -ProcessPipes::closeAllOpenFiles() noexcept -{ - rlimit lim { }; - getrlimit(RLIMIT_NOFILE, &lim); - std::vector fds; - fds.reserve(lim.rlim_max); - for (int n = 3; n < (int)lim.rlim_max; n += 1) { - fds.push_back({n, 0, 0}); + pid_t + ProcessPipes::pid() const noexcept + { + return child; } - poll(&fds.front(), fds.size(), 0); - for(const auto & pfd : fds) { - if (!(pfd.revents & POLLNVAL)) { - close(pfd.fd); + + void + ProcessPipes::closeAllOpenFiles() noexcept + { + rlimit lim {}; + getrlimit(RLIMIT_NOFILE, &lim); + std::vector fds; + fds.reserve(lim.rlim_max); + for (int n = 3; n < (int)lim.rlim_max; n += 1) { + fds.push_back({n, 0, 0}); + } + poll(&fds.front(), fds.size(), 0); + for (const auto & pfd : fds) { + if (!(pfd.revents & POLLNVAL)) { + close(pfd.fd); + } } } } -} - diff --git a/libadhocutil/processPipes.h b/libadhocutil/processPipes.h index 1b1a8fa..5ccc4c0 100644 --- a/libadhocutil/processPipes.h +++ b/libadhocutil/processPipes.h @@ -1,62 +1,61 @@ #ifndef ADHOCUTIL_PROCESSPIPES_H #define ADHOCUTIL_PROCESSPIPES_H -#include -#include -#include -#include "visibility.h" #include "c++11Helpers.h" #include "handle.h" +#include "visibility.h" +#include +#include +#include namespace AdHoc { -namespace System { - -/// Spawn a process and attach to its IO handles. -class DLL_PUBLIC ProcessPipes { - public: - /** - * Spawn a new process, providing (optional) access to its stdin, stdout and - * stderr file handles. - * @param args path and arguments to spawn (passed to execv) - * @param in Attach to stdin? - * @param out Attach to stdout? - * @param err Attach to stderr? - */ - ProcessPipes(const std::vector & args, bool in, bool out, bool err); - - /// Close input pipe to process - int closeIn(); - - /** FD handle to child's stdin. */ - [[nodiscard]] int fdIn() const noexcept; - /** FD handle to child's stdout. */ - [[nodiscard]] int fdOut() const noexcept; - /** FD handle to child's stderr. */ - [[nodiscard]] int fdError() const noexcept; - /** Process id of child. */ - [[nodiscard]] pid_t pid() const noexcept; - - private: - using PipePair = std::pair; - using InitPipe = std::optional; - - ProcessPipes(const std::vector & args, InitPipe &&, InitPipe &&, InitPipe &&); - - static InitPipe pipeSetup(bool setup, bool swap); - static void closeChild(const InitPipe & child) noexcept; - static void dupChild(int, const InitPipe & child) noexcept; - static void closeAllOpenFiles() noexcept; - - using FHandle = ::AdHoc::Handle; - using OFHandle = std::optional; - const pid_t child; - OFHandle in; - const OFHandle out, error; -}; - -} + namespace System { + + /// Spawn a process and attach to its IO handles. + class DLL_PUBLIC ProcessPipes { + public: + /** + * Spawn a new process, providing (optional) access to its stdin, stdout and + * stderr file handles. + * @param args path and arguments to spawn (passed to execv) + * @param in Attach to stdin? + * @param out Attach to stdout? + * @param err Attach to stderr? + */ + ProcessPipes(const std::vector & args, bool in, bool out, bool err); + + /// Close input pipe to process + int closeIn(); + + /** FD handle to child's stdin. */ + [[nodiscard]] int fdIn() const noexcept; + /** FD handle to child's stdout. */ + [[nodiscard]] int fdOut() const noexcept; + /** FD handle to child's stderr. */ + [[nodiscard]] int fdError() const noexcept; + /** Process id of child. */ + [[nodiscard]] pid_t pid() const noexcept; + + private: + using PipePair = std::pair; + using InitPipe = std::optional; + + ProcessPipes(const std::vector & args, InitPipe &&, InitPipe &&, InitPipe &&); + + static InitPipe pipeSetup(bool setup, bool swap); + static void closeChild(const InitPipe & child) noexcept; + static void dupChild(int, const InitPipe & child) noexcept; + static void closeAllOpenFiles() noexcept; + + using FHandle = ::AdHoc::Handle; + using OFHandle = std::optional; + const pid_t child; + OFHandle in; + const OFHandle out, error; + }; + + } } #endif - diff --git a/libadhocutil/resourcePool.cpp b/libadhocutil/resourcePool.cpp index 0724a81..cc2cec0 100644 --- a/libadhocutil/resourcePool.cpp +++ b/libadhocutil/resourcePool.cpp @@ -2,10 +2,7 @@ #include "compileTimeFormatter.h" namespace AdHoc { - TimeOutOnResourcePool::TimeOutOnResourcePool(const char * const n) : - name(n) - { - } + TimeOutOnResourcePool::TimeOutOnResourcePool(const char * const n) : name(n) { } AdHocFormatter(TimeOutOnResourcePoolMsg, "Timeout getting a resource from pool of %?"); std::string @@ -14,11 +11,7 @@ namespace AdHoc { return TimeOutOnResourcePoolMsg::get(name); } - NoCurrentResource::NoCurrentResource(const std::thread::id & id, const char * const n) : - threadId(id), - name(n) - { - } + NoCurrentResource::NoCurrentResource(const std::thread::id & id, const char * const n) : threadId(id), name(n) { } AdHocFormatter(NoCurrentResourceMsg, "Thread %? has no current resource handle of type %?"); std::string @@ -27,4 +20,3 @@ namespace AdHoc { return NoCurrentResourceMsg::get(threadId, name); } } - diff --git a/libadhocutil/resourcePool.h b/libadhocutil/resourcePool.h index 923565e..17694e8 100644 --- a/libadhocutil/resourcePool.h +++ b/libadhocutil/resourcePool.h @@ -1,156 +1,150 @@ #ifndef ADHOCUTIL_RESOURCEPOOL_H #define ADHOCUTIL_RESOURCEPOOL_H -#include -#include +#include "c++11Helpers.h" +#include "exception.h" +#include "semaphore.h" +#include "visibility.h" #include -#include #include #include -#include "semaphore.h" -#include "exception.h" -#include "visibility.h" -#include "c++11Helpers.h" +#include +#include +#include namespace AdHoc { - template - class ResourcePool; + template class ResourcePool; /// A handle to a resource allocated from a ResourcePool. - template - class DLL_PUBLIC ResourceHandle { - public: - /// Handle to an allocated resource, the pool it belongs to and a count of active references. - using Object = std::tuple, ResourcePool *>; - - /// Create a reference to a new resource. - explicit ResourceHandle(std::shared_ptr) noexcept; - /// Standard move/copy support - SPECIAL_MEMBERS_CONS(ResourceHandle, default); - ~ResourceHandle() noexcept; - - /// Reference to an existing resource. - ResourceHandle & operator=(const ResourceHandle &) noexcept; - /// Move reference to an existing resource. - ResourceHandle & operator=(ResourceHandle &&) noexcept; - /// Access to the resource. - Resource * operator->() const noexcept; - /// Access to the resource. - Resource * get() const noexcept; - /// Release the resource back to the pool. - void release() noexcept; - /// Cast to bool. - explicit operator bool() const noexcept; - - /// Get number of handles to this resource. - [[nodiscard]] unsigned int handleCount() const; - - private: - DLL_PRIVATE void decRef() noexcept; - std::shared_ptr resource; + template class DLL_PUBLIC ResourceHandle { + public: + /// Handle to an allocated resource, the pool it belongs to and a count of active references. + using Object = std::tuple, ResourcePool *>; + + /// Create a reference to a new resource. + explicit ResourceHandle(std::shared_ptr) noexcept; + /// Standard move/copy support + SPECIAL_MEMBERS_CONS(ResourceHandle, default); + ~ResourceHandle() noexcept; + + /// Reference to an existing resource. + ResourceHandle & operator=(const ResourceHandle &) noexcept; + /// Move reference to an existing resource. + ResourceHandle & operator=(ResourceHandle &&) noexcept; + /// Access to the resource. + Resource * operator->() const noexcept; + /// Access to the resource. + Resource * get() const noexcept; + /// Release the resource back to the pool. + void release() noexcept; + /// Cast to bool. + explicit operator bool() const noexcept; + + /// Get number of handles to this resource. + [[nodiscard]] unsigned int handleCount() const; + + private: + DLL_PRIVATE void decRef() noexcept; + std::shared_ptr resource; }; /// A fully featured resource pool for sharing and reusing a finite set of /// resources, possibly across multiple threads. - template - class DLL_PUBLIC ResourcePool { - public: - friend class ResourceHandle; - - /// Create a new resource pool. - /// @param maxSize The upper limit of how many concurrent active resources there can be. - /// @param keep The number of resources to cache for reuse. - ResourcePool(unsigned int maxSize, unsigned int keep); - virtual ~ResourcePool(); - - /// Standard move/copy support - SPECIAL_MEMBERS_DEFAULT_MOVE_NO_COPY(ResourcePool); - - /// Get a resource from the pool (maybe cached, maybe constructed afresh) - ResourceHandle get(); - /// Get a resource from the pool (with timeout on max size of pool) - /// @param ms Timeout in milliseconds. - ResourceHandle get(unsigned int ms); - /// Get a new handle to the resource previous allocated to the current. - ResourceHandle getMine(); - /// Go idle; destroy all cached resources, currently active instances are untouched. - void idle(); - - /// Get number of active resources. - unsigned int inUseCount() const; - /// Get number of available cached resources. - unsigned int availableCount() const; - /// Get number of free slots. - unsigned int freeCount() const; - - protected: - /// Create a new resource instance to add to the pool. - virtual std::shared_ptr createResource() const = 0; - /// Test a cached resource is still suitable for use before re-use (defaults to no-op). - virtual void testResource(Resource const *) const; - /// Test a cached resource is still suitable for use on return (defaults to no-op). - virtual void returnTestResource(Resource const *) const; - - private: - using Available = std::list>; - using InUse = std::multimap::Object>>; - - void putBack(const std::shared_ptr &); - void discard(const std::shared_ptr &); - - DLL_PRIVATE static void removeFrom(const std::shared_ptr &, InUse &); - DLL_PRIVATE ResourceHandle getOne(); - - mutable std::shared_mutex lock; - Semaphore poolSize; - unsigned int keep; - Available available; - InUse inUse; + template class DLL_PUBLIC ResourcePool { + public: + friend class ResourceHandle; + + /// Create a new resource pool. + /// @param maxSize The upper limit of how many concurrent active resources there can be. + /// @param keep The number of resources to cache for reuse. + ResourcePool(unsigned int maxSize, unsigned int keep); + virtual ~ResourcePool(); + + /// Standard move/copy support + SPECIAL_MEMBERS_DEFAULT_MOVE_NO_COPY(ResourcePool); + + /// Get a resource from the pool (maybe cached, maybe constructed afresh) + ResourceHandle get(); + /// Get a resource from the pool (with timeout on max size of pool) + /// @param ms Timeout in milliseconds. + ResourceHandle get(unsigned int ms); + /// Get a new handle to the resource previous allocated to the current. + ResourceHandle getMine(); + /// Go idle; destroy all cached resources, currently active instances are untouched. + void idle(); + + /// Get number of active resources. + unsigned int inUseCount() const; + /// Get number of available cached resources. + unsigned int availableCount() const; + /// Get number of free slots. + unsigned int freeCount() const; + + protected: + /// Create a new resource instance to add to the pool. + virtual std::shared_ptr createResource() const = 0; + /// Test a cached resource is still suitable for use before re-use (defaults to no-op). + virtual void testResource(Resource const *) const; + /// Test a cached resource is still suitable for use on return (defaults to no-op). + virtual void returnTestResource(Resource const *) const; + + private: + using Available = std::list>; + using InUse = std::multimap::Object>>; + + void putBack(const std::shared_ptr &); + void discard(const std::shared_ptr &); + + DLL_PRIVATE static void removeFrom(const std::shared_ptr &, InUse &); + DLL_PRIVATE ResourceHandle getOne(); + + mutable std::shared_mutex lock; + Semaphore poolSize; + unsigned int keep; + Available available; + InUse inUse; }; /// Represents a failure to acquire a new resource within the given timeout. class DLL_PUBLIC TimeOutOnResourcePool : public AdHoc::StdException { - public: - /// Constrcut a new timeout exception for the given resource type. - explicit TimeOutOnResourcePool(const char * const type); + public: + /// Constrcut a new timeout exception for the given resource type. + explicit TimeOutOnResourcePool(const char * const type); - std::string message() const noexcept override; + std::string message() const noexcept override; - private: - const char * const name; + private: + const char * const name; }; /// Represents a failure to acquire a new resource of type R within the given timeout. - template - class DLL_PUBLIC TimeOutOnResourcePoolT : public TimeOutOnResourcePool { - public: - TimeOutOnResourcePoolT(); + template class DLL_PUBLIC TimeOutOnResourcePoolT : public TimeOutOnResourcePool { + public: + TimeOutOnResourcePoolT(); }; /// Represents a request for the current thread's previous allocated resource /// when one has not been allocated. class DLL_PUBLIC NoCurrentResource : public AdHoc::StdException { - public: - /// Construct for a specific thread and resource type. - NoCurrentResource(const std::thread::id &, const char * const type); + public: + /// Construct for a specific thread and resource type. + NoCurrentResource(const std::thread::id &, const char * const type); - std::string message() const noexcept override; + std::string message() const noexcept override; - private: - const std::thread::id threadId; - const char * const name; + private: + const std::thread::id threadId; + const char * const name; }; /// Represents a request for the current thread's previous allocated resource /// of type R when one has not been allocated. - template - class DLL_PUBLIC NoCurrentResourceT : public NoCurrentResource { - public: - /// Construct for a specific thread and resource type R. - explicit NoCurrentResourceT(const std::thread::id &); + template class DLL_PUBLIC NoCurrentResourceT : public NoCurrentResource { + public: + /// Construct for a specific thread and resource type R. + explicit NoCurrentResourceT(const std::thread::id &); }; } #endif - diff --git a/libadhocutil/resourcePool.impl.h b/libadhocutil/resourcePool.impl.h index a58de87..954a475 100644 --- a/libadhocutil/resourcePool.impl.h +++ b/libadhocutil/resourcePool.impl.h @@ -1,31 +1,28 @@ #ifndef ADHOCUTIL_RESOURCEPOOL_IMPL_H #define ADHOCUTIL_RESOURCEPOOL_IMPL_H -#include -#include "resourcePool.h" #include "lockHelpers.h" +#include "resourcePool.h" #include "safeMapFind.h" +#include namespace AdHoc { // // ResourceHandle // - template - ResourceHandle::ResourceHandle(std::shared_ptr o) noexcept : - resource(std::move(o)) + template ResourceHandle::ResourceHandle(std::shared_ptr o) noexcept : resource(std::move(o)) { } - template - ResourceHandle::~ResourceHandle() noexcept + template ResourceHandle::~ResourceHandle() noexcept { if (resource) { decRef(); } } - template + template unsigned int ResourceHandle::handleCount() const { @@ -34,7 +31,7 @@ namespace AdHoc { return resource.use_count() - 1; } - template + template R * ResourceHandle::get() const noexcept { @@ -42,20 +39,19 @@ namespace AdHoc { return std::get<0>(*resource).get(); } - template + template void ResourceHandle::release() noexcept { decRef(); } - template - ResourceHandle::operator bool() const noexcept + template ResourceHandle::operator bool() const noexcept { return (bool)resource; } - template + template R * ResourceHandle::operator->() const noexcept { @@ -63,7 +59,7 @@ namespace AdHoc { return std::get<0>(*resource).get(); } - template + template ResourceHandle & ResourceHandle::operator=(const ResourceHandle & rh) noexcept { @@ -76,7 +72,7 @@ namespace AdHoc { return *this; } - template + template ResourceHandle & ResourceHandle::operator=(ResourceHandle && rh) noexcept { @@ -89,7 +85,7 @@ namespace AdHoc { return *this; } - template + template void ResourceHandle::decRef() noexcept { @@ -112,34 +108,28 @@ namespace AdHoc { // ResourcePool // - template - ResourcePool::ResourcePool(unsigned int max, unsigned int k) : - poolSize(max), - keep(k) - { - } + template ResourcePool::ResourcePool(unsigned int max, unsigned int k) : poolSize(max), keep(k) { } - template - ResourcePool::~ResourcePool() + template ResourcePool::~ResourcePool() { for (auto & r : inUse) { std::get<1>(*r.second) = nullptr; } } - template + template void ResourcePool::testResource(R const *) const { } - template + template void ResourcePool::returnTestResource(R const *) const { } - template + template unsigned int ResourcePool::inUseCount() const { @@ -147,7 +137,7 @@ namespace AdHoc { return inUse.size(); } - template + template unsigned int ResourcePool::availableCount() const { @@ -155,7 +145,7 @@ namespace AdHoc { return available.size(); } - template + template unsigned int ResourcePool::freeCount() const { @@ -163,7 +153,7 @@ namespace AdHoc { return poolSize.freeCount(); } - template + template ResourceHandle ResourcePool::getMine() { @@ -171,7 +161,7 @@ namespace AdHoc { return ResourceHandle(safeMapLookup>(inUse, std::this_thread::get_id())); } - template + template void ResourcePool::idle() { @@ -179,7 +169,7 @@ namespace AdHoc { available.clear(); } - template + template ResourceHandle ResourcePool::get() { @@ -187,13 +177,13 @@ namespace AdHoc { try { return ResourceHandle(getOne()); } - catch(...) { + catch (...) { poolSize.notify(); throw; } } - template + template ResourceHandle ResourcePool::get(unsigned int timeout) { @@ -203,13 +193,13 @@ namespace AdHoc { try { return getOne(); } - catch(...) { + catch (...) { poolSize.notify(); throw; } } - template + template ResourceHandle ResourcePool::getOne() { @@ -220,7 +210,7 @@ namespace AdHoc { testResource(r.get()); auto ro = std::make_shared::Object>(r, this); available.pop_front(); - inUse.insert({ std::this_thread::get_id(), ro }); + inUse.insert({std::this_thread::get_id(), ro}); return ResourceHandle(ro); } catch (...) { @@ -228,11 +218,11 @@ namespace AdHoc { } } auto ro = std::make_shared::Object>(createResource(), this); - inUse.insert({ std::this_thread::get_id(), ro }); + inUse.insert({std::this_thread::get_id(), ro}); return ResourceHandle(ro); } - template + template void ResourcePool::putBack(const std::shared_ptr & r) { @@ -249,7 +239,7 @@ namespace AdHoc { poolSize.notify(); } - template + template void ResourcePool::discard(const std::shared_ptr & r) { @@ -258,7 +248,7 @@ namespace AdHoc { poolSize.notify(); } - template + template void ResourcePool::removeFrom(const std::shared_ptr & r, InUse & inUse) { @@ -271,19 +261,15 @@ namespace AdHoc { } } - template - TimeOutOnResourcePoolT::TimeOutOnResourcePoolT() : - TimeOutOnResourcePool(typeid(R).name()) + template TimeOutOnResourcePoolT::TimeOutOnResourcePoolT() : TimeOutOnResourcePool(typeid(R).name()) { } - template - NoCurrentResourceT::NoCurrentResourceT(const std::thread::id & id) : - NoCurrentResource(id, typeid(R).name()) + template + NoCurrentResourceT::NoCurrentResourceT(const std::thread::id & id) : NoCurrentResource(id, typeid(R).name()) { } } #endif - diff --git a/libadhocutil/runtimeContext.cpp b/libadhocutil/runtimeContext.cpp index ba3e2f9..9eeee0d 100644 --- a/libadhocutil/runtimeContext.cpp +++ b/libadhocutil/runtimeContext.cpp @@ -5,44 +5,42 @@ namespace AdHoc::System { -RuntimeContext::RuntimeContext(size_t stacksize) : - stack(stacksize) -{ - if (getcontext(&ctxCallback) == -1) { - throw SystemException("getcontext(3) failed", strerror(errno), errno); + RuntimeContext::RuntimeContext(size_t stacksize) : stack(stacksize) + { + if (getcontext(&ctxCallback) == -1) { + throw SystemException("getcontext(3) failed", strerror(errno), errno); + } + ctxCallback.uc_stack.ss_sp = &stack.front(); + ctxCallback.uc_stack.ss_size = stacksize; + ctxCallback.uc_link = &ctxInitial; + makecontext(&ctxCallback, (void (*)()) & RuntimeContext::callbackWrapper, 1, this); } - ctxCallback.uc_stack.ss_sp = &stack.front(); - ctxCallback.uc_stack.ss_size = stacksize; - ctxCallback.uc_link = &ctxInitial; - makecontext(&ctxCallback, (void (*)())&RuntimeContext::callbackWrapper, 1, this); -} -void -RuntimeContext::swapContext() -{ - swapped = !swapped; - if (swapped) { - swapcontext(&ctxInitial, &ctxCallback); - } - else { - if (!completed) { - swapcontext(&ctxCallback, &ctxInitial); + void + RuntimeContext::swapContext() + { + swapped = !swapped; + if (swapped) { + swapcontext(&ctxInitial, &ctxCallback); + } + else { + if (!completed) { + swapcontext(&ctxCallback, &ctxInitial); + } } } -} -bool -RuntimeContext::hasCompleted() const -{ - return completed; -} + bool + RuntimeContext::hasCompleted() const + { + return completed; + } -void -RuntimeContext::callbackWrapper(RuntimeContext * rc) -{ - rc->callback(); - rc->completed = true; -} + void + RuntimeContext::callbackWrapper(RuntimeContext * rc) + { + rc->callback(); + rc->completed = true; + } } - diff --git a/libadhocutil/runtimeContext.h b/libadhocutil/runtimeContext.h index 4a0fada..64ee1e2 100644 --- a/libadhocutil/runtimeContext.h +++ b/libadhocutil/runtimeContext.h @@ -1,52 +1,51 @@ #ifndef ADHOCUTIL_RUNTIMECONTEXT_H #define ADHOCUTIL_RUNTIMECONTEXT_H +#include "c++11Helpers.h" +#include "visibility.h" #include #include -#include "visibility.h" -#include "c++11Helpers.h" #include namespace AdHoc { -namespace System { - -/// Runtime Context -/** - * Create an alternate stack for processing. - */ -class DLL_PUBLIC RuntimeContext { - public: + namespace System { + + /// Runtime Context /** - * Create a new RuntimeContent - * @param stacksize The size in bytes of the new stack. + * Create an alternate stack for processing. */ - explicit RuntimeContext(size_t stacksize = 16384); - virtual ~RuntimeContext() = default; - /// Standard move/copy support - SPECIAL_MEMBERS_DEFAULT_MOVE_NO_COPY(RuntimeContext); - - /** Swap to/from the contained stack. */ - void swapContext(); - - /** Has the callback on the contained stack run to completion? */ - [[nodiscard]] bool hasCompleted() const; - - protected: - /** Overridden in a sub-class to implement functionality in the alternate stack */ - DLL_PRIVATE virtual void callback() = 0; - - private: - DLL_PRIVATE static void callbackWrapper(RuntimeContext * rc); - - std::vector stack; - ucontext_t ctxInitial {}; - ucontext_t ctxCallback {}; - bool completed { false }; - bool swapped { false}; -}; - -} + class DLL_PUBLIC RuntimeContext { + public: + /** + * Create a new RuntimeContent + * @param stacksize The size in bytes of the new stack. + */ + explicit RuntimeContext(size_t stacksize = 16384); + virtual ~RuntimeContext() = default; + /// Standard move/copy support + SPECIAL_MEMBERS_DEFAULT_MOVE_NO_COPY(RuntimeContext); + + /** Swap to/from the contained stack. */ + void swapContext(); + + /** Has the callback on the contained stack run to completion? */ + [[nodiscard]] bool hasCompleted() const; + + protected: + /** Overridden in a sub-class to implement functionality in the alternate stack */ + DLL_PRIVATE virtual void callback() = 0; + + private: + DLL_PRIVATE static void callbackWrapper(RuntimeContext * rc); + + std::vector stack; + ucontext_t ctxInitial {}; + ucontext_t ctxCallback {}; + bool completed {false}; + bool swapped {false}; + }; + + } } #endif - diff --git a/libadhocutil/safeMapFind.h b/libadhocutil/safeMapFind.h index 980c9b3..3a11f0c 100644 --- a/libadhocutil/safeMapFind.h +++ b/libadhocutil/safeMapFind.h @@ -5,59 +5,59 @@ namespace AdHoc { -/* - * Find the key and return the iterator to the pair, - * or throw Ex(key) if not found. - */ -template -typename Map::const_iterator -safeMapFind(const Map & map, const typename Map::key_type & key) -{ - if (auto i = map.find(key); i != map.end()) { - return i; + /* + * Find the key and return the iterator to the pair, + * or throw Ex(key) if not found. + */ + template + typename Map::const_iterator + safeMapFind(const Map & map, const typename Map::key_type & key) + { + if (auto i = map.find(key); i != map.end()) { + return i; + } + throw Ex(key); } - throw Ex(key); -} -/* - * Find the key and return the mapped value - * or the provided default value if not found. - */ -template -typename Map::mapped_type -defaultMapLookup(const Map & map, const typename Map::key_type & key, const typename Map::mapped_type & def = typename Map::mapped_type()) -{ - if (auto i = map.find(key); i != map.end()) { - return i->second; + /* + * Find the key and return the mapped value + * or the provided default value if not found. + */ + template + typename Map::mapped_type + defaultMapLookup(const Map & map, const typename Map::key_type & key, + const typename Map::mapped_type & def = typename Map::mapped_type()) + { + if (auto i = map.find(key); i != map.end()) { + return i->second; + } + return def; } - return def; -} -/* - * Find the key and return the mapped value - * or throw Ex(key) if not found. - */ -template -const typename Map::mapped_type & -safeMapLookup(const Map & map, const typename Map::key_type & key) -{ - if (auto i = map.find(key); i != map.end()) { - return i->second; + /* + * Find the key and return the mapped value + * or throw Ex(key) if not found. + */ + template + const typename Map::mapped_type & + safeMapLookup(const Map & map, const typename Map::key_type & key) + { + if (auto i = map.find(key); i != map.end()) { + return i->second; + } + throw Ex(key); } - throw Ex(key); -} -/* - * Simple search, true if found, false otherwise - */ -template -bool -containerContains(const Cont & c, const typename Cont::value_type & v) -{ - return (std::find(c.begin(), c.end(), v) != c.end()); -} + /* + * Simple search, true if found, false otherwise + */ + template + bool + containerContains(const Cont & c, const typename Cont::value_type & v) + { + return (std::find(c.begin(), c.end(), v) != c.end()); + } } #endif - diff --git a/libadhocutil/scopeExit.cpp b/libadhocutil/scopeExit.cpp index 0163aad..7384a66 100644 --- a/libadhocutil/scopeExit.cpp +++ b/libadhocutil/scopeExit.cpp @@ -2,43 +2,43 @@ namespace AdHoc { -ScopeExit::ScopeExit() = default; + ScopeExit::ScopeExit() = default; -ScopeExit::ScopeExit(const Event & onexitpre, const Event & onsuccess, const Event & onfailure, const Event & onexitpost) -{ - if (onexitpre) { - onExitPre.push_back(onexitpre); - } - if (onsuccess) { - onSuccess.push_back(onsuccess); - } - if (onfailure) { - onFailure.push_back(onfailure); - } - if (onexitpost) { - onExitPost.push_back(onexitpost); + ScopeExit::ScopeExit( + const Event & onexitpre, const Event & onsuccess, const Event & onfailure, const Event & onexitpost) + { + if (onexitpre) { + onExitPre.push_back(onexitpre); + } + if (onsuccess) { + onSuccess.push_back(onsuccess); + } + if (onfailure) { + onFailure.push_back(onfailure); + } + if (onexitpost) { + onExitPost.push_back(onexitpost); + } } -} -ScopeExit::~ScopeExit() -{ - for(const auto & e : onExitPre) { - e(); - } - if (std::uncaught_exceptions()) { - for(const auto & e : onFailure) { + ScopeExit::~ScopeExit() + { + for (const auto & e : onExitPre) { e(); } - } - else { - for(const auto & e : onSuccess) { + if (std::uncaught_exceptions()) { + for (const auto & e : onFailure) { + e(); + } + } + else { + for (const auto & e : onSuccess) { + e(); + } + } + for (const auto & e : onExitPost) { e(); } } - for(const auto & e : onExitPost) { - e(); - } -} } - diff --git a/libadhocutil/scopeExit.h b/libadhocutil/scopeExit.h index 9a632d4..1b50fa8 100644 --- a/libadhocutil/scopeExit.h +++ b/libadhocutil/scopeExit.h @@ -1,15 +1,15 @@ #ifndef ADHOCUTIL_SCOPEEXIT_H #define ADHOCUTIL_SCOPEEXIT_H +#include "c++11Helpers.h" +#include "visibility.h" #include #include -#include "visibility.h" -#include "c++11Helpers.h" namespace AdHoc { -/// Run code at scope exit. -class DLL_PUBLIC ScopeExit { + /// Run code at scope exit. + class DLL_PUBLIC ScopeExit { public: /** Callback for code to be run. */ using Event = std::function; @@ -24,7 +24,8 @@ class DLL_PUBLIC ScopeExit { * @param failure Only run this if the scope is exitted because of an uncaught exception. * @param post Run this code (unconditionally) last. */ - explicit ScopeExit(const Event & pre, const Event & success = Event(), const Event & failure = Event(), const Event & post = Event()); + explicit ScopeExit(const Event & pre, const Event & success = Event(), const Event & failure = Event(), + const Event & post = Event()); ~ScopeExit(); /// Standard move/copy support @@ -36,9 +37,8 @@ class DLL_PUBLIC ScopeExit { std::vector onFailure; std::vector onExitPost; /// @endcond -}; + }; } #endif - diff --git a/libadhocutil/semaphore.cpp b/libadhocutil/semaphore.cpp index 38ff0fe..b2354c2 100644 --- a/libadhocutil/semaphore.cpp +++ b/libadhocutil/semaphore.cpp @@ -1,9 +1,7 @@ #include "semaphore.h" namespace AdHoc { - Semaphore::Semaphore(unsigned int initial) : count(initial) - { - } + Semaphore::Semaphore(unsigned int initial) : count(initial) { } void Semaphore::notify() @@ -43,4 +41,3 @@ namespace AdHoc { return count; } } - diff --git a/libadhocutil/semaphore.h b/libadhocutil/semaphore.h index bb20324..b3633b0 100644 --- a/libadhocutil/semaphore.h +++ b/libadhocutil/semaphore.h @@ -4,33 +4,32 @@ // Borrowed from StackOverflow // http://stackoverflow.com/questions/4792449/c0x-has-no-semaphores-how-to-synchronize-threads +#include "visibility.h" #include #include -#include "visibility.h" namespace AdHoc { /// A portable semaphore with timeout support class DLL_PUBLIC Semaphore { - public: - /// Construct a new semaphore with optional initial count. - explicit Semaphore(unsigned int initial = 0); + public: + /// Construct a new semaphore with optional initial count. + explicit Semaphore(unsigned int initial = 0); - /// Notify one waiting thread. - void notify(); - /// Wait for a single count. - void wait(); - /// Wait for a single count with timeout. - /// @param ms Timeout in milliseconds. - bool wait(unsigned int ms); - /// Free - [[nodiscard]] unsigned int freeCount() const; + /// Notify one waiting thread. + void notify(); + /// Wait for a single count. + void wait(); + /// Wait for a single count with timeout. + /// @param ms Timeout in milliseconds. + bool wait(unsigned int ms); + /// Free + [[nodiscard]] unsigned int freeCount() const; - private: - std::mutex mutex; - std::condition_variable condition; - unsigned long count; + private: + std::mutex mutex; + std::condition_variable condition; + unsigned long count; }; } #endif - diff --git a/libadhocutil/sysImpl.cpp b/libadhocutil/sysImpl.cpp index 66ac6ea..c92b445 100644 --- a/libadhocutil/sysImpl.cpp +++ b/libadhocutil/sysImpl.cpp @@ -1,17 +1,19 @@ -#include #include "compileTimeFormatter.h" +#include namespace AdHoc { AdHocFormatter(SystemExceptionMsg, "%? (%?:%?)"); - void SystemException::ice_print(std::ostream & s) const + void + SystemException::ice_print(std::ostream & s) const { SystemExceptionMsg::write(s, task, errNo, message); } AdHocFormatter(SystemExceptionOnMsg, "%? on '%?' (%?:%?)"); - void SystemExceptionOn::ice_print(std::ostream & s) const + void + SystemExceptionOn::ice_print(std::ostream & s) const { SystemExceptionOnMsg::write(s, task, objectName, errNo, message); } diff --git a/libadhocutil/unique.h b/libadhocutil/unique.h index 5c77907..d64ac47 100644 --- a/libadhocutil/unique.h +++ b/libadhocutil/unique.h @@ -6,4 +6,3 @@ #define MAKE_UNIQUE(x) CONCATENATE(x, __COUNTER__) #endif - diff --git a/libadhocutil/unittests/testBuffer.cpp b/libadhocutil/unittests/testBuffer.cpp index f9f7726..6e58120 100644 --- a/libadhocutil/unittests/testBuffer.cpp +++ b/libadhocutil/unittests/testBuffer.cpp @@ -5,7 +5,7 @@ using namespace AdHoc; -BOOST_AUTO_TEST_CASE ( create ) +BOOST_AUTO_TEST_CASE(create) { Buffer empty; Buffer copy("const", Buffer::Copy); @@ -32,7 +32,7 @@ BOOST_AUTO_TEST_CASE ( create ) BOOST_REQUIRE_EQUAL("Nonconst", fre.str()); } -BOOST_AUTO_TEST_CASE( writestream ) +BOOST_AUTO_TEST_CASE(writestream) { std::stringstream buf; Buffer b; @@ -41,7 +41,7 @@ BOOST_AUTO_TEST_CASE( writestream ) BOOST_REQUIRE_EQUAL("Some text.And then some more.", buf.str()); } -BOOST_AUTO_TEST_CASE( appendempty ) +BOOST_AUTO_TEST_CASE(appendempty) { Buffer b; // These should not add content @@ -55,13 +55,10 @@ BOOST_AUTO_TEST_CASE( appendempty ) BOOST_REQUIRE(!b); } -BOOST_AUTO_TEST_CASE( appendthings ) +BOOST_AUTO_TEST_CASE(appendthings) { Buffer b; - b.append("string a") - .append(std::string(" b")) - .appendf(" num %d", 1) - .appendbf(" num %d", 2); + b.append("string a").append(std::string(" b")).appendf(" num %d", 1).appendbf(" num %d", 2); BOOST_REQUIRE_EQUAL(22, b.length()); BOOST_REQUIRE_EQUAL("string a b num 1 num 2", b.str()); const char * cstring = b; @@ -69,19 +66,16 @@ BOOST_AUTO_TEST_CASE( appendthings ) BOOST_REQUIRE_EQUAL("string a b num 1 num 2", cstring); } -BOOST_AUTO_TEST_CASE( writeto ) +BOOST_AUTO_TEST_CASE(writeto) { Buffer b; - b.append("string a") - .append(std::string(" b")) - .appendf(" num %d", 1) - .appendbf(" num %d", 2); + b.append("string a").append(std::string(" b")).appendf(" num %d", 1).appendbf(" num %d", 2); std::string buf(22, '\0'); b.writeto(buf.data(), 23, 0); BOOST_REQUIRE_EQUAL(buf, "string a b num 1 num 2"); } -BOOST_AUTO_TEST_CASE( operators ) +BOOST_AUTO_TEST_CASE(operators) { auto expected = "cstringstd::string"; Buffer a; @@ -102,7 +96,7 @@ BOOST_AUTO_TEST_CASE( operators ) BOOST_REQUIRE_EQUAL(expected, d.str()); } -BOOST_AUTO_TEST_CASE( clear ) +BOOST_AUTO_TEST_CASE(clear) { Buffer b("some"); BOOST_REQUIRE(b); @@ -110,7 +104,7 @@ BOOST_AUTO_TEST_CASE( clear ) BOOST_REQUIRE(!b); } -BOOST_AUTO_TEST_CASE( replacesstringbf ) +BOOST_AUTO_TEST_CASE(replacesstringbf) { auto str = Buffer().appendbf("something %d", 1234).str(); BOOST_REQUIRE_EQUAL("something 1234", str); @@ -120,4 +114,3 @@ BOOST_AUTO_TEST_CASE( replacesstringbf ) std::string macrostringbf = stringbf("something %d", 1234); BOOST_REQUIRE_EQUAL("something 1234", macrostringbf); } - diff --git a/libadhocutil/unittests/testCache.cpp b/libadhocutil/unittests/testCache.cpp index 8fba9cf..373d8d8 100644 --- a/libadhocutil/unittests/testCache.cpp +++ b/libadhocutil/unittests/testCache.cpp @@ -1,20 +1,22 @@ #define BOOST_TEST_MODULE Cache #include -#include #include "cache.h" #include "cache.impl.h" +#include // NOLINTNEXTLINE(hicpp-special-member-functions) class Obj { - public: - // NOLINTNEXTLINE(hicpp-explicit-conversions) - Obj(int i) : v(i) { } - void operator=(const Obj &) = delete; - bool operator==(const int & i) const { - return v == i; - } - int v; +public: + // NOLINTNEXTLINE(hicpp-explicit-conversions) + Obj(int i) : v(i) { } + void operator=(const Obj &) = delete; + bool + operator==(const int & i) const + { + return v == i; + } + int v; }; bool @@ -25,7 +27,8 @@ operator==(const int & i, const Obj & o) namespace std { /// LCOV_EXCL_START (diagnostics) - ostream & operator<<(ostream & s, const Obj & o) + ostream & + operator<<(ostream & s, const Obj & o) { return s << o.v; } @@ -43,7 +46,7 @@ namespace AdHoc { using namespace AdHoc; -BOOST_AUTO_TEST_CASE( miss ) +BOOST_AUTO_TEST_CASE(miss) { TestCache tc; BOOST_REQUIRE_EQUAL(0, tc.size()); @@ -54,7 +57,7 @@ BOOST_AUTO_TEST_CASE( miss ) BOOST_REQUIRE_EQUAL(1, tc.size()); } -BOOST_AUTO_TEST_CASE( hit ) +BOOST_AUTO_TEST_CASE(hit) { TestCache tc; auto vu = time(nullptr) + 5; @@ -69,7 +72,7 @@ BOOST_AUTO_TEST_CASE( hit ) BOOST_REQUIRE_EQUAL(0, tc.size()); } -BOOST_AUTO_TEST_CASE( multivalues ) +BOOST_AUTO_TEST_CASE(multivalues) { TestCache tc; auto vu = time(nullptr) + 5; @@ -89,7 +92,7 @@ BOOST_AUTO_TEST_CASE( multivalues ) BOOST_REQUIRE_EQUAL(0, tc.size()); } -BOOST_AUTO_TEST_CASE( expired ) +BOOST_AUTO_TEST_CASE(expired) { TestCache tc; tc.add("miss", 3, time(nullptr) - 5); @@ -110,13 +113,19 @@ BOOST_AUTO_TEST_CASE( expired ) BOOST_REQUIRE_EQUAL(1, tc.size()); } -BOOST_AUTO_TEST_CASE( callcache ) +BOOST_AUTO_TEST_CASE(callcache) { TestCache tc; int callCount = 0; auto vu = time(nullptr) + 5; BOOST_REQUIRE_EQUAL(nullptr, tc.get("key")); - tc.addFactory("key", [&callCount]{ callCount++; return 3; }, vu); + tc.addFactory( + "key", + [&callCount] { + callCount++; + return 3; + }, + vu); BOOST_REQUIRE_EQUAL(0, callCount); BOOST_REQUIRE_EQUAL(3, *tc.get("key")); BOOST_REQUIRE_EQUAL(1, callCount); @@ -124,13 +133,19 @@ BOOST_AUTO_TEST_CASE( callcache ) BOOST_REQUIRE_EQUAL(1, callCount); } -BOOST_AUTO_TEST_CASE( pointercallcache ) +BOOST_AUTO_TEST_CASE(pointercallcache) { TestCache tc; int callCount = 0; auto vu = time(nullptr) + 5; BOOST_REQUIRE_EQUAL(nullptr, tc.get("key")); - tc.addPointerFactory("key", [&callCount]{ callCount++; return TestCache::Value(new Obj(3)); }, vu); + tc.addPointerFactory( + "key", + [&callCount] { + callCount++; + return TestCache::Value(new Obj(3)); + }, + vu); BOOST_REQUIRE_EQUAL(0, callCount); BOOST_REQUIRE_EQUAL(3, *tc.get("key")); BOOST_REQUIRE_EQUAL(1, callCount); @@ -138,7 +153,7 @@ BOOST_AUTO_TEST_CASE( pointercallcache ) BOOST_REQUIRE_EQUAL(1, callCount); } -BOOST_AUTO_TEST_CASE( hitThenRenove ) +BOOST_AUTO_TEST_CASE(hitThenRenove) { TestCache tc; tc.add("key", 3, time(nullptr) + 5); @@ -150,7 +165,7 @@ BOOST_AUTO_TEST_CASE( hitThenRenove ) BOOST_REQUIRE_EQUAL(3, *h); } -BOOST_AUTO_TEST_CASE( addPointer ) +BOOST_AUTO_TEST_CASE(addPointer) { TestCache tc; auto v = TestCache::Value(new Obj(3)); @@ -159,4 +174,3 @@ BOOST_AUTO_TEST_CASE( addPointer ) BOOST_REQUIRE(h); BOOST_REQUIRE_EQUAL(3, *h); } - diff --git a/libadhocutil/unittests/testCompileTimeFormatter.cpp b/libadhocutil/unittests/testCompileTimeFormatter.cpp index 2109e01..ad5adbf 100644 --- a/libadhocutil/unittests/testCompileTimeFormatter.cpp +++ b/libadhocutil/unittests/testCompileTimeFormatter.cpp @@ -1,10 +1,10 @@ #define BOOST_TEST_MODULE CompileTimeFormatter #include +#include "memstream.h" #include -#include #include -#include "memstream.h" +#include #include @@ -22,7 +22,10 @@ constexpr const char * formatStringCustom = "custom %()"; constexpr const char * formatStringCustomParam1 = "custom %(\x3)"; constexpr const char * formatStringCustomParam2 = "custom %(\x9)"; constexpr const char * formatStringCustomLong = "custom %(longname)"; -constexpr const char * formatStringLong = " "; +constexpr const char * formatStringLong + = " " + " " + " "; constexpr const char * formatStringMultiArg = "value%ra"; constexpr const char * formatStringEscape1 = "literal %% percentage."; constexpr const char * formatStringEscape2 = "literal %%? percentage."; @@ -33,8 +36,9 @@ namespace AdHoc { // Custom stream writer formatter, formats as // -( bracketed expression )- StreamWriterT('(', ')') { - template - static void write(stream & s, const P & p, const Pn & ... pn) + template + static void + write(stream & s, const P & p, const Pn &... pn) { s << "-( " << p << " )-"; StreamWriter::next(s, pn...); @@ -43,8 +47,9 @@ namespace AdHoc { // Custom stream writer formatter with a long identifier, formats as // ---( bracketed expression )--- StreamWriterT('(', 'l', 'o', 'n', 'g', 'n', 'a', 'm', 'e', ')') { - template - static void write(stream & s, const P & p, const Pn & ... pn) + template + static void + write(stream & s, const P & p, const Pn &... pn) { s << "---( " << p << " )---"; StreamWriter::next(s, pn...); @@ -53,8 +58,9 @@ namespace AdHoc { // Custom stream writer formatter that has parameter in the format string, formats as // dashes*-( bracketed expression )dashes*- StreamWriterTP(dashes, '(', dashes, ')') { - template - static void write(stream & s, const P & p, const Pn & ... pn) + template + static void + write(stream & s, const P & p, const Pn &... pn) { // NOLINTNEXTLINE(bugprone-string-constructor) std::string d(dashes, '-'); @@ -65,8 +71,9 @@ namespace AdHoc { // Custom stream writer formatter, formats // right-aligned by given width StreamWriterT('r', 'a') { - template - static void write(stream & s, int width, const P & p, const Pn & ... pn) + template + static void + write(stream & s, int width, const P & p, const Pn &... pn) { std::stringstream buf; buf << p; @@ -116,137 +123,137 @@ static_assert(strchrnul() == 3); static_assert(strchrnul() == 7); #endif -BOOST_FIXTURE_TEST_SUITE( TestStreamWrite, std::stringstream ) +BOOST_FIXTURE_TEST_SUITE(TestStreamWrite, std::stringstream) -BOOST_AUTO_TEST_CASE ( empty ) +BOOST_AUTO_TEST_CASE(empty) { Formatter::write(*this); BOOST_CHECK(this->str().empty()); } -BOOST_AUTO_TEST_CASE ( single ) +BOOST_AUTO_TEST_CASE(single) { Formatter::write(*this); BOOST_CHECK_EQUAL(this->str(), "1"); } -BOOST_AUTO_TEST_CASE ( start ) +BOOST_AUTO_TEST_CASE(start) { Formatter::write(*this, 10); BOOST_CHECK_EQUAL(this->str(), "10 after"); } -BOOST_AUTO_TEST_CASE ( end ) +BOOST_AUTO_TEST_CASE(end) { Formatter::write(*this, 10); BOOST_CHECK_EQUAL(this->str(), "before 10"); } -BOOST_AUTO_TEST_CASE ( lonely ) +BOOST_AUTO_TEST_CASE(lonely) { Formatter::write(*this, 10); BOOST_CHECK_EQUAL(this->str(), "10"); } -BOOST_AUTO_TEST_CASE ( literal ) +BOOST_AUTO_TEST_CASE(literal) { Formatter::write(*this); BOOST_CHECK_EQUAL(this->str(), "literal"); } -BOOST_AUTO_TEST_CASE ( singleInt ) +BOOST_AUTO_TEST_CASE(singleInt) { Formatter::write(*this, 32); BOOST_CHECK_EQUAL(this->str(), "single 32."); } -BOOST_AUTO_TEST_CASE ( singleIntReturn ) +BOOST_AUTO_TEST_CASE(singleIntReturn) { BOOST_CHECK_EQUAL(Formatter::write(*this, 32).str(), "single 32."); } -BOOST_AUTO_TEST_CASE ( singleDouble ) +BOOST_AUTO_TEST_CASE(singleDouble) { Formatter::write(*this, 3.14); BOOST_CHECK_EQUAL(this->str(), "single 3.14."); } -BOOST_AUTO_TEST_CASE ( singlePath ) +BOOST_AUTO_TEST_CASE(singlePath) { std::filesystem::path p("/tmp/test/path"); Formatter::write(*this, p); BOOST_CHECK_EQUAL(this->str(), R"(single "/tmp/test/path".)"); } -BOOST_AUTO_TEST_CASE ( multi ) +BOOST_AUTO_TEST_CASE(multi) { Formatter::write(*this, "one", "two"); BOOST_CHECK_EQUAL(this->str(), "First one, then two."); } -BOOST_AUTO_TEST_CASE ( escape1 ) +BOOST_AUTO_TEST_CASE(escape1) { Formatter::write(*this); BOOST_CHECK_EQUAL(this->str(), "literal % percentage."); } -BOOST_AUTO_TEST_CASE ( escape2 ) +BOOST_AUTO_TEST_CASE(escape2) { Formatter::write(*this); BOOST_CHECK_EQUAL(this->str(), "literal %? percentage."); } -BOOST_AUTO_TEST_CASE ( escape3 ) +BOOST_AUTO_TEST_CASE(escape3) { Formatter::write(*this, 3); BOOST_CHECK_EQUAL(this->str(), "literal %3 percentage."); } -BOOST_AUTO_TEST_CASE ( escape4 ) +BOOST_AUTO_TEST_CASE(escape4) { Formatter::write(*this, 3); BOOST_CHECK_EQUAL(this->str(), "literal %3% percentage."); } -BOOST_AUTO_TEST_CASE ( customBracketted ) +BOOST_AUTO_TEST_CASE(customBracketted) { Formatter::write(*this, "expr"); BOOST_CHECK_EQUAL(this->str(), "custom -( expr )-"); } -BOOST_AUTO_TEST_CASE ( customLongName ) +BOOST_AUTO_TEST_CASE(customLongName) { Formatter::write(*this, "some text here"); BOOST_CHECK_EQUAL(this->str(), "custom ---( some text here )---"); } -BOOST_AUTO_TEST_CASE ( customParam1 ) +BOOST_AUTO_TEST_CASE(customParam1) { Formatter::write(*this, "some text here"); BOOST_CHECK_EQUAL(this->str(), "custom ---( some text here )---"); } -BOOST_AUTO_TEST_CASE ( customParam2 ) +BOOST_AUTO_TEST_CASE(customParam2) { Formatter::write(*this, "some text here"); BOOST_CHECK_EQUAL(this->str(), "custom ---------( some text here )---------"); } using TestFormat = Formatter; -BOOST_AUTO_TEST_CASE ( typedefFormat ) +BOOST_AUTO_TEST_CASE(typedefFormat) { TestFormat::write(*this, "expr"); BOOST_CHECK_EQUAL(this->str(), "custom -( expr )-"); } AdHocFormatter(TypedefWrapper, "Typedef wrapper %?."); -BOOST_AUTO_TEST_CASE ( typedefWrapper ) +BOOST_AUTO_TEST_CASE(typedefWrapper) { TypedefWrapper::write(*this, "expr"); BOOST_CHECK_EQUAL(this->str(), "Typedef wrapper expr."); } -BOOST_AUTO_TEST_CASE ( longFormatString ) +BOOST_AUTO_TEST_CASE(longFormatString) { Formatter::write(*this); BOOST_CHECK_EQUAL(this->str().length(), 246); @@ -254,7 +261,7 @@ BOOST_AUTO_TEST_CASE ( longFormatString ) BOOST_AUTO_TEST_SUITE_END(); -BOOST_AUTO_TEST_CASE ( customMultiArgRightAlign ) +BOOST_AUTO_TEST_CASE(customMultiArgRightAlign) { std::stringstream buf1, buf2, buf3; const int width = 20; @@ -266,7 +273,7 @@ BOOST_AUTO_TEST_CASE ( customMultiArgRightAlign ) BOOST_CHECK_EQUAL(buf3.str(), "value 123.45"); } -BOOST_AUTO_TEST_CASE ( get ) +BOOST_AUTO_TEST_CASE(get) { auto s = Formatter::get(20, "something else"); BOOST_CHECK_EQUAL(s, "value something else"); @@ -274,7 +281,7 @@ BOOST_AUTO_TEST_CASE ( get ) constexpr #include -BOOST_AUTO_TEST_CASE( lorem_ipsum ) + BOOST_AUTO_TEST_CASE(lorem_ipsum) { using LIF = Formatter; auto s = LIF::get(); @@ -286,7 +293,8 @@ BOOST_AUTO_TEST_CASE( lorem_ipsum ) namespace AdHoc { template<> - inline void appendStream(FILE & strm, const char * const p, size_t n) + inline void + appendStream(FILE & strm, const char * const p, size_t n) { BOOST_VERIFY(fwrite(p, n, 1, &strm) == 1); } @@ -299,7 +307,7 @@ operator<<(FILE & strm, const char * const p) return strm; } -BOOST_AUTO_TEST_CASE( filestar ) +BOOST_AUTO_TEST_CASE(filestar) { MemStream strm; // NOLINTNEXTLINE(misc-non-copyable-objects) @@ -330,10 +338,11 @@ static_assert(419 == decdigits<'0', '4', '1', '9'>()); // The following tests represent CTF's [partial] emulation of many // POSIX formatting features #define GLIBC_FMT_TEST(NAME, FMT, ...) \ - AdHocFormatter(NAME ## fmtr, FMT); \ - BOOST_AUTO_TEST_CASE(NAME ## t) { \ + AdHocFormatter(NAME##fmtr, FMT); \ + BOOST_AUTO_TEST_CASE(NAME##t) \ + { \ BOOST_TEST_CONTEXT(FMT) { \ - auto str = NAME ## fmtr::get(__VA_ARGS__); \ + auto str = NAME##fmtr::get(__VA_ARGS__); \ char * buf = NULL; \ int len = asprintf(&buf, FMT, __VA_ARGS__); \ auto bufp = std::unique_ptr(buf, std::free); \ @@ -351,8 +360,8 @@ GLIBC_FMT_TEST(s5, "in %.*s.", 7, "other"); GLIBC_FMT_TEST(s35, "in %3s.", "other"); GLIBC_FMT_TEST(s55, "in %5s.", "other"); GLIBC_FMT_TEST(s115, "in %11s.", "other"); -//std::setw does not truncate strings -//GLIBC_FMT_TEST(sd35, "in %.3s.", "other"); +// std::setw does not truncate strings +// GLIBC_FMT_TEST(sd35, "in %.3s.", "other"); GLIBC_FMT_TEST(sd55, "in %.5s.", "other"); GLIBC_FMT_TEST(sd115, "in %.11s.", "other"); @@ -421,8 +430,7 @@ GLIBC_FMT_TEST(g6, "in %G.", -123.456789); GLIBC_FMT_TEST(g7, "in %g.", 123456789.123); GLIBC_FMT_TEST(g8, "in %g.", -123456789.123); -GLIBC_FMT_TEST(fmtlibt_fmt, "%0.10f:%04d:%+g:%s:%p:%c:%%\n", - 1.234, 42, 3.13, "str", (void*)1000, (int)'X'); +GLIBC_FMT_TEST(fmtlibt_fmt, "%0.10f:%04d:%+g:%s:%p:%c:%%\n", 1.234, 42, 3.13, "str", (void *)1000, (int)'X'); AdHocFormatter(chars_written_fmt, "%n %s %n %d %n"); BOOST_AUTO_TEST_CASE(chars_written) @@ -514,4 +522,3 @@ BOOST_AUTO_TEST_CASE(user_defined_literal_fmt_write) "foo %?"_fmt(str, 42); BOOST_CHECK_EQUAL("foo 42", str.str()); } - diff --git a/libadhocutil/unittests/testContext.cpp b/libadhocutil/unittests/testContext.cpp index 0447beb..edc5668 100644 --- a/libadhocutil/unittests/testContext.cpp +++ b/libadhocutil/unittests/testContext.cpp @@ -6,34 +6,35 @@ using namespace AdHoc::System; class TestRuntimeContext : public RuntimeContext { - public: - void run() - { - log += "a"; - swapContext(); - log += "b"; - swapContext(); - log += "c"; - swapContext(); - log += "d"; - } +public: + void + run() + { + log += "a"; + swapContext(); + log += "b"; + swapContext(); + log += "c"; + swapContext(); + log += "d"; + } - void callback() override - { - log += "e"; - swapContext(); - log += "f"; - swapContext(); - } + void + callback() override + { + log += "e"; + swapContext(); + log += "f"; + swapContext(); + } - std::string log; + std::string log; }; -BOOST_AUTO_TEST_CASE ( basic ) +BOOST_AUTO_TEST_CASE(basic) { TestRuntimeContext trc; trc.run(); BOOST_REQUIRE_EQUAL("aebfcd", trc.log); BOOST_REQUIRE(trc.hasCompleted()); } - diff --git a/libadhocutil/unittests/testCurl.cpp b/libadhocutil/unittests/testCurl.cpp index 977bbfd..5110c75 100644 --- a/libadhocutil/unittests/testCurl.cpp +++ b/libadhocutil/unittests/testCurl.cpp @@ -1,19 +1,18 @@ #define BOOST_TEST_MODULE Curl #include -#include +#include "compileTimeFormatter.h" #include "curlHandle.h" #include "curlMultiHandle.h" #include "curlStream.h" -#include "compileTimeFormatter.h" #include "definedDirs.h" #include "net.h" #include +#include using namespace AdHoc::Net; -static -size_t +static size_t discard(void *, size_t sz, size_t nm, void *) { return sz * nm; @@ -24,7 +23,7 @@ const auto urlGen = [](const std::string_view & url) { return FileUrl::get(rootDir.string(), url); }; -BOOST_AUTO_TEST_CASE( fetch_file ) +BOOST_AUTO_TEST_CASE(fetch_file) { auto url = urlGen("testCurl.cpp"); BOOST_TEST_CONTEXT(url) { @@ -34,7 +33,7 @@ BOOST_AUTO_TEST_CASE( fetch_file ) } } -BOOST_AUTO_TEST_CASE( setAndGetOptions ) +BOOST_AUTO_TEST_CASE(setAndGetOptions) { auto url = urlGen("testCurl.cpp"); CurlHandle ch(url); @@ -58,14 +57,14 @@ BOOST_AUTO_TEST_CASE( setAndGetOptions ) BOOST_REQUIRE_LT(totalTime, 50); } -BOOST_AUTO_TEST_CASE( fetch_missing ) +BOOST_AUTO_TEST_CASE(fetch_missing) { auto url = urlGen("nothere"); CurlHandle ch(url); BOOST_REQUIRE_THROW(ch.perform(), AdHoc::Net::CurlException); } -BOOST_AUTO_TEST_CASE( fetch_http_stream ) +BOOST_AUTO_TEST_CASE(fetch_http_stream) { CurlStreamSource css("https://sys.randomdan.homeip.net/env.cgi"); css.appendHeader("X-POWERED-BY: mature-cheddar"); @@ -82,7 +81,7 @@ BOOST_AUTO_TEST_CASE( fetch_http_stream ) BOOST_REQUIRE_EQUAL(1, expected); } -BOOST_AUTO_TEST_CASE( fetch_file_stream ) +BOOST_AUTO_TEST_CASE(fetch_file_stream) { auto url = urlGen("testCurl.cpp"); CurlStreamSource css(url); @@ -99,7 +98,7 @@ BOOST_AUTO_TEST_CASE( fetch_file_stream ) } } -BOOST_AUTO_TEST_CASE( fetch_missing_stream ) +BOOST_AUTO_TEST_CASE(fetch_missing_stream) { auto url = urlGen("nothere"); CurlStreamSource css(url); @@ -110,8 +109,7 @@ BOOST_AUTO_TEST_CASE( fetch_missing_stream ) BOOST_REQUIRE(!curlstrm.good()); } -static -void +static void mapFileToName(std::map & map, const std::string & file, std::istream & curlstrm) { std::string tok; @@ -121,17 +119,20 @@ mapFileToName(std::map & map, const std::string & file map[file] = tok; } -BOOST_AUTO_TEST_CASE( fetch_multi ) +BOOST_AUTO_TEST_CASE(fetch_multi) { using std::placeholders::_1; CurlMultiHandle cmh; std::map files; - cmh.addCurl(urlGen("/testBuffer.cpp"), - [&files](auto && PH1) { return mapFileToName(files, "testBuffer.cpp", PH1); }); - cmh.addCurl(urlGen("/testCurl.cpp"), - [&files](auto && PH1) { return mapFileToName(files, "testCurl.cpp", PH1); }); - cmh.addCurl(urlGen("/testLocks.cpp"), - [&files](auto && PH1) { return mapFileToName(files, "testLocks.cpp", PH1); }); + cmh.addCurl(urlGen("/testBuffer.cpp"), [&files](auto && PH1) { + return mapFileToName(files, "testBuffer.cpp", PH1); + }); + cmh.addCurl(urlGen("/testCurl.cpp"), [&files](auto && PH1) { + return mapFileToName(files, "testCurl.cpp", PH1); + }); + cmh.addCurl(urlGen("/testLocks.cpp"), [&files](auto && PH1) { + return mapFileToName(files, "testLocks.cpp", PH1); + }); cmh.performAll(); BOOST_REQUIRE_EQUAL(3, files.size()); BOOST_REQUIRE_EQUAL("Locks", files["testLocks.cpp"]); @@ -139,7 +140,7 @@ BOOST_AUTO_TEST_CASE( fetch_multi ) BOOST_REQUIRE_EQUAL("Curl", files["testCurl.cpp"]); } -BOOST_AUTO_TEST_CASE( fetch_multi_fail ) +BOOST_AUTO_TEST_CASE(fetch_multi_fail) { CurlMultiHandle cmh; bool errored = false; @@ -161,4 +162,3 @@ BOOST_AUTO_TEST_CASE( fetch_multi_fail ) BOOST_REQUIRE(!finished); BOOST_REQUIRE(errored); } - diff --git a/libadhocutil/unittests/testDirs.cpp b/libadhocutil/unittests/testDirs.cpp index 08284ee..3073897 100644 --- a/libadhocutil/unittests/testDirs.cpp +++ b/libadhocutil/unittests/testDirs.cpp @@ -4,7 +4,7 @@ #include #include -BOOST_AUTO_TEST_CASE( iexist ) +BOOST_AUTO_TEST_CASE(iexist) { BOOST_REQUIRE(std::filesystem::exists(selfExe)); BOOST_REQUIRE(selfExe.is_absolute()); @@ -13,4 +13,3 @@ BOOST_AUTO_TEST_CASE( iexist ) BOOST_REQUIRE(std::filesystem::is_directory(binDir)); BOOST_REQUIRE_EQUAL("libadhocutil", rootDir.parent_path().filename()); } - diff --git a/libadhocutil/unittests/testException.cpp b/libadhocutil/unittests/testException.cpp index 63fc2a3..ade3617 100644 --- a/libadhocutil/unittests/testException.cpp +++ b/libadhocutil/unittests/testException.cpp @@ -1,68 +1,75 @@ #define BOOST_TEST_MODULE Excetion #include -#include #include +#include using namespace AdHoc; class Ex1 : public AdHoc::StdException { - public: - Ex1(const char * f, int l) : file(f), line(l) { } - - private: - std::string message() const noexcept override - { - return stringf("Something something at %s:%d", file, line); - } +public: + Ex1(const char * f, int l) : file(f), line(l) { } + +private: + std::string + message() const noexcept override + { + return stringf("Something something at %s:%d", file, line); + } - const char * file; - const int line; + const char * file; + const int line; }; -class OtherBaseException : public std::exception { }; +class OtherBaseException : public std::exception { +}; class Ex2 : public AdHoc::Exception { - public: - Ex2(const char * f, int l) : file(f), line(l) { } - - private: - std::string message() const noexcept override - { - return stringf("Something other something at %s:%d", file, line); - } +public: + Ex2(const char * f, int l) : file(f), line(l) { } + +private: + std::string + message() const noexcept override + { + return stringf("Something other something at %s:%d", file, line); + } - const char * file; - const int line; + const char * file; + const int line; }; class Ex3 : public AdHoc::StdException { - private: - // LCOV_EXCL_START - std::string message() const noexcept override - { - // Never called - std::abort(); - } - // LCOV_EXCL_STOP +private: + // LCOV_EXCL_START + std::string + message() const noexcept override + { + // Never called + std::abort(); + } + // LCOV_EXCL_STOP }; -void failing1() +void +failing1() { throw Ex1(__PRETTY_FUNCTION__, 1); } -void failing2() +void +failing2() { throw Ex2(__PRETTY_FUNCTION__, 2); } -void failing3() +void +failing3() { throw Ex3(); } -BOOST_AUTO_TEST_CASE( throwCatch ) +BOOST_AUTO_TEST_CASE(throwCatch) { BOOST_REQUIRE_THROW(failing1(), Ex1); BOOST_REQUIRE_THROW(failing1(), std::exception); @@ -75,7 +82,7 @@ BOOST_AUTO_TEST_CASE( throwCatch ) BOOST_REQUIRE_THROW(failing3(), std::exception); } -BOOST_AUTO_TEST_CASE( message1 ) +BOOST_AUTO_TEST_CASE(message1) { try { failing1(); @@ -85,7 +92,7 @@ BOOST_AUTO_TEST_CASE( message1 ) } } -BOOST_AUTO_TEST_CASE( message2 ) +BOOST_AUTO_TEST_CASE(message2) { try { failing2(); @@ -94,4 +101,3 @@ BOOST_AUTO_TEST_CASE( message2 ) BOOST_REQUIRE_EQUAL("Something other something at void failing2():2", ex.what()); } } - diff --git a/libadhocutil/unittests/testFactory.cpp b/libadhocutil/unittests/testFactory.cpp index 868e5b8..58ed9f7 100644 --- a/libadhocutil/unittests/testFactory.cpp +++ b/libadhocutil/unittests/testFactory.cpp @@ -10,35 +10,34 @@ using namespace AdHoc; // NOLINTNEXTLINE(hicpp-special-member-functions) class BaseThing { - public: - BaseThing(int, std::string * n) : - name(n) - { - } +public: + BaseThing(int, std::string * n) : name(n) { } - virtual ~BaseThing() = default; + virtual ~BaseThing() = default; - virtual void execute() const = 0; + virtual void execute() const = 0; - protected: - std::string * name; +protected: + std::string * name; }; class ImplOfThing : public BaseThing { - public: - ImplOfThing(int i, std::string * s) : BaseThing(i, s) {} - void execute() const override - { - *name = typeid(this).name(); - } +public: + ImplOfThing(int i, std::string * s) : BaseThing(i, s) { } + void + execute() const override + { + *name = typeid(this).name(); + } }; class OtherImplOfThing : public BaseThing { - public: - OtherImplOfThing(int i, std::string * s) : BaseThing(i, s) {} - void execute() const override - { - *name = typeid(this).name(); - } +public: + OtherImplOfThing(int i, std::string * s) : BaseThing(i, s) { } + void + execute() const override + { + *name = typeid(this).name(); + } }; using BaseThingFactory = AdHoc::Factory; @@ -52,12 +51,12 @@ INSTANTIATEFACTORY(BaseThing, std::string, std::string); // Factories of things with commas INSTANTIATEFACTORY(BaseThing, std::map); -BOOST_AUTO_TEST_CASE( ready ) +BOOST_AUTO_TEST_CASE(ready) { BOOST_REQUIRE_EQUAL(2, PluginManager::getDefault()->count()); } -BOOST_AUTO_TEST_CASE( get ) +BOOST_AUTO_TEST_CASE(get) { auto all = PluginManager::getDefault()->getAll(); auto factory1 = PluginManager::getDefault()->get("a")->implementation(); @@ -69,7 +68,7 @@ BOOST_AUTO_TEST_CASE( get ) BOOST_REQUIRE_NE(factory1, factory3); } -BOOST_AUTO_TEST_CASE( create ) +BOOST_AUTO_TEST_CASE(create) { auto factory1 = BaseThingFactory::get("a"); auto factory2 = BaseThingFactory::get("OtherImplOfThing"); @@ -91,10 +90,9 @@ BOOST_AUTO_TEST_CASE( create ) BOOST_REQUIRE(i2 != i3); } -BOOST_AUTO_TEST_CASE( createNew ) +BOOST_AUTO_TEST_CASE(createNew) { std::string n; auto i = BaseThingFactory::createNew("a", 1, &n); BOOST_REQUIRE(i); } - diff --git a/libadhocutil/unittests/testFileUtils.cpp b/libadhocutil/unittests/testFileUtils.cpp index f92d03e..d8cf46a 100644 --- a/libadhocutil/unittests/testFileUtils.cpp +++ b/libadhocutil/unittests/testFileUtils.cpp @@ -1,18 +1,17 @@ #define BOOST_TEST_MODULE FileUtils #include -#include #include +#include #include -#define REQUIRE_INVALID_FH(fh) \ - BOOST_REQUIRE_EQUAL(fcntl(fh, F_GETFD), -1) +#define REQUIRE_INVALID_FH(fh) BOOST_REQUIRE_EQUAL(fcntl(fh, F_GETFD), -1) -#define REQUIRE_VALID_FH(fh) \ - BOOST_REQUIRE_NE(fcntl(fh, F_GETFD), -1) +#define REQUIRE_VALID_FH(fh) BOOST_REQUIRE_NE(fcntl(fh, F_GETFD), -1) -template -void testRaw() +template +void +testRaw() { int f = open("/proc/self/exe", O_RDONLY); BOOST_REQUIRE_NE(f, -1); @@ -20,22 +19,24 @@ void testRaw() BOOST_REQUIRE_EQUAL(f, fh); } -BOOST_AUTO_TEST_CASE( raw ) +BOOST_AUTO_TEST_CASE(raw) { testRaw(); testRaw(); testRaw(); } -template -T openfh(P ... p) +template +T +openfh(P... p) { T fh(rootDir / "testFileUtils.cpp", p...); return fh; } -template -T moveTest(P ... p) +template +T +moveTest(P... p) { T fh = openfh(p...); REQUIRE_VALID_FH(fh); @@ -45,17 +46,17 @@ T moveTest(P ... p) } class Base { - public: - explicit Base(AdHoc::FileUtils::FileHandle h) : fh(std::move(h)) { } - AdHoc::FileUtils::FileHandle fh; +public: + explicit Base(AdHoc::FileUtils::FileHandle h) : fh(std::move(h)) { } + AdHoc::FileUtils::FileHandle fh; }; class Sub : public Base { - public: - explicit Sub(AdHoc::FileUtils::FileHandle h) : Base(std::move(h)) { } +public: + explicit Sub(AdHoc::FileUtils::FileHandle h) : Base(std::move(h)) { } }; -BOOST_AUTO_TEST_CASE( movePassThrough ) +BOOST_AUTO_TEST_CASE(movePassThrough) { auto f = openfh(); int ffd = f.fh; @@ -69,8 +70,7 @@ BOOST_AUTO_TEST_CASE( movePassThrough ) REQUIRE_INVALID_FH(ffd); } - -BOOST_AUTO_TEST_CASE( moveFileHandle ) +BOOST_AUTO_TEST_CASE(moveFileHandle) { auto f = moveTest(); REQUIRE_VALID_FH(f.fh); @@ -78,7 +78,7 @@ BOOST_AUTO_TEST_CASE( moveFileHandle ) moveTest(O_RDONLY, O_NONBLOCK); } -BOOST_AUTO_TEST_CASE( moveFileHandleStat ) +BOOST_AUTO_TEST_CASE(moveFileHandleStat) { auto f = moveTest(); REQUIRE_VALID_FH(f.fh); @@ -87,7 +87,7 @@ BOOST_AUTO_TEST_CASE( moveFileHandleStat ) moveTest(O_RDONLY, O_NONBLOCK); } -BOOST_AUTO_TEST_CASE( moveMemMap ) +BOOST_AUTO_TEST_CASE(moveMemMap) { auto f = moveTest(); REQUIRE_VALID_FH(f.fh); @@ -97,7 +97,7 @@ BOOST_AUTO_TEST_CASE( moveMemMap ) moveTest(O_RDONLY, O_NONBLOCK); } -BOOST_AUTO_TEST_CASE( memmap ) +BOOST_AUTO_TEST_CASE(memmap) { AdHoc::FileUtils::MemMap f(rootDir / "testFileUtils.cpp"); BOOST_REQUIRE(f.fh); @@ -114,49 +114,42 @@ BOOST_AUTO_TEST_CASE( memmap ) BOOST_REQUIRE_EQUAL(i.length(), f.getStat().st_size / sizeof(int)); } -BOOST_AUTO_TEST_CASE( openmode ) +BOOST_AUTO_TEST_CASE(openmode) { std::filesystem::remove(binDir / "test.file"); - BOOST_REQUIRE_THROW({ - AdHoc::FileUtils::FileHandle fh(binDir / "test.file", O_RDONLY, S_IRWXU); - }, AdHoc::SystemExceptionOn); + BOOST_REQUIRE_THROW( + { AdHoc::FileUtils::FileHandle fh(binDir / "test.file", O_RDONLY, S_IRWXU); }, AdHoc::SystemExceptionOn); AdHoc::FileUtils::FileHandle fh(binDir / "test.file", O_CREAT, S_IRWXU); std::filesystem::remove(binDir / "test.file"); } -BOOST_AUTO_TEST_CASE( openfail ) +BOOST_AUTO_TEST_CASE(openfail) { - BOOST_REQUIRE_THROW({ - AdHoc::FileUtils::MemMap f("/tmp/nothere"); - }, AdHoc::SystemException); + BOOST_REQUIRE_THROW({ AdHoc::FileUtils::MemMap f("/tmp/nothere"); }, AdHoc::SystemException); } -BOOST_AUTO_TEST_CASE( mapfail ) +BOOST_AUTO_TEST_CASE(mapfail) { - BOOST_REQUIRE_THROW({ - AdHoc::FileUtils::MemMap f("/dev/null"); - }, AdHoc::SystemException); + BOOST_REQUIRE_THROW({ AdHoc::FileUtils::MemMap f("/dev/null"); }, AdHoc::SystemException); auto fd = open("/dev/null", O_RDWR); REQUIRE_VALID_FH(fd); - BOOST_REQUIRE_THROW({ - AdHoc::FileUtils::MemMap f(fd, O_RDWR); - }, AdHoc::SystemException); + BOOST_REQUIRE_THROW({ AdHoc::FileUtils::MemMap f(fd, O_RDWR); }, AdHoc::SystemException); REQUIRE_INVALID_FH(fd); } -BOOST_AUTO_TEST_CASE( msg ) +BOOST_AUTO_TEST_CASE(msg) { AdHoc::SystemException x("verb", "No such file or directory", ENOENT); BOOST_REQUIRE_EQUAL(x.what(), "verb (2:No such file or directory)"); } -BOOST_AUTO_TEST_CASE( msgOn ) +BOOST_AUTO_TEST_CASE(msgOn) { AdHoc::SystemExceptionOn x("verb", "No such file or directory", ENOENT, "noun"); BOOST_REQUIRE_EQUAL(x.what(), "verb on 'noun' (2:No such file or directory)"); } -BOOST_AUTO_TEST_CASE( pathPart ) +BOOST_AUTO_TEST_CASE(pathPart) { using namespace AdHoc::FileUtils; std::filesystem::path p("/this/is/some/path"); @@ -166,4 +159,3 @@ BOOST_AUTO_TEST_CASE( pathPart ) BOOST_REQUIRE_EQUAL(p / 3, "some"); BOOST_REQUIRE_EQUAL(p / 4, "path"); } - diff --git a/libadhocutil/unittests/testFprintbf.cpp b/libadhocutil/unittests/testFprintbf.cpp index 1f4e55a..233a3f7 100644 --- a/libadhocutil/unittests/testFprintbf.cpp +++ b/libadhocutil/unittests/testFprintbf.cpp @@ -1,11 +1,11 @@ #define BOOST_TEST_MODULE fprintbf #include -#include "fprintbf.h" #include "definedDirs.h" +#include "fprintbf.h" #include -BOOST_AUTO_TEST_CASE( writestring ) +BOOST_AUTO_TEST_CASE(writestring) { FILE * f = fopen(binDir / "writestring", "w"); BOOST_REQUIRE(f); @@ -13,7 +13,7 @@ BOOST_AUTO_TEST_CASE( writestring ) fclose(f); } -BOOST_AUTO_TEST_CASE( writestringerror ) +BOOST_AUTO_TEST_CASE(writestringerror) { FILE * f = fopen(binDir / "writestring", "r"); BOOST_REQUIRE(f); @@ -21,7 +21,7 @@ BOOST_AUTO_TEST_CASE( writestringerror ) fclose(f); } -BOOST_AUTO_TEST_CASE( writeformatNoArgs ) +BOOST_AUTO_TEST_CASE(writeformatNoArgs) { FILE * f = fopen(binDir / "writeformatNoArgs", "w"); BOOST_REQUIRE(f); @@ -29,7 +29,7 @@ BOOST_AUTO_TEST_CASE( writeformatNoArgs ) fclose(f); } -BOOST_AUTO_TEST_CASE( writeformatOneArg ) +BOOST_AUTO_TEST_CASE(writeformatOneArg) { FILE * f = fopen(binDir / "writeformatOneArg", "w"); BOOST_REQUIRE(f); @@ -37,7 +37,7 @@ BOOST_AUTO_TEST_CASE( writeformatOneArg ) fclose(f); } -BOOST_AUTO_TEST_CASE( writeformatTwoArgs ) +BOOST_AUTO_TEST_CASE(writeformatTwoArgs) { FILE * f = fopen(binDir / "writeformatTwoArgs", "w"); BOOST_REQUIRE(f); @@ -45,7 +45,7 @@ BOOST_AUTO_TEST_CASE( writeformatTwoArgs ) fclose(f); } -BOOST_AUTO_TEST_CASE( writeformatError ) +BOOST_AUTO_TEST_CASE(writeformatError) { FILE * f = fopen(binDir / "writeformatTwoArgs", "r"); BOOST_REQUIRE(f); @@ -53,8 +53,7 @@ BOOST_AUTO_TEST_CASE( writeformatError ) fclose(f); } -BOOST_AUTO_TEST_CASE( fopenerror ) +BOOST_AUTO_TEST_CASE(fopenerror) { BOOST_REQUIRE_THROW(fopen(binDir / "missing" / "folder", "r"), std::system_error); } - diff --git a/libadhocutil/unittests/testHandle.cpp b/libadhocutil/unittests/testHandle.cpp index e7f52af..6fccaa7 100644 --- a/libadhocutil/unittests/testHandle.cpp +++ b/libadhocutil/unittests/testHandle.cpp @@ -1,9 +1,9 @@ #define BOOST_TEST_MODULE Handle #include -#include -#include #include "handle.h" +#include +#include // Test case base on a file handle using T = decltype(STDIN_FILENO); @@ -20,7 +20,7 @@ static_assert(!std::is_copy_assignable_v); BOOST_AUTO_TEST_CASE(values) { - TestHandle th { open("/dev/null", O_RDWR), &close }; + TestHandle th {open("/dev/null", O_RDWR), &close}; static_assert(std::is_same_v>); static_assert(std::is_same_v>); BOOST_REQUIRE_EQUAL(1, write(th, "1", 1)); @@ -28,7 +28,7 @@ BOOST_AUTO_TEST_CASE(values) BOOST_AUTO_TEST_CASE(values_const) { - const TestHandle cth { open("/dev/null", O_RDWR), &close }; + const TestHandle cth {open("/dev/null", O_RDWR), &close}; static_assert(std::is_same_v>); static_assert(std::is_same_v>); BOOST_REQUIRE_EQUAL(1, write(cth, "1", 1)); @@ -57,4 +57,3 @@ BOOST_AUTO_TEST_CASE(make) BOOST_REQUIRE_EQUAL(-1, write(fd, "1", 1)); BOOST_REQUIRE_EQUAL(errno, EBADF); } - diff --git a/libadhocutil/unittests/testLazyPointer.cpp b/libadhocutil/unittests/testLazyPointer.cpp index 31b92a5..df9c257 100644 --- a/libadhocutil/unittests/testLazyPointer.cpp +++ b/libadhocutil/unittests/testLazyPointer.cpp @@ -6,12 +6,9 @@ using namespace AdHoc; class Test { - public: - explicit Test(int v) : - val(v) - { - } - const int val; +public: + explicit Test(int v) : val(v) { } + const int val; }; using TestLazyPointer = LazyPointer; @@ -22,23 +19,23 @@ BOOST_TEST_DONT_PRINT_LOG_VALUE(TestLazyPointer); BOOST_TEST_DONT_PRINT_LOG_VALUE(RawLazyPointer); /// LCOV_EXCL_STOP -static -TestLazyPointer::pointer_type +static TestLazyPointer::pointer_type factory() { return std::make_shared(3); } -static -TestLazyPointer::pointer_type +static TestLazyPointer::pointer_type paramFactory(const std::string & str) { return std::make_shared(str.length()); } -BOOST_AUTO_TEST_CASE ( islazy ) +BOOST_AUTO_TEST_CASE(islazy) { - TestLazyPointer p([]{ return factory(); }); + TestLazyPointer p([] { + return factory(); + }); BOOST_REQUIRE_EQUAL(false, p.hasValue()); Test * t = p.get(); BOOST_REQUIRE(t); @@ -49,40 +46,44 @@ BOOST_AUTO_TEST_CASE ( islazy ) BOOST_REQUIRE_EQUAL(3, p->val); } -BOOST_AUTO_TEST_CASE ( preinit ) +BOOST_AUTO_TEST_CASE(preinit) { Test * t = new Test(4); - TestLazyPointer p(TestLazyPointer::pointer_type{ t }); + TestLazyPointer p(TestLazyPointer::pointer_type {t}); BOOST_REQUIRE_EQUAL(true, p.hasValue()); BOOST_REQUIRE_EQUAL(p, t); BOOST_REQUIRE_EQUAL(4, p->val); } -BOOST_AUTO_TEST_CASE ( reset ) +BOOST_AUTO_TEST_CASE(reset) { Test * t = new Test(4); - TestLazyPointer p(TestLazyPointer::pointer_type{ t }); + TestLazyPointer p(TestLazyPointer::pointer_type {t}); BOOST_REQUIRE_EQUAL(true, p.hasValue()); BOOST_REQUIRE_EQUAL(4, p->val); p = nullptr; BOOST_REQUIRE_EQUAL(true, p.hasValue()); BOOST_REQUIRE_EQUAL(true, !p); - p = []{ return factory(); }; + p = [] { + return factory(); + }; BOOST_REQUIRE_EQUAL(false, p.hasValue()); BOOST_REQUIRE(p.get()); BOOST_REQUIRE_EQUAL(true, p.hasValue()); BOOST_REQUIRE_EQUAL(3, p->val); } -BOOST_AUTO_TEST_CASE ( nondefault ) +BOOST_AUTO_TEST_CASE(nondefault) { - TestLazyPointer p([]{ return paramFactory("some string"); }); + TestLazyPointer p([] { + return paramFactory("some string"); + }); BOOST_REQUIRE_EQUAL(false, p.hasValue()); BOOST_REQUIRE_EQUAL(11, (*p).val); BOOST_REQUIRE_EQUAL(true, p.hasValue()); } -BOOST_AUTO_TEST_CASE( rawPointerNull ) +BOOST_AUTO_TEST_CASE(rawPointerNull) { RawLazyPointer null; BOOST_REQUIRE(null.hasValue()); @@ -90,7 +91,7 @@ BOOST_AUTO_TEST_CASE( rawPointerNull ) BOOST_REQUIRE(!null.get()); } -BOOST_AUTO_TEST_CASE( rawPointerNonNull ) +BOOST_AUTO_TEST_CASE(rawPointerNonNull) { RawLazyPointer value(new int(3)); BOOST_REQUIRE(value.hasValue()); @@ -108,12 +109,13 @@ rawFactory(const std::string & s) return new int(s.length()); } -BOOST_AUTO_TEST_CASE( rawPointerFactory ) +BOOST_AUTO_TEST_CASE(rawPointerFactory) { - RawLazyPointer value([]{ return rawFactory(std::string("four")); }); + RawLazyPointer value([] { + return rawFactory(std::string("four")); + }); BOOST_REQUIRE(!value.hasValue()); BOOST_REQUIRE_EQUAL(*value, 4); BOOST_REQUIRE(value.hasValue()); delete (int *)value; } - diff --git a/libadhocutil/unittests/testLexer.cpp b/libadhocutil/unittests/testLexer.cpp index f58b002..3484e78 100644 --- a/libadhocutil/unittests/testLexer.cpp +++ b/libadhocutil/unittests/testLexer.cpp @@ -1,83 +1,79 @@ #define BOOST_TEST_MODULE Lexer #include -#include #include +#include using namespace AdHoc; using namespace AdHoc::LexerMatchers; -BOOST_AUTO_TEST_CASE( defaultConstructor ) +BOOST_AUTO_TEST_CASE(defaultConstructor) { AdHoc::Lexer l; - l.rules.push_back({ { AdHoc::Lexer::InitialState }, regex("a"), [](auto) { } }); + l.rules.push_back({{AdHoc::Lexer::InitialState}, regex("a"), [](auto) {}}); } -BOOST_AUTO_TEST_CASE( simple ) +BOOST_AUTO_TEST_CASE(simple) { int m = 0; - AdHoc::Lexer l({ - { { AdHoc::Lexer::InitialState }, regex("a"), [&](auto) { m += 1; } } - }); + AdHoc::Lexer l({{{AdHoc::Lexer::InitialState}, regex("a"), [&](auto) { + m += 1; + }}}); BOOST_REQUIRE_EQUAL(0, m); l.extract("aaaa", 4); BOOST_REQUIRE_EQUAL(4, m); - BOOST_REQUIRE_THROW({ - l.extract("abcd", 4); - }, std::runtime_error); + BOOST_REQUIRE_THROW({ l.extract("abcd", 4); }, std::runtime_error); } -BOOST_AUTO_TEST_CASE( state ) +BOOST_AUTO_TEST_CASE(state) { int m = 0; std::string s; - AdHoc::Lexer l({ - { { AdHoc::Lexer::InitialState }, regex("a"), [&](auto es) - { - m += 1; - BOOST_REQUIRE_EQUAL(1, es->depth()); - es->pushState("2"); - BOOST_REQUIRE_EQUAL(2, es->depth()); - } }, - { { "2" }, regex("a"), [&](auto es) - { - m += 2; - BOOST_REQUIRE_EQUAL("2", es->getState()); - BOOST_REQUIRE_EQUAL(2, es->depth()); - es->pushState("3"); - BOOST_REQUIRE_EQUAL("3", es->getState()); - BOOST_REQUIRE_EQUAL(3, es->depth()); - } }, - { { "3" }, regex("a"), [&](auto es) - { - m += 3; - s += *es->pattern()->match(0); - BOOST_REQUIRE_EQUAL(3, es->depth()); - es->setState("4"); - BOOST_REQUIRE_EQUAL(3, es->depth()); - BOOST_REQUIRE_EQUAL("4", es->getState()); - BOOST_REQUIRE_EQUAL(3, es->depth()); - BOOST_REQUIRE(!es->pattern()->match(1)); - BOOST_REQUIRE(!es->pattern()->match(2)); - es->popState(); - BOOST_REQUIRE_EQUAL(2, es->depth()); - BOOST_REQUIRE_EQUAL("2", es->getState()); - es->pushState("3"); - BOOST_REQUIRE_EQUAL(3, es->depth()); - BOOST_REQUIRE_EQUAL("3", es->getState()); - } } - }); + AdHoc::Lexer l({{{AdHoc::Lexer::InitialState}, regex("a"), + [&](auto es) { + m += 1; + BOOST_REQUIRE_EQUAL(1, es->depth()); + es->pushState("2"); + BOOST_REQUIRE_EQUAL(2, es->depth()); + }}, + {{"2"}, regex("a"), + [&](auto es) { + m += 2; + BOOST_REQUIRE_EQUAL("2", es->getState()); + BOOST_REQUIRE_EQUAL(2, es->depth()); + es->pushState("3"); + BOOST_REQUIRE_EQUAL("3", es->getState()); + BOOST_REQUIRE_EQUAL(3, es->depth()); + }}, + {{"3"}, regex("a"), [&](auto es) { + m += 3; + s += *es->pattern()->match(0); + BOOST_REQUIRE_EQUAL(3, es->depth()); + es->setState("4"); + BOOST_REQUIRE_EQUAL(3, es->depth()); + BOOST_REQUIRE_EQUAL("4", es->getState()); + BOOST_REQUIRE_EQUAL(3, es->depth()); + BOOST_REQUIRE(!es->pattern()->match(1)); + BOOST_REQUIRE(!es->pattern()->match(2)); + es->popState(); + BOOST_REQUIRE_EQUAL(2, es->depth()); + BOOST_REQUIRE_EQUAL("2", es->getState()); + es->pushState("3"); + BOOST_REQUIRE_EQUAL(3, es->depth()); + BOOST_REQUIRE_EQUAL("3", es->getState()); + }}}); BOOST_REQUIRE_EQUAL(0, m); l.extract("aaaa", 4); BOOST_REQUIRE_EQUAL(9, m); BOOST_REQUIRE_EQUAL("aa", s); } -BOOST_AUTO_TEST_CASE( multibyte ) +BOOST_AUTO_TEST_CASE(multibyte) { - AdHoc::Lexer::PatternPtr maskHead = AdHoc::LexerMatchers::regex( - "^# ([^<\n]+)? ?(<(.+?@[^\n>]+)>?)? \\((\\d+ *(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\\w* \\d+)\\)$", - (GRegexCompileFlags)(G_REGEX_OPTIMIZE | G_REGEX_CASELESS | G_REGEX_UNGREEDY)); + AdHoc::Lexer::PatternPtr maskHead + = AdHoc::LexerMatchers::regex("^# ([^<\n]+)? ?(<(.+?@[^\n>]+)>?)? \\((\\d+ " + "*(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\\w* \\d+)\\)$", + (GRegexCompileFlags)(G_REGEX_OPTIMIZE | G_REGEX_CASELESS | G_REGEX_UNGREEDY)); Glib::ustring input("# Michał Górny (28 Mar 2015)"); BOOST_REQUIRE_GT(input.bytes(), input.length()); BOOST_REQUIRE(maskHead->matches(input.c_str(), input.bytes(), 0)); @@ -92,8 +88,7 @@ BOOST_AUTO_TEST_CASE( multibyte ) BOOST_REQUIRE_EQUAL("28 Mar 2015", *maskHead->match(4)); } -BOOST_AUTO_TEST_CASE( badre ) +BOOST_AUTO_TEST_CASE(badre) { BOOST_REQUIRE_THROW(regex("["), std::runtime_error); } - diff --git a/libadhocutil/unittests/testLocks.cpp b/libadhocutil/unittests/testLocks.cpp index 0c93d99..a7a506a 100644 --- a/libadhocutil/unittests/testLocks.cpp +++ b/libadhocutil/unittests/testLocks.cpp @@ -4,7 +4,7 @@ #include "lockHelpers.h" #include -BOOST_AUTO_TEST_CASE ( lock ) +BOOST_AUTO_TEST_CASE(lock) { std::shared_mutex _lock; { @@ -19,7 +19,7 @@ BOOST_AUTO_TEST_CASE ( lock ) _lock.unlock_shared(); } -BOOST_AUTO_TEST_CASE ( sharedlock ) +BOOST_AUTO_TEST_CASE(sharedlock) { std::shared_mutex _lock; { @@ -35,7 +35,7 @@ BOOST_AUTO_TEST_CASE ( sharedlock ) _lock.unlock_shared(); } -BOOST_AUTO_TEST_CASE ( scopelock ) +BOOST_AUTO_TEST_CASE(scopelock) { std::shared_mutex _lock; ScopeLock(_lock) { @@ -49,7 +49,7 @@ BOOST_AUTO_TEST_CASE ( scopelock ) _lock.unlock_shared(); } -BOOST_AUTO_TEST_CASE ( sharedscopelock ) +BOOST_AUTO_TEST_CASE(sharedscopelock) { std::shared_mutex _lock; SharedScopeLock(_lock) { @@ -63,4 +63,3 @@ BOOST_AUTO_TEST_CASE ( sharedscopelock ) BOOST_CHECK(_lock.try_lock_shared()); _lock.unlock_shared(); } - diff --git a/libadhocutil/unittests/testMapFinds.cpp b/libadhocutil/unittests/testMapFinds.cpp index d3d0e34..bcbb69e 100644 --- a/libadhocutil/unittests/testMapFinds.cpp +++ b/libadhocutil/unittests/testMapFinds.cpp @@ -1,31 +1,22 @@ #define BOOST_TEST_MODULE MapFinds #include -#include #include "safeMapFind.h" +#include +#include #include #include -#include using namespace AdHoc; class NotFound : std::runtime_error { - public: - explicit NotFound(int key) : - std::runtime_error(boost::lexical_cast("Key not found: %d", key)) - { - } +public: + explicit NotFound(int key) : std::runtime_error(boost::lexical_cast("Key not found: %d", key)) { } }; -const std::map sample { - { 1, "one" }, - { 2, "two" }, - { 4, "four" }, - { 8, "eight" }, - { 16, "sixteen" } -}; +const std::map sample {{1, "one"}, {2, "two"}, {4, "four"}, {8, "eight"}, {16, "sixteen"}}; -BOOST_AUTO_TEST_CASE ( testSafeMapFind ) +BOOST_AUTO_TEST_CASE(testSafeMapFind) { BOOST_REQUIRE_EQUAL(safeMapFind(sample, 1)->first, 1); BOOST_REQUIRE_EQUAL(safeMapFind(sample, 1)->second, "one"); @@ -34,7 +25,7 @@ BOOST_AUTO_TEST_CASE ( testSafeMapFind ) BOOST_REQUIRE_THROW(safeMapFind(sample, 5), NotFound); } -BOOST_AUTO_TEST_CASE ( testDefaultMapLookup ) +BOOST_AUTO_TEST_CASE(testDefaultMapLookup) { BOOST_REQUIRE_EQUAL(defaultMapLookup(sample, 1), "one"); BOOST_REQUIRE_EQUAL(defaultMapLookup(sample, 4), "four"); @@ -42,18 +33,17 @@ BOOST_AUTO_TEST_CASE ( testDefaultMapLookup ) BOOST_REQUIRE_EQUAL(defaultMapLookup(sample, 5, "default"), "default"); } -BOOST_AUTO_TEST_CASE ( testSafeMapLookup ) +BOOST_AUTO_TEST_CASE(testSafeMapLookup) { BOOST_REQUIRE_EQUAL(safeMapLookup(sample, 1), "one"); BOOST_REQUIRE_EQUAL(safeMapLookup(sample, 4), "four"); BOOST_REQUIRE_THROW(safeMapLookup(sample, 5), NotFound); } -BOOST_AUTO_TEST_CASE ( testContainerContains ) +BOOST_AUTO_TEST_CASE(testContainerContains) { BOOST_REQUIRE_EQUAL(true, containerContains(sample, {1, "one"})); BOOST_REQUIRE_EQUAL(false, containerContains(sample, {2, "one"})); BOOST_REQUIRE_EQUAL(false, containerContains(sample, {1, "two"})); BOOST_REQUIRE_EQUAL(true, containerContains(sample, {2, "two"})); } - diff --git a/libadhocutil/unittests/testMemStream.cpp b/libadhocutil/unittests/testMemStream.cpp index 79100ee..5d26c42 100644 --- a/libadhocutil/unittests/testMemStream.cpp +++ b/libadhocutil/unittests/testMemStream.cpp @@ -1,6 +1,6 @@ #define BOOST_TEST_MODULE NvpParse -#include #include +#include #include "memstream.h" @@ -17,9 +17,9 @@ BOOST_AUTO_TEST_CASE(empty) } using cast_types = boost::mpl::list; -BOOST_AUTO_TEST_CASE_TEMPLATE(casts, T, cast_types ) +BOOST_AUTO_TEST_CASE_TEMPLATE(casts, T, cast_types) { - auto dummy = [](const T &) { }; + auto dummy = [](const T &) {}; dummy(*this); } @@ -44,4 +44,3 @@ BOOST_AUTO_TEST_CASE(move_assign) MemStream ms2; ms2 = std::move(ms1); } - diff --git a/libadhocutil/unittests/testNagios.cpp b/libadhocutil/unittests/testNagios.cpp index 8e8e025..0af6b25 100644 --- a/libadhocutil/unittests/testNagios.cpp +++ b/libadhocutil/unittests/testNagios.cpp @@ -4,7 +4,7 @@ #include /// LCOV_EXCL_START (calls real Nagios) -BOOST_AUTO_TEST_CASE(test_write_cmd, * boost::unit_test::disabled()) +BOOST_AUTO_TEST_CASE(test_write_cmd, *boost::unit_test::disabled()) { BOOST_REQUIRE(AdHoc::submitNagiosPassiveServiceCheck("some service", AdHoc::NagiosStatusCode::OK, "bar")); } @@ -15,4 +15,3 @@ BOOST_AUTO_TEST_CASE(test_fmtrite_cmd) std::stringstream strm; BOOST_REQUIRE(AdHoc::submitNagiosPassiveServiceCheck(strm, "some service", AdHoc::NagiosStatusCode::OK, "bar")); } - diff --git a/libadhocutil/unittests/testNvpParse.cpp b/libadhocutil/unittests/testNvpParse.cpp index 678f468..fa955e1 100644 --- a/libadhocutil/unittests/testNvpParse.cpp +++ b/libadhocutil/unittests/testNvpParse.cpp @@ -6,25 +6,25 @@ using namespace AdHoc; class TestTarget { - public: - std::string a; - std::string b; - int c {0}; - double d {0}; +public: + std::string a; + std::string b; + int c {0}; + double d {0}; }; NvpTarget(TestTarget) TestTargetMap { - NvpValue(TestTarget, a), - NvpValue(TestTarget, b), - NvpValue(TestTarget, c), - NvpValue(TestTarget, d), + NvpValue(TestTarget, a), + NvpValue(TestTarget, b), + NvpValue(TestTarget, c), + NvpValue(TestTarget, d), }; /// LCOV_EXCL_START (diagnostics) BOOST_TEST_DONT_PRINT_LOG_VALUE(decltype(TestTargetMap.find(""))); /// LCOV_EXCL_STOP -BOOST_AUTO_TEST_CASE ( targetmap ) +BOOST_AUTO_TEST_CASE(targetmap) { BOOST_REQUIRE_NE(TestTargetMap.find("a"), TestTargetMap.end()); BOOST_REQUIRE_NE(TestTargetMap.find("b"), TestTargetMap.end()); @@ -33,7 +33,7 @@ BOOST_AUTO_TEST_CASE ( targetmap ) BOOST_REQUIRE_EQUAL(TestTargetMap.find("e"), TestTargetMap.end()); } -BOOST_AUTO_TEST_CASE ( parse ) +BOOST_AUTO_TEST_CASE(parse) { TestTarget tt; std::stringstream i("a = foo;b=bar; c=3;d=3.14"); @@ -44,17 +44,16 @@ BOOST_AUTO_TEST_CASE ( parse ) BOOST_REQUIRE_CLOSE(3.14, tt.d, 0.01); } -BOOST_AUTO_TEST_CASE ( missing ) +BOOST_AUTO_TEST_CASE(missing) { TestTarget tt; std::stringstream i("missing=nothing;"); BOOST_REQUIRE_THROW(NvpParse::parse(i, TestTargetMap, tt), NvpParse::ValueNotFound); } -BOOST_AUTO_TEST_CASE ( bad ) +BOOST_AUTO_TEST_CASE(bad) { TestTarget tt; std::stringstream i("{bad="); BOOST_REQUIRE_THROW(NvpParse::parse(i, TestTargetMap, tt), std::runtime_error); } - diff --git a/libadhocutil/unittests/testOptionals.cpp b/libadhocutil/unittests/testOptionals.cpp index f6dc371..600c972 100644 --- a/libadhocutil/unittests/testOptionals.cpp +++ b/libadhocutil/unittests/testOptionals.cpp @@ -1,14 +1,14 @@ #define BOOST_TEST_MODULE Buffer #include -#include -#include #include #include +#include +#include using namespace AdHoc; -BOOST_AUTO_TEST_CASE ( general ) +BOOST_AUTO_TEST_CASE(general) { std::optional x; std::optional y = 2.3; @@ -26,9 +26,9 @@ BOOST_AUTO_TEST_CASE ( general ) BOOST_REQUIRE_EQUAL(2.3, *a1); auto a2 = x / 10; BOOST_REQUIRE_EQUAL(10, a2); - auto a3 = ix / 11; + auto a3 = ix / 11; BOOST_REQUIRE_EQUAL(11, a3); - auto a4 = iy / 11; + auto a4 = iy / 11; BOOST_REQUIRE_EQUAL(4, a4); auto s1 = p / s / r; @@ -43,4 +43,3 @@ BOOST_AUTO_TEST_CASE ( general ) delete q; } - diff --git a/libadhocutil/unittests/testPlugins.cpp b/libadhocutil/unittests/testPlugins.cpp index 9a6cc7e..a05469e 100644 --- a/libadhocutil/unittests/testPlugins.cpp +++ b/libadhocutil/unittests/testPlugins.cpp @@ -7,22 +7,22 @@ using namespace AdHoc; -BOOST_AUTO_TEST_CASE( ready ) +BOOST_AUTO_TEST_CASE(ready) { BOOST_REQUIRE(PluginManager::getDefault()); } -BOOST_AUTO_TEST_CASE( registered ) +BOOST_AUTO_TEST_CASE(registered) { BOOST_REQUIRE_EQUAL(1, PluginManager::getDefault()->count()); } -BOOST_AUTO_TEST_CASE( private_instance ) +BOOST_AUTO_TEST_CASE(private_instance) { std::make_unique(); } -BOOST_AUTO_TEST_CASE( get ) +BOOST_AUTO_TEST_CASE(get) { auto implOfThingPlugin = PluginManager::getDefault()->get("ImplOfThing"); BOOST_REQUIRE(implOfThingPlugin); @@ -32,7 +32,7 @@ BOOST_AUTO_TEST_CASE( get ) BOOST_REQUIRE_EQUAL(implOfThing, implOfThingDirect); } -BOOST_AUTO_TEST_CASE( getAll ) +BOOST_AUTO_TEST_CASE(getAll) { auto all = PluginManager::getDefault()->getAll(); BOOST_REQUIRE_EQUAL(1, all.size()); @@ -44,10 +44,11 @@ BOOST_AUTO_TEST_CASE( getAll ) BOOST_REQUIRE_EQUAL(1, allOf.size()); } -BOOST_AUTO_TEST_CASE( addManual ) +BOOST_AUTO_TEST_CASE(addManual) { auto o1 = PluginManager::getDefault()->get("ImplOfThing"); - PluginManager::getDefault()->add(std::make_shared>(std::make_shared(), "custom1", __FILE__, __LINE__)); + PluginManager::getDefault()->add( + std::make_shared>(std::make_shared(), "custom1", __FILE__, __LINE__)); BOOST_REQUIRE_EQUAL(2, PluginManager::getDefault()->count()); auto c1 = PluginManager::getDefault()->get("custom1"); PluginManager::getDefault()->add(std::make_shared(), "custom2", __FILE__, __LINE__); @@ -63,7 +64,7 @@ BOOST_AUTO_TEST_CASE( addManual ) BOOST_REQUIRE_NE(c2, o1); } -BOOST_AUTO_TEST_CASE( removeManual ) +BOOST_AUTO_TEST_CASE(removeManual) { BOOST_REQUIRE_EQUAL(3, PluginManager::getDefault()->count()); PluginManager::getDefault()->remove("custom1"); @@ -77,7 +78,7 @@ BOOST_AUTO_TEST_CASE( removeManual ) BOOST_REQUIRE(PluginManager::getDefault()->get("ImplOfThing")); } -BOOST_AUTO_TEST_CASE( createAndRemove ) +BOOST_AUTO_TEST_CASE(createAndRemove) { PluginManager::getDefault()->create("custom1", __FILE__, __LINE__); BOOST_REQUIRE_EQUAL(2, PluginManager::getDefault()->count()); @@ -86,19 +87,21 @@ BOOST_AUTO_TEST_CASE( createAndRemove ) PluginManager::getDefault()->remove("custom1"); } -BOOST_AUTO_TEST_CASE( nameAndTypeClash ) +BOOST_AUTO_TEST_CASE(nameAndTypeClash) { // Same name, different type PluginManager::getDefault()->add(std::make_shared(), "ImplOfThing", __FILE__, __LINE__); // Different name, same type PluginManager::getDefault()->add(std::make_shared(), "Different", __FILE__, __LINE__); // Same name, same thing, should error - BOOST_REQUIRE_THROW(PluginManager::getDefault()->add(std::make_shared(), "ImplOfThing", __FILE__, __LINE__), DuplicatePluginException); + BOOST_REQUIRE_THROW(PluginManager::getDefault()->add( + std::make_shared(), "ImplOfThing", __FILE__, __LINE__), + DuplicatePluginException); PluginManager::getDefault()->remove("ImplOfThing"); PluginManager::getDefault()->remove("Different"); } -BOOST_AUTO_TEST_CASE( otherTypes ) +BOOST_AUTO_TEST_CASE(otherTypes) { PluginManager::getDefault()->add(std::make_shared(), "ImplOfThing", __FILE__, __LINE__); BOOST_REQUIRE_EQUAL(2, PluginManager::getDefault()->count()); @@ -114,4 +117,3 @@ BOOST_AUTO_TEST_CASE( otherTypes ) BOOST_REQUIRE_EQUAL(1, PluginManager::getDefault()->count()); BOOST_REQUIRE(PluginManager::getDefault()->get("ImplOfThing")); } - diff --git a/libadhocutil/unittests/testPluginsRuntime.cpp b/libadhocutil/unittests/testPluginsRuntime.cpp index c3ecf34..7836ed5 100644 --- a/libadhocutil/unittests/testPluginsRuntime.cpp +++ b/libadhocutil/unittests/testPluginsRuntime.cpp @@ -23,18 +23,18 @@ static std::optional nullResolver(const std::type_info &, const std static std::optional badResolver(const std::type_info &, const std::string_view &); static std::optional goodResolver(const std::type_info &, const std::string_view &); -BOOST_AUTO_TEST_CASE( ready ) +BOOST_AUTO_TEST_CASE(ready) { BOOST_REQUIRE(PluginManager::getDefault()); BOOST_REQUIRE(std::filesystem::exists(lib)); } -BOOST_AUTO_TEST_CASE( clean ) +BOOST_AUTO_TEST_CASE(clean) { BOOST_REQUIRE_EQUAL(0, AdHoc::PluginManager::getDefault()->getAll().size()); } -BOOST_AUTO_TEST_CASE( loadAndUnloadlib ) +BOOST_AUTO_TEST_CASE(loadAndUnloadlib) { void * handle = dlopen(lib.c_str(), RTLD_NOW); BOOST_REQUIRE(handle); @@ -63,7 +63,7 @@ goodResolver(const std::type_info & t, const std::string_view & n) return lib; } -BOOST_AUTO_TEST_CASE( addAndRemoveResolver ) +BOOST_AUTO_TEST_CASE(addAndRemoveResolver) { auto pm = AdHoc::PluginManager::getDefault(); BOOST_REQUIRE_EQUAL(0, pm->countResolvers()); @@ -75,7 +75,7 @@ BOOST_AUTO_TEST_CASE( addAndRemoveResolver ) BOOST_REQUIRE_EQUAL(0, pm->countResolvers()); } -BOOST_AUTO_TEST_CASE( null ) +BOOST_AUTO_TEST_CASE(null) { auto pm = AdHoc::PluginManager::getDefault(); pm->addResolver(nullResolver); @@ -83,7 +83,7 @@ BOOST_AUTO_TEST_CASE( null ) pm->removeResolver(); } -BOOST_AUTO_TEST_CASE( bad ) +BOOST_AUTO_TEST_CASE(bad) { auto pm = AdHoc::PluginManager::getDefault(); pm->addResolver(badResolver); @@ -91,11 +91,10 @@ BOOST_AUTO_TEST_CASE( bad ) pm->removeResolver(); } -BOOST_AUTO_TEST_CASE( good ) +BOOST_AUTO_TEST_CASE(good) { auto pm = AdHoc::PluginManager::getDefault(); pm->addResolver(goodResolver); BOOST_REQUIRE(pm->get("ImplOfThing")); pm->removeResolver(); } - diff --git a/libadhocutil/unittests/testProcessPipes.cpp b/libadhocutil/unittests/testProcessPipes.cpp index 968ac2a..6251022 100644 --- a/libadhocutil/unittests/testProcessPipes.cpp +++ b/libadhocutil/unittests/testProcessPipes.cpp @@ -1,13 +1,13 @@ #define BOOST_TEST_MODULE ProcessPipes #include -#include "processPipes.h" #include "definedDirs.h" +#include "processPipes.h" #include using namespace AdHoc::System; -BOOST_AUTO_TEST_CASE( readfind ) +BOOST_AUTO_TEST_CASE(readfind) { ProcessPipes pp({"/usr/bin/find", rootDir, "-maxdepth", "1"}, false, true, true); BOOST_REQUIRE_EQUAL(pp.fdIn(), -1); @@ -23,7 +23,7 @@ BOOST_AUTO_TEST_CASE( readfind ) waitpid(pp.pid(), &status, 0); } -BOOST_AUTO_TEST_CASE( readwrite ) +BOOST_AUTO_TEST_CASE(readwrite) { ProcessPipes pp({"/usr/bin/md5sum"}, true, true, false); BOOST_REQUIRE_NE(pp.fdIn(), -1); @@ -38,10 +38,7 @@ BOOST_AUTO_TEST_CASE( readwrite ) waitpid(pp.pid(), &status, 0); } -BOOST_AUTO_TEST_CASE( noargs ) +BOOST_AUTO_TEST_CASE(noargs) { - BOOST_CHECK_THROW({ - ProcessPipes({}, false, false, false); - }, std::invalid_argument); + BOOST_CHECK_THROW({ ProcessPipes({}, false, false, false); }, std::invalid_argument); } - diff --git a/libadhocutil/unittests/testResourcePool.cpp b/libadhocutil/unittests/testResourcePool.cpp index 4fd1f72..5f67424 100644 --- a/libadhocutil/unittests/testResourcePool.cpp +++ b/libadhocutil/unittests/testResourcePool.cpp @@ -4,59 +4,75 @@ #include class MockResource { - public: - MockResource() : id(ids++) { count += 1; } - ~MockResource() { count -= 1; } +public: + MockResource() : id(ids++) + { + count += 1; + } + ~MockResource() + { + count -= 1; + } - SPECIAL_MEMBERS_DELETE(MockResource); + SPECIAL_MEMBERS_DELETE(MockResource); - [[ nodiscard ]] bool valid() const { return true; } + [[nodiscard]] bool + valid() const + { + return true; + } - const unsigned int id; - static std::atomic ids; - static std::atomic count; + const unsigned int id; + static std::atomic ids; + static std::atomic count; }; std::atomic MockResource::ids; std::atomic MockResource::count; class TRP : public AdHoc::ResourcePool { - public: - TRP() : AdHoc::ResourcePool(10, 10) { } - protected: - std::shared_ptr createResource() const override - { - return std::make_shared(); - } +public: + TRP() : AdHoc::ResourcePool(10, 10) { } + +protected: + std::shared_ptr + createResource() const override + { + return std::make_shared(); + } }; class TRPSmall : public AdHoc::ResourcePool { - public: - TRPSmall() : AdHoc::ResourcePool(3, 1) { } - protected: - std::shared_ptr createResource() const override - { - return std::make_shared(); - } +public: + TRPSmall() : AdHoc::ResourcePool(3, 1) { } + +protected: + std::shared_ptr + createResource() const override + { + return std::make_shared(); + } }; class TRPCreateFail : public TRPSmall { - protected: - std::shared_ptr createResource() const override - { - throw std::exception(); - } +protected: + std::shared_ptr + createResource() const override + { + throw std::exception(); + } }; class TRPReturnFail : public TRPSmall { - protected: - void returnTestResource(MockResource const *) const override - { - throw std::exception(); - } +protected: + void + returnTestResource(MockResource const *) const override + { + throw std::exception(); + } }; -BOOST_AUTO_TEST_CASE ( get ) +BOOST_AUTO_TEST_CASE(get) { { TRP pool; @@ -109,7 +125,7 @@ BOOST_AUTO_TEST_CASE ( get ) BOOST_REQUIRE_EQUAL(0, MockResource::count); } -BOOST_AUTO_TEST_CASE( destroyPoolWhenInUse ) +BOOST_AUTO_TEST_CASE(destroyPoolWhenInUse) { auto rp = new TRP(); auto rh1 = rp->get(); @@ -122,7 +138,7 @@ BOOST_AUTO_TEST_CASE( destroyPoolWhenInUse ) BOOST_REQUIRE(rh3->valid()); } -BOOST_AUTO_TEST_CASE ( getMine ) +BOOST_AUTO_TEST_CASE(getMine) { TRP pool; auto r1 = pool.get(); @@ -133,7 +149,7 @@ BOOST_AUTO_TEST_CASE ( getMine ) BOOST_REQUIRE_EQUAL(2, r2.handleCount()); } -BOOST_AUTO_TEST_CASE( getMineNoCurrent ) +BOOST_AUTO_TEST_CASE(getMineNoCurrent) { TRP pool; BOOST_REQUIRE_THROW(pool.getMine(), AdHoc::NoCurrentResourceT); @@ -145,7 +161,7 @@ BOOST_AUTO_TEST_CASE( getMineNoCurrent ) BOOST_REQUIRE_THROW(pool.getMine(), AdHoc::NoCurrentResource); } -BOOST_AUTO_TEST_CASE( move ) +BOOST_AUTO_TEST_CASE(move) { TRP pool; { @@ -177,7 +193,7 @@ BOOST_AUTO_TEST_CASE( move ) BOOST_CHECK_EQUAL(pool.inUseCount(), 0); } -BOOST_AUTO_TEST_CASE( discard ) +BOOST_AUTO_TEST_CASE(discard) { TRP pool; try { @@ -193,7 +209,7 @@ BOOST_AUTO_TEST_CASE( discard ) } } -BOOST_AUTO_TEST_CASE( keepSome1 ) +BOOST_AUTO_TEST_CASE(keepSome1) { TRPSmall pool; { @@ -228,7 +244,7 @@ BOOST_AUTO_TEST_CASE( keepSome1 ) BOOST_REQUIRE_EQUAL(1, MockResource::count); } -BOOST_AUTO_TEST_CASE( keepSome2 ) +BOOST_AUTO_TEST_CASE(keepSome2) { TRPSmall pool; { @@ -244,7 +260,7 @@ BOOST_AUTO_TEST_CASE( keepSome2 ) BOOST_REQUIRE_EQUAL(1, MockResource::count); } -BOOST_AUTO_TEST_CASE( idle ) +BOOST_AUTO_TEST_CASE(idle) { TRP pool; { @@ -270,12 +286,12 @@ BOOST_AUTO_TEST_CASE( idle ) BOOST_REQUIRE_EQUAL(0, MockResource::count); } -BOOST_AUTO_TEST_CASE( threading1, * boost::unit_test::timeout(10) ) +BOOST_AUTO_TEST_CASE(threading1, *boost::unit_test::timeout(10)) { TRPSmall pool; std::list threads; for (int x = 0; x < 100; x += 1) { - threads.emplace_back([&pool](){ + threads.emplace_back([&pool]() { auto r = pool.get(); usleep(50000); }); @@ -283,15 +299,14 @@ BOOST_AUTO_TEST_CASE( threading1, * boost::unit_test::timeout(10) ) // pool size never exceeds 3 BOOST_REQUIRE_LE(pool.inUseCount(), 3); } - for(auto & thread : threads) { + for (auto & thread : threads) { thread.join(); } // pool keep returns to 1 BOOST_REQUIRE_EQUAL(1, pool.availableCount()); } -static -void +static void acquireAndKeepFor1Second(TRPSmall * pool, AdHoc::Semaphore & s) { auto r = pool->get(); @@ -299,13 +314,19 @@ acquireAndKeepFor1Second(TRPSmall * pool, AdHoc::Semaphore & s) sleep(1); } -BOOST_AUTO_TEST_CASE( threading2 ) +BOOST_AUTO_TEST_CASE(threading2) { TRPSmall pool; AdHoc::Semaphore s; - std::thread t1([&pool, &s]() { acquireAndKeepFor1Second(&pool, s); }); - std::thread t2([&pool, &s]() { acquireAndKeepFor1Second(&pool, s); }); - std::thread t3([&pool, &s]() { acquireAndKeepFor1Second(&pool, s); }); + std::thread t1([&pool, &s]() { + acquireAndKeepFor1Second(&pool, s); + }); + std::thread t2([&pool, &s]() { + acquireAndKeepFor1Second(&pool, s); + }); + std::thread t3([&pool, &s]() { + acquireAndKeepFor1Second(&pool, s); + }); s.wait(); s.wait(); @@ -325,19 +346,21 @@ BOOST_AUTO_TEST_CASE( threading2 ) } class TTRP : public TRP { - public: - void testResource(MockResource const *) const override - { - n += 1; - if (n % 2) { - throw std::exception(); - } +public: + void + testResource(MockResource const *) const override + { + n += 1; + if (n % 2) { + throw std::exception(); } - private: - mutable int n{0}; + } + +private: + mutable int n {0}; }; -BOOST_AUTO_TEST_CASE( test ) +BOOST_AUTO_TEST_CASE(test) { TTRP pool; unsigned int rpId; @@ -360,7 +383,7 @@ BOOST_AUTO_TEST_CASE( test ) } } -BOOST_AUTO_TEST_CASE( createFail ) +BOOST_AUTO_TEST_CASE(createFail) { TRPCreateFail pool; BOOST_REQUIRE_EQUAL(0, MockResource::count); @@ -382,7 +405,7 @@ BOOST_AUTO_TEST_CASE( createFail ) BOOST_REQUIRE_EQUAL(3, pool.freeCount()); } -BOOST_AUTO_TEST_CASE( returnFail ) +BOOST_AUTO_TEST_CASE(returnFail) { TRPReturnFail pool; { @@ -396,9 +419,8 @@ BOOST_AUTO_TEST_CASE( returnFail ) BOOST_REQUIRE_EQUAL(3, pool.freeCount()); } -BOOST_AUTO_TEST_CASE( exception_msgs ) +BOOST_AUTO_TEST_CASE(exception_msgs) { BOOST_CHECK_NO_THROW(AdHoc::TimeOutOnResourcePool("foo").message()); BOOST_CHECK_NO_THROW(AdHoc::NoCurrentResource(std::this_thread::get_id(), "foo").message()); } - diff --git a/libadhocutil/unittests/testScopeExit.cpp b/libadhocutil/unittests/testScopeExit.cpp index 66f4c48..edb8f99 100644 --- a/libadhocutil/unittests/testScopeExit.cpp +++ b/libadhocutil/unittests/testScopeExit.cpp @@ -6,24 +6,49 @@ using namespace AdHoc; -BOOST_AUTO_TEST_CASE ( cleanexit ) +BOOST_AUTO_TEST_CASE(cleanexit) { std::string log; { - ScopeExit se([&log]{ log += "before"; }, [&log]{ log += "clean"; }, [&log]{ log += "error"; }, [&log]{ log += "after"; }); + ScopeExit se( + [&log] { + log += "before"; + }, + [&log] { + log += "clean"; + }, + [&log] { + log += "error"; + }, + [&log] { + log += "after"; + }); } BOOST_REQUIRE_EQUAL(log, "beforecleanafter"); } -BOOST_AUTO_TEST_CASE ( uncaught ) +BOOST_AUTO_TEST_CASE(uncaught) { - BOOST_REQUIRE_THROW({ - std::string log; - { - ScopeExit se([&log]{ log += "before"; }, [&log]{ log += "clean"; }, [&log]{ log += "error"; }, [&log]{ log += "after"; }); - throw std::runtime_error("test unclean exit"); - } - BOOST_REQUIRE_EQUAL(log, "beforeerrorafter"); - }, std::runtime_error); + BOOST_REQUIRE_THROW( + { + std::string log; + { + ScopeExit se( + [&log] { + log += "before"; + }, + [&log] { + log += "clean"; + }, + [&log] { + log += "error"; + }, + [&log] { + log += "after"; + }); + throw std::runtime_error("test unclean exit"); + } + BOOST_REQUIRE_EQUAL(log, "beforeerrorafter"); + }, + std::runtime_error); } - diff --git a/libadhocutil/unittests/testSemaphore.cpp b/libadhocutil/unittests/testSemaphore.cpp index 38f9b8f..e2cdb7a 100644 --- a/libadhocutil/unittests/testSemaphore.cpp +++ b/libadhocutil/unittests/testSemaphore.cpp @@ -1,17 +1,17 @@ #define BOOST_TEST_MODULE Semaphore #include -#include #include +#include -BOOST_AUTO_TEST_CASE( addRemoveOne ) +BOOST_AUTO_TEST_CASE(addRemoveOne) { AdHoc::Semaphore s; s.notify(); s.wait(); } -BOOST_AUTO_TEST_CASE( initial ) +BOOST_AUTO_TEST_CASE(initial) { AdHoc::Semaphore s(2); s.wait(); @@ -19,7 +19,7 @@ BOOST_AUTO_TEST_CASE( initial ) BOOST_REQUIRE_EQUAL(false, s.wait(0)); } -BOOST_AUTO_TEST_CASE( addRemoveSome ) +BOOST_AUTO_TEST_CASE(addRemoveSome) { AdHoc::Semaphore s; BOOST_REQUIRE_EQUAL(0, s.freeCount()); @@ -37,7 +37,7 @@ BOOST_AUTO_TEST_CASE( addRemoveSome ) BOOST_REQUIRE_EQUAL(0, s.freeCount()); } -BOOST_AUTO_TEST_CASE( addRemoveTimeOut ) +BOOST_AUTO_TEST_CASE(addRemoveTimeOut) { AdHoc::Semaphore s; s.notify(); @@ -46,14 +46,16 @@ BOOST_AUTO_TEST_CASE( addRemoveTimeOut ) BOOST_REQUIRE_EQUAL(false, s.wait(0)); } -BOOST_AUTO_TEST_CASE( addRemoveWait ) +BOOST_AUTO_TEST_CASE(addRemoveWait) { AdHoc::Semaphore s; s.notify(); s.wait(); - std::thread th([&s]() { usleep(100000); s.notify(); }); + std::thread th([&s]() { + usleep(100000); + s.notify(); + }); BOOST_REQUIRE_EQUAL(false, s.wait(1)); s.wait(); th.join(); } - diff --git a/libadhocutil/unittests/testUriParse.cpp b/libadhocutil/unittests/testUriParse.cpp index 600f0f0..5e54e46 100644 --- a/libadhocutil/unittests/testUriParse.cpp +++ b/libadhocutil/unittests/testUriParse.cpp @@ -3,7 +3,7 @@ #include "uriParse.h" -BOOST_AUTO_TEST_CASE( simple ) +BOOST_AUTO_TEST_CASE(simple) { AdHoc::Uri u("http://localhost"); BOOST_REQUIRE_EQUAL("http", u.scheme); @@ -16,7 +16,7 @@ BOOST_AUTO_TEST_CASE( simple ) BOOST_REQUIRE(!u.fragment); } -BOOST_AUTO_TEST_CASE( lowerScheme ) +BOOST_AUTO_TEST_CASE(lowerScheme) { AdHoc::Uri u("HtTP://localhost"); BOOST_REQUIRE_EQUAL("http", u.scheme); @@ -29,7 +29,7 @@ BOOST_AUTO_TEST_CASE( lowerScheme ) BOOST_REQUIRE(!u.fragment); } -BOOST_AUTO_TEST_CASE( simpleTrailingSlash ) +BOOST_AUTO_TEST_CASE(simpleTrailingSlash) { AdHoc::Uri u("ssh+git://localhost/"); BOOST_REQUIRE_EQUAL("ssh+git", u.scheme); @@ -43,7 +43,7 @@ BOOST_AUTO_TEST_CASE( simpleTrailingSlash ) BOOST_REQUIRE(!u.fragment); } -BOOST_AUTO_TEST_CASE( simpleWithPort ) +BOOST_AUTO_TEST_CASE(simpleWithPort) { AdHoc::Uri u("http://localhost:80"); BOOST_REQUIRE_EQUAL("http", u.scheme); @@ -57,7 +57,7 @@ BOOST_AUTO_TEST_CASE( simpleWithPort ) BOOST_REQUIRE(!u.fragment); } -BOOST_AUTO_TEST_CASE( simpleTrailingSlashWithPort ) +BOOST_AUTO_TEST_CASE(simpleTrailingSlashWithPort) { AdHoc::Uri u("http://localhost:80/"); BOOST_REQUIRE_EQUAL("http", u.scheme); @@ -72,7 +72,7 @@ BOOST_AUTO_TEST_CASE( simpleTrailingSlashWithPort ) BOOST_REQUIRE(!u.fragment); } -BOOST_AUTO_TEST_CASE( username ) +BOOST_AUTO_TEST_CASE(username) { AdHoc::Uri u("http://user@localhost"); BOOST_REQUIRE_EQUAL("http", u.scheme); @@ -85,7 +85,7 @@ BOOST_AUTO_TEST_CASE( username ) BOOST_REQUIRE(!u.fragment); } -BOOST_AUTO_TEST_CASE( usernameAndPassword ) +BOOST_AUTO_TEST_CASE(usernameAndPassword) { AdHoc::Uri u("http://user:pass@localhost"); BOOST_REQUIRE_EQUAL("http", u.scheme); @@ -99,7 +99,7 @@ BOOST_AUTO_TEST_CASE( usernameAndPassword ) BOOST_REQUIRE(!u.fragment); } -BOOST_AUTO_TEST_CASE( path ) +BOOST_AUTO_TEST_CASE(path) { AdHoc::Uri u("http://localhost/path/to/resource"); BOOST_REQUIRE_EQUAL("http", u.scheme); @@ -112,7 +112,7 @@ BOOST_AUTO_TEST_CASE( path ) BOOST_REQUIRE(!u.fragment); } -BOOST_AUTO_TEST_CASE( query0 ) +BOOST_AUTO_TEST_CASE(query0) { AdHoc::Uri u("http://localhost/?"); BOOST_REQUIRE_EQUAL("http", u.scheme); @@ -120,7 +120,7 @@ BOOST_AUTO_TEST_CASE( query0 ) BOOST_REQUIRE_EQUAL(0, u.query.size()); } -BOOST_AUTO_TEST_CASE( query1 ) +BOOST_AUTO_TEST_CASE(query1) { AdHoc::Uri u("http://localhost/?var=val"); BOOST_REQUIRE_EQUAL("http", u.scheme); @@ -130,7 +130,7 @@ BOOST_AUTO_TEST_CASE( query1 ) BOOST_REQUIRE_EQUAL("val", u.query.begin()->second); } -BOOST_AUTO_TEST_CASE( query2 ) +BOOST_AUTO_TEST_CASE(query2) { AdHoc::Uri u("http://localhost/?var=val&name=value"); BOOST_REQUIRE_EQUAL("http", u.scheme); @@ -142,7 +142,7 @@ BOOST_AUTO_TEST_CASE( query2 ) BOOST_REQUIRE_EQUAL("val", u.query.rbegin()->second); } -BOOST_AUTO_TEST_CASE( queryMany ) +BOOST_AUTO_TEST_CASE(queryMany) { AdHoc::Uri u("http://localhost/?name=val&name=value"); BOOST_REQUIRE_EQUAL("http", u.scheme); @@ -154,7 +154,7 @@ BOOST_AUTO_TEST_CASE( queryMany ) BOOST_REQUIRE_EQUAL("value", u.query.rbegin()->second); } -BOOST_AUTO_TEST_CASE( queryNoValue1 ) +BOOST_AUTO_TEST_CASE(queryNoValue1) { AdHoc::Uri u("http://localhost/?n1"); BOOST_REQUIRE_EQUAL("http", u.scheme); @@ -164,7 +164,7 @@ BOOST_AUTO_TEST_CASE( queryNoValue1 ) BOOST_REQUIRE_EQUAL("", u.query.begin()->second); } -BOOST_AUTO_TEST_CASE( queryNoValue1eq ) +BOOST_AUTO_TEST_CASE(queryNoValue1eq) { AdHoc::Uri u("http://localhost/?n1="); BOOST_REQUIRE_EQUAL("http", u.scheme); @@ -174,7 +174,7 @@ BOOST_AUTO_TEST_CASE( queryNoValue1eq ) BOOST_REQUIRE_EQUAL("", u.query.begin()->second); } -BOOST_AUTO_TEST_CASE( queryNoValue2 ) +BOOST_AUTO_TEST_CASE(queryNoValue2) { AdHoc::Uri u("http://localhost/?n1=&n2"); BOOST_REQUIRE_EQUAL("http", u.scheme); @@ -186,7 +186,7 @@ BOOST_AUTO_TEST_CASE( queryNoValue2 ) BOOST_REQUIRE_EQUAL("", u.query.rbegin()->second); } -BOOST_AUTO_TEST_CASE( fragment ) +BOOST_AUTO_TEST_CASE(fragment) { AdHoc::Uri u("http://localhost/path/to/resource#someFrag"); BOOST_REQUIRE_EQUAL("http", u.scheme); @@ -200,7 +200,7 @@ BOOST_AUTO_TEST_CASE( fragment ) BOOST_REQUIRE_EQUAL("someFrag", *u.fragment); } -BOOST_AUTO_TEST_CASE( ipv6 ) +BOOST_AUTO_TEST_CASE(ipv6) { AdHoc::Uri u("http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html"); BOOST_REQUIRE_EQUAL("http", u.scheme); @@ -211,7 +211,7 @@ BOOST_AUTO_TEST_CASE( ipv6 ) BOOST_REQUIRE_EQUAL("index.html", *u.path); } -BOOST_AUTO_TEST_CASE( bad ) +BOOST_AUTO_TEST_CASE(bad) { BOOST_REQUIRE_THROW(AdHoc::Uri(""), AdHoc::InvalidUri); BOOST_REQUIRE_THROW(AdHoc::Uri("localhost"), AdHoc::InvalidUri); @@ -227,4 +227,3 @@ BOOST_AUTO_TEST_CASE( bad ) AdHoc::InvalidUri ui("message", "http://localhost"); BOOST_REQUIRE_EQUAL("InvalidUri (message) parsing [http://localhost]", ui.what()); } - diff --git a/libadhocutil/unittests/utilTestClasses.cpp b/libadhocutil/unittests/utilTestClasses.cpp index cb31104..4ae241c 100644 --- a/libadhocutil/unittests/utilTestClasses.cpp +++ b/libadhocutil/unittests/utilTestClasses.cpp @@ -2,4 +2,3 @@ #include "plugins.impl.h" PLUGIN(ImplOfThing, BaseThing); - diff --git a/libadhocutil/unittests/utilTestClasses.h b/libadhocutil/unittests/utilTestClasses.h index 18ddbef..1fbe766 100644 --- a/libadhocutil/unittests/utilTestClasses.h +++ b/libadhocutil/unittests/utilTestClasses.h @@ -19,4 +19,3 @@ class OtherImpl : public OtherBase { }; #endif - diff --git a/libadhocutil/uriParse.cpp b/libadhocutil/uriParse.cpp index ba507c8..df19abc 100644 --- a/libadhocutil/uriParse.cpp +++ b/libadhocutil/uriParse.cpp @@ -1,11 +1,12 @@ #include "uriParse.h" +#include "compileTimeFormatter.h" #include #include #include -#include "compileTimeFormatter.h" namespace AdHoc { - static inline int _is_scheme_char(int c) + static inline int + _is_scheme_char(int c) { return (!isalpha(c) && '+' != c && '-' != c && '.' != c) ? 0 : 1; } @@ -13,7 +14,7 @@ namespace AdHoc { Uri::Uri(const std::string & uri) { auto * puri = this; - const char *curstr; + const char * curstr; int userpass_flag; int bracket_flag; @@ -47,7 +48,8 @@ namespace AdHoc { if ('@' == *tmpstr) { userpass_flag = 1; break; - } else if ('/' == *tmpstr) { + } + else if ('/' == *tmpstr) { userpass_flag = 0; break; } @@ -69,7 +71,7 @@ namespace AdHoc { tmpstr++; } len = tmpstr - curstr; - puri->password = std::string(curstr, len); + puri->password = std::string(curstr, len); curstr = tmpstr; } if ('@' != *curstr) { @@ -80,7 +82,8 @@ namespace AdHoc { if ('[' == *curstr) { bracket_flag = 1; - } else { + } + else { bracket_flag = 0; } @@ -89,7 +92,8 @@ namespace AdHoc { if (bracket_flag && ']' == *tmpstr) { tmpstr++; break; - } else if (!bracket_flag && (':' == *tmpstr || '/' == *tmpstr)) { + } + else if (!bracket_flag && (':' == *tmpstr || '/' == *tmpstr)) { break; } tmpstr++; @@ -123,7 +127,7 @@ namespace AdHoc { curstr++; tmpstr = curstr; - while ('\0' != *tmpstr && '#' != *tmpstr && '?' != *tmpstr) { + while ('\0' != *tmpstr && '#' != *tmpstr && '?' != *tmpstr) { tmpstr++; } len = tmpstr - curstr; @@ -138,7 +142,7 @@ namespace AdHoc { tmpstr++; } len = tmpstr - curstr; - auto q = puri->query.insert({ std::string(curstr, len), std::string() }); + auto q = puri->query.insert({std::string(curstr, len), std::string()}); curstr = tmpstr; if ('=' == *curstr) { curstr++; @@ -171,10 +175,8 @@ namespace AdHoc { } } - InvalidUri::InvalidUri(std::string e, std::string u) : - Exception(std::string()), - err(std::move(e)), - uri(std::move(u)) + InvalidUri::InvalidUri(std::string e, std::string u) : + Exception(std::string()), err(std::move(e)), uri(std::move(u)) { } @@ -186,4 +188,3 @@ namespace AdHoc { return InvalidUriMsg::get(err, uri); } } - diff --git a/libadhocutil/uriParse.h b/libadhocutil/uriParse.h index e6fd0cb..f0c3d49 100644 --- a/libadhocutil/uriParse.h +++ b/libadhocutil/uriParse.h @@ -1,57 +1,56 @@ #ifndef ADHOCUTIL_URIPARSE_H #define ADHOCUTIL_URIPARSE_H -#include "visibility.h" #include "exception.h" -#include +#include "visibility.h" #include -#include #include +#include +#include namespace AdHoc { /** * Class representing a broken down URI. */ class DLL_PUBLIC Uri { - public: - /// Constructor accepting a URI to parse. - /// @param uri the URI to parse. - explicit Uri(const std::string & uri); - - /// The scheme. - std::string scheme; - /// The optional username. - std::optional username; - /// The optional password. - std::optional password; - /// The host. - std::string host; - /// The optional port. - std::optional port; - /// The optional path. - std::optional path; - /// The parsed components of the query string. - std::multimap query; - /// The optional fragment. - std::optional fragment; + public: + /// Constructor accepting a URI to parse. + /// @param uri the URI to parse. + explicit Uri(const std::string & uri); + + /// The scheme. + std::string scheme; + /// The optional username. + std::optional username; + /// The optional password. + std::optional password; + /// The host. + std::string host; + /// The optional port. + std::optional port; + /// The optional path. + std::optional path; + /// The parsed components of the query string. + std::multimap query; + /// The optional fragment. + std::optional fragment; }; /** * Exception representing a failure attempting to parse a URI. */ class DLL_PUBLIC InvalidUri : public Exception { - public: - /// Constructor accepting what went wrong and the URI being parsed. - InvalidUri(std::string err, std::string uri); + public: + /// Constructor accepting what went wrong and the URI being parsed. + InvalidUri(std::string err, std::string uri); - std::string message() const noexcept override; + std::string message() const noexcept override; - /// The parse error. - const std::string err; - /// The URI being parsed when the error occurred. - const std::string uri; + /// The parse error. + const std::string err; + /// The URI being parsed when the error occurred. + const std::string uri; }; } #endif - diff --git a/libadhocutil/visibility.h b/libadhocutil/visibility.h index 63378b7..c049b82 100644 --- a/libadhocutil/visibility.h +++ b/libadhocutil/visibility.h @@ -1,8 +1,7 @@ #ifndef DLL_PUBLIC -#define DLL_PUBLIC __attribute__ ((visibility ("default"))) +#define DLL_PUBLIC __attribute__((visibility("default"))) #endif #ifndef DLL_PRIVATE -#define DLL_PRIVATE __attribute__ ((visibility ("hidden"))) +#define DLL_PRIVATE __attribute__((visibility("hidden"))) #endif - -- cgit v1.2.3