diff --git a/CMakeLists.txt b/CMakeLists.txt index 0f0d8417..03d89a71 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3,10 +3,12 @@ cmake_minimum_required(VERSION 3.11) project(finalmq) +option(FINALMQ_FETCH_HL7 "Fetches HL7" ON) option(FINALMQ_BUILD_EXAMPLES "Build examples" ON) option(FINALMQ_BUILD_TESTS "Build tests" OFF) option(FINALMQ_BUILD_COVERAGE "Enable gcov" OFF) option(FINALMQ_BUILD_DOXYGEN "Enable doxygen" OFF) +option(FINALMQ_HAS_NOT_WEAK_FROM_THIS "Has weak_from_this" OFF) if (WIN32) # option(FINALMQ_BUILD_FMQFCGI "Build fmqfcgi" OFF) # avoid dependency to fcgi for windows @@ -21,8 +23,8 @@ SET(FINALMQ_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}) SET(FINALMQ_BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR}) +if (FINALMQ_FETCH_HL7) include(FetchContent) - function(CloneRepository repositoryURL branchName projectName sourceDir) #Commands are left empty so that we only checkout the source and no not perform any kind of build message("Starting to clone ${projectName} into ${sourceDir}") @@ -37,8 +39,8 @@ function(CloneRepository repositoryURL branchName projectName sourceDir) ) FetchContent_MakeAvailable(${projectName}) endfunction(CloneRepository) - CloneRepository("https://github.com/beckdave/hl7-dictionary.git" "beckdave-fix-compounds" "hl7-dictionary" "${FINALMQ_BINARY_DIR}/hl7-dictionary") +endif(FINALMQ_FETCH_HL7) # Add compile flags to determine coverage if (FINALMQ_BUILD_COVERAGE) @@ -60,14 +62,15 @@ endif(FINALMQ_USE_SSL) SET( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${GCC_COVERAGE_COMPILE_FLAGS} -DNOMINMAX" ) SET( CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${GCC_COVERAGE_LINK_FLAGS}" ) +if (FINALMQ_HAS_NOT_WEAK_FROM_THIS) + SET( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DFINALMQ_HAS_NOT_WEAK_FROM_THIS" ) +endif(FINALMQ_HAS_NOT_WEAK_FROM_THIS) set(CMAKE_CXX_STANDARD 14) # this target needs to be set before digging into subdirectories add_custom_target( verify ${CMAKE_CURRENT_BINARY_DIR}/test/testfinalmq) -message(${CMAKE_CURRENT_BINARY_DIR}) - if (FINALMQ_BUILD_COVERAGE) # go for the latest gcovr version locally installed via pip if available # since latest only gcov 3.4 supports branch coverage display in html details @@ -143,9 +146,6 @@ add_custom_command( ) -#Bring the headers into the project -#include_directories(inc) - #However, the file(GLOB...) allows for wildcard additions: file(GLOB SOURCES "src/*.cpp" "inc/finalmq/*.h" "src/helpers/*.cpp" "inc/finalmq/helpers/*.h" @@ -189,7 +189,7 @@ target_include_directories(finalmq PUBLIC ${FINALMQ_SOURCE_DIR}/inc) #target_include_directories(finalmqStatic PUBLIC ${FINALMQ_SOURCE_DIR}/inc) if (WIN32) - message("== WIN32 ==") +# message("== WIN32 ==") set(LINKLIBS ${LINKLIBS} wsock32 ws2_32 Rpcrt4) if (FINALMQ_USE_SSL) SET(OPENSSL_DIR "$ENV{OPENSSL_ROOT_DIR}") @@ -198,13 +198,11 @@ if (WIN32) set(LINKLIBS ${LINKLIBS} wsock32 ws2_32 Rpcrt4 "${OPENSSL_DIR}/lib/libssl.lib" "${OPENSSL_DIR}/lib/libcrypto.lib") endif() target_compile_options(finalmq PRIVATE -DEXPORT_finalmq) -# target_compile_options(finalmqStatic PRIVATE -DEXPORT_finalmq) elseif(UNIX) - message("== UNIX ==") +# message("== UNIX ==") target_compile_options(finalmq PRIVATE -Werror -Wall -Wextra) -# target_compile_options(finalmqStatic PRIVATE -Werror -Wall -Wextra) if (${CMAKE_SYSTEM_NAME} MATCHES "QNX") - message("== QNX ==") +# message("== QNX ==") else() set(LINKLIBS ${LINKLIBS} uuid pthread) endif() diff --git a/codegenerator/cpp/cpp_cpp.ejs b/codegenerator/cpp/cpp_cpp.ejs index 7a96d528..babb3d00 100644 --- a/codegenerator/cpp/cpp_cpp.ejs +++ b/codegenerator/cpp/cpp_cpp.ejs @@ -109,6 +109,10 @@ std::shared_ptr <%- plaintype %>::clone() const return std::make_shared<<%- plaintype %>>(*this); } +#ifndef WIN32 +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wfloat-equal" +#endif bool <%- plaintype %>::operator ==(const <%- plaintype %>& <% if (stru.fields.length == 0) { %>/*<% } %>rhs<% if (stru.fields.length == 0) { %>*/<% } %>) const { <% if (stru.fields.length > 0) { %> @@ -124,6 +128,10 @@ bool <%- plaintype %>::operator ==(const <%- plaintype %>& <% if (stru.fields.le return true; <% } -%> } +#ifndef WIN32 +#pragma GCC diagnostic pop +#endif + bool <%- plaintype %>::operator !=(const <%- plaintype %>& rhs) const { return !(*this == rhs); diff --git a/codegenerator/cpp/cpp_h.ejs b/codegenerator/cpp/cpp_h.ejs index 78a218fe..cc35f197 100644 --- a/codegenerator/cpp/cpp_h.ejs +++ b/codegenerator/cpp/cpp_h.ejs @@ -101,7 +101,7 @@ class SYMBOLEXP <%- plaintype %> : public finalmq::StructBase public:<% -%> <% for (var n = 0; n < stru.fields.length; n++) { field = stru.fields[n] %> - <%- helper.tid2type(data, field) %> <%- helper.avoidCppKeyWords(field.name) %><% if (helper.tid2default(field.tid)){%> = <%- helper.tid2default(field.tid)%><% } %>;<% -%> + <%- helper.tid2type(data, field) %> <%- helper.avoidCppKeyWords(field.name) %>{};<% -%> <% } %> <%- plaintype %>(); diff --git a/codegenerator/cpp/helper.js b/codegenerator/cpp/helper.js index cea2c777..ff85f3af 100644 --- a/codegenerator/cpp/helper.js +++ b/codegenerator/cpp/helper.js @@ -185,73 +185,6 @@ module.exports = { } }, - tid2default : function(tid) { - - switch (tid) - { - case 'bool': - case 'TYPE_BOOL': return 'false' - case 'int8': - case 'TYPE_INT8': return '0' - case 'uint8': - case 'TYPE_UINT8': return '0' - case 'int16': - case 'TYPE_INT16': return '0' - case 'uint16': - case 'TYPE_UINT16': return '0' - case 'int32': - case 'TYPE_INT32': return '0' - case 'uint32': - case 'TYPE_UINT32': return '0' - case 'int64': - case 'TYPE_INT64': return '0' - case 'uint64': - case 'TYPE_UINT64': return '0' - case 'float': - case 'TYPE_FLOAT': return '0.0' - case 'double': - case 'TYPE_DOUBLE': return '0.0' - case 'string': - case 'TYPE_STRING': return null - case 'bytes': - case 'TYPE_BYTES': return null - case 'struct': - case 'TYPE_STRUCT': return null - case 'enum': - case 'TYPE_ENUM': return null - case 'variant': - case 'TYPE_VARIANT': return null - case 'bool[]': - case 'TYPE_ARRAY_BOOL': return null - case 'int8[]': - case 'TYPE_ARRAY_INT8': return null - case 'int16[]': - case 'TYPE_ARRAY_INT16': return null - case 'uint16[]': - case 'TYPE_ARRAY_UINT16': return null - case 'int32[]': - case 'TYPE_ARRAY_INT32': return null - case 'uint32[]': - case 'TYPE_ARRAY_UINT32': return null - case 'int64[]': - case 'TYPE_ARRAY_INT64': return null - case 'uint64[]': - case 'TYPE_ARRAY_UINT64': return null - case 'float[]': - case 'TYPE_ARRAY_FLOAT': return null - case 'double[]': - case 'TYPE_ARRAY_DOUBLE': return null - case 'string[]': - case 'TYPE_ARRAY_STRING': return null - case 'bytes[]': - case 'TYPE_ARRAY_BYTES': return null - case 'struct[]': - case 'TYPE_ARRAY_STRUCT': return null - case 'enum[]': - case 'TYPE_ARRAY_ENUM': return null - } - }, - convertFlags : function(flagArray) { var flags = 'finalmq::METAFLAG_NONE' diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index 96be29e8..ca752aa4 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -3,6 +3,9 @@ add_subdirectory(cpp/helloworld) add_subdirectory(cpp/timer) add_subdirectory(cpp/restapi) -add_subdirectory(cpp/hl7) add_subdirectory(cpp/experimental/registry) add_subdirectory(cpp/experimental/http) + +if (FINALMQ_FETCH_HL7) + add_subdirectory(cpp/hl7) +endif(FINALMQ_FETCH_HL7) \ No newline at end of file diff --git a/inc/finalmq/connectionhub/ConnectionHub.h b/inc/finalmq/connectionhub/ConnectionHub.h index a1187d85..e16499a7 100644 --- a/inc/finalmq/connectionhub/ConnectionHub.h +++ b/inc/finalmq/connectionhub/ConnectionHub.h @@ -24,19 +24,18 @@ #include "finalmq/protocolsession/ProtocolSessionContainer.h" - -namespace finalmq { - - +namespace finalmq +{ struct IConnectionHub { - virtual ~IConnectionHub() {} + virtual ~IConnectionHub() + {} virtual void init(int cycleTime = 100, int checkReconnectInterval = 1000) = 0; virtual int bind(const std::string& endpoint, const BindProperties& bindProperties = {}) = 0; virtual void unbind(const std::string& endpoint) = 0; virtual IProtocolSessionPtr connect(const std::string& endpoint, const ConnectProperties& connectProperties = {}) = 0; - virtual std::vector< IProtocolSessionPtr > getAllSessions() const = 0; + virtual std::vector getAllSessions() const = 0; virtual IProtocolSessionPtr getSession(std::int64_t sessionId) const = 0; virtual void run() = 0; virtual void waitForTerminationOfPollerLoop() = 0; @@ -46,11 +45,7 @@ struct IConnectionHub virtual void stopForwardingToSession(std::int64_t sessionId) = 0; }; - - - -class SYMBOLEXP ConnectionHub : public IConnectionHub - , private IProtocolSessionCallback +class SYMBOLEXP ConnectionHub : public IConnectionHub, private IProtocolSessionCallback { public: ConnectionHub(); @@ -61,7 +56,7 @@ class SYMBOLEXP ConnectionHub : public IConnectionHub virtual int bind(const std::string& endpoint, const BindProperties& bindProperties = {}) override; virtual void unbind(const std::string& endpoint) override; virtual IProtocolSessionPtr connect(const std::string& endpoint, const ConnectProperties& connectProperties = {}) override; - virtual std::vector< IProtocolSessionPtr > getAllSessions() const override; + virtual std::vector getAllSessions() const override; virtual IProtocolSessionPtr getSession(std::int64_t sessionId) const override; virtual void run() override; virtual void waitForTerminationOfPollerLoop() override; @@ -78,14 +73,13 @@ class SYMBOLEXP ConnectionHub : public IConnectionHub virtual void socketConnected(const IProtocolSessionPtr& session) override; virtual void socketDisconnected(const IProtocolSessionPtr& session) override; - std::unique_ptr m_protocolSessionContainer; - std::vector m_sessionIdsStopForwardingFromSession; - std::vector m_sessionIdsStopForwardingToSession; - bool m_startMessageForwarding = false; - std::vector> m_messagesForForwarding; - - std::recursive_mutex m_mutex; + std::unique_ptr m_protocolSessionContainer{}; + std::vector m_sessionIdsStopForwardingFromSession{}; + std::vector m_sessionIdsStopForwardingToSession{}; + bool m_startMessageForwarding = false; + std::vector> m_messagesForForwarding{}; + std::recursive_mutex m_mutex{}; }; -} // namespace finalmq +} // namespace finalmq diff --git a/inc/finalmq/conversions/Conversions.h b/inc/finalmq/conversions/Conversions.h index aeb311af..2c0a9451 100644 --- a/inc/finalmq/conversions/Conversions.h +++ b/inc/finalmq/conversions/Conversions.h @@ -1,24 +1,30 @@ #pragma once - -#include "finalmq/helpers/FmqDefines.h" #include +#include +#include "finalmq/helpers/FmqDefines.h" -template +template void string2Number(const std::string& str, T& number) { } - -template <> +template<> void string2Number(const std::string& str, bool& number) { static const std::string STR_TRUE = "true"; if (str != STR_TRUE) { double value = strtof64(str.c_str(), nullptr); +#ifndef WIN32 +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wfloat-equal" +#endif if (value == 0) +#ifndef WIN32 +#pragma GCC diagnostic pop +#endif { number = false; } @@ -26,63 +32,62 @@ void string2Number(const std::string& str, bool& number) number = true; } -template <> +template<> void string2Number(const std::string& str, std::int8_t& number) { number = static_cast(strtol(str.c_str(), nullptr, 10)); } -template <> +template<> void string2Number(const std::string& str, std::uint8_t& number) { number = static_cast(strtoul(str.c_str(), nullptr, 10)); } -template <> +template<> void string2Number(const std::string& str, std::int16_t& number) { number = static_cast(strtol(str.c_str(), nullptr, 10)); } -template <> +template<> void string2Number(const std::string& str, std::uint16_t& number) { number = static_cast(strtoul(str.c_str(), nullptr, 10)); } -template <> +template<> void string2Number(const std::string& str, std::int32_t& number) { - number = strtol(str.c_str(), nullptr, 10); + number = static_cast(strtol(str.c_str(), nullptr, 10)); } -template <> +template<> void string2Number(const std::string& str, std::uint32_t& number) { - number = strtoul(str.c_str(), nullptr, 10); + number = static_cast(strtoul(str.c_str(), nullptr, 10)); } -template <> +template<> void string2Number(const std::string& str, std::int64_t& number) { number = strtoll(str.c_str(), nullptr, 10); } -template <> +template<> void string2Number(const std::string& str, std::uint64_t& number) { number = strtoull(str.c_str(), nullptr, 10); } -template <> +template<> void string2Number(const std::string& str, float& number) { number = strtof32(str.c_str(), nullptr); } -template <> +template<> void string2Number(const std::string& str, double& number) { number = strtof64(str.c_str(), nullptr); } - diff --git a/inc/finalmq/conversions/diyfp.h b/inc/finalmq/conversions/diyfp.h index 77a8105d..f9015eee 100644 --- a/inc/finalmq/conversions/diyfp.h +++ b/inc/finalmq/conversions/diyfp.h @@ -20,15 +20,15 @@ #define RAPIDJSON_DIYFP_H_ //#include "../rapidjson.h" -#include "clzll.h" #include +#include "clzll.h" + #if defined(_MSC_VER) && defined(_M_AMD64) && !defined(__INTEL_COMPILER) #include #pragma intrinsic(_umul128) #endif - /////////////////////////////////////////////////////////////////////////////// // RAPIDJSON_UINT64_C2 @@ -42,9 +42,8 @@ #define RAPIDJSON_UINT64_C2(high32, low32) ((static_cast(high32) << 32) | static_cast(low32)) #endif - -namespace rapidjson { - +namespace rapidjson +{ //#ifdef __GNUC__ //RAPIDJSON_DIAG_PUSH //RAPIDJSON_DIAG_OFF(effc++) @@ -55,41 +54,52 @@ namespace rapidjson { //RAPIDJSON_DIAG_OFF(padded) //#endif -struct DiyFp { - DiyFp() : f(), e() {} +struct DiyFp +{ + DiyFp() + : f(), e() + {} - DiyFp(uint64_t fp, int exp) : f(fp), e(exp) {} + DiyFp(uint64_t fp, int exp) + : f(fp), e(exp) + {} - explicit DiyFp(double d) { - union { + explicit DiyFp(double d) + { + union + { double d; uint64_t u64; - } u = { d }; + } u = {d}; int biased_e = static_cast((u.u64 & kDpExponentMask) >> kDpSignificandSize); uint64_t significand = (u.u64 & kDpSignificandMask); - if (biased_e != 0) { + if (biased_e != 0) + { f = significand + kDpHiddenBit; e = biased_e - kDpExponentBias; } - else { + else + { f = significand; e = kDpMinExponent + 1; } } - DiyFp operator-(const DiyFp& rhs) const { + DiyFp operator-(const DiyFp& rhs) const + { return DiyFp(f - rhs.f, e); } - DiyFp operator*(const DiyFp& rhs) const { + DiyFp operator*(const DiyFp& rhs) const + { #if defined(_MSC_VER) && defined(_M_AMD64) uint64_t h; uint64_t l = _umul128(f, rhs.f, &h); if (l & (uint64_t(1) << 63)) // rounding h++; return DiyFp(h, e + rhs.e + 64); -#elif (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) && defined(__x86_64__) +#elif(__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) && defined(__x86_64__) __extension__ typedef unsigned __int128 uint128; uint128 p = static_cast(f) * static_cast(rhs.f); uint64_t h = static_cast(p >> 64); @@ -108,19 +118,22 @@ struct DiyFp { const uint64_t ad = a * d; const uint64_t bd = b * d; uint64_t tmp = (bd >> 32) + (ad & M32) + (bc & M32); - tmp += 1U << 31; /// mult_round + tmp += 1U << 31; /// mult_round return DiyFp(ac + (ad >> 32) + (bc >> 32) + (tmp >> 32), e + rhs.e + 64); #endif } - DiyFp Normalize() const { + DiyFp Normalize() const + { int s = static_cast(clzll(f)); return DiyFp(f << s, e - s); } - DiyFp NormalizeBoundary() const { + DiyFp NormalizeBoundary() const + { DiyFp res = *this; - while (!(res.f & (kDpHiddenBit << 1))) { + while (!(res.f & (kDpHiddenBit << 1))) + { res.f <<= 1; res.e--; } @@ -129,7 +142,8 @@ struct DiyFp { return res; } - void NormalizedBoundaries(DiyFp* minus, DiyFp* plus) const { + void NormalizedBoundaries(DiyFp* minus, DiyFp* plus) const + { DiyFp pl = DiyFp((f << 1) + 1, e - 1).NormalizeBoundary(); DiyFp mi = (f == kDpHiddenBit) ? DiyFp((f << 2) - 1, e - 2) : DiyFp((f << 1) - 1, e - 1); mi.f <<= mi.e - pl.e; @@ -138,22 +152,25 @@ struct DiyFp { *minus = mi; } - double ToDouble() const { - union { + double ToDouble() const + { + union + { double d; uint64_t u64; - }u; + } u; assert(f <= kDpHiddenBit + kDpSignificandMask); - if (e < kDpDenormalExponent) { + if (e < kDpDenormalExponent) + { // Underflow. return 0.0; } - if (e >= kDpMaxExponent) { + if (e >= kDpMaxExponent) + { // Overflow. return std::numeric_limits::infinity(); } - const uint64_t be = (e == kDpDenormalExponent && (f & kDpHiddenBit) == 0) ? 0 : - static_cast(e + kDpExponentBias); + const uint64_t be = (e == kDpDenormalExponent && (f & kDpHiddenBit) == 0) ? 0 : static_cast(e + kDpExponentBias); u.u64 = (f & kDpSignificandMask) | (be << kDpSignificandSize); return u.d; } @@ -168,88 +185,37 @@ struct DiyFp { static const uint64_t kDpSignificandMask = RAPIDJSON_UINT64_C2(0x000FFFFF, 0xFFFFFFFF); static const uint64_t kDpHiddenBit = RAPIDJSON_UINT64_C2(0x00100000, 0x00000000); - uint64_t f; - int e; + uint64_t f{}; + int e{}; }; -inline DiyFp GetCachedPowerByIndex(size_t index) { +inline DiyFp GetCachedPowerByIndex(size_t index) +{ // 10^-348, 10^-340, ..., 10^340 static const uint64_t kCachedPowers_F[] = { - RAPIDJSON_UINT64_C2(0xfa8fd5a0, 0x081c0288), RAPIDJSON_UINT64_C2(0xbaaee17f, 0xa23ebf76), - RAPIDJSON_UINT64_C2(0x8b16fb20, 0x3055ac76), RAPIDJSON_UINT64_C2(0xcf42894a, 0x5dce35ea), - RAPIDJSON_UINT64_C2(0x9a6bb0aa, 0x55653b2d), RAPIDJSON_UINT64_C2(0xe61acf03, 0x3d1a45df), - RAPIDJSON_UINT64_C2(0xab70fe17, 0xc79ac6ca), RAPIDJSON_UINT64_C2(0xff77b1fc, 0xbebcdc4f), - RAPIDJSON_UINT64_C2(0xbe5691ef, 0x416bd60c), RAPIDJSON_UINT64_C2(0x8dd01fad, 0x907ffc3c), - RAPIDJSON_UINT64_C2(0xd3515c28, 0x31559a83), RAPIDJSON_UINT64_C2(0x9d71ac8f, 0xada6c9b5), - RAPIDJSON_UINT64_C2(0xea9c2277, 0x23ee8bcb), RAPIDJSON_UINT64_C2(0xaecc4991, 0x4078536d), - RAPIDJSON_UINT64_C2(0x823c1279, 0x5db6ce57), RAPIDJSON_UINT64_C2(0xc2109436, 0x4dfb5637), - RAPIDJSON_UINT64_C2(0x9096ea6f, 0x3848984f), RAPIDJSON_UINT64_C2(0xd77485cb, 0x25823ac7), - RAPIDJSON_UINT64_C2(0xa086cfcd, 0x97bf97f4), RAPIDJSON_UINT64_C2(0xef340a98, 0x172aace5), - RAPIDJSON_UINT64_C2(0xb23867fb, 0x2a35b28e), RAPIDJSON_UINT64_C2(0x84c8d4df, 0xd2c63f3b), - RAPIDJSON_UINT64_C2(0xc5dd4427, 0x1ad3cdba), RAPIDJSON_UINT64_C2(0x936b9fce, 0xbb25c996), - RAPIDJSON_UINT64_C2(0xdbac6c24, 0x7d62a584), RAPIDJSON_UINT64_C2(0xa3ab6658, 0x0d5fdaf6), - RAPIDJSON_UINT64_C2(0xf3e2f893, 0xdec3f126), RAPIDJSON_UINT64_C2(0xb5b5ada8, 0xaaff80b8), - RAPIDJSON_UINT64_C2(0x87625f05, 0x6c7c4a8b), RAPIDJSON_UINT64_C2(0xc9bcff60, 0x34c13053), - RAPIDJSON_UINT64_C2(0x964e858c, 0x91ba2655), RAPIDJSON_UINT64_C2(0xdff97724, 0x70297ebd), - RAPIDJSON_UINT64_C2(0xa6dfbd9f, 0xb8e5b88f), RAPIDJSON_UINT64_C2(0xf8a95fcf, 0x88747d94), - RAPIDJSON_UINT64_C2(0xb9447093, 0x8fa89bcf), RAPIDJSON_UINT64_C2(0x8a08f0f8, 0xbf0f156b), - RAPIDJSON_UINT64_C2(0xcdb02555, 0x653131b6), RAPIDJSON_UINT64_C2(0x993fe2c6, 0xd07b7fac), - RAPIDJSON_UINT64_C2(0xe45c10c4, 0x2a2b3b06), RAPIDJSON_UINT64_C2(0xaa242499, 0x697392d3), - RAPIDJSON_UINT64_C2(0xfd87b5f2, 0x8300ca0e), RAPIDJSON_UINT64_C2(0xbce50864, 0x92111aeb), - RAPIDJSON_UINT64_C2(0x8cbccc09, 0x6f5088cc), RAPIDJSON_UINT64_C2(0xd1b71758, 0xe219652c), - RAPIDJSON_UINT64_C2(0x9c400000, 0x00000000), RAPIDJSON_UINT64_C2(0xe8d4a510, 0x00000000), - RAPIDJSON_UINT64_C2(0xad78ebc5, 0xac620000), RAPIDJSON_UINT64_C2(0x813f3978, 0xf8940984), - RAPIDJSON_UINT64_C2(0xc097ce7b, 0xc90715b3), RAPIDJSON_UINT64_C2(0x8f7e32ce, 0x7bea5c70), - RAPIDJSON_UINT64_C2(0xd5d238a4, 0xabe98068), RAPIDJSON_UINT64_C2(0x9f4f2726, 0x179a2245), - RAPIDJSON_UINT64_C2(0xed63a231, 0xd4c4fb27), RAPIDJSON_UINT64_C2(0xb0de6538, 0x8cc8ada8), - RAPIDJSON_UINT64_C2(0x83c7088e, 0x1aab65db), RAPIDJSON_UINT64_C2(0xc45d1df9, 0x42711d9a), - RAPIDJSON_UINT64_C2(0x924d692c, 0xa61be758), RAPIDJSON_UINT64_C2(0xda01ee64, 0x1a708dea), - RAPIDJSON_UINT64_C2(0xa26da399, 0x9aef774a), RAPIDJSON_UINT64_C2(0xf209787b, 0xb47d6b85), - RAPIDJSON_UINT64_C2(0xb454e4a1, 0x79dd1877), RAPIDJSON_UINT64_C2(0x865b8692, 0x5b9bc5c2), - RAPIDJSON_UINT64_C2(0xc83553c5, 0xc8965d3d), RAPIDJSON_UINT64_C2(0x952ab45c, 0xfa97a0b3), - RAPIDJSON_UINT64_C2(0xde469fbd, 0x99a05fe3), RAPIDJSON_UINT64_C2(0xa59bc234, 0xdb398c25), - RAPIDJSON_UINT64_C2(0xf6c69a72, 0xa3989f5c), RAPIDJSON_UINT64_C2(0xb7dcbf53, 0x54e9bece), - RAPIDJSON_UINT64_C2(0x88fcf317, 0xf22241e2), RAPIDJSON_UINT64_C2(0xcc20ce9b, 0xd35c78a5), - RAPIDJSON_UINT64_C2(0x98165af3, 0x7b2153df), RAPIDJSON_UINT64_C2(0xe2a0b5dc, 0x971f303a), - RAPIDJSON_UINT64_C2(0xa8d9d153, 0x5ce3b396), RAPIDJSON_UINT64_C2(0xfb9b7cd9, 0xa4a7443c), - RAPIDJSON_UINT64_C2(0xbb764c4c, 0xa7a44410), RAPIDJSON_UINT64_C2(0x8bab8eef, 0xb6409c1a), - RAPIDJSON_UINT64_C2(0xd01fef10, 0xa657842c), RAPIDJSON_UINT64_C2(0x9b10a4e5, 0xe9913129), - RAPIDJSON_UINT64_C2(0xe7109bfb, 0xa19c0c9d), RAPIDJSON_UINT64_C2(0xac2820d9, 0x623bf429), - RAPIDJSON_UINT64_C2(0x80444b5e, 0x7aa7cf85), RAPIDJSON_UINT64_C2(0xbf21e440, 0x03acdd2d), - RAPIDJSON_UINT64_C2(0x8e679c2f, 0x5e44ff8f), RAPIDJSON_UINT64_C2(0xd433179d, 0x9c8cb841), - RAPIDJSON_UINT64_C2(0x9e19db92, 0xb4e31ba9), RAPIDJSON_UINT64_C2(0xeb96bf6e, 0xbadf77d9), - RAPIDJSON_UINT64_C2(0xaf87023b, 0x9bf0ee6b) - }; + RAPIDJSON_UINT64_C2(0xfa8fd5a0, 0x081c0288), RAPIDJSON_UINT64_C2(0xbaaee17f, 0xa23ebf76), RAPIDJSON_UINT64_C2(0x8b16fb20, 0x3055ac76), RAPIDJSON_UINT64_C2(0xcf42894a, 0x5dce35ea), RAPIDJSON_UINT64_C2(0x9a6bb0aa, 0x55653b2d), RAPIDJSON_UINT64_C2(0xe61acf03, 0x3d1a45df), RAPIDJSON_UINT64_C2(0xab70fe17, 0xc79ac6ca), RAPIDJSON_UINT64_C2(0xff77b1fc, 0xbebcdc4f), RAPIDJSON_UINT64_C2(0xbe5691ef, 0x416bd60c), RAPIDJSON_UINT64_C2(0x8dd01fad, 0x907ffc3c), RAPIDJSON_UINT64_C2(0xd3515c28, 0x31559a83), RAPIDJSON_UINT64_C2(0x9d71ac8f, 0xada6c9b5), RAPIDJSON_UINT64_C2(0xea9c2277, 0x23ee8bcb), RAPIDJSON_UINT64_C2(0xaecc4991, 0x4078536d), RAPIDJSON_UINT64_C2(0x823c1279, 0x5db6ce57), RAPIDJSON_UINT64_C2(0xc2109436, 0x4dfb5637), RAPIDJSON_UINT64_C2(0x9096ea6f, 0x3848984f), RAPIDJSON_UINT64_C2(0xd77485cb, 0x25823ac7), RAPIDJSON_UINT64_C2(0xa086cfcd, 0x97bf97f4), RAPIDJSON_UINT64_C2(0xef340a98, 0x172aace5), RAPIDJSON_UINT64_C2(0xb23867fb, 0x2a35b28e), RAPIDJSON_UINT64_C2(0x84c8d4df, 0xd2c63f3b), RAPIDJSON_UINT64_C2(0xc5dd4427, 0x1ad3cdba), RAPIDJSON_UINT64_C2(0x936b9fce, 0xbb25c996), RAPIDJSON_UINT64_C2(0xdbac6c24, 0x7d62a584), RAPIDJSON_UINT64_C2(0xa3ab6658, 0x0d5fdaf6), RAPIDJSON_UINT64_C2(0xf3e2f893, 0xdec3f126), RAPIDJSON_UINT64_C2(0xb5b5ada8, 0xaaff80b8), RAPIDJSON_UINT64_C2(0x87625f05, 0x6c7c4a8b), RAPIDJSON_UINT64_C2(0xc9bcff60, 0x34c13053), RAPIDJSON_UINT64_C2(0x964e858c, 0x91ba2655), RAPIDJSON_UINT64_C2(0xdff97724, 0x70297ebd), RAPIDJSON_UINT64_C2(0xa6dfbd9f, 0xb8e5b88f), RAPIDJSON_UINT64_C2(0xf8a95fcf, 0x88747d94), RAPIDJSON_UINT64_C2(0xb9447093, 0x8fa89bcf), RAPIDJSON_UINT64_C2(0x8a08f0f8, 0xbf0f156b), RAPIDJSON_UINT64_C2(0xcdb02555, 0x653131b6), RAPIDJSON_UINT64_C2(0x993fe2c6, 0xd07b7fac), RAPIDJSON_UINT64_C2(0xe45c10c4, 0x2a2b3b06), RAPIDJSON_UINT64_C2(0xaa242499, 0x697392d3), RAPIDJSON_UINT64_C2(0xfd87b5f2, 0x8300ca0e), RAPIDJSON_UINT64_C2(0xbce50864, 0x92111aeb), RAPIDJSON_UINT64_C2(0x8cbccc09, 0x6f5088cc), RAPIDJSON_UINT64_C2(0xd1b71758, 0xe219652c), RAPIDJSON_UINT64_C2(0x9c400000, 0x00000000), RAPIDJSON_UINT64_C2(0xe8d4a510, 0x00000000), RAPIDJSON_UINT64_C2(0xad78ebc5, 0xac620000), RAPIDJSON_UINT64_C2(0x813f3978, 0xf8940984), RAPIDJSON_UINT64_C2(0xc097ce7b, 0xc90715b3), RAPIDJSON_UINT64_C2(0x8f7e32ce, 0x7bea5c70), RAPIDJSON_UINT64_C2(0xd5d238a4, 0xabe98068), RAPIDJSON_UINT64_C2(0x9f4f2726, 0x179a2245), RAPIDJSON_UINT64_C2(0xed63a231, 0xd4c4fb27), RAPIDJSON_UINT64_C2(0xb0de6538, 0x8cc8ada8), RAPIDJSON_UINT64_C2(0x83c7088e, 0x1aab65db), RAPIDJSON_UINT64_C2(0xc45d1df9, 0x42711d9a), RAPIDJSON_UINT64_C2(0x924d692c, 0xa61be758), RAPIDJSON_UINT64_C2(0xda01ee64, 0x1a708dea), RAPIDJSON_UINT64_C2(0xa26da399, 0x9aef774a), RAPIDJSON_UINT64_C2(0xf209787b, 0xb47d6b85), RAPIDJSON_UINT64_C2(0xb454e4a1, 0x79dd1877), RAPIDJSON_UINT64_C2(0x865b8692, 0x5b9bc5c2), RAPIDJSON_UINT64_C2(0xc83553c5, 0xc8965d3d), RAPIDJSON_UINT64_C2(0x952ab45c, 0xfa97a0b3), RAPIDJSON_UINT64_C2(0xde469fbd, 0x99a05fe3), RAPIDJSON_UINT64_C2(0xa59bc234, 0xdb398c25), RAPIDJSON_UINT64_C2(0xf6c69a72, 0xa3989f5c), RAPIDJSON_UINT64_C2(0xb7dcbf53, 0x54e9bece), RAPIDJSON_UINT64_C2(0x88fcf317, 0xf22241e2), RAPIDJSON_UINT64_C2(0xcc20ce9b, 0xd35c78a5), RAPIDJSON_UINT64_C2(0x98165af3, 0x7b2153df), RAPIDJSON_UINT64_C2(0xe2a0b5dc, 0x971f303a), RAPIDJSON_UINT64_C2(0xa8d9d153, 0x5ce3b396), RAPIDJSON_UINT64_C2(0xfb9b7cd9, 0xa4a7443c), RAPIDJSON_UINT64_C2(0xbb764c4c, 0xa7a44410), RAPIDJSON_UINT64_C2(0x8bab8eef, 0xb6409c1a), RAPIDJSON_UINT64_C2(0xd01fef10, 0xa657842c), RAPIDJSON_UINT64_C2(0x9b10a4e5, 0xe9913129), RAPIDJSON_UINT64_C2(0xe7109bfb, 0xa19c0c9d), RAPIDJSON_UINT64_C2(0xac2820d9, 0x623bf429), RAPIDJSON_UINT64_C2(0x80444b5e, 0x7aa7cf85), RAPIDJSON_UINT64_C2(0xbf21e440, 0x03acdd2d), RAPIDJSON_UINT64_C2(0x8e679c2f, 0x5e44ff8f), RAPIDJSON_UINT64_C2(0xd433179d, 0x9c8cb841), RAPIDJSON_UINT64_C2(0x9e19db92, 0xb4e31ba9), RAPIDJSON_UINT64_C2(0xeb96bf6e, 0xbadf77d9), RAPIDJSON_UINT64_C2(0xaf87023b, 0x9bf0ee6b)}; static const int16_t kCachedPowers_E[] = { - -1220, -1193, -1166, -1140, -1113, -1087, -1060, -1034, -1007, -980, - -954, -927, -901, -874, -847, -821, -794, -768, -741, -715, - -688, -661, -635, -608, -582, -555, -529, -502, -475, -449, - -422, -396, -369, -343, -316, -289, -263, -236, -210, -183, - -157, -130, -103, -77, -50, -24, 3, 30, 56, 83, - 109, 136, 162, 189, 216, 242, 269, 295, 322, 348, - 375, 402, 428, 455, 481, 508, 534, 561, 588, 614, - 641, 667, 694, 720, 747, 774, 800, 827, 853, 880, - 907, 933, 960, 986, 1013, 1039, 1066 - }; + -1220, -1193, -1166, -1140, -1113, -1087, -1060, -1034, -1007, -980, -954, -927, -901, -874, -847, -821, -794, -768, -741, -715, -688, -661, -635, -608, -582, -555, -529, -502, -475, -449, -422, -396, -369, -343, -316, -289, -263, -236, -210, -183, -157, -130, -103, -77, -50, -24, 3, 30, 56, 83, 109, 136, 162, 189, 216, 242, 269, 295, 322, 348, 375, 402, 428, 455, 481, 508, 534, 561, 588, 614, 641, 667, 694, 720, 747, 774, 800, 827, 853, 880, 907, 933, 960, 986, 1013, 1039, 1066}; assert(index < 87); return DiyFp(kCachedPowers_F[index], kCachedPowers_E[index]); } -inline DiyFp GetCachedPower(int e, int* K) { - +inline DiyFp GetCachedPower(int e, int* K) +{ //int k = static_cast(ceil((-61 - e) * 0.30102999566398114)) + 374; - double dk = (-61 - e) * 0.30102999566398114 + 347; // dk must be positive, so can do ceiling in positive + double dk = (-61 - e) * 0.30102999566398114 + 347; // dk must be positive, so can do ceiling in positive int k = static_cast(dk); if (dk - k > 0.0) k++; unsigned index = static_cast((k >> 3) + 1); - *K = -(-348 + static_cast(index << 3)); // decimal exponent no need lookup table + *K = -(-348 + static_cast(index << 3)); // decimal exponent no need lookup table return GetCachedPowerByIndex(index); } -inline DiyFp GetCachedPower10(int exp, int *outExp) { +inline DiyFp GetCachedPower10(int exp, int* outExp) +{ assert(exp >= -348); unsigned index = static_cast(exp + 348) / 8u; *outExp = -348 + static_cast(index) * 8; diff --git a/inc/finalmq/helpers/CondVar.h b/inc/finalmq/helpers/CondVar.h index ede7ec1e..5e33a68c 100644 --- a/inc/finalmq/helpers/CondVar.h +++ b/inc/finalmq/helpers/CondVar.h @@ -23,15 +23,14 @@ #pragma once #include -#include "finalmq/helpers/FmqDefines.h" - -namespace finalmq { +#include "finalmq/helpers/FmqDefines.h" +namespace finalmq +{ class SYMBOLEXP CondVar { public: - /** * Enumeration for the two CSignal modes. */ @@ -75,7 +74,7 @@ class SYMBOLEXP CondVar * Example: CondVar condVar = true; //condVar is true * @param val the value to set the CondVar */ - void operator =(bool val); + const CondVar& operator=(bool val); /** * The conversion operator bool allows read access to the CondVar value. @@ -95,10 +94,10 @@ class SYMBOLEXP CondVar CondVar(const CondVar& obj) = delete; const CondVar& operator=(const CondVar& obj) = delete; - mutable std::condition_variable m_condvar; - mutable bool m_value = false; - const CondVarMode m_mode = CondVarMode::CONDVAR_MANUALRESET; - mutable std::mutex m_mutex; + mutable std::condition_variable m_condvar{}; + mutable bool m_value = false; + const CondVarMode m_mode = CondVarMode::CONDVAR_MANUALRESET; + mutable std::mutex m_mutex{}; }; } // namespace finalmq diff --git a/inc/finalmq/helpers/Executor.h b/inc/finalmq/helpers/Executor.h index 33ac37a6..222036f3 100644 --- a/inc/finalmq/helpers/Executor.h +++ b/inc/finalmq/helpers/Executor.h @@ -22,25 +22,22 @@ #pragma once -#include "finalmq/helpers/CondVar.h" -#include "finalmq/helpers/IExecutor.h" - -#include -#include -#include #include +#include +#include #include #include #include +#include +#include "finalmq/helpers/CondVar.h" +#include "finalmq/helpers/IExecutor.h" -namespace finalmq { - - +namespace finalmq +{ class SYMBOLEXP ExecutorBase : public IExecutor { public: - private: virtual void registerActionNotification(std::function func) override; virtual void run() override; @@ -48,19 +45,15 @@ class SYMBOLEXP ExecutorBase : public IExecutor virtual bool isTerminating() const override; protected: - std::atomic m_terminate; - CondVar m_newActions; - std::function m_funcNotify; - std::mutex m_mutex; + std::atomic m_terminate{}; + CondVar m_newActions{}; + std::function m_funcNotify{}; + std::mutex m_mutex{}; }; - - - class SYMBOLEXP Executor : public ExecutorBase { public: - private: virtual bool runAvailableActions(const FuncIsAbort& funcIsAbort = nullptr) override; virtual bool runAvailableActionBatch(const FuncIsAbort& funcIsAbort = nullptr) override; @@ -69,7 +62,6 @@ class SYMBOLEXP Executor : public ExecutorBase inline bool areRunnableActionsAvailable() const; private: - struct ActionEntry { ActionEntry(std::int64_t i, std::unique_ptr>&& f) @@ -77,33 +69,28 @@ class SYMBOLEXP Executor : public ExecutorBase { funcs.emplace_back(std::move(f)); } - std::int64_t instanceId; - std::deque>> funcs; + std::int64_t instanceId{}; + std::deque>> funcs{}; }; - std::list m_actions; + std::list m_actions{}; - std::unordered_map m_storedIds; - std::unordered_set m_runningIds; - int m_zeroIdCounter = 0; + std::unordered_map m_storedIds{}; + std::unordered_set m_runningIds{}; + int m_zeroIdCounter = 0; }; - - class SYMBOLEXP ExecutorIgnoreOrderOfInstance : public ExecutorBase { public: - private: virtual bool runAvailableActions(const FuncIsAbort& funcIsAbort = nullptr) override; virtual bool runAvailableActionBatch(const FuncIsAbort& funcIsAbort = nullptr) override; virtual void addAction(std::function func, std::int64_t instanceId = 0) override; private: - std::deque> m_actions; + std::deque> m_actions{}; }; - - class SYMBOLEXP ExecutorWorkerBase : public IExecutorWorker { public: @@ -118,14 +105,12 @@ class SYMBOLEXP ExecutorWorkerBase : public IExecutorWorker private: ExecutorWorkerBase(const ExecutorWorkerBase&) = delete; - const ExecutorWorkerBase& operator =(const ExecutorWorkerBase&) = delete; + const ExecutorWorkerBase& operator=(const ExecutorWorkerBase&) = delete; - std::shared_ptr m_executor; - std::vector m_threads; + std::shared_ptr m_executor{}; + std::vector m_threads{}; }; - - template class ExecutorWorker : public ExecutorWorkerBase { @@ -136,8 +121,6 @@ class ExecutorWorker : public ExecutorWorkerBase } }; - - class SYMBOLEXP GlobalExecutorWorker { public: @@ -168,6 +151,4 @@ class SYMBOLEXP GlobalExecutorWorker static std::unique_ptr& getStaticUniquePtrRef(); }; - - } // namespace finalmq diff --git a/inc/finalmq/helpers/FmqDefines.h b/inc/finalmq/helpers/FmqDefines.h index a72e252e..f2dcb164 100644 --- a/inc/finalmq/helpers/FmqDefines.h +++ b/inc/finalmq/helpers/FmqDefines.h @@ -22,34 +22,30 @@ #pragma once -#include #include - - +#include #if defined(WIN32) -#define DLL_IMPORT __declspec(dllimport) -#define DLL_EXPORT __declspec(dllexport) -#pragma warning(disable: 4251) -#pragma warning(disable: 4275) +#define DLL_IMPORT __declspec(dllimport) +#define DLL_EXPORT __declspec(dllexport) +#pragma warning(disable : 4251) +#pragma warning(disable : 4275) -#else +#else -#define DLL_IMPORT -#define DLL_EXPORT __attribute__ ((visibility("default"))) +#define DLL_IMPORT +#define DLL_EXPORT __attribute__((visibility("default"))) #endif - #undef SYMBOLEXP #ifdef EXPORT_finalmq -#define SYMBOLEXP DLL_EXPORT -#else -#define SYMBOLEXP DLL_IMPORT +#define SYMBOLEXP DLL_EXPORT +#else +#define SYMBOLEXP DLL_IMPORT #endif - #if defined(WIN32) || defined(__MINGW32__) #include using ssize_t = std::int64_t; @@ -59,9 +55,10 @@ using ssize_t = std::int64_t; #else #include using SOCKET = int; -namespace finalmq { - static const SOCKET INVALID_SOCKET = -1; -} // namespace finalmq +namespace finalmq +{ +static const SOCKET INVALID_SOCKET = -1; +} // namespace finalmq #endif #ifdef __QNX__ @@ -71,219 +68,221 @@ namespace finalmq { constexpr ssize_t CHECK_ON_ZEROTERM = -1; - -#define TOKENPASTE(x, y) x ## y +#define TOKENPASTE(x, y) x##y #define TOKENPASTE2(x, y) TOKENPASTE(x, y) #ifdef _MSC_VER - // Assuming windows is always little-endian. +// Assuming windows is always little-endian. #define FINALMQ_LITTLE_ENDIAN 1 #if _MSC_VER >= 1300 && !defined(__INTEL_COMPILER) - // If MSVC has "/RTCc" set, it will complain about truncating casts at - // runtime. This file contains some intentional truncating casts. +// If MSVC has "/RTCc" set, it will complain about truncating casts at +// runtime. This file contains some intentional truncating casts. #pragma runtime_checks("c", off) #endif #else -#include // __BYTE_ORDER -#if ((defined(__LITTLE_ENDIAN__) && !defined(__BIG_ENDIAN__)) || \ - (defined(__BYTE_ORDER) && __BYTE_ORDER == __LITTLE_ENDIAN)) +#include // __BYTE_ORDER +#if ((defined(__LITTLE_ENDIAN__) && !defined(__BIG_ENDIAN__)) || (defined(__BYTE_ORDER) && __BYTE_ORDER == __LITTLE_ENDIAN)) #define FINALMQ_LITTLE_ENDIAN 1 #endif -#ifdef __QNX__ // todo: recognize byte order for QNX +#ifdef __QNX__ // todo: recognize byte order for QNX #define FINALMQ_LITTLE_ENDIAN 1 #endif #endif +namespace finalmq +{ +template +struct EndianHelper; -namespace finalmq { - - template - struct EndianHelper; - - template <> - struct EndianHelper<1> +template<> +struct EndianHelper<1> +{ + template + static void read(const char* p, T& value) { - template - static void read(const char* p, T& value) { value = *reinterpret_cast(p); } + value = *reinterpret_cast(p); + } - template - static void write(char* p, T value) { *static_cast(p) = value; } - }; + template + static void write(char* p, T value) + { + *static_cast(p) = value; + } +}; - template <> - struct EndianHelper<2> +template<> +struct EndianHelper<2> +{ + template + static void read(const char* p, T& value) { - template - static void read(const char* p, T& value) - { #ifdef FINALMQ_LITTLE_ENDIAN - std::memcpy(&value, p, sizeof(T)); + std::memcpy(&value, p, sizeof(T)); #else - std::uint16_t v; - std::memcpy(&v, p, sizeof(T)); - v = bswap_16(v); - value = *reinterpret_cast(&v); + std::uint16_t v; + std::memcpy(&v, p, sizeof(T)); + v = bswap_16(v); + value = *reinterpret_cast(&v); #endif - } + } - template - static void write(char* p, T value) - { + template + static void write(char* p, T value) + { #ifdef FINALMQ_LITTLE_ENDIAN - std::memcpy(p, &value, sizeof(T)); + std::memcpy(p, &value, sizeof(T)); #else - std::uint16_t v = *reinterpret_cast(&value); - v = bswap_16(value); - std::memcpy(p, &v, sizeof(T)); + std::uint16_t v = *reinterpret_cast(&value); + v = bswap_16(value); + std::memcpy(p, &v, sizeof(T)); #endif - } - }; + } +}; - template <> - struct EndianHelper<4> { - template - static void read(const char* p, T& value) - { +template<> +struct EndianHelper<4> +{ + template + static void read(const char* p, T& value) + { #ifdef FINALMQ_LITTLE_ENDIAN - std::memcpy(&value, p, sizeof(T)); + std::memcpy(&value, p, sizeof(T)); #else - std::uint32_t v; - std::memcpy(&v, p, sizeof(T)); - v = bswap_32(v); - value = *reinterpret_cast(&v); + std::uint32_t v; + std::memcpy(&v, p, sizeof(T)); + v = bswap_32(v); + value = *reinterpret_cast(&v); #endif - } + } - template - static void write(char* p, T value) - { + template + static void write(char* p, T value) + { #ifdef FINALMQ_LITTLE_ENDIAN - std::memcpy(p, &value, sizeof(T)); + std::memcpy(p, &value, sizeof(T)); #else - std::uint32_t v = *reinterpret_cast(&value); - v = bswap_32(value); - std::memcpy(p, &v, sizeof(T)); + std::uint32_t v = *reinterpret_cast(&value); + v = bswap_32(value); + std::memcpy(p, &v, sizeof(T)); #endif - } - }; + } +}; - template <> - struct EndianHelper<8> { - template - static void read(const char* p, T& value) - { +template<> +struct EndianHelper<8> +{ + template + static void read(const char* p, T& value) + { #ifdef FINALMQ_LITTLE_ENDIAN - std::memcpy(&value, p, sizeof(T)); + std::memcpy(&value, p, sizeof(T)); #else - std::uint64_t v; - std::memcpy(&v, p, sizeof(T)); - v = bswap_64(v); - value = *reinterpret_cast(&v); + std::uint64_t v; + std::memcpy(&v, p, sizeof(T)); + v = bswap_64(v); + value = *reinterpret_cast(&v); #endif - } + } - template - static void write(char* p, T value) - { + template + static void write(char* p, T value) + { #ifdef FINALMQ_LITTLE_ENDIAN - std::memcpy(p, &value, sizeof(T)); + std::memcpy(p, &value, sizeof(T)); #else - std::uint64_t v = *reinterpret_cast(&value); - v = bswap_64(value); - std::memcpy(p, &v, sizeof(T)); + std::uint64_t v = *reinterpret_cast(&value); + v = bswap_64(value); + std::memcpy(p, &v, sizeof(T)); #endif - } - }; - - - + } +}; - // constants - const unsigned int LEAD_OFFSET = static_cast(0xD800 - (0x10000 >> 10)); - const unsigned int SURROGATE_OFFSET = static_cast(0x10000 - (0xD800 << 10) - 0xDC00); +// constants +const unsigned int LEAD_OFFSET = static_cast(0xD800 - (0x10000 >> 10)); +const unsigned int SURROGATE_OFFSET = static_cast(0x10000 - (0xD800 << 10) - 0xDC00); - // first 16bit in the lower word, second 16bit in higher word. - static inline unsigned int utf32to16(unsigned int utf32) +// first 16bit in the lower word, second 16bit in higher word. +static inline unsigned int utf32to16(unsigned int utf32) +{ + if (utf32 > 0x0000ffff) { - if (utf32 > 0x0000ffff) - { - unsigned int lead = LEAD_OFFSET + (utf32 >> 10); - unsigned int trail = 0xDC00 + (utf32 & 0x3FF); - return (trail << 16) + lead; - } - else - { - return utf32; - } + unsigned int lead = LEAD_OFFSET + (utf32 >> 10); + unsigned int trail = 0xDC00 + (utf32 & 0x3FF); + return (trail << 16) + lead; } + else + { + return utf32; + } +} - // first 16bit in the lower word, second 16bit in higher word. - static inline unsigned int utf16to32(unsigned int utf16) +// first 16bit in the lower word, second 16bit in higher word. +static inline unsigned int utf16to32(unsigned int utf16) +{ + unsigned int trail = utf16 >> 16; + if (trail != 0) + { + unsigned int lead = utf16 & 0x0000ffff; + return (lead << 10) + trail + SURROGATE_OFFSET; + } + else + { + return utf16; + } +} +static inline unsigned int utf32to8(unsigned int utf32) +{ + if (utf32 <= 0x7f) + { + return utf32; + } + else if ((utf32 > 0x7f) && (utf32 <= 0x07ff)) + { + unsigned int lead = (utf32 >> 6) | 0xc0; + unsigned int trail = (utf32 & 0x3f) | 0x80; + return (trail << 8) + lead; + } + else if ((utf32 > 0x07ff) && (utf32 <= 0xffff)) + { + unsigned int lead = (utf32 >> 12) | 0xe0; + unsigned int trail1 = ((utf32 >> 6) & 0x3f) | 0x80; + unsigned int trail2 = (utf32 & 0x3f) | 0x80; + return (trail2 << 16) + (trail1 << 8) + lead; + } + else + { + unsigned int lead = (utf32 >> 18) | 0xf0; + unsigned int trail1 = ((utf32 >> 6) & 0x3f) | 0x80; + unsigned int trail2 = ((utf32 >> 12) & 0x3f) | 0x80; + unsigned int trail3 = (utf32 & 0x3f) | 0x80; + return (trail3 << 24) + (trail2 << 16) + (trail1 << 8) + lead; + } +} +static inline unsigned int utf8to32(unsigned int utf8) +{ + unsigned char c = utf8 & 0x000000ff; + if (c <= 0x7f) + { + return c; + } + else if ((c >= 0xc0) && (c <= 0xdf)) { - unsigned int trail = utf16 >> 16; - if (trail != 0) - { - unsigned int lead = utf16 & 0x0000ffff; - return (lead << 10) + trail + SURROGATE_OFFSET; - } - else - { - return utf16; - } + unsigned char c2 = (utf8 >> 8) & 0x000000ff; + return (((c & 0x1f) << 6) | (c2 & 0x3f)); } - static inline unsigned int utf32to8(unsigned int utf32) + else if ((c >= 0xe0) && (c <= 0xef)) { - if (utf32 <= 0x7f) - { - return utf32; - } - else if ((utf32 > 0x7f) && (utf32 <= 0x07ff)) - { - unsigned int lead = (utf32 >> 6) | 0xc0; - unsigned int trail = (utf32 & 0x3f) | 0x80; - return (trail << 8) + lead; - } - else if ((utf32 > 0x07ff) && (utf32 <= 0xffff)) - { - unsigned int lead = (utf32 >> 12) | 0xe0; - unsigned int trail1 = ((utf32 >> 6) & 0x3f) | 0x80; - unsigned int trail2 = (utf32 & 0x3f) | 0x80; - return (trail2 << 16) + (trail1 << 8) + lead; - } - else - { - unsigned int lead = (utf32 >> 18) | 0xf0; - unsigned int trail1 = ((utf32 >> 6) & 0x3f) | 0x80; - unsigned int trail2 = ((utf32 >> 12) & 0x3f) | 0x80; - unsigned int trail3 = (utf32 & 0x3f) | 0x80; - return (trail3 << 24) + (trail2 << 16) + (trail1 << 8) + lead; - } + unsigned char c2 = (utf8 >> 8) & 0x000000ff; + unsigned char c3 = (utf8 >> 16) & 0x000000ff; + return (((c & 0x0f) << 12) | ((c2 & 0x3f) << 6) | (c3 & 0x3f)); } - static inline unsigned int utf8to32(unsigned int utf8) + else { - unsigned char c = utf8 & 0x000000ff; - if (c <= 0x7f) - { - return c; - } - else if ((c >= 0xc0) && (c <= 0xdf)) - { - unsigned char c2 = (utf8 >> 8) & 0x000000ff; - return (((c & 0x1f) << 6) | (c2 & 0x3f)); - } - else if ((c >= 0xe0) && (c <= 0xef)) - { - unsigned char c2 = (utf8 >> 8) & 0x000000ff; - unsigned char c3 = (utf8 >> 16) & 0x000000ff; - return (((c & 0x0f) << 12) | ((c2 & 0x3f) << 6) | (c3 & 0x3f)); - } - else - { - unsigned char c2 = (utf8 >> 8) & 0x000000ff; - unsigned char c3 = (utf8 >> 16) & 0x000000ff; - unsigned char c4 = (utf8 >> 24) & 0x000000ff; - return (((c & 0x07) << 18) | ((c2 & 0x3f) << 12) | ((c3 & 0x3f) << 6) | (c4 & 0x3f)); - } + unsigned char c2 = static_cast((utf8 >> 8) & 0x000000ff); + unsigned char c3 = static_cast((utf8 >> 16) & 0x000000ff); + unsigned char c4 = static_cast((utf8 >> 24) & 0x000000ff); + return (((c & 0x07) << 18) | ((c2 & 0x3f) << 12) | ((c3 & 0x3f) << 6) | (c4 & 0x3f)); } +} -} // namespace finalmq +} // namespace finalmq diff --git a/inc/finalmq/helpers/OperatingSystem.h b/inc/finalmq/helpers/OperatingSystem.h index 6ed8da9c..a926d480 100644 --- a/inc/finalmq/helpers/OperatingSystem.h +++ b/inc/finalmq/helpers/OperatingSystem.h @@ -59,79 +59,76 @@ typedef sockaddr t_sockaddr; #include "finalmq/helpers/FmqDefines.h" #include "finalmq/helpers/IOperatingSystem.h" - -namespace finalmq { - - class SYMBOLEXP OperatingSystemImpl : public IOperatingSystem - { - public: - OperatingSystemImpl(); - - private: - // IOperatingSystem - virtual int open(const char* filename, int flags) override; - virtual int stat(const char* filename, struct stat* buf) override; - virtual int fstat(int fd, struct ::stat* buf) override; - virtual int close(int fd) override; - virtual int closeSocket(SOCKET fd) override; - virtual SOCKET socket(int af, int type, int protocol) override; - virtual int bind(SOCKET fd, const struct sockaddr* name, socklen_t namelen) override; - virtual SOCKET accept(SOCKET fd, struct sockaddr* addr, socklen_t* addrlen) override; - virtual int listen(SOCKET fd, int backlog) override; - virtual int connect(SOCKET fd, const struct sockaddr* name, socklen_t namelen) override; - virtual int setsockopt(SOCKET fd, int level, int optname, const char* optval, int optlen) override; - virtual int getsockname(SOCKET fd, struct sockaddr* name, socklen_t* namelen) override; - virtual int write(int fd, const char* buffer, int len) override; - virtual int read(int fd, char* buffer, int len) override; - virtual int send(SOCKET fd, const char* buffer, int len, int flags) override; - virtual int recv(SOCKET fd, char* buffer, int len, int flags) override; - virtual int getLastError() override; - virtual int select(int nfds, fd_set* readfds, fd_set* writefds, fd_set* exceptfds, struct timeval* timeout) override; +namespace finalmq +{ +class SYMBOLEXP OperatingSystemImpl : public IOperatingSystem +{ +public: + OperatingSystemImpl(); + +private: + // IOperatingSystem + virtual int open(const char* filename, int flags) override; + virtual int stat(const char* filename, struct stat* buf) override; + virtual int fstat(int fd, struct ::stat* buf) override; + virtual int close(int fd) override; + virtual int closeSocket(SOCKET fd) override; + virtual SOCKET socket(int af, int type, int protocol) override; + virtual int bind(SOCKET fd, const struct sockaddr* name, socklen_t namelen) override; + virtual SOCKET accept(SOCKET fd, struct sockaddr* addr, socklen_t* addrlen) override; + virtual int listen(SOCKET fd, int backlog) override; + virtual int connect(SOCKET fd, const struct sockaddr* name, socklen_t namelen) override; + virtual int setsockopt(SOCKET fd, int level, int optname, const char* optval, int optlen) override; + virtual int getsockname(SOCKET fd, struct sockaddr* name, socklen_t* namelen) override; + virtual int write(int fd, const char* buffer, int len) override; + virtual int read(int fd, char* buffer, int len) override; + virtual int send(SOCKET fd, const char* buffer, int len, int flags) override; + virtual int recv(SOCKET fd, char* buffer, int len, int flags) override; + virtual int getLastError() override; + virtual int select(int nfds, fd_set* readfds, fd_set* writefds, fd_set* exceptfds, struct timeval* timeout) override; #if !defined(WIN32) && !defined(__MINGW32__) && !defined(__QNX__) - virtual int epoll_create1(int flags) override; - virtual int epoll_ctl(int epfd, int op, int fd, struct epoll_event* event) override; - virtual int epoll_pwait(int epfd, struct epoll_event* events, int maxevents, int timeout, const sigset_t* sigmask) override; + virtual int epoll_create1(int flags) override; + virtual int epoll_ctl(int epfd, int op, int fd, struct epoll_event* event) override; + virtual int epoll_pwait(int epfd, struct epoll_event* events, int maxevents, int timeout, const sigset_t* sigmask) override; #endif - virtual int makeSocketPair(SocketDescriptorPtr& socket1, SocketDescriptorPtr& socket2) override; - virtual int ioctlInt(SOCKET fd, unsigned long int request, int* value) override; - virtual int setNoDelay(SOCKET fd, bool noDelay) override; - virtual int setNonBlocking(SOCKET fd, bool nonBlock) override; - virtual int setLinger(SOCKET fd, bool on, int timeToLinger) override; - - OperatingSystemImpl(const OperatingSystemImpl&) = delete; - const OperatingSystemImpl& operator =(const OperatingSystemImpl&) = delete; - - }; - - - class SYMBOLEXP OperatingSystem + virtual int makeSocketPair(SocketDescriptorPtr& socket1, SocketDescriptorPtr& socket2) override; + virtual int ioctlInt(SOCKET fd, unsigned long int request, int* value) override; + virtual int setNoDelay(SOCKET fd, bool noDelay) override; + virtual int setNonBlocking(SOCKET fd, bool nonBlock) override; + virtual int setLinger(SOCKET fd, bool on, int timeToLinger) override; + + OperatingSystemImpl(const OperatingSystemImpl&) = delete; + const OperatingSystemImpl& operator=(const OperatingSystemImpl&) = delete; +}; + +class SYMBOLEXP OperatingSystem +{ +public: + inline static IOperatingSystem& instance() { - public: - inline static IOperatingSystem& instance() + static auto& instanceRef = getStaticInstanceRef(); + auto* inst = instanceRef.load(std::memory_order_acquire); + if (!inst) { - static auto& instanceRef = getStaticInstanceRef(); - auto* inst = instanceRef.load(std::memory_order_acquire); - if (!inst) - { - inst = createInstance(); - } - return *inst; + inst = createInstance(); } + return *inst; + } - /** + /** * Overwrite the default implementation, e.g. with a mock for testing purposes. * This method is not thread-safe. Make sure that no one uses the current instance before * calling this method. */ - static void setInstance(std::unique_ptr&& instance); + static void setInstance(std::unique_ptr&& instance); - private: - OperatingSystem() = delete; - ~OperatingSystem() = delete; - static IOperatingSystem* createInstance(); +private: + OperatingSystem() = delete; + ~OperatingSystem() = delete; + static IOperatingSystem* createInstance(); - static std::atomic& getStaticInstanceRef(); - static std::unique_ptr& getStaticUniquePtrRef(); - }; + static std::atomic& getStaticInstanceRef(); + static std::unique_ptr& getStaticUniquePtrRef(); +}; -} // namespace finalmq +} // namespace finalmq diff --git a/inc/finalmq/helpers/PollingTimer.h b/inc/finalmq/helpers/PollingTimer.h index 239290b2..d7943d1d 100644 --- a/inc/finalmq/helpers/PollingTimer.h +++ b/inc/finalmq/helpers/PollingTimer.h @@ -22,11 +22,11 @@ #pragma once +#include #include -namespace finalmq { - - +namespace finalmq +{ class PollingTimer { public: @@ -69,5 +69,4 @@ class PollingTimer std::atomic m_timeExpired{-1}; }; - } // namespace finalmq diff --git a/inc/finalmq/helpers/ZeroCopyBuffer.h b/inc/finalmq/helpers/ZeroCopyBuffer.h index 065f4eee..57d69061 100644 --- a/inc/finalmq/helpers/ZeroCopyBuffer.h +++ b/inc/finalmq/helpers/ZeroCopyBuffer.h @@ -22,14 +22,13 @@ #pragma once -#include "IZeroCopyBuffer.h" - #include #include -namespace finalmq { - +#include "IZeroCopyBuffer.h" +namespace finalmq +{ class SYMBOLEXP ZeroCopyBuffer : public IZeroCopyBuffer { public: @@ -41,9 +40,7 @@ class SYMBOLEXP ZeroCopyBuffer : public IZeroCopyBuffer virtual void downsizeLastBuffer(ssize_t newSize) override; virtual ssize_t getRemainingSize() const override; - std::list m_chunks; + std::list m_chunks{}; }; - -} // namespace finalmq - +} // namespace finalmq diff --git a/inc/finalmq/helpers/hybrid_ptr.h b/inc/finalmq/helpers/hybrid_ptr.h index cb2df943..d3c523f8 100644 --- a/inc/finalmq/helpers/hybrid_ptr.h +++ b/inc/finalmq/helpers/hybrid_ptr.h @@ -23,13 +23,12 @@ #pragma once #include -#include +#include namespace finalmq { - -template +template class transient_ptr { public: @@ -44,25 +43,25 @@ class transient_ptr m_shared = nullptr; } - T* operator ->() + T* operator->() { assert(m_raw); return m_raw; } - const T* operator ->() const + const T* operator->() const { assert(m_raw); return m_raw; } - T& operator *() + T& operator*() { assert(m_raw); return *m_raw; } - const T& operator *() const + const T& operator*() const { assert(m_raw); return *m_raw; @@ -73,10 +72,44 @@ class transient_ptr return (m_raw != nullptr); } + transient_ptr(const transient_ptr& rhs) + : m_shared(rhs.m_shared), m_raw(rhs.shared ? rhs.shared.get() : rhs.m_raw) + { + } + transient_ptr(transient_ptr&& rhs) + : m_shared(rhs.m_shared), m_raw(m_shared ? m_shared.get() : rhs.m_raw) + { + } + const transient_ptr& operator=(const transient_ptr& rhs) + { + m_shared = rhs.m_shared; + if (m_shared) + { + m_raw = m_shared.get(); + } + else + { + m_raw = rhs.m_raw; + } + return *this; + } + const transient_ptr& operator=(transient_ptr&& rhs) + { + m_shared = rhs.m_shared; + if (m_shared) + { + m_raw = m_shared.get(); + } + else + { + m_raw = rhs.m_raw; + } + return *this; + } + private: explicit transient_ptr(const std::shared_ptr& shared) - : m_shared(shared) - , m_raw(shared.get()) + : m_shared(shared), m_raw(shared.get()) { } @@ -85,15 +118,14 @@ class transient_ptr { } - std::shared_ptr m_shared; - T* m_raw = nullptr; + std::shared_ptr m_shared{}; + T* m_raw = nullptr; - template friend class hybrid_ptr; + template + friend class hybrid_ptr; }; - - -template +template class hybrid_ptr { private: @@ -111,35 +143,58 @@ class hybrid_ptr { } + hybrid_ptr(const hybrid_ptr& rhs) + : m_mode(rhs.m_mode), m_shared(rhs.m_shared), m_weak(rhs.m_weak), m_raw(rhs.m_raw) + { + } + + hybrid_ptr(hybrid_ptr&& rhs) + : m_mode(rhs.m_mode), m_shared(rhs.m_shared), m_weak(rhs.m_weak), m_raw(rhs.m_raw) + { + } + + const hybrid_ptr& operator=(const hybrid_ptr& rhs) + { + m_mode = rhs.m_mode; + m_shared = rhs.m_shared; + m_weak = rhs.m_weak; + m_raw = rhs.m_raw; + return *this; + } + + const hybrid_ptr& operator=(hybrid_ptr&& rhs) + { + m_mode = rhs.m_mode; + m_shared = rhs.m_shared; + m_weak = rhs.m_weak; + m_raw = rhs.m_raw; + return *this; + } + hybrid_ptr(const std::shared_ptr& shared) - : m_mode(Mode::MODE_SHARED) - , m_shared(shared) + : m_mode(Mode::MODE_SHARED), m_shared(shared) { } hybrid_ptr(const std::weak_ptr& weak) - : m_mode(Mode::MODE_WEAK) - , m_weak(weak) + : m_mode(Mode::MODE_WEAK), m_weak(weak) { } hybrid_ptr(T* raw) - : m_mode(Mode::MODE_RAW) - , m_raw(raw) + : m_mode(Mode::MODE_RAW), m_raw(raw) { } - template + template hybrid_ptr(const std::shared_ptr& shared) - : m_mode(Mode::MODE_SHARED) - , m_shared(shared) + : m_mode(Mode::MODE_SHARED), m_shared(shared) { } - template + template hybrid_ptr(const std::weak_ptr& weak) - : m_mode(Mode::MODE_WEAK) - , m_weak(weak) + : m_mode(Mode::MODE_WEAK), m_weak(weak) { } @@ -153,30 +208,29 @@ class hybrid_ptr transient_ptr lock() const { - switch (m_mode) + switch(m_mode) { - case Mode::MODE_SHARED: - return transient_ptr(m_shared); - break; - case Mode::MODE_WEAK: - return transient_ptr(m_weak.lock()); - break; - case Mode::MODE_RAW: - return transient_ptr(m_raw); - break; - default: - return transient_ptr(nullptr); - break; + case Mode::MODE_SHARED: + return transient_ptr(m_shared); + break; + case Mode::MODE_WEAK: + return transient_ptr(m_weak.lock()); + break; + case Mode::MODE_RAW: + return transient_ptr(m_raw); + break; + default: + return transient_ptr(nullptr); + break; } return transient_ptr(nullptr); } private: - Mode m_mode; - std::shared_ptr m_shared; - std::weak_ptr m_weak; - T* m_raw = nullptr; + Mode m_mode{}; + std::shared_ptr m_shared{}; + std::weak_ptr m_weak{}; + T* m_raw{nullptr}; }; - -} // namespace bex +} // namespace finalmq diff --git a/inc/finalmq/hl7/Hl7Builder.h b/inc/finalmq/hl7/Hl7Builder.h index ae79626d..e8592412 100644 --- a/inc/finalmq/hl7/Hl7Builder.h +++ b/inc/finalmq/hl7/Hl7Builder.h @@ -22,16 +22,17 @@ #pragma once -#include "finalmq/helpers/IZeroCopyBuffer.h" #include #include -namespace finalmq { - +#include "finalmq/helpers/IZeroCopyBuffer.h" +namespace finalmq +{ struct IHl7BuilderVisitor { - virtual ~IHl7BuilderVisitor() {} + virtual ~IHl7BuilderVisitor() + {} virtual void enterNull(const int* levelIndex, int sizeLevelIndex, int index) = 0; virtual void enterInt64(const int* levelIndex, int sizeLevelIndex, int index, std::int64_t value) = 0; virtual void enterUInt64(const int* levelIndex, int sizeLevelIndex, int index, std::uint64_t value) = 0; @@ -42,10 +43,8 @@ struct IHl7BuilderVisitor virtual void finished() = 0; }; - class Hl7Node; - class SYMBOLEXP Hl7Builder : public IHl7BuilderVisitor { public: @@ -53,6 +52,11 @@ class SYMBOLEXP Hl7Builder : public IHl7BuilderVisitor ~Hl7Builder(); private: + Hl7Builder(const Hl7Builder&) = delete; + Hl7Builder(Hl7Builder&&) = delete; + const Hl7Builder& operator=(const Hl7Builder&) = delete; + const Hl7Builder& operator=(Hl7Builder&&) = delete; + // IHl7BuilderVisitor virtual void enterNull(const int* levelIndex, int sizeLevelIndex, int index) override; virtual void enterInt64(const int* levelIndex, int sizeLevelIndex, int index, std::int64_t value) override; @@ -68,20 +72,20 @@ class SYMBOLEXP Hl7Builder : public IHl7BuilderVisitor void escapeString(const char* str, ssize_t size); void serialize(const Hl7Node& node, int index, int iStart); - IZeroCopyBuffer& m_zeroCopybuffer; - ssize_t m_maxBlockSize = 512; - char* m_bufferStart = nullptr; - char* m_buffer = nullptr; - char* m_bufferEnd = nullptr; + IZeroCopyBuffer& m_zeroCopybuffer; + ssize_t m_maxBlockSize{512}; + char* m_bufferStart{nullptr}; + char* m_buffer{nullptr}; + char* m_bufferEnd{nullptr}; - static const int LAYER_MAX = 5; // array index is on index = 2 + static const int LAYER_MAX = 5; // array index is on index = 2 - std::string m_delimitersForField; - char m_delimiterField[LAYER_MAX]; - char m_delimiterRepeat; - char m_escape; + std::string m_delimitersForField{}; + char m_delimiterField[LAYER_MAX]{}; + char m_delimiterRepeat{}; + char m_escape{}; - std::unique_ptr m_root; + std::unique_ptr m_root{}; }; -} // namespace finalmq +} // namespace finalmq diff --git a/inc/finalmq/hl7/Hl7Parser.h b/inc/finalmq/hl7/Hl7Parser.h index 58962e70..2a200cda 100644 --- a/inc/finalmq/hl7/Hl7Parser.h +++ b/inc/finalmq/hl7/Hl7Parser.h @@ -22,18 +22,18 @@ #pragma once -#include "finalmq/helpers/FmqDefines.h" - #include #include #include -namespace finalmq { - +#include "finalmq/helpers/FmqDefines.h" +namespace finalmq +{ struct IHl7Parser { - virtual ~IHl7Parser() {} + virtual ~IHl7Parser() + {} virtual bool startParse(const char* str, ssize_t size = CHECK_ON_ZEROTERM) = 0; virtual int parseToken(int level, std::string& token, bool& isarray) = 0; virtual int parseTokenArray(int level, std::vector& array) = 0; @@ -43,7 +43,6 @@ struct IHl7Parser virtual const char* getCurrentPosition() const = 0; }; - class SYMBOLEXP Hl7Parser : public IHl7Parser { public: @@ -58,6 +57,11 @@ class SYMBOLEXP Hl7Parser : public IHl7Parser virtual const char* getCurrentPosition() const override; private: + Hl7Parser(const Hl7Parser&) = delete; + Hl7Parser(Hl7Parser&&) = delete; + const Hl7Parser& operator=(const Hl7Parser&) = delete; + const Hl7Parser& operator=(Hl7Parser&&) = delete; + inline char getChar(const char* str) const; void skipControlCharacters(); int isDelimiter(char c) const; @@ -69,11 +73,11 @@ class SYMBOLEXP Hl7Parser : public IHl7Parser static const int LAYER_MAX = 4; - char m_delimiterField[LAYER_MAX] = {0, 0, 0, 0}; - char m_delimiterRepeat = 0; - char m_escape = 0; + char m_delimiterField[LAYER_MAX] = {0, 0, 0, 0}; + char m_delimiterRepeat = 0; + char m_escape = 0; - int m_waitForDeleimiterField = 0; + int m_waitForDeleimiterField = 0; }; -} // namespace finalmq +} // namespace finalmq diff --git a/inc/finalmq/json/JsonBuilder.h b/inc/finalmq/json/JsonBuilder.h index 71b2b82a..af11c18e 100644 --- a/inc/finalmq/json/JsonBuilder.h +++ b/inc/finalmq/json/JsonBuilder.h @@ -22,11 +22,11 @@ #pragma once -#include "finalmq/json/JsonParser.h" #include "finalmq/helpers/IZeroCopyBuffer.h" +#include "finalmq/json/JsonParser.h" -namespace finalmq { - +namespace finalmq +{ class SYMBOLEXP JsonBuilder : public IJsonParserVisitor { public: @@ -34,6 +34,11 @@ class SYMBOLEXP JsonBuilder : public IJsonParserVisitor ~JsonBuilder(); private: + JsonBuilder(const JsonBuilder&) = delete; + JsonBuilder(JsonBuilder&&) = delete; + const JsonBuilder& operator=(const JsonBuilder&) = delete; + const JsonBuilder& operator=(JsonBuilder&&) = delete; + // IJsonParserVisitor virtual void syntaxError(const char* str, const char* message) override; virtual void enterNull() override; @@ -58,11 +63,11 @@ class SYMBOLEXP JsonBuilder : public IJsonParserVisitor void correctComma(); void escapeString(const char* str, ssize_t size); - IZeroCopyBuffer& m_zeroCopybuffer; - ssize_t m_maxBlockSize = 512; - char* m_bufferStart = nullptr; - char* m_buffer = nullptr; - char* m_bufferEnd = nullptr; + IZeroCopyBuffer& m_zeroCopybuffer; + ssize_t m_maxBlockSize = 512; + char* m_bufferStart = nullptr; + char* m_buffer = nullptr; + char* m_bufferEnd = nullptr; }; -} // namespace finalmq +} // namespace finalmq diff --git a/inc/finalmq/logger/Logger.h b/inc/finalmq/logger/Logger.h index 70d1ca8d..092525ed 100644 --- a/inc/finalmq/logger/Logger.h +++ b/inc/finalmq/logger/Logger.h @@ -22,53 +22,46 @@ #pragma once -#include "finalmq/helpers/FmqDefines.h" - -#include -#include #include #include +#include +#include #include +#include "finalmq/helpers/FmqDefines.h" -namespace finalmq { - - - +namespace finalmq +{ enum LogLevel { - LOG_NONE = 0, - LOG_DEBUG = 1, - LOG_INFO = 2, - LOG_WARNING = 3, - LOG_ERROR = 4, - LOG_CRITICAL = 5, - LOG_FATAL = 6, + LOG_NONE = 0, + LOG_DEBUG = 1, + LOG_INFO = 2, + LOG_WARNING = 3, + LOG_ERROR = 4, + LOG_CRITICAL = 5, + LOG_FATAL = 6, }; - struct LogContext { - LogLevel level = LOG_NONE; + LogLevel level = LOG_NONE; const char* module = nullptr; const char* method = nullptr; const char* filename = nullptr; - int line = -1; + int line = -1; }; - typedef std::function FuncLogEvent; - struct ILogger { - virtual ~ILogger() {} + virtual ~ILogger() + {} virtual void registerConsumer(FuncLogEvent consumer) = 0; virtual void triggerLog(const LogContext& context, const char* text) = 0; }; - - /** * @brief The LoggerImpl class implements a central point of collecting log data * of the whole application. @@ -86,12 +79,11 @@ class SYMBOLEXP LoggerImpl : public ILogger virtual void registerConsumer(FuncLogEvent consumer) override; virtual void triggerLog(const LogContext& context, const char* text) override; - std::deque m_consumers; - std::atomic_int m_sizeConsumers{}; - std::mutex m_mutex; + std::deque m_consumers{}; + std::atomic_int m_sizeConsumers{}; + std::mutex m_mutex{}; }; - class SYMBOLEXP Logger { public: @@ -122,6 +114,4 @@ class SYMBOLEXP Logger static std::unique_ptr& getStaticUniquePtrRef(); }; - } // namespace finalmq - diff --git a/inc/finalmq/metadata/MetaData.h b/inc/finalmq/metadata/MetaData.h index 1a1f5288..26e1aed7 100644 --- a/inc/finalmq/metadata/MetaData.h +++ b/inc/finalmq/metadata/MetaData.h @@ -22,21 +22,19 @@ #pragma once -#include "finalmq/metadata/MetaStruct.h" -#include "finalmq/metadata/MetaEnum.h" - -#include +#include #include #include -#include - - -namespace finalmq { +#include "finalmq/metadata/MetaEnum.h" +#include "finalmq/metadata/MetaStruct.h" +namespace finalmq +{ struct IMetaData { - virtual ~IMetaData() {} + virtual ~IMetaData() + {} virtual const MetaStruct* getStruct(const std::string& typeName) const = 0; virtual const MetaEnum* getEnum(const std::string& typeName) const = 0; virtual const MetaStruct* getStruct(const MetaField& field) const = 0; @@ -56,11 +54,9 @@ struct IMetaData virtual const std::unordered_map getAllEnums() const = 0; }; - class SYMBOLEXP MetaData : public IMetaData { public: - private: // IMetaData virtual const MetaStruct* getStruct(const std::string& typeName) const override; @@ -81,12 +77,11 @@ class SYMBOLEXP MetaData : public IMetaData virtual const std::unordered_map getAllStructs() const override; virtual const std::unordered_map getAllEnums() const override; - std::unordered_map m_name2Struct; - std::unordered_map m_name2Enum; - mutable std::mutex m_mutex; + std::unordered_map m_name2Struct{}; + std::unordered_map m_name2Enum{}; + mutable std::mutex m_mutex{}; }; - class SYMBOLEXP MetaDataGlobal { public: @@ -117,4 +112,4 @@ class SYMBOLEXP MetaDataGlobal static std::unique_ptr& getStaticUniquePtrRef(); }; -} // namespace finalmq +} // namespace finalmq diff --git a/inc/finalmq/metadata/MetaEnum.h b/inc/finalmq/metadata/MetaEnum.h index 3e486232..b15d6daa 100644 --- a/inc/finalmq/metadata/MetaEnum.h +++ b/inc/finalmq/metadata/MetaEnum.h @@ -22,27 +22,24 @@ #pragma once -#include "finalmq/helpers/FmqDefines.h" - -#include -#include #include +#include #include +#include -namespace finalmq { - +#include "finalmq/helpers/FmqDefines.h" +namespace finalmq +{ struct MetaEnumEntry { public: - std::string name; - int id = 0; - std::string description; - std::string alias; + std::string name{}; + int id{0}; + std::string description{}; + std::string alias{}; }; - - class SYMBOLEXP MetaEnum { public: @@ -84,15 +81,15 @@ class SYMBOLEXP MetaEnum private: static std::unordered_map generateProperties(const std::vector& attrs); - - std::string m_typeName; - std::string m_description; - std::vector> m_entries; - const std::vector m_attrs; - const std::unordered_map m_properties; - std::unordered_map> m_id2Entry; - std::unordered_map> m_name2Entry; - std::unordered_map> m_alias2Entry; + + std::string m_typeName{}; + std::string m_description{}; + std::vector> m_entries{}; + const std::vector m_attrs{}; + const std::unordered_map m_properties{}; + std::unordered_map> m_id2Entry{}; + std::unordered_map> m_name2Entry{}; + std::unordered_map> m_alias2Entry{}; }; -} // namespace finalmq +} // namespace finalmq diff --git a/inc/finalmq/metadata/MetaStruct.h b/inc/finalmq/metadata/MetaStruct.h index 3f4a5865..aa450a7e 100644 --- a/inc/finalmq/metadata/MetaStruct.h +++ b/inc/finalmq/metadata/MetaStruct.h @@ -22,18 +22,16 @@ #pragma once -#include "MetaField.h" -#include "finalmq/helpers/FmqDefines.h" - -#include #include -#include #include +#include +#include +#include "MetaField.h" +#include "finalmq/helpers/FmqDefines.h" -namespace finalmq { - - +namespace finalmq +{ enum MetaStructFlags : std::int32_t { METASTRUCTFLAG_NONE = 0, @@ -41,7 +39,6 @@ enum MetaStructFlags : std::int32_t METASTRUCTFLAG_CHOICE = 2, }; - class SYMBOLEXP MetaStruct { public: @@ -77,15 +74,15 @@ class SYMBOLEXP MetaStruct private: static std::unordered_map generateProperties(const std::vector& attrs); - - const std::string m_typeName; - const std::string m_typeNameWithoutNamespace; - const std::string m_description; - std::vector> m_fields; - const int m_flags; - const std::vector m_attrs; - const std::unordered_map m_properties; - std::unordered_map> m_name2Field; + + const std::string m_typeName{}; + const std::string m_typeNameWithoutNamespace{}; + const std::string m_description{}; + std::vector> m_fields{}; + const int m_flags{}; + const std::vector m_attrs{}; + const std::unordered_map m_properties{}; + std::unordered_map> m_name2Field{}; }; -} // namespace finalmq +} // namespace finalmq diff --git a/inc/finalmq/poller/Poller.h b/inc/finalmq/poller/Poller.h index 94a6599d..459ba1e6 100644 --- a/inc/finalmq/poller/Poller.h +++ b/inc/finalmq/poller/Poller.h @@ -22,14 +22,14 @@ #pragma once - -#include "finalmq/helpers/SocketDescriptor.h" #include -#include +#include -namespace finalmq { +#include "finalmq/helpers/SocketDescriptor.h" +namespace finalmq +{ struct DescriptorInfo { void clear() @@ -47,7 +47,6 @@ struct DescriptorInfo std::int32_t bytesToRead = 0; }; - class DescriptorInfos { public: @@ -74,7 +73,7 @@ class DescriptorInfos return m_size; } - const DescriptorInfo& operator [](ssize_t ix) const + const DescriptorInfo& operator[](ssize_t ix) const { assert(ix < m_size); assert(ix < static_cast(m_descriptorInfos.size())); @@ -82,12 +81,10 @@ class DescriptorInfos } private: - ssize_t m_size = 0; - std::vector m_descriptorInfos; + ssize_t m_size{0}; + std::vector m_descriptorInfos{}; }; - - struct PollerResult { bool error = false; @@ -108,11 +105,10 @@ struct PollerResult PollerResult(PollerResult&) = delete; }; - - struct IPoller { - virtual ~IPoller() {} + virtual ~IPoller() + {} virtual void init() = 0; virtual void addSocket(const SocketDescriptorPtr& fd) = 0; virtual void addSocketEnableRead(const SocketDescriptorPtr& fd) = 0; @@ -127,4 +123,4 @@ struct IPoller typedef std::shared_ptr IPollerPtr; -} // namespace finalmq +} // namespace finalmq diff --git a/inc/finalmq/poller/PollerImplEpoll.h b/inc/finalmq/poller/PollerImplEpoll.h index 3ce421f3..3c5c8ba3 100644 --- a/inc/finalmq/poller/PollerImplEpoll.h +++ b/inc/finalmq/poller/PollerImplEpoll.h @@ -24,18 +24,17 @@ #if !defined(WIN32) && !defined(__MINGW32__) && !defined(__QNX__) -#include "Poller.h" -#include #include #include #include - +#include #include -namespace finalmq { - +#include "Poller.h" +namespace finalmq +{ class SYMBOLEXP PollerImplEpoll : public IPoller { public: @@ -44,9 +43,9 @@ class SYMBOLEXP PollerImplEpoll : public IPoller private: PollerImplEpoll(const PollerImplEpoll&) = delete; - const PollerImplEpoll& operator =(const PollerImplEpoll&) = delete; + const PollerImplEpoll& operator=(const PollerImplEpoll&) = delete; PollerImplEpoll(const PollerImplEpoll&&) = delete; - const PollerImplEpoll& operator =(PollerImplEpoll&&) = delete; + const PollerImplEpoll& operator=(PollerImplEpoll&&) = delete; virtual void init() override; virtual void addSocket(const SocketDescriptorPtr& fd) override; @@ -65,24 +64,22 @@ class SYMBOLEXP PollerImplEpoll : public IPoller void collectSockets(int res); void releaseWaitInternal(char info); - SocketDescriptorPtr m_controlSocketRead; - SocketDescriptorPtr m_controlSocketWrite; + SocketDescriptorPtr m_controlSocketRead{}; + SocketDescriptorPtr m_controlSocketWrite{}; - std::unordered_map m_socketDescriptors; + std::unordered_map m_socketDescriptors{}; - PollerResult m_result; - int m_fdEpoll = -1; - std::atomic_flag m_socketDescriptorsStable{}; + PollerResult m_result{}; + int m_fdEpoll{-1}; + std::atomic_flag m_socketDescriptorsStable{ATOMIC_FLAG_INIT}; std::atomic_uint32_t m_releaseFlags{}; - std::array m_events; + std::array m_events{}; + std::vector m_socketDescriptorsConstForEpoll{}; - std::vector m_socketDescriptorsConstForEpoll; - - std::mutex m_mutex; + std::mutex m_mutex{}; }; -} // namespace finalmq - +} // namespace finalmq #endif diff --git a/inc/finalmq/poller/PollerImplSelect.h b/inc/finalmq/poller/PollerImplSelect.h index 744dd595..d73a6164 100644 --- a/inc/finalmq/poller/PollerImplSelect.h +++ b/inc/finalmq/poller/PollerImplSelect.h @@ -22,18 +22,18 @@ #pragma once -#include "Poller.h" -#include #include #include +#include + +#include "Poller.h" #ifdef __QNX__ #include #endif - -namespace finalmq { - +namespace finalmq +{ class SYMBOLEXP PollerImplSelect : public IPoller { public: @@ -41,9 +41,9 @@ class SYMBOLEXP PollerImplSelect : public IPoller private: PollerImplSelect(const PollerImplSelect&) = delete; - const PollerImplSelect& operator =(const PollerImplSelect&) = delete; + const PollerImplSelect& operator=(const PollerImplSelect&) = delete; PollerImplSelect(const PollerImplSelect&&) = delete; - const PollerImplSelect& operator =(PollerImplSelect&&) = delete; + const PollerImplSelect& operator=(PollerImplSelect&&) = delete; virtual void init() override; virtual void addSocket(const SocketDescriptorPtr& fd) override; @@ -70,13 +70,12 @@ class SYMBOLEXP PollerImplSelect : public IPoller void collectSockets(int res); + SocketDescriptorPtr m_controlSocketRead{}; + SocketDescriptorPtr m_controlSocketWrite{}; - SocketDescriptorPtr m_controlSocketRead; - SocketDescriptorPtr m_controlSocketWrite; - - std::unordered_set m_socketDescriptors; + std::unordered_set m_socketDescriptors{}; - PollerResult m_result; + PollerResult m_result{}; fd_set m_readfdsCached{}; fd_set m_writefdsCached{}; fd_set m_errorfdsCached{}; @@ -93,9 +92,9 @@ class SYMBOLEXP PollerImplSelect : public IPoller // parameters that are const during select and collect. int m_sdMax = 0; - std::vector m_socketDescriptorsConstForSelect; + std::vector m_socketDescriptorsConstForSelect{}; - std::mutex m_mutex; + std::mutex m_mutex{}; }; -} // namespace finalmq +} // namespace finalmq diff --git a/inc/finalmq/protocols/ProtocolHeaderBinarySize.h b/inc/finalmq/protocols/ProtocolHeaderBinarySize.h index 1b320b69..a4e9585a 100644 --- a/inc/finalmq/protocols/ProtocolHeaderBinarySize.h +++ b/inc/finalmq/protocols/ProtocolHeaderBinarySize.h @@ -22,19 +22,16 @@ #pragma once -#include "finalmq/streamconnection/IMessage.h" -#include "finalmq/protocolsession/IProtocol.h" #include "finalmq/protocols/protocolhelpers/ProtocolFixHeaderHelper.h" +#include "finalmq/protocolsession/IProtocol.h" +#include "finalmq/streamconnection/IMessage.h" - - -namespace finalmq { - - +namespace finalmq +{ class SYMBOLEXP ProtocolHeaderBinarySize : public IProtocol { public: - static const std::uint32_t PROTOCOL_ID; // 2 + static const std::uint32_t PROTOCOL_ID; // 2 static const std::string PROTOCOL_NAME; // headersize ProtocolHeaderBinarySize(); @@ -67,20 +64,18 @@ class SYMBOLEXP ProtocolHeaderBinarySize : public IProtocol virtual IProtocolSessionDataPtr createProtocolSessionData() override; virtual void setProtocolSessionData(const IProtocolSessionDataPtr& protocolSessionData) override; - std::weak_ptr m_callback; - IStreamConnectionPtr m_connection; - ProtocolFixHeaderHelper m_headerHelper; - mutable std::mutex m_mutex; + std::weak_ptr m_callback{}; + IStreamConnectionPtr m_connection{}; + ProtocolFixHeaderHelper m_headerHelper; + mutable std::mutex m_mutex{}; }; - class SYMBOLEXP ProtocolHeaderBinarySizeFactory : public IProtocolFactory { public: - private: // IProtocolFactory virtual IProtocolPtr createProtocol(const Variant& data) override; }; -} // namespace finalmq +} // namespace finalmq diff --git a/inc/finalmq/protocols/ProtocolHttpClient.h b/inc/finalmq/protocols/ProtocolHttpClient.h index c9c5d671..91324311 100644 --- a/inc/finalmq/protocols/ProtocolHttpClient.h +++ b/inc/finalmq/protocols/ProtocolHttpClient.h @@ -22,16 +22,15 @@ #pragma once -#include "finalmq/streamconnection/IMessage.h" -#include "finalmq/protocolsession/IProtocol.h" -#include "finalmq/helpers/FmqDefines.h" -#include "finalmq/helpers/Executor.h" - #include +#include "finalmq/helpers/Executor.h" +#include "finalmq/helpers/FmqDefines.h" +#include "finalmq/protocolsession/IProtocol.h" +#include "finalmq/streamconnection/IMessage.h" -namespace finalmq { - +namespace finalmq +{ class Cookie; class CookieStore : public IProtocolSessionData @@ -45,17 +44,22 @@ class CookieStore : public IProtocolSessionData std::vector> getCookiesIntern(const std::string& host, const std::string& path); std::shared_ptr& getCookieInternExactPath(const std::string& host, const std::string& path); - std::list> m_cookies; - mutable std::mutex m_mutex; + std::list> m_cookies{}; + mutable std::mutex m_mutex{}; }; typedef std::shared_ptr CookieStorePtr; - -class SYMBOLEXP ProtocolHttpClient : public IProtocol - , public std::enable_shared_from_this +#ifndef WIN32 +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wnon-virtual-dtor" +#endif +class SYMBOLEXP ProtocolHttpClient : public IProtocol, public std::enable_shared_from_this { +#ifndef WIN32 +#pragma GCC diagnostic pop +#endif public: - static const std::uint32_t PROTOCOL_ID; // 7 + static const std::uint32_t PROTOCOL_ID; // 7 static const std::string PROTOCOL_NAME; // httpclient static const std::string FMQ_HTTP; @@ -72,7 +76,6 @@ class SYMBOLEXP ProtocolHttpClient : public IProtocol virtual ~ProtocolHttpClient(); private: - // IProtocol virtual void setCallback(const std::weak_ptr& callback) override; virtual void setConnection(const IStreamConnectionPtr& connection) override; @@ -99,10 +102,9 @@ class SYMBOLEXP ProtocolHttpClient : public IProtocol virtual IProtocolSessionDataPtr createProtocolSessionData() override; virtual void setProtocolSessionData(const IProtocolSessionDataPtr& protocolSessionData) override; - bool receiveHeaders(ssize_t bytesReceived); void reset(); -// bool handleInternalCommands(const std::shared_ptr& callback, bool& ok); + // bool handleInternalCommands(const std::shared_ptr& callback, bool& ok); enum class State { @@ -119,38 +121,36 @@ class SYMBOLEXP ProtocolHttpClient : public IProtocol SESSIONID_FMQ = 2 }; - std::random_device m_randomDevice; - std::mt19937 m_randomGenerator; - std::uniform_int_distribution m_randomVariable; - IMessage::Metainfo m_headerSendNext; - - State m_state = State::STATE_FIND_FIRST_LINE; - std::string m_receiveBuffer; - ssize_t m_offsetRemaining = 0; - ssize_t m_sizeRemaining = 0; - IMessagePtr m_message; - ssize_t m_contentLength = 0; - ssize_t m_indexFilled = 0; - std::string m_headerHost; - std::string m_hostname; - std::int64_t m_connectionId = 0; - std::weak_ptr m_callback; - IStreamConnectionPtr m_connection; - bool m_multipart = false; - - CookieStorePtr m_cookieStore; - - mutable std::mutex m_mutex; + std::random_device m_randomDevice{}; + std::mt19937 m_randomGenerator{}; + std::uniform_int_distribution m_randomVariable{}; + IMessage::Metainfo m_headerSendNext{}; + + State m_state = State::STATE_FIND_FIRST_LINE; + std::string m_receiveBuffer{}; + ssize_t m_offsetRemaining = 0; + ssize_t m_sizeRemaining = 0; + IMessagePtr m_message{}; + ssize_t m_contentLength = 0; + ssize_t m_indexFilled = 0; + std::string m_headerHost{}; + std::string m_hostname{}; + std::int64_t m_connectionId = 0; + std::weak_ptr m_callback{}; + IStreamConnectionPtr m_connection{}; + bool m_multipart = false; + + CookieStorePtr m_cookieStore{}; + + mutable std::mutex m_mutex{}; }; - class SYMBOLEXP ProtocolHttpClientFactory : public IProtocolFactory { public: - private: // IProtocolFactory virtual IProtocolPtr createProtocol(const Variant& data) override; }; -} // namespace finalmq +} // namespace finalmq diff --git a/inc/finalmq/protocols/ProtocolHttpServer.h b/inc/finalmq/protocols/ProtocolHttpServer.h index 4d0f3a6d..20667915 100644 --- a/inc/finalmq/protocols/ProtocolHttpServer.h +++ b/inc/finalmq/protocols/ProtocolHttpServer.h @@ -22,22 +22,26 @@ #pragma once -#include "finalmq/streamconnection/IMessage.h" -#include "finalmq/protocolsession/IProtocol.h" -#include "finalmq/helpers/FmqDefines.h" -#include "finalmq/helpers/Executor.h" - #include +#include "finalmq/helpers/Executor.h" +#include "finalmq/helpers/FmqDefines.h" +#include "finalmq/protocolsession/IProtocol.h" +#include "finalmq/streamconnection/IMessage.h" -namespace finalmq { - - -class SYMBOLEXP ProtocolHttpServer : public IProtocol - , public std::enable_shared_from_this +namespace finalmq +{ +#ifndef WIN32 +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wnon-virtual-dtor" +#endif +class SYMBOLEXP ProtocolHttpServer : public IProtocol, public std::enable_shared_from_this { +#ifndef WIN32 +#pragma GCC diagnostic pop +#endif public: - static const std::uint32_t PROTOCOL_ID; // 4 + static const std::uint32_t PROTOCOL_ID; // 4 static const std::string PROTOCOL_NAME; // httpserver static const std::string FMQ_HTTP; @@ -54,6 +58,10 @@ class SYMBOLEXP ProtocolHttpServer : public IProtocol virtual ~ProtocolHttpServer(); private: + ProtocolHttpServer(const ProtocolHttpServer&) = delete; + ProtocolHttpServer(ProtocolHttpServer&&) = delete; + const ProtocolHttpServer& operator=(const ProtocolHttpServer&) = delete; + const ProtocolHttpServer& operator=(ProtocolHttpServer&&) = delete; enum ChunkedState { @@ -90,7 +98,6 @@ class SYMBOLEXP ProtocolHttpServer : public IProtocol virtual IProtocolSessionDataPtr createProtocolSessionData() override; virtual void setProtocolSessionData(const IProtocolSessionDataPtr& protocolSessionData) override; - bool receiveHeaders(ssize_t bytesReceived); void reset(); std::string createSessionName(); @@ -113,44 +120,42 @@ class SYMBOLEXP ProtocolHttpServer : public IProtocol SESSIONID_FMQ = 2 }; - std::random_device m_randomDevice; - std::mt19937 m_randomGenerator; - std::uniform_int_distribution m_randomVariable; - IMessage::Metainfo m_headerSendNext; - StateSessionId m_stateSessionId = StateSessionId::SESSIONID_NONE; - std::vector m_sessionNames; - - State m_state = State::STATE_FIND_FIRST_LINE; - std::string m_receiveBuffer; - ssize_t m_offsetRemaining = 0; - ssize_t m_sizeRemaining = 0; - IMessagePtr m_message; - ssize_t m_contentLength = 0; - ssize_t m_indexFilled = 0; - std::string m_headerHost; - std::int64_t m_connectionId = 0; - bool m_createSession = false; - std::string m_sessionName; - std::weak_ptr m_callback; - IStreamConnectionPtr m_connection; - ChunkedState m_chunkedState = STATE_STOP; - bool m_multipart = false; + std::random_device m_randomDevice{}; + std::mt19937 m_randomGenerator{}; + std::uniform_int_distribution m_randomVariable{}; + IMessage::Metainfo m_headerSendNext{}; + StateSessionId m_stateSessionId = StateSessionId::SESSIONID_NONE; + std::vector m_sessionNames{}; + + State m_state = State::STATE_FIND_FIRST_LINE; + std::string m_receiveBuffer{}; + ssize_t m_offsetRemaining = 0; + ssize_t m_sizeRemaining = 0; + IMessagePtr m_message{}; + ssize_t m_contentLength = 0; + ssize_t m_indexFilled = 0; + std::string m_headerHost{}; + std::int64_t m_connectionId = 0; + bool m_createSession = false; + std::string m_sessionName{}; + std::weak_ptr m_callback{}; + IStreamConnectionPtr m_connection{}; + ChunkedState m_chunkedState = STATE_STOP; + bool m_multipart = false; // path - std::string* m_path = nullptr; + std::string* m_path = nullptr; - mutable std::mutex m_mutex; - static std::atomic_int64_t m_nextSessionNameCounter; + mutable std::mutex m_mutex{}; + static std::atomic_int64_t m_nextSessionNameCounter; }; - class SYMBOLEXP ProtocolHttpServerFactory : public IProtocolFactory { public: - private: // IProtocolFactory virtual IProtocolPtr createProtocol(const Variant& data) override; }; -} // namespace finalmq +} // namespace finalmq diff --git a/inc/finalmq/protocols/ProtocolMqtt5Client.h b/inc/finalmq/protocols/ProtocolMqtt5Client.h index 529bc1af..a5b9c804 100644 --- a/inc/finalmq/protocols/ProtocolMqtt5Client.h +++ b/inc/finalmq/protocols/ProtocolMqtt5Client.h @@ -22,28 +22,25 @@ #pragma once -#include "finalmq/protocolsession/IProtocol.h" -#include "finalmq/helpers/FmqDefines.h" -#include "finalmq/protocols/mqtt5/Mqtt5Client.h" - #include #include -namespace finalmq { - +#include "finalmq/helpers/FmqDefines.h" +#include "finalmq/protocols/mqtt5/Mqtt5Client.h" +#include "finalmq/protocolsession/IProtocol.h" -class SYMBOLEXP ProtocolMqtt5Client : public IProtocol - , public IMqtt5ClientCallback +namespace finalmq +{ +class SYMBOLEXP ProtocolMqtt5Client : public IProtocol, public IMqtt5ClientCallback { public: - static const std::string KEY_USERNAME; ///< the username for the broker - static const std::string KEY_PASSWORD; ///< the password for the broker - static const std::string KEY_SESSIONEXPIRYINTERVAL; ///< the mqtt session expiry interval in seconds - static const std::string KEY_KEEPALIVE; ///< the mqtt keep alive interval in seconds - - static const std::uint32_t PROTOCOL_ID; // 5 - static const std::string PROTOCOL_NAME; // mqtt5client + static const std::string KEY_USERNAME; ///< the username for the broker + static const std::string KEY_PASSWORD; ///< the password for the broker + static const std::string KEY_SESSIONEXPIRYINTERVAL; ///< the mqtt session expiry interval in seconds + static const std::string KEY_KEEPALIVE; ///< the mqtt keep alive interval in seconds + static const std::uint32_t PROTOCOL_ID; // 5 + static const std::string PROTOCOL_NAME; // mqtt5client ProtocolMqtt5Client(const Variant& data); ~ProtocolMqtt5Client(); @@ -96,35 +93,32 @@ class SYMBOLEXP ProtocolMqtt5Client : public IProtocol bool receiveHeader(const SocketPtr& socket, int& bytesToRead); bool receiveRemainingSize(const SocketPtr& socket, int& bytesToRead); void setPayloadSize(); - bool receivePayload(const SocketPtr& socket, int& bytesToRead); + bool receivePayload(const SocketPtr& socket, int& bytesToRead); bool processPayload(); void clearState(); - std::string m_username; - std::string m_password; - std::uint32_t m_sessionExpiryInterval = 5*60; // default 5 minutes - std::uint32_t m_keepAlive = 20; // default 20 seconds - std::string m_clientId; - std::string m_virtualSessionId; + std::string m_username{}; + std::string m_password{}; + std::uint32_t m_sessionExpiryInterval = 5 * 60; // default 5 minutes + std::uint32_t m_keepAlive = 20; // default 20 seconds + std::string m_clientId{}; + std::string m_virtualSessionId{}; - bool m_firstConnection = true; - PollingTimer m_timerReconnect; + bool m_firstConnection = true; + PollingTimer m_timerReconnect{}; - std::weak_ptr m_callback; - IStreamConnectionPtr m_connection; - std::unique_ptr m_client; - mutable std::mutex m_mutex; + std::weak_ptr m_callback{}; + IStreamConnectionPtr m_connection{}; + std::unique_ptr m_client{}; + mutable std::mutex m_mutex{}; }; - class SYMBOLEXP ProtocolMqtt5ClientFactory : public IProtocolFactory { public: - private: // IProtocolFactory virtual IProtocolPtr createProtocol(const Variant& data) override; }; - -} // namespace finalmq +} // namespace finalmq diff --git a/inc/finalmq/protocols/ProtocolStream.h b/inc/finalmq/protocols/ProtocolStream.h index c77f2e0d..21986eb3 100644 --- a/inc/finalmq/protocols/ProtocolStream.h +++ b/inc/finalmq/protocols/ProtocolStream.h @@ -22,13 +22,11 @@ #pragma once -#include "finalmq/streamconnection/IMessage.h" #include "finalmq/protocolsession/IProtocol.h" +#include "finalmq/streamconnection/IMessage.h" - -namespace finalmq { - - +namespace finalmq +{ class SYMBOLEXP ProtocolStream : public IProtocol { public: @@ -65,19 +63,17 @@ class SYMBOLEXP ProtocolStream : public IProtocol virtual IProtocolSessionDataPtr createProtocolSessionData() override; virtual void setProtocolSessionData(const IProtocolSessionDataPtr& protocolSessionData) override; - std::weak_ptr m_callback; - IStreamConnectionPtr m_connection; - mutable std::mutex m_mutex; + std::weak_ptr m_callback{}; + IStreamConnectionPtr m_connection{}; + mutable std::mutex m_mutex{}; }; - class SYMBOLEXP ProtocolStreamFactory : public IProtocolFactory { public: - private: // IProtocolFactory virtual IProtocolPtr createProtocol(const Variant& data) override; }; -} // namespace finalmq +} // namespace finalmq diff --git a/inc/finalmq/protocols/mqtt5/Mqtt5Client.h b/inc/finalmq/protocols/mqtt5/Mqtt5Client.h index 7438142d..48d55fd2 100644 --- a/inc/finalmq/protocols/mqtt5/Mqtt5Client.h +++ b/inc/finalmq/protocols/mqtt5/Mqtt5Client.h @@ -22,16 +22,14 @@ #pragma once -#include "finalmq/streamconnection/IMessage.h" -#include "finalmq/streamconnection/StreamConnection.h" +#include "finalmq/helpers/PollingTimer.h" #include "finalmq/metadata/MetaType.h" #include "finalmq/protocols/mqtt5/Mqtt5Protocol.h" -#include "finalmq/helpers/PollingTimer.h" - - -namespace finalmq { - +#include "finalmq/streamconnection/IMessage.h" +#include "finalmq/streamconnection/StreamConnection.h" +namespace finalmq +{ struct IMqtt5ClientCallback { virtual ~IMqtt5ClientCallback() = default; @@ -45,15 +43,15 @@ struct IMqtt5ClientCallback std::uint8_t maximumQoS = 2; bool retainAvailable = true; std::uint32_t maximumPacketSize = 268435455; - std::string assignedClientId; - std::string reasonString; + std::string assignedClientId{}; + std::string reasonString{}; bool wildcardSubscriptionAvailable = true; bool subscriptionIdentifiersAvailable = true; bool sharedSubscriptionAvailable = true; std::uint16_t serverKeepAlive = 0; - std::string serverReference; - std::string authenticationMethod; - Bytes authenticationData; + std::string serverReference{}; + std::string authenticationMethod{}; + Bytes authenticationData{}; }; virtual void receivedConnAck(const ConnAckData& data) = 0; @@ -61,11 +59,11 @@ struct IMqtt5ClientCallback { std::uint8_t qos = 0; bool retain = false; - std::string topic; + std::string topic{}; std::uint32_t messageExpiryInterval = 0; - std::string responseTopic; - Bytes correlationData; - std::string contentType; + std::string responseTopic{}; + Bytes correlationData{}; + std::string contentType{}; }; virtual void receivedPublish(const PublishData& data, const IMessagePtr& message) = 0; @@ -76,17 +74,17 @@ struct IMqtt5ClientCallback struct DisconnectData { std::uint8_t reasoncode = 0; - std::string reasonString; - std::string serverReference; + std::string reasonString{}; + std::string serverReference{}; }; virtual void receivedDisconnect(const DisconnectData& data) = 0; struct AuthData { std::uint8_t reasoncode = 0; - std::string authenticationMethod; - Bytes authenticationData; - std::string reasonString; + std::string authenticationMethod{}; + Bytes authenticationData{}; + std::string reasonString{}; }; virtual void receivedAuth(const AuthData& data) = 0; @@ -104,20 +102,20 @@ struct IMqtt5Client std::uint8_t qos = 0; bool retain = false; std::uint32_t delayInterval = 0; - std::string contentType; - std::string topic; - Bytes payload; + std::string contentType{}; + std::string topic{}; + Bytes payload{}; }; struct ConnectData { bool cleanStart = false; - std::unique_ptr willMessage; - std::string username; - std::string password; + std::unique_ptr willMessage{}; + std::string username{}; + std::string password{}; std::uint16_t keepAlive = 0; std::uint32_t sessionExpiryInterval = 0; std::uint16_t receiveMaximum = 65535; - std::string clientId; + std::string clientId{}; }; virtual void startConnection(const IStreamConnectionPtr& connection, const ConnectData& data) = 0; @@ -125,17 +123,17 @@ struct IMqtt5Client { std::uint8_t qos = 0; bool retain = false; - std::string topic; + std::string topic{}; std::uint32_t messageExpiryInterval = 0; - std::string responseTopic; - Bytes correlationData; - std::string contentType; + std::string responseTopic{}; + Bytes correlationData{}; + std::string contentType{}; }; virtual void publish(const IStreamConnectionPtr& connection, PublishData&& data, const IMessagePtr& message) = 0; struct SubscribeEntry { - std::string topic; + std::string topic{}; unsigned int retainHandling = 0; bool retainAsPublished = false; bool noLocal = false; @@ -143,7 +141,7 @@ struct IMqtt5Client }; struct SubscribeData { - std::vector subscriptions; + std::vector subscriptions{}; }; virtual void subscribe(const IStreamConnectionPtr& connection, const SubscribeData& data) = 0; virtual void unsubscribe(const IStreamConnectionPtr& connection, const std::vector& topics) = 0; @@ -168,10 +166,7 @@ struct IMqtt5Client virtual void cycleTime(const IStreamConnectionPtr& connection) = 0; }; - - -class Mqtt5Client : public IMqtt5Client - , private IMqtt5ProtocolCallback +class Mqtt5Client : public IMqtt5Client, private IMqtt5ProtocolCallback { public: Mqtt5Client(); @@ -203,16 +198,14 @@ class Mqtt5Client : public IMqtt5Client void setReceiveActivity(); - hybrid_ptr m_callback; + hybrid_ptr m_callback{}; std::uint16_t m_keepAlive = 0; - PollingTimer m_timerPing; - PollingTimer m_timerReceiveActivity; + PollingTimer m_timerPing{}; + PollingTimer m_timerReceiveActivity{}; std::uint32_t m_sessionExpiryInterval = 0; std::unique_ptr m_protocol = std::make_unique(); }; - - -} // namespace finalmq +} // namespace finalmq diff --git a/inc/finalmq/protocols/mqtt5/Mqtt5CommandData.h b/inc/finalmq/protocols/mqtt5/Mqtt5CommandData.h index 6db0d57d..70d3aae3 100644 --- a/inc/finalmq/protocols/mqtt5/Mqtt5CommandData.h +++ b/inc/finalmq/protocols/mqtt5/Mqtt5CommandData.h @@ -22,37 +22,34 @@ #pragma once -#include "finalmq/metadata/MetaType.h" -#include "finalmq/variant/Variant.h" - #include -namespace finalmq { - - - +#include "finalmq/metadata/MetaType.h" +#include "finalmq/variant/Variant.h" +namespace finalmq +{ struct Mqtt5WillMessage { - std::unordered_map properties; - std::unordered_map metainfo; - std::string topic; - Bytes payload; + std::unordered_map properties{}; + std::unordered_map metainfo{}; + std::string topic{}; + Bytes payload{}; bool retain = false; unsigned int qos = 0; }; struct Mqtt5ConnectData { - std::string protocol; + std::string protocol{}; unsigned int version = 0; unsigned int keepAlive = 0; - std::unordered_map properties; - std::unordered_map metainfo; - std::string clientId; - std::unique_ptr willMessage; - std::string username; - std::string password; + std::unordered_map properties{}; + std::unordered_map metainfo{}; + std::string clientId{}; + std::unique_ptr willMessage{}; + std::string username{}; + std::string password{}; bool cleanStart = false; }; @@ -60,8 +57,8 @@ struct Mqtt5ConnAckData { bool sessionPresent = false; unsigned int reasoncode = 0; - std::unordered_map properties; - std::unordered_map metainfo; + std::unordered_map properties{}; + std::unordered_map metainfo{}; }; struct Mqtt5PublishData @@ -69,23 +66,23 @@ struct Mqtt5PublishData unsigned int qos = 0; bool dup = false; bool retain = false; - std::string topic; + std::string topic{}; unsigned int packetId = 0; - std::unordered_map properties; - std::unordered_map metainfo; + std::unordered_map properties{}; + std::unordered_map metainfo{}; }; struct Mqtt5PubAckData { unsigned int packetId = 0; unsigned int reasoncode = 0; - std::unordered_map properties; - std::unordered_map metainfo; + std::unordered_map properties{}; + std::unordered_map metainfo{}; }; struct Mqtt5SubscribeEntry { - std::string topic; + std::string topic{}; unsigned int retainHandling = 0; bool retainAsPublished = false; bool noLocal = false; @@ -95,40 +92,39 @@ struct Mqtt5SubscribeEntry struct Mqtt5SubscribeData { unsigned int packetId = 0; - std::unordered_map properties; - std::unordered_map metainfo; - std::vector subscriptions; + std::unordered_map properties{}; + std::unordered_map metainfo{}; + std::vector subscriptions{}; }; struct Mqtt5SubAckData { unsigned int packetId = 0; - std::unordered_map properties; - std::unordered_map metainfo; - std::vector reasoncodes; + std::unordered_map properties{}; + std::unordered_map metainfo{}; + std::vector reasoncodes{}; }; struct Mqtt5UnsubscribeData { unsigned int packetId = 0; - std::unordered_map properties; - std::unordered_map metainfo; - std::vector topics; + std::unordered_map properties{}; + std::unordered_map metainfo{}; + std::vector topics{}; }; struct Mqtt5DisconnectData { unsigned int reasoncode = 0; - std::unordered_map properties; - std::unordered_map metainfo; + std::unordered_map properties{}; + std::unordered_map metainfo{}; }; struct Mqtt5AuthData { unsigned int reasoncode = 0; - std::unordered_map properties; - std::unordered_map metainfo; + std::unordered_map properties{}; + std::unordered_map metainfo{}; }; - -} // namespace finalmq +} // namespace finalmq diff --git a/inc/finalmq/protocols/mqtt5/Mqtt5Protocol.h b/inc/finalmq/protocols/mqtt5/Mqtt5Protocol.h index ed045b94..36996ffe 100644 --- a/inc/finalmq/protocols/mqtt5/Mqtt5Protocol.h +++ b/inc/finalmq/protocols/mqtt5/Mqtt5Protocol.h @@ -22,23 +22,22 @@ #pragma once -#include "finalmq/streamconnection/IMessage.h" -#include "finalmq/protocols/mqtt5/Mqtt5CommandData.h" -#include "finalmq/streamconnection/StreamConnection.h" -#include "Mqtt5Serialization.h" - #include #include #include -namespace finalmq { - +#include "Mqtt5Serialization.h" +#include "finalmq/protocols/mqtt5/Mqtt5CommandData.h" +#include "finalmq/streamconnection/IMessage.h" +#include "finalmq/streamconnection/StreamConnection.h" -enum Mqtt5ReasonCode { +namespace finalmq +{ +enum Mqtt5ReasonCode +{ ReasonKeepAliveTimeout = 0x8d, }; - struct IMqtt5ProtocolCallback { virtual ~IMqtt5ProtocolCallback() = default; @@ -71,13 +70,17 @@ struct IMqtt5Protocol virtual void sendAuth(const IStreamConnectionPtr& connection, const Mqtt5AuthData& data) = 0; }; - class Mqtt5Protocol : public IMqtt5Protocol { public: Mqtt5Protocol(); public: + Mqtt5Protocol(const Mqtt5Protocol&) = delete; + Mqtt5Protocol(Mqtt5Protocol&&) = delete; + const Mqtt5Protocol& operator=(const Mqtt5Protocol&) = delete; + const Mqtt5Protocol& operator=(Mqtt5Protocol&&) = delete; + enum class State { WAITFORHEADER, @@ -108,7 +111,6 @@ class Mqtt5Protocol : public IMqtt5Protocol void sendPubAck(const IStreamConnectionPtr& connection, Mqtt5Command command, const Mqtt5PubAckData& data); void sendSubAck(const IStreamConnectionPtr& connection, Mqtt5Command command, const Mqtt5SubAckData& data); - // IMqtt5Protocol virtual void setCallback(hybrid_ptr callback) override; virtual bool receive(const IStreamConnectionPtr& connection, const SocketPtr& socket, int bytesToRead) override; @@ -123,22 +125,22 @@ class Mqtt5Protocol : public IMqtt5Protocol virtual void sendAuth(const IStreamConnectionPtr& connection, const Mqtt5AuthData& data) override; char m_header{}; - int m_remainingSize = 0; - int m_remainingSizeShift = 0; - State m_state = State::WAITFORHEADER; - ssize_t m_sizeCurrent = 0; + int m_remainingSize = 0; + int m_remainingSizeShift = 0; + State m_state = State::WAITFORHEADER; + ssize_t m_sizeCurrent = 0; - ssize_t m_sizePayload = 0; - IMessagePtr m_message; - Bytes m_messageBuffer; - char* m_buffer = nullptr; + ssize_t m_sizePayload = 0; + IMessagePtr m_message{}; + Bytes m_messageBuffer{}; + char* m_buffer = nullptr; struct PendingMessage { - IMessagePtr message; - std::uint8_t* bufferPacketId = nullptr; - unsigned int qos = 0; - Mqtt5Command command {}; + IMessagePtr message; + std::uint8_t* bufferPacketId = nullptr; + unsigned int qos = 0; + Mqtt5Command command{}; }; struct MessageStatus { @@ -152,23 +154,21 @@ class Mqtt5Protocol : public IMqtt5Protocol SENDSTAT_WAITUNSUBACK, }; - Status status = SENDSTAT_NONE; - std::list::iterator iterator; + Status status = SENDSTAT_NONE; + std::list::iterator iterator; }; - bool m_connecting = true; - std::uint16_t m_sendMax = 0; ///< max. messages that will wait for an ack. In case of exceed, the messages will wait in m_messagesPending. - std::deque m_messagesPending; ///< messages that were not sent, yet, because of flow control - std::list m_messagesWaitAck; ///< keeps the messages in order that could be resent - std::deque m_messageIdsAllocated; ///< the message status of messages that wait for ack, the index is the message id - std::deque m_messageIdsFree; ///< free message ids - std::unordered_set m_setExactlyOne; + bool m_connecting = true; + std::uint16_t m_sendMax = 0; ///< max. messages that will wait for an ack. In case of exceed, the messages will wait in m_messagesPending. + std::deque m_messagesPending{}; ///< messages that were not sent, yet, because of flow control + std::list m_messagesWaitAck{}; ///< keeps the messages in order that could be resent + std::deque m_messageIdsAllocated{}; ///< the message status of messages that wait for ack, the index is the message id + std::deque m_messageIdsFree{}; ///< free message ids + std::unordered_set m_setExactlyOne{}; - hybrid_ptr m_callback; + hybrid_ptr m_callback{}; - std::mutex m_mutex; + std::mutex m_mutex{}; }; - - -} // namespace finalmq +} // namespace finalmq diff --git a/inc/finalmq/protocols/protocolhelpers/ProtocolDelimiter.h b/inc/finalmq/protocols/protocolhelpers/ProtocolDelimiter.h index aa6aba3a..8e07ad61 100644 --- a/inc/finalmq/protocols/protocolhelpers/ProtocolDelimiter.h +++ b/inc/finalmq/protocols/protocolhelpers/ProtocolDelimiter.h @@ -22,15 +22,14 @@ #pragma once -#include "finalmq/streamconnection/IMessage.h" -#include "finalmq/protocolsession/IProtocol.h" -#include "finalmq/helpers/FmqDefines.h" #include +#include "finalmq/helpers/FmqDefines.h" +#include "finalmq/protocolsession/IProtocol.h" +#include "finalmq/streamconnection/IMessage.h" -namespace finalmq { - - +namespace finalmq +{ class SYMBOLEXP ProtocolDelimiter : public IProtocol { public: @@ -43,7 +42,7 @@ class SYMBOLEXP ProtocolDelimiter : public IProtocol virtual void setConnection(const IStreamConnectionPtr& connection) override; virtual IStreamConnectionPtr getConnection() const override; virtual void disconnect() override; - virtual std::uint32_t getProtocolId() const = 0; + //virtual std::uint32_t getProtocolId() const = 0; virtual bool areMessagesResendable() const override; virtual bool doesSupportMetainfo() const override; virtual bool doesSupportSession() const override; @@ -66,27 +65,25 @@ class SYMBOLEXP ProtocolDelimiter : public IProtocol std::vector findEndOfMessage(const char* buffer, ssize_t size); - std::weak_ptr m_callback; - IStreamConnectionPtr m_connection; + std::weak_ptr m_callback{}; + IStreamConnectionPtr m_connection{}; - const std::string m_delimiter; - const char m_delimiterStart; - ssize_t m_indexStartMessage = 0; - std::shared_ptr m_receiveBuffer; - ssize_t m_bufferSize = 0; + const std::string m_delimiter{}; + const char m_delimiterStart{}; + ssize_t m_indexStartMessage = 0; + std::shared_ptr m_receiveBuffer{}; + ssize_t m_bufferSize = 0; struct ReceiveBufferStore { - std::shared_ptr receiveBuffer; - ssize_t indexStartMessage = -1; - ssize_t indexEndMessage = -1; + std::shared_ptr receiveBuffer{}; + ssize_t indexStartMessage = -1; + ssize_t indexEndMessage = -1; }; - std::vector m_receiveBuffers; - ssize_t m_receiveBuffersTotal = 0; + std::vector m_receiveBuffers{}; + ssize_t m_receiveBuffersTotal = 0; - mutable std::mutex m_mutex; + mutable std::mutex m_mutex{}; }; - - -} // namespace finalmq +} // namespace finalmq diff --git a/inc/finalmq/protocols/protocolhelpers/ProtocolFixHeaderHelper.h b/inc/finalmq/protocols/protocolhelpers/ProtocolFixHeaderHelper.h index 5e051261..ae9f1828 100644 --- a/inc/finalmq/protocols/protocolhelpers/ProtocolFixHeaderHelper.h +++ b/inc/finalmq/protocols/protocolhelpers/ProtocolFixHeaderHelper.h @@ -22,15 +22,15 @@ #pragma once -#include "finalmq/streamconnection/IMessage.h" -#include "finalmq/protocolsession/IProtocol.h" -#include "finalmq/helpers/FmqDefines.h" - #include #include -namespace finalmq { +#include "finalmq/helpers/FmqDefines.h" +#include "finalmq/protocolsession/IProtocol.h" +#include "finalmq/streamconnection/IMessage.h" +namespace finalmq +{ class SYMBOLEXP ProtocolFixHeaderHelper { public: @@ -39,6 +39,10 @@ class SYMBOLEXP ProtocolFixHeaderHelper bool receive(const SocketPtr& socket, int bytesToRead, std::deque& messages); private: + ProtocolFixHeaderHelper(const ProtocolFixHeaderHelper&) = delete; + ProtocolFixHeaderHelper(ProtocolFixHeaderHelper&&) = delete; + const ProtocolFixHeaderHelper& operator=(const ProtocolFixHeaderHelper&) = delete; + const ProtocolFixHeaderHelper& operator=(ProtocolFixHeaderHelper&&) = delete; enum class State { @@ -52,17 +56,17 @@ class SYMBOLEXP ProtocolFixHeaderHelper void handlePayloadReceived(); void clearState(); - std::string m_header; - State m_state = State::WAITFORHEADER; - ssize_t m_sizeCurrent = 0; + std::string m_header{}; + State m_state = State::WAITFORHEADER; + ssize_t m_sizeCurrent = 0; - ssize_t m_sizePayload = 0; - IMessagePtr m_message; - char* m_buffer = nullptr; + ssize_t m_sizePayload = 0; + IMessagePtr m_message{}; + char* m_buffer = nullptr; std::deque* m_messages = nullptr; - std::function m_funcGetPayloadSize; + std::function m_funcGetPayloadSize; }; -} // namespace finalmq +} // namespace finalmq diff --git a/inc/finalmq/protocolsession/ProtocolMessage.h b/inc/finalmq/protocolsession/ProtocolMessage.h index e12d072c..bf1812e7 100644 --- a/inc/finalmq/protocolsession/ProtocolMessage.h +++ b/inc/finalmq/protocolsession/ProtocolMessage.h @@ -22,24 +22,22 @@ #pragma once -#include "finalmq/streamconnection/IMessage.h" +#include + #include "finalmq/protocolsession/IProtocol.h" +#include "finalmq/streamconnection/IMessage.h" #include "finalmq/variant/Variant.h" -#include "finalmq/variant/VariantValues.h" -#include "finalmq/variant/VariantValueStruct.h" #include "finalmq/variant/VariantValueList.h" +#include "finalmq/variant/VariantValueStruct.h" +#include "finalmq/variant/VariantValues.h" - -#include - -namespace finalmq { - - +namespace finalmq +{ class SYMBOLEXP ProtocolMessage : public IMessage { public: static const std::string FMQ_PROTOCOLDATA; - + ProtocolMessage(std::uint32_t protocolId, ssize_t sizeHeader = 0, ssize_t sizeTrailer = 0); private: @@ -95,40 +93,39 @@ class SYMBOLEXP ProtocolMessage : public IMessage virtual void prepareMessageToSend() override; // for the protocol to check if which protocol created the message - virtual std::uint32_t getProtocolId() const; + virtual std::uint32_t getProtocolId() const override; virtual bool wasSent() const override; virtual void addMessage(const IMessagePtr& msg) override; virtual IMessagePtr getMessage(std::uint32_t protocolId) const override; private: - - Metainfo m_metainfo; - Variant m_controlData; - Variant m_echoData; + Metainfo m_metainfo{}; + Variant m_controlData{}; + Variant m_echoData{}; // send - std::list m_headerBuffers; - std::list m_payloadBuffers; - std::list m_sendBufferRefs; - std::list::iterator m_itSendBufferRefsPayloadBegin; - ssize_t m_offset = -1; - ssize_t m_sizeLastBlock = 0; - ssize_t m_sizeSendBufferTotal = 0; - std::list m_sendPayloadRefs; - ssize_t m_sizeSendPayloadTotal = 0; + std::list m_headerBuffers{}; + std::list m_payloadBuffers{}; + std::list m_sendBufferRefs{}; + std::list::iterator m_itSendBufferRefsPayloadBegin{}; + ssize_t m_offset = -1; + ssize_t m_sizeLastBlock = 0; + ssize_t m_sizeSendBufferTotal = 0; + std::list m_sendPayloadRefs{}; + ssize_t m_sizeSendPayloadTotal = 0; // receive - std::shared_ptr m_receiveBuffer; - BufferRef m_receiveBufferRef; + std::shared_ptr m_receiveBuffer{}; + BufferRef m_receiveBufferRef{}; - ssize_t m_sizeHeader = 0; - ssize_t m_sizeTrailer = 0; + ssize_t m_sizeHeader = 0; + ssize_t m_sizeTrailer = 0; - bool m_preparedToSend = false; - const std::uint32_t m_protocolId; + bool m_preparedToSend = false; + const std::uint32_t m_protocolId; - std::unordered_map m_messages; + std::unordered_map m_messages{}; }; -} // namespace finalmq +} // namespace finalmq diff --git a/inc/finalmq/protocolsession/ProtocolRegistry.h b/inc/finalmq/protocolsession/ProtocolRegistry.h index 2f833915..ec1da0e8 100644 --- a/inc/finalmq/protocolsession/ProtocolRegistry.h +++ b/inc/finalmq/protocolsession/ProtocolRegistry.h @@ -22,36 +22,30 @@ #pragma once - -#include "finalmq/protocolsession/IProtocol.h" - -#include - -#include #include +#include +#include -namespace finalmq { - +#include "finalmq/protocolsession/IProtocol.h" +namespace finalmq +{ enum { REMOTEENTITYPROTOCOL_DELIMITERLINEFEED = 1, REMOTEENTITYPROTOCOL_HEADERBINARYSIZE = 2, }; - struct IProtocolRegistry { - virtual ~IProtocolRegistry() {} + virtual ~IProtocolRegistry() + {} virtual void registerProtocolFactory(const std::string& protocolName, int protocolId, const IProtocolFactoryPtr& protocolFactory) = 0; virtual IProtocolFactoryPtr getProtocolFactory(const std::string& protocolName) const = 0; virtual IProtocolFactoryPtr getProtocolFactory(int protocolId) const = 0; }; - - - class ProtocolRegistryImpl : public IProtocolRegistry { public: @@ -60,11 +54,10 @@ class ProtocolRegistryImpl : public IProtocolRegistry virtual IProtocolFactoryPtr getProtocolFactory(int protocolId) const override; private: - std::unordered_map m_protocolNameToFactory; - std::unordered_map m_protocolIdToFactory; + std::unordered_map m_protocolNameToFactory{}; + std::unordered_map m_protocolIdToFactory{}; }; - class SYMBOLEXP ProtocolRegistry { public: @@ -94,5 +87,4 @@ class SYMBOLEXP ProtocolRegistry static std::unique_ptr& getStaticUniquePtrRef(); }; - -} // namespace finalmq +} // namespace finalmq diff --git a/inc/finalmq/protocolsession/ProtocolSession.h b/inc/finalmq/protocolsession/ProtocolSession.h index 313f7db0..485ff3d7 100644 --- a/inc/finalmq/protocolsession/ProtocolSession.h +++ b/inc/finalmq/protocolsession/ProtocolSession.h @@ -22,41 +22,45 @@ #pragma once -#include "finalmq/streamconnection/StreamConnection.h" -#include "finalmq/variant/Variant.h" -#include "finalmq/helpers/IExecutor.h" -#include "finalmq/helpers/PollingTimer.h" -#include "IProtocol.h" -#include "ProtocolSessionList.h" -#include "IProtocolSession.h" - #include -namespace finalmq { - +#include "IProtocol.h" +#include "IProtocolSession.h" +#include "ProtocolSessionList.h" +#include "finalmq/helpers/IExecutor.h" +#include "finalmq/helpers/PollingTimer.h" +#include "finalmq/streamconnection/StreamConnection.h" +#include "finalmq/variant/Variant.h" +namespace finalmq +{ struct IProtocolSessionPrivate : public IProtocolSession { + virtual ~IProtocolSessionPrivate() override + {} virtual bool connect() = 0; -// virtual void createConnection() = 0; + // virtual void createConnection() = 0; virtual void setConnection(const IStreamConnectionPtr& connection, bool verified) = 0; virtual void setProtocol(const IProtocolPtr& protocol) = 0; virtual void setSessionNameInternal(const std::string& sessionName) = 0; virtual void cycleTime() = 0; + + virtual bool connect(const std::string& endpoint, const ConnectProperties& connectionProperties = {}, int contentType = 0) override = 0; }; typedef std::shared_ptr IProtocolSessionPrivatePtr; - struct IStreamConnectionContainer; - - - -class ProtocolSession : public IProtocolSessionPrivate - , public IProtocolCallback - , public std::enable_shared_from_this +#ifndef WIN32 +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wnon-virtual-dtor" +#endif +class ProtocolSession : public IProtocolSessionPrivate, public IProtocolCallback, public std::enable_shared_from_this { +#ifndef WIN32 +#pragma GCC diagnostic pop +#endif public: ProtocolSession(hybrid_ptr callback, const IExecutorPtr& executor, const IExecutorPtr& executorPollerThread, const IProtocolPtr& protocol, const std::shared_ptr& protocolSessionList, const BindProperties& bindProperties, int contentType); ProtocolSession(hybrid_ptr callback, const IExecutorPtr& executor, const IExecutorPtr& executorPollerThread, const IProtocolFactoryPtr& protocolFactory, const std::shared_ptr& protocolSessionList, const std::shared_ptr& streamConnectionContainer, const std::string& endpointStreamConnection, const ConnectProperties& connectProperties, int contentType); @@ -68,7 +72,7 @@ class ProtocolSession : public IProtocolSessionPrivate // IProtocolSession virtual IMessagePtr createMessage() const override; virtual void sendMessage(const IMessagePtr& msg, bool isReply = false) override; - virtual std::int64_t getSessionId() const; + virtual std::int64_t getSessionId() const override; virtual ConnectionData getConnectionData() const override; virtual int getContentType() const override; virtual bool doesSupportMetainfo() const override; @@ -78,7 +82,7 @@ class ProtocolSession : public IProtocolSessionPrivate virtual bool doesSupportFileTransfer() const override; virtual bool isSynchronousRequestReply() const override; virtual void disconnect() override; -// virtual bool connect(const std::string& endpoint, const ConnectProperties& connectionProperties = {}) override; + // virtual bool connect(const std::string& endpoint, const ConnectProperties& connectionProperties = {}) override; virtual bool connect(const std::string& endpoint, const ConnectProperties& connectionProperties = {}, int contentType = 0) override; virtual IExecutorPtr getExecutor() const override; virtual void subscribe(const std::vector& subscribtions) override; @@ -91,7 +95,7 @@ class ProtocolSession : public IProtocolSessionPrivate // IProtocolSessionPrivate virtual bool connect() override; -// virtual void createConnection() override; + // virtual void createConnection() override; virtual void setConnection(const IStreamConnectionPtr& connection, bool verified) override; virtual void setProtocol(const IProtocolPtr& protocol) override; virtual void setSessionNameInternal(const std::string& sessionName) override; @@ -127,63 +131,62 @@ class ProtocolSession : public IProtocolSessionPrivate IProtocolPtr createRequestConnection(); void sendNextRequests(); - - const hybrid_ptr m_callback; - const IExecutorPtr m_executor; - const IExecutorPtr m_executorPollerThread; - IProtocolPtr m_protocol; - std::atomic m_connectionId{0}; - std::unordered_map m_multiProtocols; - std::unordered_set m_unallocatedConnections; - - const std::weak_ptr m_protocolSessionList; - const int64_t m_sessionId = 0; - const int64_t m_instanceId = 0; - - std::atomic m_contentType{false}; - std::uint32_t m_protocolId = false; - std::atomic m_protocolFlagMessagesResendable{false}; - std::atomic m_protocolFlagSupportMetainfo{false}; - std::atomic m_protocolFlagNeedsReply{false}; - std::atomic m_protocolFlagIsMultiConnectionSession{false}; - std::atomic m_protocolFlagIsSendRequestByPoll{false}; - std::atomic m_protocolFlagSupportFileTransfer{ false }; - std::atomic m_protocolFlagSynchronousRequestReply{ false }; - - IProtocolFactoryPtr m_protocolFactory; - IProtocol::FuncCreateMessage m_messageFactory; - std::atomic_bool m_protocolSet{false}; - bool m_triggeredConnected = false; - bool m_triggeredDisconnected = false; - - const std::shared_ptr m_streamConnectionContainer; - std::string m_endpointStreamConnection; - - const BindProperties m_bindProperties; - ConnectProperties m_connectionProperties; - Variant m_protocolData; - IProtocolSessionDataPtr m_protocolSessionData; - Variant m_formatData; - int m_maxSynchReqRepConnections = -1; - - std::deque m_messagesBuffered; - std::unordered_map m_runningRequests; - - std::deque m_pollMessages; - int m_pollMaxRequests = 10000; -// IMessagePtr m_pollReply; - IProtocolPtr m_pollProtocol = nullptr; - PollingTimer m_pollTimer; - int m_pollCountMax = 0; - int m_pollCounter = 0; - - std::atomic m_activityTimeout{ -1 }; - PollingTimer m_activityTimer; - - bool m_verified = false; - std::string m_sessionName; - - mutable std::mutex m_mutex; + const hybrid_ptr m_callback; + const IExecutorPtr m_executor; + const IExecutorPtr m_executorPollerThread; + IProtocolPtr m_protocol{}; + std::atomic m_connectionId{0}; + std::unordered_map m_multiProtocols{}; + std::unordered_set m_unallocatedConnections{}; + + const std::weak_ptr m_protocolSessionList; + const int64_t m_sessionId = 0; + const int64_t m_instanceId = 0; + + std::atomic m_contentType{false}; + std::uint32_t m_protocolId = false; + std::atomic m_protocolFlagMessagesResendable{false}; + std::atomic m_protocolFlagSupportMetainfo{false}; + std::atomic m_protocolFlagNeedsReply{false}; + std::atomic m_protocolFlagIsMultiConnectionSession{false}; + std::atomic m_protocolFlagIsSendRequestByPoll{false}; + std::atomic m_protocolFlagSupportFileTransfer{false}; + std::atomic m_protocolFlagSynchronousRequestReply{false}; + + IProtocolFactoryPtr m_protocolFactory{}; + IProtocol::FuncCreateMessage m_messageFactory{}; + std::atomic_bool m_protocolSet{false}; + bool m_triggeredConnected = false; + bool m_triggeredDisconnected = false; + + const std::shared_ptr m_streamConnectionContainer{}; + std::string m_endpointStreamConnection{}; + + const BindProperties m_bindProperties{}; + ConnectProperties m_connectionProperties{}; + Variant m_protocolData{}; + IProtocolSessionDataPtr m_protocolSessionData{}; + Variant m_formatData{}; + int m_maxSynchReqRepConnections = -1; + + std::deque m_messagesBuffered{}; + std::unordered_map m_runningRequests{}; + + std::deque m_pollMessages{}; + int m_pollMaxRequests = 10000; + // IMessagePtr m_pollReply; + IProtocolPtr m_pollProtocol = nullptr; + PollingTimer m_pollTimer{}; + int m_pollCountMax = 0; + int m_pollCounter = 0; + + std::atomic m_activityTimeout{-1}; + PollingTimer m_activityTimer{}; + + bool m_verified = false; + std::string m_sessionName{}; + + mutable std::mutex m_mutex{}; }; -} // namespace finalmq +} // namespace finalmq diff --git a/inc/finalmq/protocolsession/ProtocolSessionContainer.h b/inc/finalmq/protocolsession/ProtocolSessionContainer.h index b3816644..3ae24cbc 100644 --- a/inc/finalmq/protocolsession/ProtocolSessionContainer.h +++ b/inc/finalmq/protocolsession/ProtocolSessionContainer.h @@ -22,28 +22,29 @@ #pragma once -#include "ProtocolSession.h" -#include "IProtocol.h" -#include "ProtocolSessionList.h" - -#include #include +#include -namespace finalmq { +#include "IProtocol.h" +#include "ProtocolSession.h" +#include "ProtocolSessionList.h" -typedef std::function FuncTimer; +namespace finalmq +{ +typedef std::function FuncTimer; struct IProtocolSessionContainer { - virtual ~IProtocolSessionContainer() {} + virtual ~IProtocolSessionContainer() + {} virtual void init(const IExecutorPtr& executor = nullptr, int cycleTime = 100, FuncTimer funcTimer = {}, int checkReconnectInterval = 1000) = 0; virtual int bind(const std::string& endpoint, hybrid_ptr callback, const BindProperties& bindProperties = {}, int contentType = 0) = 0; virtual void unbind(const std::string& endpoint) = 0; virtual IProtocolSessionPtr connect(const std::string& endpoint, hybrid_ptr callback, const ConnectProperties& connectProperties = {}, int contentType = 0) = 0; -// virtual IProtocolSessionPtr createSession(hybrid_ptr callback, const IProtocolPtr& protocol, int contentType = 0) = 0; + // virtual IProtocolSessionPtr createSession(hybrid_ptr callback, const IProtocolPtr& protocol, int contentType = 0) = 0; virtual IProtocolSessionPtr createSession(hybrid_ptr callback) = 0; - virtual std::vector< IProtocolSessionPtr > getAllSessions() const = 0; + virtual std::vector getAllSessions() const = 0; virtual IProtocolSessionPtr getSession(std::int64_t sessionId) const = 0; virtual void run() = 0; virtual void terminatePollerLoop() = 0; @@ -52,11 +53,8 @@ struct IProtocolSessionContainer typedef std::shared_ptr IProtocolSessionContainerPtr; - - struct IStreamConnectionContainer; - class ProtocolBind : public IStreamConnectionCallback { public: @@ -68,21 +66,17 @@ class ProtocolBind : public IStreamConnectionCallback virtual void disconnected(const IStreamConnectionPtr& connection) override; virtual bool received(const IStreamConnectionPtr& connection, const SocketPtr& socket, int bytesToRead) override; - const hybrid_ptr m_callback; - const IExecutorPtr m_executor; - const IExecutorPtr m_executorPollerThread; - const IProtocolFactoryPtr m_protocolFactory; - const std::weak_ptr m_protocolSessionList; - const BindProperties m_bindProperties; - const int m_contentType = 0; + const hybrid_ptr m_callback; + const IExecutorPtr m_executor; + const IExecutorPtr m_executorPollerThread; + const IProtocolFactoryPtr m_protocolFactory; + const std::weak_ptr m_protocolSessionList; + const BindProperties m_bindProperties; + const int m_contentType = 0; }; typedef std::shared_ptr ProtocolBindPtr; - - - - class SYMBOLEXP ProtocolSessionContainer : public IProtocolSessionContainer { public: @@ -94,23 +88,23 @@ class SYMBOLEXP ProtocolSessionContainer : public IProtocolSessionContainer virtual int bind(const std::string& endpoint, hybrid_ptr callback, const BindProperties& bindProperties = {}, int contentType = 0) override; virtual void unbind(const std::string& endpoint) override; virtual IProtocolSessionPtr connect(const std::string& endpoint, hybrid_ptr callback, const ConnectProperties& connectProperties = {}, int contentType = 0) override; -// virtual IProtocolSessionPtr createSession(hybrid_ptr callback, const IProtocolPtr& protocol, int contentType = 0) override; + // virtual IProtocolSessionPtr createSession(hybrid_ptr callback, const IProtocolPtr& protocol, int contentType = 0) override; virtual IProtocolSessionPtr createSession(hybrid_ptr callback) override; - virtual std::vector< IProtocolSessionPtr > getAllSessions() const override; + virtual std::vector getAllSessions() const override; virtual IProtocolSessionPtr getSession(std::int64_t sessionId) const override; virtual void run() override; virtual void terminatePollerLoop() override; virtual IExecutorPtr getExecutor() const override; private: - IProtocolSessionListPtr m_protocolSessionList; - std::unordered_map m_endpoint2Bind; - std::shared_ptr m_streamConnectionContainer; - int m_counterTimer = 0; - IExecutorPtr m_executor; - IExecutorPtr m_executorPollerThread; - std::thread m_thread; - mutable std::mutex m_mutex; + IProtocolSessionListPtr m_protocolSessionList{}; + std::unordered_map m_endpoint2Bind{}; + std::shared_ptr m_streamConnectionContainer{}; + int m_counterTimer = 0; + IExecutorPtr m_executor{}; + IExecutorPtr m_executorPollerThread{}; + std::thread m_thread{}; + mutable std::mutex m_mutex{}; }; -} // namespace finalmq +} // namespace finalmq diff --git a/inc/finalmq/protocolsession/ProtocolSessionList.h b/inc/finalmq/protocolsession/ProtocolSessionList.h index 781da8c6..e4f9c3f3 100644 --- a/inc/finalmq/protocolsession/ProtocolSessionList.h +++ b/inc/finalmq/protocolsession/ProtocolSessionList.h @@ -22,23 +22,23 @@ #pragma once -#include "IProtocolSession.h" - #include -namespace finalmq { +#include "IProtocolSession.h" +namespace finalmq +{ struct IProtocolSessionPrivate; typedef std::shared_ptr IProtocolSessionPrivatePtr; - struct IProtocolSessionList { - virtual ~IProtocolSessionList() {} + virtual ~IProtocolSessionList() + {} virtual std::int64_t getNextSessionId() = 0; virtual void addProtocolSession(IProtocolSessionPrivatePtr ProtocolSession, std::int64_t sessionId, bool verified) = 0; virtual void removeProtocolSession(std::int64_t sessionId) = 0; - virtual std::vector< IProtocolSessionPrivatePtr > getAllSessions() const = 0; + virtual std::vector getAllSessions() const = 0; virtual IProtocolSessionPtr getSession(std::int64_t sessionId) const = 0; virtual IProtocolSessionPrivatePtr findSessionByName(const std::string& sessionName) const = 0; virtual bool setSessionName(std::int64_t sessionId, const std::string& sessionName) = 0; @@ -46,32 +46,31 @@ struct IProtocolSessionList typedef std::shared_ptr IProtocolSessionListPtr; - - class ProtocolSessionList : public IProtocolSessionList { public: ProtocolSessionList(); virtual ~ProtocolSessionList(); + private: virtual std::int64_t getNextSessionId() override; virtual void addProtocolSession(IProtocolSessionPrivatePtr ProtocolSession, std::int64_t sessionId, bool verified) override; virtual void removeProtocolSession(std::int64_t sessionId) override; - virtual std::vector< IProtocolSessionPrivatePtr > getAllSessions() const override; + virtual std::vector getAllSessions() const override; virtual IProtocolSessionPtr getSession(std::int64_t sessionId) const override; virtual IProtocolSessionPrivatePtr findSessionByName(const std::string& sessionName) const override; virtual bool setSessionName(std::int64_t sessionId, const std::string& sessionName) override; struct SessionData { - IProtocolSessionPrivatePtr session; - bool verified = false; - std::string name; + IProtocolSessionPrivatePtr session{}; + bool verified = false; + std::string name{}; }; - std::unordered_map m_connectionId2ProtocolSession; - static std::atomic_int64_t m_nextSessionId; - mutable std::mutex m_mutex; + std::unordered_map m_connectionId2ProtocolSession{}; + static std::atomic_int64_t m_nextSessionId; + mutable std::mutex m_mutex{}; }; -} // namespace finalmq +} // namespace finalmq diff --git a/inc/finalmq/remoteentity/FmqRegistryClient.h b/inc/finalmq/remoteentity/FmqRegistryClient.h index d6cdf098..8c6823fe 100644 --- a/inc/finalmq/remoteentity/FmqRegistryClient.h +++ b/inc/finalmq/remoteentity/FmqRegistryClient.h @@ -22,13 +22,13 @@ #pragma once -#include "finalmq/remoteentity/RemoteEntityContainer.h" -#include "finalmq/interfaces/fmqreg.fmq.h" - #include -namespace finalmq { +#include "finalmq/interfaces/fmqreg.fmq.h" +#include "finalmq/remoteentity/RemoteEntityContainer.h" +namespace finalmq +{ class SYMBOLEXP FmqRegistryClient { public: @@ -44,11 +44,9 @@ class SYMBOLEXP FmqRegistryClient void init(); SessionInfo createRegistrySession(const std::string& hostname, const ConnectProperties& connectProperties = {}); - bool m_init = false; - hybrid_ptr m_remoteEntityContainer; - IRemoteEntityPtr m_entityRegistry; + bool m_init = false; + hybrid_ptr m_remoteEntityContainer{}; + IRemoteEntityPtr m_entityRegistry{}; }; - -} // namespace finalmq - +} // namespace finalmq diff --git a/inc/finalmq/remoteentity/IRemoteEntity.h b/inc/finalmq/remoteentity/IRemoteEntity.h index 1e642a1a..42da309c 100644 --- a/inc/finalmq/remoteentity/IRemoteEntity.h +++ b/inc/finalmq/remoteentity/IRemoteEntity.h @@ -22,13 +22,11 @@ #pragma once - -#include "finalmq/remoteentity/entitydata.fmq.h" #include "finalmq/remoteentity/FileTransferReply.h" +#include "finalmq/remoteentity/entitydata.fmq.h" - -namespace finalmq { - +namespace finalmq +{ using PeerId = std::int64_t; static constexpr PeerId PEERID_INVALID = 0; @@ -50,8 +48,7 @@ class SessionInfo { public: SessionInfo(const hybrid_ptr& entityContainer, const IProtocolSessionPtr& session) - : m_entityContainer(entityContainer) - , m_session(session) + : m_entityContainer(entityContainer), m_session(session) { assert(m_entityContainer.lock()); assert(m_session); @@ -108,26 +105,21 @@ class SessionInfo } private: - hybrid_ptr m_entityContainer; - IProtocolSessionPtr m_session; + hybrid_ptr m_entityContainer{}; + IProtocolSessionPtr m_session{}; std::int64_t m_sessionId = 0; }; - - struct ReceiveData { - SessionInfo session; - std::string virtualSessionId; - IMessagePtr message; - Header header; - bool automaticConnect = false; - std::shared_ptr structBase; + SessionInfo session{}; + std::string virtualSessionId{}; + IMessagePtr message{}; + Header header{}; + bool automaticConnect = false; + std::shared_ptr structBase{}; }; - - - typedef std::function FuncReply; typedef std::function FuncReplyMeta; typedef std::function FuncCommand; @@ -135,13 +127,13 @@ typedef std::function FuncReplyEvent; // return bool reply handled -> skip looking for reply lambda. typedef std::function FuncReplyConnect; - struct IRemoteEntity { /** * @brief ~IRemoteEntity is the virtual destructor of the interface. */ - virtual ~IRemoteEntity() {} + virtual ~IRemoteEntity() + {} /** * @brief requestReply sends a request to the peer and the funcReply is triggered when @@ -157,24 +149,25 @@ struct IRemoteEntity */ template CorrelationId requestReply(const PeerId& peerId, - const std::string& path, const StructBase& structBase, - std::function& reply)> funcReply) + const std::string& path, + const StructBase& structBase, + std::function& reply)> funcReply) { assert(funcReply); - CorrelationId correlationId = sendRequest(peerId, path, structBase, [funcReply{ std::move(funcReply) }](PeerId peerId, Status status, const StructBasePtr& structBase) { + CorrelationId correlationId = sendRequest(peerId, path, structBase, [funcReply{std::move(funcReply)}](PeerId peerId1, Status status, const StructBasePtr& structBase1) { std::shared_ptr reply; - if (status == Status::STATUS_OK && structBase != nullptr) + if (status == Status::STATUS_OK && structBase1 != nullptr) { - if (structBase->getStructInfo().getTypeName() == R::structInfo().getTypeName()) + if (structBase1->getStructInfo().getTypeName() == R::structInfo().getTypeName()) { - reply = std::static_pointer_cast(structBase); + reply = std::static_pointer_cast(structBase1); } if (reply == nullptr) { status = Status::STATUS_WRONG_REPLY_TYPE; } } - funcReply(peerId, status, reply); + funcReply(peerId1, status, reply); }); return correlationId; } @@ -196,26 +189,26 @@ struct IRemoteEntity */ template CorrelationId requestReply(const PeerId& peerId, - const std::string& path, - IMessage::Metainfo&& metainfo, - const StructBase& structBase, - std::function& reply)> funcReply) + const std::string& path, + IMessage::Metainfo&& metainfo, + const StructBase& structBase, + std::function& reply)> funcReply) { assert(funcReply); - CorrelationId correlationId = sendRequest(peerId, path, std::move(metainfo), structBase, [funcReply{ std::move(funcReply) }](PeerId peerId, Status status, IMessage::Metainfo& metainfo, const StructBasePtr& structBase) { + CorrelationId correlationId = sendRequest(peerId, path, std::move(metainfo), structBase, [funcReply{std::move(funcReply)}](PeerId peerId1, Status status, IMessage::Metainfo& metainfo1, const StructBasePtr& structBase1) { std::shared_ptr reply; - if (status == Status::STATUS_OK && structBase != nullptr) + if (status == Status::STATUS_OK && structBase1 != nullptr) { - if (structBase->getStructInfo().getTypeName() == R::structInfo().getTypeName()) + if (structBase1->getStructInfo().getTypeName() == R::structInfo().getTypeName()) { - reply = std::static_pointer_cast(structBase); + reply = std::static_pointer_cast(structBase1); } if (reply == nullptr) { status = Status::STATUS_WRONG_REPLY_TYPE; } } - funcReply(peerId, status, metainfo, reply); + funcReply(peerId1, status, metainfo1, reply); }); return correlationId; } @@ -233,24 +226,24 @@ struct IRemoteEntity */ template CorrelationId requestReply(const PeerId& peerId, - const StructBase& structBase, - std::function& reply)> funcReply) + const StructBase& structBase, + std::function& reply)> funcReply) { assert(funcReply); - CorrelationId correlationId = sendRequest(peerId, structBase, [funcReply{ std::move(funcReply) }](PeerId peerId, Status status, const StructBasePtr& structBase) { + CorrelationId correlationId = sendRequest(peerId, structBase, [funcReply{std::move(funcReply)}](PeerId peerId1, Status status, const StructBasePtr& structBase1) { std::shared_ptr reply; - if (status == Status::STATUS_OK && structBase != nullptr) + if (status == Status::STATUS_OK && structBase1 != nullptr) { - if (structBase->getStructInfo().getTypeName() == R::structInfo().getTypeName()) + if (structBase1->getStructInfo().getTypeName() == R::structInfo().getTypeName()) { - reply = std::static_pointer_cast(structBase); + reply = std::static_pointer_cast(structBase1); } if (reply == nullptr) { status = Status::STATUS_WRONG_REPLY_TYPE; } } - funcReply(peerId, status, reply); + funcReply(peerId1, status, reply); }); return correlationId; } @@ -271,25 +264,25 @@ struct IRemoteEntity */ template CorrelationId requestReply(const PeerId& peerId, - IMessage::Metainfo&& metainfo, - const StructBase& structBase, - std::function& reply)> funcReply) + IMessage::Metainfo&& metainfo, + const StructBase& structBase, + std::function& reply)> funcReply) { assert(funcReply); - CorrelationId correlationId = sendRequest(peerId, std::move(metainfo), structBase, [funcReply{ std::move(funcReply) }](PeerId peerId, Status status, IMessage::Metainfo& metainfo, const StructBasePtr& structBase) { + CorrelationId correlationId = sendRequest(peerId, std::move(metainfo), structBase, [funcReply{std::move(funcReply)}](PeerId peerId1, Status status, IMessage::Metainfo& metainfo1, const StructBasePtr& structBase1) { std::shared_ptr reply; - if (status == Status::STATUS_OK && structBase != nullptr) + if (status == Status::STATUS_OK && structBase1 != nullptr) { - if (structBase->getStructInfo().getTypeName() == R::structInfo().getTypeName()) + if (structBase1->getStructInfo().getTypeName() == R::structInfo().getTypeName()) { - reply = std::static_pointer_cast(structBase); + reply = std::static_pointer_cast(structBase1); } if (reply == nullptr) { status = Status::STATUS_WRONG_REPLY_TYPE; } } - funcReply(peerId, status, metainfo, reply); + funcReply(peerId1, status, metainfo1, reply); }); return correlationId; } @@ -632,7 +625,6 @@ struct IRemoteEntity */ virtual PeerId createPublishPeer(const SessionInfo& session, const std::string& entityName) = 0; - private: // methods for RemoteEntityContainer virtual void sessionDisconnected(const IProtocolSessionPtr& session) = 0; @@ -644,7 +636,4 @@ struct IRemoteEntity }; typedef std::shared_ptr IRemoteEntityPtr; - - - -} // namespace finalmq +} // namespace finalmq diff --git a/inc/finalmq/remoteentity/RemoteEntity.h b/inc/finalmq/remoteentity/RemoteEntity.h index f56580f5..6838fe36 100644 --- a/inc/finalmq/remoteentity/RemoteEntity.h +++ b/inc/finalmq/remoteentity/RemoteEntity.h @@ -22,48 +22,43 @@ #pragma once -#include "finalmq/protocolsession/ProtocolSessionContainer.h" -#include "finalmq/remoteentity/RemoteEntityFormatRegistry.h" -#include "finalmq/remoteentity/IRemoteEntity.h" - - +#include #include -#include -#include #include -#include - +#include +#include -namespace finalmq { +#include "finalmq/protocolsession/ProtocolSessionContainer.h" +#include "finalmq/remoteentity/IRemoteEntity.h" +#include "finalmq/remoteentity/RemoteEntityFormatRegistry.h" +namespace finalmq +{ static const std::string FMQ_VIRTUAL_SESSION_ID = "fmq_virtsessid"; - struct IProtocolSession; typedef std::shared_ptr IProtocolSessionPtr; - class Status; class Header; - - /** * @brief The PeerEvent class is an enum with possible entity connection states. */ class SYMBOLEXP PeerEvent { public: - enum Enum : std::int32_t { - PEER_CONNECTED = 0, ///< The entity connected to a remote entity or a remote entity connected to the entity. - PEER_DISCONNECTED = 1 ///< The entity disconnected from a remote entity or a remote entity disconnected from the entity. + enum Enum : std::int32_t + { + PEER_CONNECTED = 0, ///< The entity connected to a remote entity or a remote entity connected to the entity. + PEER_DISCONNECTED = 1 ///< The entity disconnected from a remote entity or a remote entity disconnected from the entity. }; PeerEvent(); PeerEvent(Enum en); operator const Enum&() const; operator Enum&(); - const PeerEvent& operator =(Enum en); + const PeerEvent& operator=(Enum en); const std::string& toName() const; const std::string& toString() const; void fromString(const std::string& name); @@ -73,13 +68,9 @@ class SYMBOLEXP PeerEvent static const EnumInfo _enumInfo; }; - - - class SYMBOLEXP PeerManager { public: - enum ReadyToSend { RTS_READY, @@ -89,8 +80,8 @@ class SYMBOLEXP PeerManager struct Request { - StructBasePtr structBase; - CorrelationId correlationId = CORRELATIONID_NONE; + StructBasePtr structBase; + CorrelationId correlationId = CORRELATIONID_NONE; }; PeerManager(); @@ -112,45 +103,32 @@ class SYMBOLEXP PeerManager private: struct Peer { - SessionInfo session; - std::string virtualSessionId; - EntityId entityId{ ENTITYID_INVALID }; - std::string entityName; - bool incoming = false; - std::deque requests; + SessionInfo session{}; + std::string virtualSessionId{}; + EntityId entityId{ENTITYID_INVALID}; + std::string entityName{}; + bool incoming = false; + std::deque requests{}; }; - void removePeerFromSessionEntityToPeerId(std::int64_t sessionId, const std::string& virtualSessionId, EntityId entityId, const std::string& entityName); PeerId getPeerIdIntern(std::int64_t sessionId, const std::string& virtualSessionId, EntityId entityId, const std::string& entityName) const; std::shared_ptr getPeer(const PeerId& peerId) const; - - EntityId m_entityId{ENTITYID_INVALID}; - std::shared_ptr m_funcPeerEvent; - std::unordered_map> m_peers; - PeerId m_nextPeerId{1}; - std::unordered_map, std::unordered_map>>> m_sessionEntityToPeerId; - mutable std::mutex m_mutex; + EntityId m_entityId{ENTITYID_INVALID}; + std::shared_ptr m_funcPeerEvent{}; + std::unordered_map> m_peers{}; + PeerId m_nextPeerId{1}; + std::unordered_map, std::unordered_map>>> m_sessionEntityToPeerId{}; + mutable std::mutex m_mutex{}; }; typedef std::shared_ptr PeerManagerPtr; - - - class RequestContext : public std::enable_shared_from_this { public: inline RequestContext(const PeerManagerPtr& sessionIdEntityIdToPeerId, EntityId entityIdSrc, ReceiveData& receiveData) - : m_peerManager(sessionIdEntityIdToPeerId) - , m_session(receiveData.session) - , m_virtualSessionId(std::move(receiveData.virtualSessionId)) - , m_entityIdDest(receiveData.header.srcid) - , m_entityIdSrc(entityIdSrc) - , m_correlationId(receiveData.header.corrid) - , m_replySent(false) - , m_metainfo(std::move(receiveData.message->getAllMetainfo())) - , m_echoData(std::move(receiveData.message->getEchoData())) + : m_peerManager(sessionIdEntityIdToPeerId), m_session(receiveData.session), m_virtualSessionId(std::move(receiveData.virtualSessionId)), m_entityIdDest(receiveData.header.srcid), m_entityIdSrc(entityIdSrc), m_correlationId(receiveData.header.corrid), m_replySent(false), m_metainfo(std::move(receiveData.message->getAllMetainfo())), m_echoData(std::move(receiveData.message->getEchoData())) { } @@ -178,7 +156,7 @@ class RequestContext : public std::enable_shared_from_this { if (!m_replySent) { - Header header{ m_entityIdDest, "", m_entityIdSrc, MsgMode::MSG_REPLY, Status::STATUS_OK, {}, structBase.getStructInfo().getTypeName(), m_correlationId, {} }; + Header header{m_entityIdDest, "", m_entityIdSrc, MsgMode::MSG_REPLY, Status::STATUS_OK, {}, structBase.getStructInfo().getTypeName(), m_correlationId, {}}; RemoteEntityFormatRegistry::instance().send(m_session.getSession(), m_virtualSessionId, header, std::move(m_echoData), &structBase, metainfo); m_replySent = true; } @@ -188,7 +166,7 @@ class RequestContext : public std::enable_shared_from_this { if (!m_replySent) { - Header header{ m_entityIdDest, "", m_entityIdSrc, MsgMode::MSG_REPLY, Status::STATUS_OK, {}, {}, m_correlationId, {} }; + Header header{m_entityIdDest, "", m_entityIdSrc, MsgMode::MSG_REPLY, Status::STATUS_OK, {}, {}, m_correlationId, {}}; RemoteEntityFormatRegistry::instance().send(m_session.getSession(), m_virtualSessionId, header, std::move(m_echoData), nullptr, metainfo, &controlData); m_replySent = true; } @@ -198,7 +176,7 @@ class RequestContext : public std::enable_shared_from_this { if (!m_replySent) { - Header header{ m_entityIdDest, "", m_entityIdSrc, MsgMode::MSG_REPLY, status, {}, {}, m_correlationId, {} }; + Header header{m_entityIdDest, "", m_entityIdSrc, MsgMode::MSG_REPLY, status, {}, {}, m_correlationId, {}}; RemoteEntityFormatRegistry::instance().send(m_session.getSession(), m_virtualSessionId, header, std::move(m_echoData)); m_replySent = true; } @@ -214,7 +192,7 @@ class RequestContext : public std::enable_shared_from_this { RawBytes replyBytes; replyBytes.data.resize(size); - memcpy(const_cast(replyBytes.data.data()), buffer, size); + memcpy(replyBytes.data.data(), buffer, size); reply(replyBytes, metainfo); } @@ -258,33 +236,27 @@ class RequestContext : public std::enable_shared_from_this } private: - RequestContext(const RequestContext&) = delete; - const RequestContext& operator =(const RequestContext&) = delete; + const RequestContext& operator=(const RequestContext&) = delete; RequestContext(const RequestContext&&) = delete; - const RequestContext& operator =(const RequestContext&&) = delete; + const RequestContext& operator=(const RequestContext&&) = delete; + private: - PeerManagerPtr m_peerManager; - SessionInfo m_session; - std::string m_virtualSessionId; - EntityId m_entityIdDest = ENTITYID_INVALID; - EntityId m_entityIdSrc = ENTITYID_INVALID; - CorrelationId m_correlationId = CORRELATIONID_NONE; - PeerId m_peerId = PEERID_INVALID; - bool m_replySent = false; - IMessage::Metainfo m_metainfo; - Variant m_echoData; + PeerManagerPtr m_peerManager; + SessionInfo m_session; + std::string m_virtualSessionId; + EntityId m_entityIdDest = ENTITYID_INVALID; + EntityId m_entityIdSrc = ENTITYID_INVALID; + CorrelationId m_correlationId = CORRELATIONID_NONE; + PeerId m_peerId = PEERID_INVALID; + bool m_replySent = false; + IMessage::Metainfo m_metainfo; + Variant m_echoData; friend class RemoteEntity; }; - - - - - -class SYMBOLEXP RemoteEntity : public IRemoteEntity - , private std::enable_shared_from_this +class SYMBOLEXP RemoteEntity : public IRemoteEntity, private std::enable_shared_from_this { public: RemoteEntity(); @@ -338,12 +310,12 @@ class SYMBOLEXP RemoteEntity : public IRemoteEntity struct Function { - std::string type; - std::shared_ptr func; + std::string type{}; + std::shared_ptr func{}; }; struct FunctionVar : public Function { - std::vector pathEntries; + std::vector pathEntries{}; }; const Function* getFunction(const std::string& path, IMessage::Metainfo* keys = nullptr) const; @@ -351,38 +323,32 @@ class SYMBOLEXP RemoteEntity : public IRemoteEntity struct Request { inline Request(PeerId peerId_, const std::shared_ptr& func_) - : peerId(peerId_) - , func(func_) + : peerId(peerId_), func(func_) { } inline Request(PeerId peerId_, const std::shared_ptr& func_) - : peerId(peerId_) - , funcMeta(func_) + : peerId(peerId_), funcMeta(func_) { } - PeerId peerId = PEERID_INVALID; - std::shared_ptr func; - std::shared_ptr funcMeta; + PeerId peerId = PEERID_INVALID; + std::shared_ptr func{}; + std::shared_ptr funcMeta{}; }; - - const EntityId m_entityId{ ENTITYID_INVALID }; - static std::atomic m_entityIdNext; - - std::vector m_funcsReplyEvent; - std::atomic_int64_t m_funcsReplyEventChanged = {}; - std::unordered_map> m_requests; - std::unordered_map m_funcCommandsStatic; - std::list m_funcCommandsVar; - std::list m_funcCommandsVarStar; - const std::shared_ptr m_peerManager; - mutable std::atomic_uint64_t m_nextCorrelationId{1}; - mutable std::mutex m_mutex; - mutable std::mutex m_mutexRequests; - mutable std::mutex m_mutexFunctions; + const EntityId m_entityId{ENTITYID_INVALID}; + static std::atomic m_entityIdNext; + + std::vector m_funcsReplyEvent{}; + std::atomic_int64_t m_funcsReplyEventChanged = {}; + std::unordered_map> m_requests{}; + std::unordered_map m_funcCommandsStatic{}; + std::list m_funcCommandsVar{}; + std::list m_funcCommandsVarStar{}; + const std::shared_ptr m_peerManager{}; + mutable std::atomic_uint64_t m_nextCorrelationId{1}; + mutable std::mutex m_mutex{}; + mutable std::mutex m_mutexRequests{}; + mutable std::mutex m_mutexFunctions{}; }; - - - -} // namespace finalmq +} // namespace finalmq diff --git a/inc/finalmq/remoteentity/RemoteEntityContainer.h b/inc/finalmq/remoteentity/RemoteEntityContainer.h index f11d9399..3cb0e9e8 100644 --- a/inc/finalmq/remoteentity/RemoteEntityContainer.h +++ b/inc/finalmq/remoteentity/RemoteEntityContainer.h @@ -22,16 +22,16 @@ #pragma once -#include "finalmq/remoteentity/RemoteEntity.h" #include "finalmq/remoteentity/FileTransferReply.h" +#include "finalmq/remoteentity/RemoteEntity.h" - -namespace finalmq { - +namespace finalmq +{ class SYMBOLEXP ConnectionEvent { public: - enum Enum : std::int32_t { + enum Enum : std::int32_t + { CONNECTIONEVENT_CONNECTED = 0, CONNECTIONEVENT_DISCONNECTED = 1, CONNECTIONEVENT_SOCKET_CONNECTED = 2, @@ -42,7 +42,7 @@ class SYMBOLEXP ConnectionEvent ConnectionEvent(Enum en); operator const Enum&() const; operator Enum&(); - const ConnectionEvent& operator =(Enum en); + const ConnectionEvent& operator=(Enum en); const std::string& toName() const; const std::string& toString() const; void fromString(const std::string& name); @@ -52,16 +52,15 @@ class SYMBOLEXP ConnectionEvent static const EnumInfo _enumInfo; }; - typedef std::function FuncConnectionEvent; - struct IRemoteEntityContainer { /** * @brief ~IRemoteEntityContainer is the virtual destructor of the interface. */ - virtual ~IRemoteEntityContainer() {} + virtual ~IRemoteEntityContainer() + {} /** * @brief init initializes the instance. Call it once after constructing the object. @@ -177,13 +176,7 @@ struct IRemoteEntityContainer typedef std::shared_ptr IRemoteEntityContainerPtr; - - - - -class SYMBOLEXP RemoteEntityContainer : public IRemoteEntityContainer - , private IProtocolSessionCallback - , private std::enable_shared_from_this +class SYMBOLEXP RemoteEntityContainer : public IRemoteEntityContainer, private IProtocolSessionCallback, private std::enable_shared_from_this { public: RemoteEntityContainer(); @@ -199,7 +192,7 @@ class SYMBOLEXP RemoteEntityContainer : public IRemoteEntityContainer virtual IExecutorPtr getExecutor() const override; virtual EntityId registerEntity(hybrid_ptr remoteEntity, std::string name = "") override; -// virtual void addPureDataPaths(std::vector& paths) override; + // virtual void addPureDataPaths(std::vector& paths) override; virtual void unregisterEntity(EntityId entityId) override; virtual void registerConnectionEvent(FuncConnectionEvent funcConnectionEvent) override; @@ -219,25 +212,25 @@ class SYMBOLEXP RemoteEntityContainer : public IRemoteEntityContainer SessionInfo createSessionInfo(const IProtocolSessionPtr& session); inline void triggerConnectionEvent(const SessionInfo& session, ConnectionEvent connectionEvent) const; void deinit(); -// bool isPureDataPath(const std::string& path); + // bool isPureDataPath(const std::string& path); void subscribeEntityNames(const IProtocolSessionPtr& session); void subscribeSessions(std::string name); - const std::unique_ptr m_protocolSessionContainer; - std::unordered_map> m_name2entity; - std::unordered_map> m_entityId2entity; - std::unordered_map m_entityId2name; - std::shared_ptr m_funcConnectionEvent; - bool m_storeRawDataInReceiveStruct = false; -// std::list m_pureDataPaths; -// std::list m_pureDataPathPrefixes; - const IExecutorPtr m_executor; - - std::atomic_int64_t m_entitiesChanged = {}; - static std::atomic_uint64_t m_nextContainerId; - const std::uint64_t m_containerId; - - mutable std::mutex m_mutex; + const std::unique_ptr m_protocolSessionContainer{}; + std::unordered_map> m_name2entity{}; + std::unordered_map> m_entityId2entity{}; + std::unordered_map m_entityId2name{}; + std::shared_ptr m_funcConnectionEvent{}; + bool m_storeRawDataInReceiveStruct = false; + // std::list m_pureDataPaths{}; + // std::list m_pureDataPathPrefixes{}; + const IExecutorPtr m_executor; + + std::atomic_int64_t m_entitiesChanged = {}; + static std::atomic_uint64_t m_nextContainerId; + const std::uint64_t m_containerId{}; + + mutable std::mutex m_mutex{}; }; -} // namespace finalmq +} // namespace finalmq diff --git a/inc/finalmq/remoteentity/RemoteEntityFormatRegistry.h b/inc/finalmq/remoteentity/RemoteEntityFormatRegistry.h index adfda5ec..4adb2e9d 100644 --- a/inc/finalmq/remoteentity/RemoteEntityFormatRegistry.h +++ b/inc/finalmq/remoteentity/RemoteEntityFormatRegistry.h @@ -22,14 +22,14 @@ #pragma once -#include "finalmq/protocolsession/ProtocolSessionContainer.h" -#include "finalmq/remoteentity/IRemoteEntity.h" - -#include #include +#include -namespace finalmq { +#include "finalmq/protocolsession/ProtocolSessionContainer.h" +#include "finalmq/remoteentity/IRemoteEntity.h" +namespace finalmq +{ typedef std::shared_ptr IProtocolSessionPtr; class Header; @@ -42,20 +42,20 @@ enum FormatStatus FORMATSTATUS_HEADER_PARSED_BY_FORMAT = 4, }; - struct IRemoteEntityFormat { - virtual ~IRemoteEntityFormat() {} + virtual ~IRemoteEntityFormat() + {} virtual std::shared_ptr parse(const IProtocolSessionPtr& session, const BufferRef& bufferRef, bool storeRawData, const std::unordered_map>& name2Entity, Header& header, int& formatStatus) = 0; virtual std::shared_ptr parseData(const IProtocolSessionPtr& session, const BufferRef& bufferRef, bool storeRawData, std::string& type, int& formatStatus) = 0; virtual void serialize(const IProtocolSessionPtr& session, IMessage& message, const Header& header, const StructBase* structBase = nullptr) = 0; virtual void serializeData(const IProtocolSessionPtr& session, IMessage& message, const StructBase* structBase = nullptr) = 0; }; - struct IRemoteEntityFormatRegistry { - virtual ~IRemoteEntityFormatRegistry() {} + virtual ~IRemoteEntityFormatRegistry() + {} virtual std::shared_ptr parse(const IProtocolSessionPtr& session, IMessage& message, bool storeRawData, const std::unordered_map>& name2Entity, Header& header, int& formatStatus) = 0; virtual std::shared_ptr parseHeaderInMetainfo(const IProtocolSessionPtr& session, IMessage& message, bool storeRawData, const std::unordered_map>& name2Entity, Header& header, int& formatStatus) = 0; virtual void send(const IProtocolSessionPtr& session, const std::string& virtualSessionId, Header& header, Variant&& echoData, const StructBase* structBase = nullptr, IMessage::Metainfo* metainfo = nullptr, Variant* controlData = nullptr) = 0; @@ -65,9 +65,6 @@ struct IRemoteEntityFormatRegistry virtual int getContentType(const std::string& contentTypeName) const = 0; }; - - - class RemoteEntityFormatRegistryImpl : public IRemoteEntityFormatRegistry { public: @@ -84,11 +81,10 @@ class RemoteEntityFormatRegistryImpl : public IRemoteEntityFormatRegistry bool serialize(const IProtocolSessionPtr& session, IMessage& message, const Header& header, const StructBase* structBase = nullptr); bool serializeData(const IProtocolSessionPtr& session, IMessage& message, const StructBase* structBase); - std::unordered_map> m_contentTypeToFormat; - std::unordered_map m_contentTypeNameToContentType; + std::unordered_map> m_contentTypeToFormat{}; + std::unordered_map m_contentTypeNameToContentType{}; }; - class SYMBOLEXP RemoteEntityFormatRegistry { public: @@ -118,8 +114,4 @@ class SYMBOLEXP RemoteEntityFormatRegistry static std::unique_ptr& getStaticUniquePtrRef(); }; - - - - -} // namespace finalmq +} // namespace finalmq diff --git a/inc/finalmq/serialize/ParserAbortAndIndex.h b/inc/finalmq/serialize/ParserAbortAndIndex.h index e8ddf646..6dc9c580 100644 --- a/inc/finalmq/serialize/ParserAbortAndIndex.h +++ b/inc/finalmq/serialize/ParserAbortAndIndex.h @@ -22,22 +22,25 @@ #pragma once -#include "finalmq/metadata/MetaStruct.h" -#include "finalmq/serialize/IParserVisitor.h" - #include +#include "finalmq/metadata/MetaStruct.h" +#include "finalmq/serialize/IParserVisitor.h" -namespace finalmq { - - +namespace finalmq +{ class SYMBOLEXP ParserAbortAndIndex : public IParserVisitor { public: ParserAbortAndIndex(IParserVisitor* visitor = nullptr); - void setVisitor(IParserVisitor &visitor); + void setVisitor(IParserVisitor& visitor); private: + ParserAbortAndIndex(const ParserAbortAndIndex&) = delete; + ParserAbortAndIndex(ParserAbortAndIndex&&) = delete; + const ParserAbortAndIndex& operator=(const ParserAbortAndIndex&) = delete; + const ParserAbortAndIndex& operator=(ParserAbortAndIndex&&) = delete; + // IParserVisitor virtual void notifyError(const char* str, const char* message) override; virtual void startStruct(const MetaStruct& stru) override; @@ -122,7 +125,7 @@ class SYMBOLEXP ParserAbortAndIndex : public IParserVisitor std::int32_t arrayStructCounter = -1; }; - std::deque m_levelState; + std::deque m_levelState{}; }; -} // namespace finalmq +} // namespace finalmq diff --git a/inc/finalmq/serialize/ParserConverter.h b/inc/finalmq/serialize/ParserConverter.h index 49051da6..a63d8568 100644 --- a/inc/finalmq/serialize/ParserConverter.h +++ b/inc/finalmq/serialize/ParserConverter.h @@ -25,10 +25,8 @@ #include "finalmq/metadata/MetaStruct.h" #include "finalmq/serialize/IParserVisitor.h" -namespace finalmq { - - - +namespace finalmq +{ class SYMBOLEXP ParserConverter : public IParserVisitor { public: @@ -36,6 +34,11 @@ class SYMBOLEXP ParserConverter : public IParserVisitor void setVisitor(IParserVisitor& visitor); private: + ParserConverter(const ParserConverter&) = delete; + ParserConverter(ParserConverter&&) = delete; + const ParserConverter& operator=(const ParserConverter&) = delete; + const ParserConverter& operator=(ParserConverter&&) = delete; + // IParserVisitor virtual void notifyError(const char* str, const char* message) override; virtual void startStruct(const MetaStruct& stru) override; @@ -106,8 +109,7 @@ class SYMBOLEXP ParserConverter : public IParserVisitor void convertString(const MetaField& field, const char* value, ssize_t size); void convertArraytString(const MetaField& field, const std::vector& value); - IParserVisitor* m_visitor = nullptr; + IParserVisitor* m_visitor = nullptr; }; -} // namespace finalmq - +} // namespace finalmq diff --git a/inc/finalmq/serialize/ParserProcessDefaultValues.h b/inc/finalmq/serialize/ParserProcessDefaultValues.h index 218028c6..3ceee318 100644 --- a/inc/finalmq/serialize/ParserProcessDefaultValues.h +++ b/inc/finalmq/serialize/ParserProcessDefaultValues.h @@ -22,23 +22,26 @@ #pragma once -#include "finalmq/metadata/MetaStruct.h" -#include "finalmq/serialize/IParserVisitor.h" - #include +#include "finalmq/metadata/MetaStruct.h" +#include "finalmq/serialize/IParserVisitor.h" -namespace finalmq { - - +namespace finalmq +{ class SYMBOLEXP ParserProcessDefaultValues : public IParserVisitor { public: ParserProcessDefaultValues(bool skipDefaultValues, IParserVisitor* visitor = nullptr); - void setVisitor(IParserVisitor &visitor); + void setVisitor(IParserVisitor& visitor); void resetVarValueActive(); private: + ParserProcessDefaultValues(const ParserProcessDefaultValues&) = delete; + ParserProcessDefaultValues(ParserProcessDefaultValues&&) = delete; + const ParserProcessDefaultValues& operator=(const ParserProcessDefaultValues&) = delete; + const ParserProcessDefaultValues& operator=(ParserProcessDefaultValues&&) = delete; + // IParserVisitor virtual void notifyError(const char* str, const char* message) override; virtual void startStruct(const MetaStruct& stru) override; @@ -107,11 +110,7 @@ class SYMBOLEXP ParserProcessDefaultValues : public IParserVisitor { public: EntrySkipDefault(const MetaField* field, bool enterStructCalled) - : m_field(field) - , m_fieldArrayStruct(nullptr) - , m_enterArrayStructCalled(false) - , m_countMember(0) - , m_enterStructCalled(enterStructCalled) + : m_field(field), m_fieldArrayStruct(nullptr), m_enterArrayStructCalled(false), m_countMember(0), m_enterStructCalled(enterStructCalled) { } @@ -148,12 +147,12 @@ class SYMBOLEXP ParserProcessDefaultValues : public IParserVisitor bool m_enterStructCalled; }; - IParserVisitor* m_visitor = nullptr; - bool m_skipDefaultValues = true; - const MetaStruct* m_struct = nullptr; - std::deque> m_stackFieldsDone; - int m_varValueActive = 0; - std::deque m_stackSkipDefault; + IParserVisitor* m_visitor{nullptr}; + bool m_skipDefaultValues{true}; + const MetaStruct* m_struct{nullptr}; + std::deque> m_stackFieldsDone{}; + int m_varValueActive{0}; + std::deque m_stackSkipDefault{}; }; -} // namespace finalmq +} // namespace finalmq diff --git a/inc/finalmq/serialize/ParserProcessValuesInOrder.h b/inc/finalmq/serialize/ParserProcessValuesInOrder.h index bf125085..a7b638f4 100644 --- a/inc/finalmq/serialize/ParserProcessValuesInOrder.h +++ b/inc/finalmq/serialize/ParserProcessValuesInOrder.h @@ -22,24 +22,27 @@ #pragma once -#include "finalmq/metadata/MetaStruct.h" -#include "finalmq/serialize/IParserVisitor.h" - #include -#include #include +#include +#include "finalmq/metadata/MetaStruct.h" +#include "finalmq/serialize/IParserVisitor.h" -namespace finalmq { - - +namespace finalmq +{ class SYMBOLEXP ParserProcessValuesInOrder : public IParserVisitor { public: ParserProcessValuesInOrder(IParserVisitor* visitor = nullptr); - void setVisitor(IParserVisitor &visitor); + void setVisitor(IParserVisitor& visitor); private: + ParserProcessValuesInOrder(const ParserProcessValuesInOrder&) = delete; + ParserProcessValuesInOrder(ParserProcessValuesInOrder&&) = delete; + const ParserProcessValuesInOrder& operator=(const ParserProcessValuesInOrder&) = delete; + const ParserProcessValuesInOrder& operator=(ParserProcessValuesInOrder&&) = delete; + // IParserVisitor virtual void notifyError(const char* str, const char* message) override; virtual void startStruct(const MetaStruct& stru) override; @@ -100,7 +103,6 @@ class SYMBOLEXP ParserProcessValuesInOrder : public IParserVisitor virtual void enterArrayEnumMove(const MetaField& field, std::vector&& value) override; virtual void enterArrayEnum(const MetaField& field, const std::vector& value) override; - struct CallNode { std::vector> calls; @@ -110,7 +112,7 @@ class SYMBOLEXP ParserProcessValuesInOrder : public IParserVisitor IParserVisitor* m_visitor; CallNode* m_currentCalls = nullptr; - std::deque m_stackCalls; + std::deque m_stackCalls{}; }; -} // namespace finalmq +} // namespace finalmq diff --git a/inc/finalmq/serializehl7/ParserHl7.h b/inc/finalmq/serializehl7/ParserHl7.h index 4aafc96d..db075adf 100644 --- a/inc/finalmq/serializehl7/ParserHl7.h +++ b/inc/finalmq/serializehl7/ParserHl7.h @@ -22,16 +22,15 @@ #pragma once -#include "finalmq/metadata/MetaStruct.h" -#include "finalmq/serialize/IParserVisitor.h" -#include "finalmq/hl7/Hl7Parser.h" - - -#include #include +#include -namespace finalmq { +#include "finalmq/hl7/Hl7Parser.h" +#include "finalmq/metadata/MetaStruct.h" +#include "finalmq/serialize/IParserVisitor.h" +namespace finalmq +{ class SYMBOLEXP ParserHl7 { public: @@ -40,16 +39,20 @@ class SYMBOLEXP ParserHl7 const char* parseStruct(const std::string& typeName); private: + ParserHl7(const ParserHl7&) = delete; + ParserHl7(ParserHl7&&) = delete; + const ParserHl7& operator=(const ParserHl7&) = delete; + const ParserHl7& operator=(ParserHl7&&) = delete; + int parseStruct(int levelSegment, const MetaStruct& stru, bool& isarray); bool matches(const std::string& segId, const MetaStruct& stru, ssize_t ixStart); bool matchesUp(const std::string& segId); - - const char* m_ptr = nullptr; - ssize_t m_size = 0; - IParserVisitor& m_visitor; - Hl7Parser m_parser; - std::vector> m_stackStruct; + const char* m_ptr = nullptr; + ssize_t m_size = 0; + IParserVisitor& m_visitor; + Hl7Parser m_parser{}; + std::vector> m_stackStruct{}; }; -} // namespace finalmq +} // namespace finalmq diff --git a/inc/finalmq/serializehl7/SerializerHl7.h b/inc/finalmq/serializehl7/SerializerHl7.h index 91b1b89d..04698af6 100644 --- a/inc/finalmq/serializehl7/SerializerHl7.h +++ b/inc/finalmq/serializehl7/SerializerHl7.h @@ -22,14 +22,14 @@ #pragma once -#include "finalmq/metadata/MetaStruct.h" #include "finalmq/helpers/IZeroCopyBuffer.h" +#include "finalmq/hl7/Hl7Builder.h" +#include "finalmq/metadata/MetaStruct.h" #include "finalmq/serialize/IParserVisitor.h" #include "finalmq/serialize/ParserProcessDefaultValues.h" -#include "finalmq/hl7/Hl7Builder.h" - -namespace finalmq { +namespace finalmq +{ class SYMBOLEXP SerializerHl7 : public ParserProcessDefaultValues { public: @@ -40,6 +40,7 @@ class SYMBOLEXP SerializerHl7 : public ParserProcessDefaultValues { public: Internal(IZeroCopyBuffer& buffer, int maxBlockSize); + private: // IParserVisitor virtual void notifyError(const char* str, const char* message) override; @@ -105,16 +106,16 @@ class SYMBOLEXP SerializerHl7 : public ParserProcessDefaultValues static const int NO_ARRAY_STRUCT = -2; - std::unique_ptr m_uniqueHl7Builder; - IHl7BuilderVisitor& m_hl7Builder; + std::unique_ptr m_uniqueHl7Builder{}; + IHl7BuilderVisitor& m_hl7Builder; - bool m_inSegment = false; + bool m_inSegment = false; - std::vector m_indexOfLayer; - int m_ixArrayStruct = NO_ARRAY_STRUCT; + std::vector m_indexOfLayer{}; + int m_ixArrayStruct = NO_ARRAY_STRUCT; }; - Internal m_internal; + Internal m_internal; }; -} // namespace finalmq +} // namespace finalmq diff --git a/inc/finalmq/serializejson/ParserJson.h b/inc/finalmq/serializejson/ParserJson.h index 640c7599..d1cad486 100644 --- a/inc/finalmq/serializejson/ParserJson.h +++ b/inc/finalmq/serializejson/ParserJson.h @@ -22,16 +22,15 @@ #pragma once -#include "finalmq/metadata/MetaStruct.h" -#include "finalmq/serialize/IParserVisitor.h" -#include "finalmq/json/JsonParser.h" - - -#include #include +#include -namespace finalmq { +#include "finalmq/json/JsonParser.h" +#include "finalmq/metadata/MetaStruct.h" +#include "finalmq/serialize/IParserVisitor.h" +namespace finalmq +{ class SYMBOLEXP ParserJson : public IJsonParserVisitor { public: @@ -40,6 +39,11 @@ class SYMBOLEXP ParserJson : public IJsonParserVisitor const char* parseStruct(const std::string& typeName); private: + ParserJson(const ParserJson&) = delete; + ParserJson(ParserJson&&) = delete; + const ParserJson& operator=(const ParserJson&) = delete; + const ParserJson& operator=(ParserJson&&) = delete; + // IJsonParserVisitor virtual void syntaxError(const char* str, const char* message) override; virtual void enterNull() override; @@ -59,34 +63,33 @@ class SYMBOLEXP ParserJson : public IJsonParserVisitor virtual void enterKey(std::string&& key) override; virtual void finished() override; - template void enterNumber(T value); - template< class T> + template T convert(const char* value, ssize_t size); - const char* m_ptr = nullptr; - ssize_t m_size = 0; - IParserVisitor& m_visitor; - JsonParser m_parser; - - std::deque m_stack; - const MetaStruct* m_structCurrent = nullptr; - const MetaField* m_fieldCurrent = nullptr; - - std::vector m_arrayBool; - std::vector m_arrayInt8; - std::vector m_arrayInt16; - std::vector m_arrayUInt16; - std::vector m_arrayInt32; - std::vector m_arrayUInt32; - std::vector m_arrayInt64; - std::vector m_arrayUInt64; - std::vector m_arrayFloat; - std::vector m_arrayDouble; - std::vector m_arrayString; - std::vector m_arrayBytes; + const char* m_ptr = nullptr; + ssize_t m_size = 0; + IParserVisitor& m_visitor; + JsonParser m_parser; + + std::deque m_stack{}; + const MetaStruct* m_structCurrent = nullptr; + const MetaField* m_fieldCurrent = nullptr; + + std::vector m_arrayBool{}; + std::vector m_arrayInt8{}; + std::vector m_arrayInt16{}; + std::vector m_arrayUInt16{}; + std::vector m_arrayInt32{}; + std::vector m_arrayUInt32{}; + std::vector m_arrayInt64{}; + std::vector m_arrayUInt64{}; + std::vector m_arrayFloat{}; + std::vector m_arrayDouble{}; + std::vector m_arrayString{}; + std::vector m_arrayBytes{}; }; -} // namespace finalmq +} // namespace finalmq diff --git a/inc/finalmq/serializeproto/SerializerProto.h b/inc/finalmq/serializeproto/SerializerProto.h index ccc43958..20479980 100644 --- a/inc/finalmq/serializeproto/SerializerProto.h +++ b/inc/finalmq/serializeproto/SerializerProto.h @@ -22,14 +22,14 @@ #pragma once -#include "finalmq/metadata/MetaStruct.h" -#include "finalmq/helpers/IZeroCopyBuffer.h" -#include "finalmq/serialize/ParserConverter.h" - #include -namespace finalmq { +#include "finalmq/helpers/IZeroCopyBuffer.h" +#include "finalmq/metadata/MetaStruct.h" +#include "finalmq/serialize/ParserConverter.h" +namespace finalmq +{ class SYMBOLEXP SerializerProto : public ParserConverter { public: @@ -50,7 +50,13 @@ class SYMBOLEXP SerializerProto : public ParserConverter { public: Internal(IZeroCopyBuffer& buffer, int maxBlockSize); + private: + Internal(const Internal&) = delete; + Internal(Internal&&) = delete; + const Internal& operator=(const Internal&) = delete; + const Internal& operator=(Internal&&) = delete; + // IParserVisitor virtual void notifyError(const char* str, const char* message) override; virtual void startStruct(const MetaStruct& stru) override; @@ -147,33 +153,30 @@ class SYMBOLEXP SerializerProto : public ParserConverter struct StructData { StructData(char* bstart, char* bsize, char* b, bool ae) - : bufferStructStart(bstart) - , bufferStructSize(bsize) - , buffer(b) - , arrayEntry(ae) + : bufferStructStart(bstart), bufferStructSize(bsize), buffer(b), arrayEntry(ae) { } - char* bufferStructStart = nullptr; - char* bufferStructSize = nullptr; - char* buffer = nullptr; + char* bufferStructStart = nullptr; + char* bufferStructSize = nullptr; + char* buffer = nullptr; ssize_t size = 0; - bool allocateNextDataBuffer = false; - bool arrayParent = false; - bool arrayEntry = false; + bool allocateNextDataBuffer = false; + bool arrayParent = false; + bool arrayEntry = false; }; - IZeroCopyBuffer& m_zeroCopybuffer; - ssize_t m_maxBlockSize = 512; - char* m_bufferStart = nullptr; - char* m_buffer = nullptr; - char* m_bufferEnd = nullptr; - bool m_arrayParent = false; - std::deque m_stackStruct; + IZeroCopyBuffer& m_zeroCopybuffer; + ssize_t m_maxBlockSize = 512; + char* m_bufferStart = nullptr; + char* m_buffer = nullptr; + char* m_bufferEnd = nullptr; + bool m_arrayParent = false; + std::deque m_stackStruct{}; }; - Internal m_internal; + Internal m_internal; - std::unique_ptr m_parserAbortAndIndex; + std::unique_ptr m_parserAbortAndIndex; }; -} // namespace finalmq +} // namespace finalmq diff --git a/inc/finalmq/serializeqt/SerializerQt.h b/inc/finalmq/serializeqt/SerializerQt.h index 4e3c73e4..a2afac65 100644 --- a/inc/finalmq/serializeqt/SerializerQt.h +++ b/inc/finalmq/serializeqt/SerializerQt.h @@ -22,145 +22,151 @@ #pragma once -#include "finalmq/metadata/MetaStruct.h" +#include + #include "finalmq/helpers/IZeroCopyBuffer.h" +#include "finalmq/metadata/MetaStruct.h" #include "finalmq/serialize/IParserVisitor.h" #include "finalmq/serialize/ParserConverter.h" -#include +namespace finalmq +{ +class SYMBOLEXP SerializerQt : public ParserConverter +{ +public: + enum class Mode + { + NONE, + WRAPPED_BY_QVARIANTLIST, + WRAPPED_BY_QVARIANT, + }; -namespace finalmq { + SerializerQt(IZeroCopyBuffer& buffer, Mode mode = Mode::NONE, int maxBlockSize = 512); - class SYMBOLEXP SerializerQt : public ParserConverter +private: + class Internal : public IParserVisitor { public: - enum class Mode - { - NONE, - WRAPPED_BY_QVARIANTLIST, - WRAPPED_BY_QVARIANT, - }; - - SerializerQt(IZeroCopyBuffer& buffer, Mode mode = Mode::NONE, int maxBlockSize = 512); + Internal(IZeroCopyBuffer& buffer, int maxBlockSize, Mode mode); private: - class Internal : public IParserVisitor + Internal(const Internal&) = delete; + Internal(Internal&&) = delete; + const Internal& operator=(const Internal&) = delete; + const Internal& operator=(Internal&&) = delete; + + // IParserVisitor + virtual void notifyError(const char* str, const char* message) override; + virtual void startStruct(const MetaStruct& stru) override; + virtual void finished() override; + + virtual void enterStruct(const MetaField& field) override; + virtual void exitStruct(const MetaField& field) override; + virtual void enterStructNull(const MetaField& field) override; + + virtual void enterArrayStruct(const MetaField& field) override; + virtual void exitArrayStruct(const MetaField& field) override; + + virtual void enterBool(const MetaField& field, bool value) override; + virtual void enterInt8(const MetaField& field, std::int8_t value) override; + virtual void enterUInt8(const MetaField& field, std::uint8_t value) override; + virtual void enterInt16(const MetaField& field, std::int16_t value) override; + virtual void enterUInt16(const MetaField& field, std::uint16_t value) override; + virtual void enterInt32(const MetaField& field, std::int32_t value) override; + virtual void enterUInt32(const MetaField& field, std::uint32_t value) override; + virtual void enterInt64(const MetaField& field, std::int64_t value) override; + virtual void enterUInt64(const MetaField& field, std::uint64_t value) override; + virtual void enterFloat(const MetaField& field, float value) override; + virtual void enterDouble(const MetaField& field, double value) override; + virtual void enterString(const MetaField& field, std::string&& value) override; + virtual void enterString(const MetaField& field, const char* value, ssize_t size) override; + virtual void enterBytes(const MetaField& field, Bytes&& value) override; + virtual void enterBytes(const MetaField& field, const BytesElement* value, ssize_t size) override; + virtual void enterEnum(const MetaField& field, std::int32_t value) override; + virtual void enterEnum(const MetaField& field, std::string&& value) override; + virtual void enterEnum(const MetaField& field, const char* value, ssize_t size) override; + + virtual void enterArrayBoolMove(const MetaField& field, std::vector&& value) override; + virtual void enterArrayBool(const MetaField& field, const std::vector& value) override; + virtual void enterArrayInt8(const MetaField& field, std::vector&& value) override; + virtual void enterArrayInt8(const MetaField& field, const std::int8_t* value, ssize_t size) override; + virtual void enterArrayInt16(const MetaField& field, std::vector&& value) override; + virtual void enterArrayInt16(const MetaField& field, const std::int16_t* value, ssize_t size) override; + virtual void enterArrayUInt16(const MetaField& field, std::vector&& value) override; + virtual void enterArrayUInt16(const MetaField& field, const std::uint16_t* value, ssize_t size) override; + virtual void enterArrayInt32(const MetaField& field, std::vector&& value) override; + virtual void enterArrayInt32(const MetaField& field, const std::int32_t* value, ssize_t size) override; + virtual void enterArrayUInt32(const MetaField& field, std::vector&& value) override; + virtual void enterArrayUInt32(const MetaField& field, const std::uint32_t* value, ssize_t size) override; + virtual void enterArrayInt64(const MetaField& field, std::vector&& value) override; + virtual void enterArrayInt64(const MetaField& field, const std::int64_t* value, ssize_t size) override; + virtual void enterArrayUInt64(const MetaField& field, std::vector&& value) override; + virtual void enterArrayUInt64(const MetaField& field, const std::uint64_t* value, ssize_t size) override; + virtual void enterArrayFloat(const MetaField& field, std::vector&& value) override; + virtual void enterArrayFloat(const MetaField& field, const float* value, ssize_t size) override; + virtual void enterArrayDouble(const MetaField& field, std::vector&& value) override; + virtual void enterArrayDouble(const MetaField& field, const double* value, ssize_t size) override; + virtual void enterArrayStringMove(const MetaField& field, std::vector&& value) override; + virtual void enterArrayString(const MetaField& field, const std::vector& value) override; + virtual void enterArrayBytesMove(const MetaField& field, std::vector&& value) override; + virtual void enterArrayBytes(const MetaField& field, const std::vector& value) override; + virtual void enterArrayEnum(const MetaField& field, std::vector&& value) override; + virtual void enterArrayEnum(const MetaField& field, const std::int32_t* value, ssize_t size) override; + virtual void enterArrayEnumMove(const MetaField& field, std::vector&& value) override; + virtual void enterArrayEnum(const MetaField& field, const std::vector& value) override; + + void serialize(char value); + void serialize(std::int8_t value); + void serialize(std::uint8_t value); + void serialize(std::int16_t value); + void serialize(std::uint16_t value); + void serialize(std::int32_t value); + void serialize(std::uint32_t value); + void serialize(std::int64_t value); + void serialize(std::uint64_t value); + void serialize(float value); + void serialize(double value); + + void serializeString(const std::string& value); + void serializeString(const char* value, ssize_t size); + + template + void serialize(const T* value, ssize_t size, bool sizeTimesTwo = false); + + void serializeArrayBool(const std::vector& value); + void serializeArrayString(const std::vector& value); + void serializeArrayBytes(const std::vector& value); + + void serializeQVariantHeader(const MetaField& field); + bool isWrappedByQVariant() const; + static bool getQVariantTypeFromMetaTypeId(const MetaField& field, std::uint32_t& typeId, std::string& typeName); + static std::uint32_t getTypeIdByName(const std::string& typeName); + static void getQVariantType(const MetaField& field, std::uint32_t& typeId, std::string& typeName); + + void reserveSpace(ssize_t space); + void resizeBuffer(); + + IZeroCopyBuffer& m_zeroCopybuffer; + ssize_t m_maxBlockSize = 512; + char* m_bufferStart = nullptr; + char* m_buffer = nullptr; + char* m_bufferEnd = nullptr; + + const Mode m_mode = Mode::NONE; + + struct LevelState { - public: - Internal(IZeroCopyBuffer& buffer, int maxBlockSize, Mode mode); - private: - // IParserVisitor - virtual void notifyError(const char* str, const char* message) override; - virtual void startStruct(const MetaStruct& stru) override; - virtual void finished() override; - - virtual void enterStruct(const MetaField& field) override; - virtual void exitStruct(const MetaField& field) override; - virtual void enterStructNull(const MetaField& field) override; - - virtual void enterArrayStruct(const MetaField& field) override; - virtual void exitArrayStruct(const MetaField& field) override; - - virtual void enterBool(const MetaField& field, bool value) override; - virtual void enterInt8(const MetaField& field, std::int8_t value) override; - virtual void enterUInt8(const MetaField& field, std::uint8_t value) override; - virtual void enterInt16(const MetaField& field, std::int16_t value) override; - virtual void enterUInt16(const MetaField& field, std::uint16_t value) override; - virtual void enterInt32(const MetaField& field, std::int32_t value) override; - virtual void enterUInt32(const MetaField& field, std::uint32_t value) override; - virtual void enterInt64(const MetaField& field, std::int64_t value) override; - virtual void enterUInt64(const MetaField& field, std::uint64_t value) override; - virtual void enterFloat(const MetaField& field, float value) override; - virtual void enterDouble(const MetaField& field, double value) override; - virtual void enterString(const MetaField& field, std::string&& value) override; - virtual void enterString(const MetaField& field, const char* value, ssize_t size) override; - virtual void enterBytes(const MetaField& field, Bytes&& value) override; - virtual void enterBytes(const MetaField& field, const BytesElement* value, ssize_t size) override; - virtual void enterEnum(const MetaField& field, std::int32_t value) override; - virtual void enterEnum(const MetaField& field, std::string&& value) override; - virtual void enterEnum(const MetaField& field, const char* value, ssize_t size) override; - - virtual void enterArrayBoolMove(const MetaField& field, std::vector&& value) override; - virtual void enterArrayBool(const MetaField& field, const std::vector& value) override; - virtual void enterArrayInt8(const MetaField& field, std::vector&& value) override; - virtual void enterArrayInt8(const MetaField& field, const std::int8_t* value, ssize_t size) override; - virtual void enterArrayInt16(const MetaField& field, std::vector&& value) override; - virtual void enterArrayInt16(const MetaField& field, const std::int16_t* value, ssize_t size) override; - virtual void enterArrayUInt16(const MetaField& field, std::vector&& value) override; - virtual void enterArrayUInt16(const MetaField& field, const std::uint16_t* value, ssize_t size) override; - virtual void enterArrayInt32(const MetaField& field, std::vector&& value) override; - virtual void enterArrayInt32(const MetaField& field, const std::int32_t* value, ssize_t size) override; - virtual void enterArrayUInt32(const MetaField& field, std::vector&& value) override; - virtual void enterArrayUInt32(const MetaField& field, const std::uint32_t* value, ssize_t size) override; - virtual void enterArrayInt64(const MetaField& field, std::vector&& value) override; - virtual void enterArrayInt64(const MetaField& field, const std::int64_t* value, ssize_t size) override; - virtual void enterArrayUInt64(const MetaField& field, std::vector&& value) override; - virtual void enterArrayUInt64(const MetaField& field, const std::uint64_t* value, ssize_t size) override; - virtual void enterArrayFloat(const MetaField& field, std::vector&& value) override; - virtual void enterArrayFloat(const MetaField& field, const float* value, ssize_t size) override; - virtual void enterArrayDouble(const MetaField& field, std::vector&& value) override; - virtual void enterArrayDouble(const MetaField& field, const double* value, ssize_t size) override; - virtual void enterArrayStringMove(const MetaField& field, std::vector&& value) override; - virtual void enterArrayString(const MetaField& field, const std::vector& value) override; - virtual void enterArrayBytesMove(const MetaField& field, std::vector&& value) override; - virtual void enterArrayBytes(const MetaField& field, const std::vector& value) override; - virtual void enterArrayEnum(const MetaField& field, std::vector&& value) override; - virtual void enterArrayEnum(const MetaField& field, const std::int32_t* value, ssize_t size) override; - virtual void enterArrayEnumMove(const MetaField& field, std::vector&& value) override; - virtual void enterArrayEnum(const MetaField& field, const std::vector& value) override; - - void serialize(char value); - void serialize(std::int8_t value); - void serialize(std::uint8_t value); - void serialize(std::int16_t value); - void serialize(std::uint16_t value); - void serialize(std::int32_t value); - void serialize(std::uint32_t value); - void serialize(std::int64_t value); - void serialize(std::uint64_t value); - void serialize(float value); - void serialize(double value); - - void serializeString(const std::string& value); - void serializeString(const char* value, ssize_t size); - - template - void serialize(const T* value, ssize_t size, bool sizeTimesTwo = false); - - void serializeArrayBool(const std::vector& value); - void serializeArrayString(const std::vector& value); - void serializeArrayBytes(const std::vector& value); - - void serializeQVariantHeader(const MetaField& field); - bool isWrappedByQVariant() const; - static bool getQVariantTypeFromMetaTypeId(const MetaField& field, std::uint32_t& typeId, std::string& typeName); - static std::uint32_t getTypeIdByName(const std::string& typeName); - static void getQVariantType(const MetaField& field, std::uint32_t& typeId, std::string& typeName); - - void reserveSpace(ssize_t space); - void resizeBuffer(); - - IZeroCopyBuffer& m_zeroCopybuffer; - ssize_t m_maxBlockSize = 512; - char* m_bufferStart = nullptr; - char* m_buffer = nullptr; - char* m_bufferEnd = nullptr; - - const Mode m_mode = Mode::NONE; - - struct LevelState - { - char* arrayStructCounterBuffer = nullptr; - std::int32_t arrayStructCounter = -1; - }; - - std::deque m_levelState; + char* arrayStructCounterBuffer = nullptr; + std::int32_t arrayStructCounter = -1; }; - Internal m_internal; - std::unique_ptr m_parserProcessDefaultValues; - std::unique_ptr m_parserAbortAndIndex; - std::unique_ptr m_parserProcessValuesInOrder; + std::deque m_levelState{}; }; -} // namespace finalmq + Internal m_internal; + std::unique_ptr m_parserProcessDefaultValues{}; + std::unique_ptr m_parserAbortAndIndex{}; + std::unique_ptr m_parserProcessValuesInOrder{}; +}; + +} // namespace finalmq diff --git a/inc/finalmq/serializestruct/SerializerStruct.h b/inc/finalmq/serializestruct/SerializerStruct.h index c99189ee..ca41c1ea 100644 --- a/inc/finalmq/serializestruct/SerializerStruct.h +++ b/inc/finalmq/serializestruct/SerializerStruct.h @@ -22,14 +22,14 @@ #pragma once -#include "finalmq/metadata/MetaStruct.h" -#include "finalmq/serialize/ParserConverter.h" -#include "StructBase.h" - #include -namespace finalmq { +#include "StructBase.h" +#include "finalmq/metadata/MetaStruct.h" +#include "finalmq/serialize/ParserConverter.h" +namespace finalmq +{ class VarValueToVariant; class SYMBOLEXP SerializerStruct : public IParserVisitor @@ -39,6 +39,11 @@ class SYMBOLEXP SerializerStruct : public IParserVisitor void setExitNotification(std::function funcExit); private: + SerializerStruct(const SerializerStruct&) = delete; + SerializerStruct(SerializerStruct&&) = delete; + const SerializerStruct& operator=(const SerializerStruct&) = delete; + const SerializerStruct& operator=(SerializerStruct&&) = delete; + // IParserVisitor virtual void notifyError(const char* str, const char* message) override; virtual void startStruct(const MetaStruct& stru) override; @@ -99,27 +104,27 @@ class SYMBOLEXP SerializerStruct : public IParserVisitor virtual void enterArrayEnumMove(const MetaField& field, std::vector&& value) override; virtual void enterArrayEnum(const MetaField& field, const std::vector& value) override; - template + template void setValue(StructBase& structBase, const FieldInfo& fieldInfoDest, const T& value); - template + template void setValue(StructBase& structBase, const FieldInfo& fieldInfoDest, T&& value); template void convertNumber(StructBase& structBase, const FieldInfo& fieldInfoDest, T value); - + void convertString(StructBase& structBase, const FieldInfo& fieldInfoDest, const char* value, ssize_t size); - + template void convertArrayNumber(StructBase& structBase, const FieldInfo& fieldInfoDest, const T* value, ssize_t size); - + void convertArrayString(StructBase& structBase, const FieldInfo& fieldInfoDest, const std::vector& value); - + template void setValueNumber(const MetaField& field, T value); void setValueString(const MetaField& field, const char* value, ssize_t size); - + template void setValueArrayNumber(const MetaField& field, const T* value, ssize_t size); template @@ -127,23 +132,23 @@ class SYMBOLEXP SerializerStruct : public IParserVisitor void setValueArrayString(const MetaField& field, const std::vector& value); void setValueArrayString(const MetaField& field, std::vector&& value); - + const FieldInfo* getFieldInfoDest(const MetaField& field); struct StackEntry { StructBase* structBase = nullptr; - ssize_t structArrayIndex = -1; + ssize_t structArrayIndex = -1; }; - StructBase& m_root; - StackEntry* m_current = nullptr; - std::deque m_stack; - std::function m_funcExit; - std::shared_ptr m_varValueToVariant; - bool m_wasStartStructCalled = false; - Variant m_variantDummy; - IParserVisitor* m_visitor = nullptr; + StructBase& m_root; + StackEntry* m_current = nullptr; + std::deque m_stack{}; + std::function m_funcExit{}; + std::shared_ptr m_varValueToVariant{}; + bool m_wasStartStructCalled = false; + Variant m_variantDummy{}; + IParserVisitor* m_visitor = nullptr; }; -} // namespace finalmq +} // namespace finalmq diff --git a/inc/finalmq/serializestruct/StructBase.h b/inc/finalmq/serializestruct/StructBase.h index f5e68ca8..c9a2e223 100644 --- a/inc/finalmq/serializestruct/StructBase.h +++ b/inc/finalmq/serializestruct/StructBase.h @@ -22,270 +22,259 @@ #pragma once -#include "finalmq/metadata/MetaField.h" -#include "finalmq/metadata/MetaEnum.h" -#include "finalmq/metadata/MetaStruct.h" -#include "finalmq/variant/Variant.h" - -#include #include +#include #include -#include - - -namespace finalmq { +#include - class StructBase; - typedef std::shared_ptr StructBasePtr; +#include "finalmq/metadata/MetaEnum.h" +#include "finalmq/metadata/MetaField.h" +#include "finalmq/metadata/MetaStruct.h" +#include "finalmq/variant/Variant.h" - struct IArrayStructAdapter +namespace finalmq +{ +class StructBase; +typedef std::shared_ptr StructBasePtr; + +struct IArrayStructAdapter +{ + virtual ~IArrayStructAdapter() + {} + virtual StructBase* add(char& array) = 0; + virtual ssize_t size(const char& array) const = 0; + virtual const StructBase& at(const char& array, ssize_t index) const = 0; +}; + +struct IStructPtrAdapter +{ + virtual ~IStructPtrAdapter() + {} + virtual StructBasePtr create() const = 0; +}; + +template +class ArrayStructAdapter : public IArrayStructAdapter +{ +private: + // IArrayStructAdapter + virtual StructBase* add(char& array) override { - virtual ~IArrayStructAdapter() {} - virtual StructBase* add(char& array) = 0; - virtual ssize_t size(const char& array) const = 0; - virtual const StructBase& at(const char& array, ssize_t index) const = 0; - }; + std::vector& vect = reinterpret_cast&>(array); + vect.resize(vect.size() + 1); + return &vect.back(); + } - struct IStructPtrAdapter + virtual ssize_t size(const char& array) const override { - virtual ~IStructPtrAdapter() {} - virtual StructBasePtr create() const = 0; - }; - + const std::vector& vect = reinterpret_cast&>(array); + return vect.size(); + } - template - class ArrayStructAdapter : public IArrayStructAdapter + virtual const StructBase& at(const char& array, ssize_t index) const override { - private: - // IArrayStructAdapter - virtual StructBase* add(char& array) override - { - std::vector& vect = reinterpret_cast&>(array); - vect.resize(vect.size() + 1); - return &vect.back(); - } - - virtual ssize_t size(const char& array) const override - { - const std::vector& vect = reinterpret_cast&>(array); - return vect.size(); - } - - virtual const StructBase& at(const char& array, ssize_t index) const override - { - const std::vector& vect = reinterpret_cast&>(array); - assert(index >= 0 && index < static_cast(vect.size())); - return vect[index]; - } - }; - - template - class StructPtrAdapter : public IStructPtrAdapter + const std::vector& vect = reinterpret_cast&>(array); + assert(index >= 0 && index < static_cast(vect.size())); + return vect[index]; + } +}; + +template +class StructPtrAdapter : public IStructPtrAdapter +{ +private: + // IStructPtrAdapter + virtual StructBasePtr create() const override { - private: - // IStructPtrAdapter - virtual StructBasePtr create() const override - { - return std::make_shared(); - } - }; + return std::make_shared(); + } +}; +class SYMBOLEXP FieldInfo +{ +public: + FieldInfo(int offset, IArrayStructAdapter* arrayStructAdapter = nullptr, IStructPtrAdapter* structPtrAdapter = nullptr); + void setField(const MetaField* field); - class SYMBOLEXP FieldInfo + inline const MetaField* getField() const { - public: - FieldInfo(int offset, IArrayStructAdapter* arrayStructAdapter = nullptr, IStructPtrAdapter* structPtrAdapter = nullptr); - void setField(const MetaField* field); - - inline const MetaField* getField() const - { - return m_field; - } - inline int getOffset() const - { - return m_offset; - } - inline IArrayStructAdapter* getArrayStructAdapter() const - { - return m_arrayStructAdapter; - } - inline StructBasePtr createStruct() const + return m_field; + } + inline int getOffset() const + { + return m_offset; + } + inline IArrayStructAdapter* getArrayStructAdapter() const + { + return m_arrayStructAdapter; + } + inline StructBasePtr createStruct() const + { + if (m_structPtrAdapter) { - if (m_structPtrAdapter) - { - return m_structPtrAdapter->create(); - } - return nullptr; + return m_structPtrAdapter->create(); } + return nullptr; + } - private: - const MetaField* m_field = nullptr; - int m_offset; - IArrayStructAdapter* m_arrayStructAdapter = nullptr; - IStructPtrAdapter* m_structPtrAdapter = nullptr; - }; - +private: + const MetaField* m_field = nullptr; + int m_offset; + IArrayStructAdapter* m_arrayStructAdapter = nullptr; + IStructPtrAdapter* m_structPtrAdapter = nullptr; +}; - typedef std::function()> FuncStructBaseFactory; +typedef std::function()> FuncStructBaseFactory; +class SYMBOLEXP StructInfo +{ +public: + StructInfo(const std::string& typeName, const std::string& description, int flags, const std::vector& attrs, FuncStructBaseFactory factory, std::vector&& fields, std::vector&& fieldInfos); - class SYMBOLEXP StructInfo + inline const std::string& getTypeName() const { - public: - StructInfo(const std::string& typeName, const std::string& description, int flags, const std::vector& attrs, FuncStructBaseFactory factory, std::vector&& fields, std::vector&& fieldInfos); - - inline const std::string& getTypeName() const - { - return m_metaStruct.getTypeName(); - } + return m_metaStruct.getTypeName(); + } - inline const FieldInfo* getField(ssize_t index) const - { - if (0 <= index && index < static_cast(m_fieldInfos.size())) - { - return &m_fieldInfos[index]; - } - return nullptr; - } - - inline const std::vector& getFields() const - { - return m_fieldInfos; - } - - inline const MetaStruct& getMetaStruct() const + inline const FieldInfo* getField(ssize_t index) const + { + if (0 <= index && index < static_cast(m_fieldInfos.size())) { - return m_metaStruct; + return &m_fieldInfos[index]; } + return nullptr; + } - private: - const MetaStruct& m_metaStruct; - std::vector m_fieldInfos; - }; - - - class SYMBOLEXP EnumInfo + inline const std::vector& getFields() const { - public: - EnumInfo(const std::string& typeName, const std::string& description, const std::vector& attrs, std::vector&& entries); - const MetaEnum& getMetaEnum() const; + return m_fieldInfos; + } - private: - const MetaEnum& m_metaEnum; - }; - - template <> - class MetaTypeInfo - { - public: - static const int TypeId = MetaTypeId::TYPE_STRUCT; - }; - template <> - class MetaTypeInfo + inline const MetaStruct& getMetaStruct() const { - public: - static const int TypeId = MetaTypeId::TYPE_STRUCT; - }; - template <> - class MetaTypeInfo - { - public: - static const int TypeId = MetaTypeId::TYPE_STRUCT; - }; + return m_metaStruct; + } + +private: + const MetaStruct& m_metaStruct; + std::vector m_fieldInfos; +}; + +class SYMBOLEXP EnumInfo +{ +public: + EnumInfo(const std::string& typeName, const std::string& description, const std::vector& attrs, std::vector&& entries); + const MetaEnum& getMetaEnum() const; + +private: + const MetaEnum& m_metaEnum; +}; + +template<> +class MetaTypeInfo +{ +public: + static const int TypeId = MetaTypeId::TYPE_STRUCT; +}; +template<> +class MetaTypeInfo +{ +public: + static const int TypeId = MetaTypeId::TYPE_STRUCT; +}; +template<> +class MetaTypeInfo +{ +public: + static const int TypeId = MetaTypeId::TYPE_STRUCT; +}; + +class SYMBOLEXP StructBase +{ +public: + virtual ~StructBase() = default; + + StructBase* add(ssize_t index); + + virtual void clear() = 0; - - - class SYMBOLEXP StructBase + template + T* getData(const FieldInfo& fieldInfo) { - public: - virtual ~StructBase() = default; - - StructBase* add(ssize_t index); - - virtual void clear() = 0; - - template - T* getData(const FieldInfo& fieldInfo) + const MetaField* fieldDest = fieldInfo.getField(); + if (fieldDest) { - const MetaField* fieldDest = fieldInfo.getField(); - if (fieldDest) + if ((fieldDest->typeId == MetaTypeInfo::TypeId) + || ((MetaTypeInfo::TypeId == MetaTypeInfo::TypeId) && (fieldDest->typeId == MetaTypeId::TYPE_ENUM)) + || ((MetaTypeInfo::TypeId == MetaTypeInfo>::TypeId) && (fieldDest->typeId == MetaTypeId::TYPE_ARRAY_ENUM))) { - if ((fieldDest->typeId == MetaTypeInfo::TypeId) - || ((MetaTypeInfo::TypeId == MetaTypeInfo::TypeId) && (fieldDest->typeId == MetaTypeId::TYPE_ENUM)) - || ((MetaTypeInfo::TypeId == MetaTypeInfo>::TypeId) && (fieldDest->typeId == MetaTypeId::TYPE_ARRAY_ENUM))) - { - int offset = fieldInfo.getOffset(); - return reinterpret_cast(reinterpret_cast(this) + offset); - } + int offset = fieldInfo.getOffset(); + return reinterpret_cast(reinterpret_cast(this) + offset); } - return nullptr; } + return nullptr; + } + template + const T& getValue(const FieldInfo& fieldInfo) const + { + int offset = fieldInfo.getOffset(); + const T& data = *reinterpret_cast(reinterpret_cast(const_cast(this)) + offset); + return data; + } - template - const T& getValue(const FieldInfo& fieldInfo) const - { - int offset = fieldInfo.getOffset(); - const T& data = *reinterpret_cast(reinterpret_cast(const_cast(this)) + offset); - return data; - } - - virtual const StructInfo& getStructInfo() const = 0; - virtual std::shared_ptr clone() const = 0; + virtual const StructInfo& getStructInfo() const = 0; + virtual std::shared_ptr clone() const = 0; - private: - struct RawData - { - std::string type; - int contentType = 0; - std::string data; - }; +private: + struct RawData + { + std::string type{}; + int contentType = 0; + std::string data{}; + }; - public: - void setRawData(const std::string& type, int contentType, const char* rawData, ssize_t size) +public: + void setRawData(const std::string& type, int contentType, const char* rawData, ssize_t size) + { + if (!m_rawData) { - if (!m_rawData) - { - m_rawData = std::make_shared(RawData{ type, contentType, {rawData, rawData + size} }); - } + m_rawData = std::make_shared(RawData{type, contentType, {rawData, rawData + size}}); } - const std::string* getRawType() const + } + const std::string* getRawType() const + { + if (m_rawData) { - if (m_rawData) - { - return &m_rawData->type; - } - return nullptr; + return &m_rawData->type; } - int getRawContentType() const + return nullptr; + } + int getRawContentType() const + { + if (m_rawData) { - if (m_rawData) - { - return m_rawData->contentType; - } - return 0; + return m_rawData->contentType; } - const std::string* getRawData() const + return 0; + } + const std::string* getRawData() const + { + if (m_rawData) { - if (m_rawData) - { - return &m_rawData->data; - } - return nullptr; + return &m_rawData->data; } + return nullptr; + } - private: - std::shared_ptr m_rawData; - }; - - typedef std::shared_ptr StructBasePtr; - - -#define OFFSET_STRUCTBASE_TO_PARAM(type, param) ((int)((long long)(&((type*)1000)->param) - ((long long)(StructBase*)((type*)1000)))) -#define OFFSET_STRUCTBASE_TO_STRUCTBASE(type, param) ((int)((long long)((StructBase*)&((type*)1000)->param) - ((long long)(StructBase*)((type*)1000)))) - +private: + std::shared_ptr m_rawData{}; +}; +typedef std::shared_ptr StructBasePtr; -} // namespace finalmq +#define OFFSET_STRUCTBASE_TO_PARAM(type, param) (static_cast(reinterpret_cast(&(reinterpret_cast(1000))->param) - (reinterpret_cast(reinterpret_cast(reinterpret_cast(1000)))))) +#define OFFSET_STRUCTBASE_TO_STRUCTBASE(type, param) (static_cast(reinterpret_cast(reinterpret_cast(&(reinterpret_cast(1000))->param)) - (reinterpret_cast(reinterpret_cast(reinterpret_cast(1000)))))) +} // namespace finalmq diff --git a/inc/finalmq/serializestruct/StructFactoryRegistry.h b/inc/finalmq/serializestruct/StructFactoryRegistry.h index 689353b3..05270034 100644 --- a/inc/finalmq/serializestruct/StructFactoryRegistry.h +++ b/inc/finalmq/serializestruct/StructFactoryRegistry.h @@ -22,35 +22,32 @@ #pragma once -#include "StructBase.h" - +#include #include -#include #include -#include - - -namespace finalmq { +#include +#include "StructBase.h" +namespace finalmq +{ struct IStructFactoryRegistry { - virtual ~IStructFactoryRegistry() {} + virtual ~IStructFactoryRegistry() + {} virtual void registerFactory(const std::string& typeName, FuncStructBaseFactory factory) = 0; virtual std::shared_ptr createStruct(const std::string& typeName) = 0; }; - class SYMBOLEXP StructFactoryRegistryImpl : public IStructFactoryRegistry { public: - private: // IStructFactoryRegistry virtual void registerFactory(const std::string& typeName, FuncStructBaseFactory factory) override; virtual std::shared_ptr createStruct(const std::string& typeName) override; - std::unordered_map m_factories; + std::unordered_map m_factories{}; }; class SYMBOLEXP StructFactoryRegistry @@ -83,7 +80,4 @@ class SYMBOLEXP StructFactoryRegistry static std::unique_ptr& getStaticUniquePtrRef(); }; - - -} // namespace finalmq - +} // namespace finalmq diff --git a/inc/finalmq/serializevariant/SerializerVariant.h b/inc/finalmq/serializevariant/SerializerVariant.h index 7d1f9ddf..5f07deb2 100644 --- a/inc/finalmq/serializevariant/SerializerVariant.h +++ b/inc/finalmq/serializevariant/SerializerVariant.h @@ -22,14 +22,14 @@ #pragma once +#include + #include "finalmq/metadata/MetaStruct.h" #include "finalmq/serialize/ParserConverter.h" #include "finalmq/variant/Variant.h" -#include - -namespace finalmq { - +namespace finalmq +{ class VarValueToVariant; class ParserProcessDefaultValues; @@ -43,7 +43,13 @@ class SYMBOLEXP SerializerVariant : public ParserConverter { public: Internal(SerializerVariant& outer, Variant& root, bool enumAsString); + private: + Internal(const Internal&) = delete; + Internal(Internal&&) = delete; + const Internal& operator=(const Internal&) = delete; + const Internal& operator=(Internal&&) = delete; + // IParserVisitor virtual void notifyError(const char* str, const char* message) override; virtual void startStruct(const MetaStruct& stru) override; @@ -104,22 +110,22 @@ class SYMBOLEXP SerializerVariant : public ParserConverter virtual void enterArrayEnumMove(const MetaField& field, std::vector&& value) override; virtual void enterArrayEnum(const MetaField& field, const std::vector& value) override; - template + template inline void add(const MetaField& field, const T& value); - template + template void add(const MetaField& field, T&& value); - Variant& m_root; - Variant* m_current = nullptr; - std::deque m_stack; - bool m_enumAsString = true; - std::shared_ptr m_varValueToVariant; - SerializerVariant& m_outer; + Variant& m_root; + Variant* m_current = nullptr; + std::deque m_stack{}; + bool m_enumAsString = true; + std::shared_ptr m_varValueToVariant{}; + SerializerVariant& m_outer; }; - Internal m_internal; - std::unique_ptr m_parserAbortAndIndex; - std::shared_ptr m_parserProcessDefaultValues; + Internal m_internal; + std::unique_ptr m_parserAbortAndIndex{}; + std::shared_ptr m_parserProcessDefaultValues{}; }; -} // namespace finalmq +} // namespace finalmq diff --git a/inc/finalmq/serializevariant/VarValueToVariant.h b/inc/finalmq/serializevariant/VarValueToVariant.h index 03b3a2b0..028fae72 100644 --- a/inc/finalmq/serializevariant/VarValueToVariant.h +++ b/inc/finalmq/serializevariant/VarValueToVariant.h @@ -22,18 +22,15 @@ #pragma once - -#include "finalmq/helpers/FmqDefines.h" -#include "finalmq/variant/Variant.h" -#include "finalmq/serialize/IParserVisitor.h" - - #include #include +#include "finalmq/helpers/FmqDefines.h" +#include "finalmq/serialize/IParserVisitor.h" +#include "finalmq/variant/Variant.h" -namespace finalmq { - +namespace finalmq +{ enum VarValueType2Index { VARVALUETYPE_NONE = 0, @@ -66,10 +63,9 @@ enum VarValueType2Index VARVALUETYPE_VARIANTLIST = 27, }; - - -namespace variant { - class VarValue; +namespace variant +{ +class VarValue; } class SerializerStruct; @@ -84,15 +80,15 @@ class SYMBOLEXP VarValueToVariant private: VarValueToVariant(const VarValueToVariant&) = delete; - const VarValueToVariant& operator =(const VarValueToVariant&) = delete; + const VarValueToVariant& operator=(const VarValueToVariant&) = delete; VarValueToVariant(const VarValueToVariant&&) = delete; - const VarValueToVariant& operator =(const VarValueToVariant&&) = delete; + const VarValueToVariant& operator=(const VarValueToVariant&&) = delete; void processVarValue(const variant::VarValue& varValue, Variant& variant); - Variant& m_variant; - std::shared_ptr m_serializerStruct; - std::shared_ptr m_varValue; + Variant& m_variant; + std::shared_ptr m_serializerStruct{}; + std::shared_ptr m_varValue{}; }; -} // namespace finalmq +} // namespace finalmq diff --git a/inc/finalmq/streamconnection/ConnectionData.h b/inc/finalmq/streamconnection/ConnectionData.h index 933d245b..66e9fc3e 100644 --- a/inc/finalmq/streamconnection/ConnectionData.h +++ b/inc/finalmq/streamconnection/ConnectionData.h @@ -22,14 +22,13 @@ #pragma once - - -#include "finalmq/helpers/FmqDefines.h" -#include #include +#include -namespace finalmq { +#include "finalmq/helpers/FmqDefines.h" +namespace finalmq +{ enum class ConnectionState { CONNECTIONSTATE_CREATED = 0, @@ -39,28 +38,26 @@ enum class ConnectionState CONNECTIONSTATE_DISCONNECTED = 4, }; - - struct ConnectionData { - std::int64_t connectionId = 0; - std::string endpoint; - std::string hostname; - int port = 0; - std::string endpointPeer; - std::string addressPeer; - int af = 0; - int type = 0; - int protocol = 0; - int portPeer = 0; - std::string sockaddr; - bool incomingConnection = false; - SOCKET sd = INVALID_SOCKET; - int reconnectInterval = 5000; - int totalReconnectDuration = -1; + std::int64_t connectionId = 0; + std::string endpoint{}; + std::string hostname{}; + int port = 0; + std::string endpointPeer{}; + std::string addressPeer{}; + int af = 0; + int type = 0; + int protocol = 0; + int portPeer = 0; + std::string sockaddr{}; + bool incomingConnection = false; + SOCKET sd = INVALID_SOCKET; + int reconnectInterval = 5000; + int totalReconnectDuration = -1; std::chrono::time_point startTime{}; - bool ssl = false; + bool ssl = false; ConnectionState connectionState = ConnectionState::CONNECTIONSTATE_CREATED; }; -} // namespace finalmq +} // namespace finalmq diff --git a/inc/finalmq/streamconnection/OpenSsl.h b/inc/finalmq/streamconnection/OpenSsl.h index 4c73c875..3c406d8c 100644 --- a/inc/finalmq/streamconnection/OpenSsl.h +++ b/inc/finalmq/streamconnection/OpenSsl.h @@ -22,11 +22,11 @@ #pragma once -#include "finalmq/logger/LogStream.h" - -#include -#include #include +#include +#include + +#include "finalmq/logger/LogStream.h" #ifdef USE_OPENSSL #include "openssl/ossl_typ.h" @@ -35,52 +35,48 @@ struct x509_store_ctx_st; typedef struct x509_store_ctx_st X509_STORE_CTX; - -namespace finalmq { - - +namespace finalmq +{ struct CertificateData { bool ssl = false; - int verifyMode = 0; // SSL_CTX_set_verify: SSL_VERIFY_NONE, SSL_VERIFY_PEER, SSL_VERIFY_FAIL_IF_NO_PEER_CERT, SSL_VERIFY_CLIENT_ONCE - std::string certificateFile; // SSL_CTX_use_certificate_file, pem - std::string privateKeyFile; // SSL_CTX_use_PrivateKey_file, pem - std::string caFile; // SSL_CTX_load_verify_location, pem - std::string caPath; // SSL_CTX_load_verify_location, pem - std::string certificateChainFile; // SSL_CTX_use_certificate_chain_file, pem - std::string clientCaFile; // SSL_load_client_CA_file, pem, SSL_CTX_set_client_CA_list - std::function verifyCallback; // SSL_CTX_set_verify + int verifyMode = 0; // SSL_CTX_set_verify: SSL_VERIFY_NONE, SSL_VERIFY_PEER, SSL_VERIFY_FAIL_IF_NO_PEER_CERT, SSL_VERIFY_CLIENT_ONCE + std::string certificateFile; // SSL_CTX_use_certificate_file, pem + std::string privateKeyFile; // SSL_CTX_use_PrivateKey_file, pem + std::string caFile; // SSL_CTX_load_verify_location, pem + std::string caPath; // SSL_CTX_load_verify_location, pem + std::string certificateChainFile; // SSL_CTX_use_certificate_chain_file, pem + std::string clientCaFile; // SSL_load_client_CA_file, pem, SSL_CTX_set_client_CA_list + std::function verifyCallback; // SSL_CTX_set_verify }; -} // namespace finalmq +} // namespace finalmq #ifdef USE_OPENSSL -#define MODULENAME "FinalMQ" +#define MODULENAME "FinalMQ" -#include #include #include -#include - +#include -namespace finalmq { +#include +namespace finalmq +{ class SslContext; class SslSocket; - struct IOpenSsl { - virtual ~IOpenSsl() {} + virtual ~IOpenSsl() + {} virtual std::shared_ptr createServerContext(const CertificateData& certificateData) = 0; virtual std::shared_ptr createClientContext(const CertificateData& certificateData) = 0; virtual std::mutex& getMutex() = 0; }; - - class SYMBOLEXP OpenSslImpl : public IOpenSsl { public: @@ -96,12 +92,11 @@ class SYMBOLEXP OpenSslImpl : public IOpenSsl std::shared_ptr configContext(SSL_CTX* ctx, const CertificateData& certificateData); OpenSslImpl(const OpenSslImpl&) = delete; - const OpenSslImpl& operator =(const OpenSslImpl&) = delete; + const OpenSslImpl& operator=(const OpenSslImpl&) = delete; - std::mutex m_sslMutex; + std::mutex m_sslMutex{}; }; - class SYMBOLEXP OpenSsl { public: @@ -132,13 +127,9 @@ class SYMBOLEXP OpenSsl static std::unique_ptr& getStaticUniquePtrRef(); }; - - - class SslSocket { public: - enum class IoState { SUCCESS, @@ -148,8 +139,7 @@ class SslSocket }; SslSocket(SSL* ssl) - : m_ssl(ssl) - , m_sslMutex(OpenSsl::instance().getMutex()) + : m_ssl(ssl), m_sslMutex(OpenSsl::instance().getMutex()) { } ~SslSocket() @@ -324,7 +314,7 @@ class SslSocket private: SslSocket(const SslSocket&) = delete; - const SslSocket& operator =(const SslSocket&) = delete; + const SslSocket& operator=(const SslSocket&) = delete; SSL* m_ssl = nullptr; bool m_readWhenWritable = false; @@ -332,14 +322,11 @@ class SslSocket std::mutex& m_sslMutex; }; - - class SslContext { public: SslContext(SSL_CTX* ctx) - : m_ctx(ctx) - , m_sslMutex(OpenSsl::instance().getMutex()) + : m_ctx(ctx), m_sslMutex(OpenSsl::instance().getMutex()) { } ~SslContext() @@ -364,7 +351,11 @@ class SslContext SSL* ssl = SSL_new(m_ctx); if (ssl) { - SSL_set_fd(ssl, static_cast(sd)); // the cast is not nice for win64 sockets, but it works! +#ifdef WIN32 + SSL_set_fd(ssl, static_cast(sd)); // the cast is not nice for win64 sockets, but it works! +#else + SSL_set_fd(ssl, sd); +#endif return std::make_shared(ssl); } return nullptr; @@ -382,18 +373,15 @@ class SslContext private: SslContext(const SslContext&) = delete; - const SslContext& operator =(const SslContext&) = delete; + const SslContext& operator=(const SslContext&) = delete; - SSL_CTX* m_ctx = nullptr; - std::function m_verifyCallback; + SSL_CTX* m_ctx{nullptr}; + std::function m_verifyCallback{}; std::mutex& m_sslMutex; }; - -} // namespace finalmq +} // namespace finalmq #undef MODULENAME -#endif // USE_OPENSSL - - +#endif // USE_OPENSSL diff --git a/inc/finalmq/streamconnection/Socket.h b/inc/finalmq/streamconnection/Socket.h index b74be271..0d3e9613 100644 --- a/inc/finalmq/streamconnection/Socket.h +++ b/inc/finalmq/streamconnection/Socket.h @@ -22,27 +22,26 @@ #pragma once -#include "finalmq/helpers/SocketDescriptor.h" -#include "finalmq/helpers/OperatingSystem.h" -#include "OpenSsl.h" - #include -#include #include +#include + +#include "OpenSsl.h" +#include "finalmq/helpers/OperatingSystem.h" +#include "finalmq/helpers/SocketDescriptor.h" #if !defined(WIN32) && !defined(__MINGW32__) #include #endif -namespace finalmq { - +namespace finalmq +{ class SslContext; class SslSocket; class Socket; typedef std::shared_ptr SocketPtr; - class SYMBOLEXP Socket { public: @@ -71,14 +70,14 @@ class SYMBOLEXP Socket private: Socket(const Socket& obj) = delete; - const Socket& operator =(const Socket& obj) = delete; + const Socket& operator=(const Socket& obj) = delete; int handleError(int err, const char* funcName); - SocketDescriptorPtr m_sd; - int m_af = 0; - int m_protocol = 0; - std::string m_name; + SocketDescriptorPtr m_sd{}; + int m_af = 0; + int m_protocol = 0; + std::string m_name{}; #ifdef USE_OPENSSL public: @@ -109,14 +108,15 @@ class SYMBOLEXP Socket return false; } int sslPending(); + private: void startSslAccept(const std::shared_ptr& sslContext); #endif - std::shared_ptr m_sslContext; - std::shared_ptr m_sslSocket; - bool m_readWhenWritable = false; - bool m_writeWhenReadable = false; - //std::mutex m_mtx; + std::shared_ptr m_sslContext{}; + std::shared_ptr m_sslSocket{}; + bool m_readWhenWritable = false; + bool m_writeWhenReadable = false; + //std::mutex m_mtx{}; }; -} // namespace finalmq +} // namespace finalmq diff --git a/inc/finalmq/streamconnection/StreamConnection.h b/inc/finalmq/streamconnection/StreamConnection.h index 8a9f14b1..e3cc5b99 100644 --- a/inc/finalmq/streamconnection/StreamConnection.h +++ b/inc/finalmq/streamconnection/StreamConnection.h @@ -22,70 +22,65 @@ #pragma once +#include +#include +#include +#include + +#include #include "ConnectionData.h" #include "Socket.h" -#include "finalmq/poller/Poller.h" -#include "finalmq/helpers/hybrid_ptr.h" -#include "finalmq/streamconnection/IMessage.h" #include "finalmq/helpers/CondVar.h" #include "finalmq/helpers/IExecutor.h" +#include "finalmq/helpers/hybrid_ptr.h" +#include "finalmq/poller/Poller.h" +#include "finalmq/streamconnection/IMessage.h" #include "finalmq/variant/Variant.h" -#include -#include -#include -#include -#include - - -namespace finalmq { - -#define RELEASE_DISCONNECT 1 -#define RELEASE_EXECUTEINPOLLERTHREAD 2 -#define RELEASE_TERMINATE 4 - +namespace finalmq +{ +#define RELEASE_DISCONNECT 1 +#define RELEASE_EXECUTEINPOLLERTHREAD 2 +#define RELEASE_TERMINATE 4 struct BindProperties { - CertificateData certificateData; - Variant protocolData; - Variant formatData; ///< data for the serialization format + CertificateData certificateData{}; + Variant protocolData{}; + Variant formatData{}; ///< data for the serialization format }; struct ConnectConfig { - int reconnectInterval = 5000; ///< if the server is not available, you can pass a reconnection intervall in [ms] - int totalReconnectDuration = -1; ///< if the server is not available, you can pass a duration in [ms] how long the reconnect shall happen. -1 means: try for ever. + int reconnectInterval = 5000; ///< if the server is not available, you can pass a reconnection intervall in [ms] + int totalReconnectDuration = -1; ///< if the server is not available, you can pass a duration in [ms] how long the reconnect shall happen. -1 means: try for ever. }; struct ConnectProperties { - CertificateData certificateData; - ConnectConfig config; - Variant protocolData; - Variant formatData; ///< data for the serialization format + CertificateData certificateData{}; + ConnectConfig config{}; + Variant protocolData{}; + Variant formatData{}; ///< data for the serialization format }; - - struct IStreamConnection; typedef std::shared_ptr IStreamConnectionPtr; struct IStreamConnectionCallback { - virtual ~IStreamConnectionCallback() {} + virtual ~IStreamConnectionCallback() + {} virtual hybrid_ptr connected(const IStreamConnectionPtr& connection) = 0; virtual void disconnected(const IStreamConnectionPtr& connection) = 0; virtual bool received(const IStreamConnectionPtr& connection, const SocketPtr& socket, int bytesToRead) = 0; }; - - - struct IStreamConnection { - virtual ~IStreamConnection() {} + virtual ~IStreamConnection() + {} virtual void sendMessage(const IMessagePtr& msg) = 0; virtual ConnectionData getConnectionData() const = 0; virtual ConnectionState getConnectionState() const = 0; @@ -94,7 +89,6 @@ struct IStreamConnection virtual void disconnect() = 0; }; - struct IStreamConnectionPrivate : public IStreamConnection { virtual bool connect() = 0; @@ -111,11 +105,8 @@ struct IStreamConnectionPrivate : public IStreamConnection virtual bool received(const IStreamConnectionPtr& connection, const SocketPtr& socket, int bytesToRead) = 0; }; - - typedef std::shared_ptr IStreamConnectionPrivatePtr; - class SYMBOLEXP StreamConnection : public IStreamConnectionPrivate { public: @@ -147,23 +138,23 @@ class SYMBOLEXP StreamConnection : public IStreamConnectionPrivate struct MessageSendState { - IMessagePtr msg; - std::list::const_iterator it; + IMessagePtr msg{}; + std::list::const_iterator it{}; int offset = 0; }; - const std::int64_t m_connectionId = 0; - ConnectionData m_connectionData; - SocketPtr m_socketPrivate; - SocketPtr m_socket; - const IPollerPtr m_poller; - std::list m_pendingMessages; - std::atomic m_disconnectFlag{}; - hybrid_ptr m_callback; + const std::int64_t m_connectionId = 0; + ConnectionData m_connectionData{}; + SocketPtr m_socketPrivate{}; + SocketPtr m_socket{}; + const IPollerPtr m_poller{}; + std::list m_pendingMessages{}; + std::atomic m_disconnectFlag{}; + hybrid_ptr m_callback{}; - std::chrono::time_point m_lastReconnectTime; + std::chrono::time_point m_lastReconnectTime{}; - mutable std::mutex m_mutex; + mutable std::mutex m_mutex{}; }; -} // namespace finalmq +} // namespace finalmq diff --git a/inc/finalmq/streamconnection/StreamConnectionContainer.h b/inc/finalmq/streamconnection/StreamConnectionContainer.h index 2cb38eb2..0adf0720 100644 --- a/inc/finalmq/streamconnection/StreamConnectionContainer.h +++ b/inc/finalmq/streamconnection/StreamConnectionContainer.h @@ -22,28 +22,28 @@ #pragma once -#include "finalmq/helpers/hybrid_ptr.h" -#include "ConnectionData.h" -#include "finalmq/poller/Poller.h" -#include "Socket.h" -#include "StreamConnection.h" -#include "finalmq/helpers/CondVar.h" -#include "finalmq/helpers/IExecutor.h" - #include -#include #include #include #include +#include +#include "ConnectionData.h" +#include "Socket.h" +#include "StreamConnection.h" +#include "finalmq/helpers/CondVar.h" +#include "finalmq/helpers/IExecutor.h" +#include "finalmq/helpers/hybrid_ptr.h" +#include "finalmq/poller/Poller.h" -namespace finalmq { - -typedef std::function FuncPollerLoopTimer; +namespace finalmq +{ +typedef std::function FuncPollerLoopTimer; struct IStreamConnectionContainer { - virtual ~IStreamConnectionContainer() {} + virtual ~IStreamConnectionContainer() + {} virtual void init(int cycleTime = 100, FuncPollerLoopTimer funcTimer = {}, int checkReconnectInterval = 1000) = 0; virtual int bind(const std::string& endpoint, hybrid_ptr callback, const BindProperties& bindProperties = {}) = 0; @@ -51,16 +51,13 @@ struct IStreamConnectionContainer virtual IStreamConnectionPtr connect(const std::string& endpoint, hybrid_ptr callback, const ConnectProperties& connectionProperties = {}) = 0; virtual IStreamConnectionPtr createConnection(hybrid_ptr callback) = 0; virtual bool connect(const std::string& endpoint, const IStreamConnectionPtr& streamConnection, const ConnectProperties& connectionProperties = {}) = 0; - virtual std::vector< IStreamConnectionPtr > getAllConnections() const = 0; + virtual std::vector getAllConnections() const = 0; virtual IStreamConnectionPtr getConnection(std::int64_t connectionId) const = 0; virtual void run() = 0; virtual void terminatePollerLoop() = 0; virtual IExecutorPtr getPollerThreadExecutor() const = 0; }; - - - class SYMBOLEXP StreamConnectionContainer : public IStreamConnectionContainer { public: @@ -75,7 +72,7 @@ class SYMBOLEXP StreamConnectionContainer : public IStreamConnectionContainer virtual IStreamConnectionPtr connect(const std::string& endpoint, hybrid_ptr callback, const ConnectProperties& connectionProperties = {}) override; virtual IStreamConnectionPtr createConnection(hybrid_ptr callback) override; virtual bool connect(const std::string& endpoint, const IStreamConnectionPtr& streamConnection, const ConnectProperties& connectionProperties = {}) override; - virtual std::vector< IStreamConnectionPtr > getAllConnections() const override; + virtual std::vector getAllConnections() const override; virtual IStreamConnectionPtr getConnection(std::int64_t connectionId) const override; virtual void run() override; virtual void terminatePollerLoop() override; @@ -85,9 +82,9 @@ class SYMBOLEXP StreamConnectionContainer : public IStreamConnectionContainer struct BindData { - ConnectionData connectionData; - SocketPtr socket; - hybrid_ptr callback; + ConnectionData connectionData{}; + SocketPtr socket{}; + hybrid_ptr callback{}; }; std::unordered_map::iterator findBindByEndpoint(const std::string& endpoint); @@ -103,23 +100,23 @@ class SYMBOLEXP StreamConnectionContainer : public IStreamConnectionContainer static bool isTimerExpired(std::chrono::time_point& lastTime, int interval); void doReconnect(); - const std::shared_ptr m_poller; - std::unordered_map m_sd2binds; - std::unordered_map m_connectionId2Connection; - std::unordered_map m_sd2Connection; - std::unordered_map m_sd2ConnectionPollerLoop; - std::atomic_flag m_connectionsStable{}; - static std::atomic_int64_t m_nextConnectionId; - std::atomic_bool m_terminatePollerLoop{false}; - int m_cycleTime = 100; - int m_checkReconnectInterval = 1000; - FuncPollerLoopTimer m_funcTimer; - const IExecutorPtr m_executorPollerThread; - std::unique_ptr m_executorWorker; - std::thread m_threadTimer; - mutable std::mutex m_mutex; - - std::chrono::time_point m_lastReconnectTime; + const std::shared_ptr m_poller{}; + std::unordered_map m_sd2binds{}; + std::unordered_map m_connectionId2Connection{}; + std::unordered_map m_sd2Connection{}; + std::unordered_map m_sd2ConnectionPollerLoop{}; + std::atomic_flag m_connectionsStable{}; + static std::atomic_int64_t m_nextConnectionId; + std::atomic_bool m_terminatePollerLoop{false}; + int m_cycleTime = 100; + int m_checkReconnectInterval = 1000; + FuncPollerLoopTimer m_funcTimer{}; + const IExecutorPtr m_executorPollerThread; + std::unique_ptr m_executorWorker{}; + std::thread m_threadTimer{}; + mutable std::mutex m_mutex{}; + + std::chrono::time_point m_lastReconnectTime{}; #ifdef USE_OPENSSL struct SslAcceptingData @@ -129,8 +126,8 @@ class SYMBOLEXP StreamConnectionContainer : public IStreamConnectionContainer hybrid_ptr callback; }; bool sslAccepting(SslAcceptingData& sslAcceptingData); - std::unordered_map m_sslAcceptings; + std::unordered_map m_sslAcceptings{}; #endif }; -} // namespace finalmq +} // namespace finalmq diff --git a/inc/finalmq/variant/Variant.h b/inc/finalmq/variant/Variant.h index 6ca541de..9ec6edca 100644 --- a/inc/finalmq/variant/Variant.h +++ b/inc/finalmq/variant/Variant.h @@ -22,17 +22,15 @@ #pragma once -#include #include #include + #include #include "IVariantValue.h" - -namespace finalmq { - - +namespace finalmq +{ ////////////////////// const static int VARTYPE_NONE = 0; @@ -51,9 +49,17 @@ class SYMBOLEXP Variant } template - void operator =(T data) + const Variant& operator=(T data) { m_value = std::make_shared::VariantValueType>(std::move(data)); +#ifndef WIN32 +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Weffc++" +#endif + return *this; +#ifndef WIN32 +#pragma GCC diagnostic pop +#endif } template @@ -141,18 +147,17 @@ class SYMBOLEXP Variant } } - Variant(const Variant& rhs); - const Variant& operator =(const Variant& rhs); + const Variant& operator=(const Variant& rhs); Variant(Variant&& rhs) noexcept; - Variant& operator =(Variant&& rhs) noexcept; + Variant& operator=(Variant&& rhs) noexcept; void accept(IVariantVisitor& visitor, ssize_t index = 0, int level = 0, ssize_t size = 0, const std::string& name = ""); Variant* getVariant(const std::string& name); const Variant* getVariant(const std::string& name) const; - bool operator ==(const Variant& rhs) const; + bool operator==(const Variant& rhs) const; bool add(const std::string& name, const Variant& variant); bool add(const std::string& name, Variant&& variant); @@ -163,16 +168,12 @@ class SYMBOLEXP Variant Variant& getOrCreate(const std::string& name); private: - - std::shared_ptr m_value; + std::shared_ptr m_value{}; }; - -} // namespace finalmq - +} // namespace finalmq // includes, so that the application does not have to include these header files -#include "VariantValues.h" -#include "VariantValueStruct.h" #include "VariantValueList.h" - +#include "VariantValueStruct.h" +#include "VariantValues.h" diff --git a/inc/finalmq/variant/VariantValueTemplate.h b/inc/finalmq/variant/VariantValueTemplate.h index 7f4f31c7..b4f48aba 100644 --- a/inc/finalmq/variant/VariantValueTemplate.h +++ b/inc/finalmq/variant/VariantValueTemplate.h @@ -22,18 +22,16 @@ #pragma once -#include "IVariantValue.h" -#include "Variant.h" -#include "finalmq/metadata/MetaType.h" -#include "assert.h" - #include #include +#include "IVariantValue.h" +#include "Variant.h" +#include "assert.h" +#include "finalmq/metadata/MetaType.h" -namespace finalmq { - - +namespace finalmq +{ template class VariantValueTemplate : public IVariantValue { @@ -84,7 +82,7 @@ class VariantValueTemplate : public IVariantValue return std::make_shared(*this); } - virtual bool operator ==(const IVariantValue& rhs) const override + virtual bool operator==(const IVariantValue& rhs) const override { if (this == &rhs) { @@ -99,7 +97,14 @@ class VariantValueTemplate : public IVariantValue const typename MetaTypeIdInfo::Type* rhsData = static_cast::Type*>(rhs.getData()); assert(rhsData); +#ifndef WIN32 +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wfloat-equal" +#endif return m_value == *rhsData; +#ifndef WIN32 +#pragma GCC diagnostic pop +#endif } virtual bool add(const std::string& /*name*/, const Variant& /*variant*/) override @@ -131,4 +136,4 @@ class VariantValueTemplate : public IVariantValue typename MetaTypeIdInfo::Type m_value; }; -} // namespace finalmq +} // namespace finalmq diff --git a/services/fmqfcgi/fmqfcgi.cpp b/services/fmqfcgi/fmqfcgi.cpp index c15c7d17..e5d3253a 100644 --- a/services/fmqfcgi/fmqfcgi.cpp +++ b/services/fmqfcgi/fmqfcgi.cpp @@ -945,7 +945,7 @@ class RequestManager const char* httpHeaderCreateSession = FCGX_GetParam("HTTP_FMQ_CREATESESSION", request->envp); const char* httpHeaderSessionId = FCGX_GetParam("HTTP_FMQ_SESSIONID", request->envp); - //for(int i=0; request->envp[i] != NULL; i+=1) + //for (int i=0; request->envp[i] != NULL; i+=1) //{ // streamInfo << request->envp[i]; //} diff --git a/src/helpers/CondVar.cpp b/src/helpers/CondVar.cpp index 7a52cefb..2e4b6b3c 100644 --- a/src/helpers/CondVar.cpp +++ b/src/helpers/CondVar.cpp @@ -22,11 +22,8 @@ #include "finalmq/helpers/CondVar.h" - - -namespace finalmq { - - +namespace finalmq +{ CondVar::CondVar(CondVar::CondVarMode mode) : m_mode(mode) { @@ -36,7 +33,6 @@ CondVar::~CondVar(void) { } - void CondVar::setValue() { std::unique_lock locker(m_mutex); @@ -52,7 +48,6 @@ void CondVar::setValue() } } - void CondVar::resetValue() { std::unique_lock locker(m_mutex); @@ -60,7 +55,6 @@ void CondVar::resetValue() locker.unlock(); } - bool CondVar::wait(int timeout) const { bool ret = false; @@ -75,11 +69,11 @@ bool CondVar::wait(int timeout) const { if (timeout < 0) { - m_condvar.wait(locker, [this] () { return m_value; }); + m_condvar.wait(locker, [this]() { return m_value; }); } else { - m_condvar.wait_for(locker, std::chrono::milliseconds(timeout), [this] () { return m_value; }); + m_condvar.wait_for(locker, std::chrono::milliseconds(timeout), [this]() { return m_value; }); } } ret = m_value; @@ -92,8 +86,7 @@ bool CondVar::wait(int timeout) const return ret; } - -void CondVar::operator =(bool val) +const CondVar& CondVar::operator=(bool val) { if (val) { @@ -103,15 +96,14 @@ void CondVar::operator =(bool val) { resetValue(); } + return *this; } - CondVar::operator bool() const { return wait(0); } - bool CondVar::getValue() const { return wait(0); diff --git a/src/helpers/Executor.cpp b/src/helpers/Executor.cpp index 4800f228..afbd0297 100644 --- a/src/helpers/Executor.cpp +++ b/src/helpers/Executor.cpp @@ -21,21 +21,18 @@ //SOFTWARE. #include "finalmq/helpers/Executor.h" -#include - #include +#include -namespace finalmq { - - +namespace finalmq +{ void ExecutorBase::registerActionNotification(std::function func) { m_funcNotify = func; } - void ExecutorBase::run() { while (!m_terminate.load()) @@ -63,14 +60,8 @@ bool ExecutorBase::isTerminating() const return m_terminate; } - - - //////////////////////////////////////////////////////// - - - bool Executor::runAvailableActions(const FuncIsAbort& funcIsAbort) { std::list actions; @@ -84,12 +75,12 @@ bool Executor::runAvailableActions(const FuncIsAbort& funcIsAbort) if (!actions.empty()) { - for (auto it = actions.begin(); it != actions.end(); ++it) + for (auto it1 = actions.begin(); it1 != actions.end(); ++it1) { - ActionEntry& entry = *it; - for (auto it = entry.funcs.begin(); it != entry.funcs.end(); ++it) + ActionEntry& entry = *it1; + for (auto it2 = entry.funcs.begin(); it2 != entry.funcs.end(); ++it2) { - std::unique_ptr>& func = *it; + std::unique_ptr>& func = *it2; assert(func && *func); if (!funcIsAbort || !funcIsAbort()) { @@ -108,7 +99,6 @@ bool Executor::runAvailableActions(const FuncIsAbort& funcIsAbort) return false; } } - bool Executor::areRunnableActionsAvailable() const { @@ -119,8 +109,6 @@ bool Executor::areRunnableActionsAvailable() const return true; } - - bool Executor::runAvailableActionBatch(const FuncIsAbort& funcIsAbort) { bool wasAvailable = false; @@ -253,9 +241,6 @@ void Executor::addAction(std::function func, std::int64_t instanceId) } } - - - ////////////////////////////////////////////////// bool ExecutorIgnoreOrderOfInstance::runAvailableActions(const FuncIsAbort& funcIsAbort) @@ -331,10 +316,8 @@ void ExecutorIgnoreOrderOfInstance::addAction(std::function func, std::i } } - ////////////////////////////////////////////////// - ExecutorWorkerBase::ExecutorWorkerBase(const std::shared_ptr& executor, int numberOfWorkerThreads) : m_executor(executor) { @@ -380,7 +363,6 @@ void ExecutorWorkerBase::join() } } - ///////////////////////////////////////////////////// void GlobalExecutorWorker::setInstance(std::unique_ptr&& instanceUniquePtr) diff --git a/src/helpers/OperatingSystem.cpp b/src/helpers/OperatingSystem.cpp index c81e7dda..9c5f3f34 100644 --- a/src/helpers/OperatingSystem.cpp +++ b/src/helpers/OperatingSystem.cpp @@ -38,342 +38,326 @@ #endif #endif - -namespace finalmq { - - - OperatingSystemImpl::OperatingSystemImpl() - { - } - - - // IOperatingSystem - int OperatingSystemImpl::open(const char* filename, int flags) - { - return ::open(filename, flags); - } - - int OperatingSystemImpl::stat(const char* filename, struct stat* buf) - { - return ::stat(filename, buf); - } - - int OperatingSystemImpl::fstat(int fd, struct stat* buf) - { - return ::fstat(fd, buf); - } - - int OperatingSystemImpl::close(int fd) - { +namespace finalmq +{ +OperatingSystemImpl::OperatingSystemImpl() +{ +} + +// IOperatingSystem +int OperatingSystemImpl::open(const char* filename, int flags) +{ + return ::open(filename, flags); +} + +int OperatingSystemImpl::stat(const char* filename, struct stat* buf) +{ + return ::stat(filename, buf); +} + +int OperatingSystemImpl::fstat(int fd, struct stat* buf) +{ + return ::fstat(fd, buf); +} + +int OperatingSystemImpl::close(int fd) +{ #if defined(WIN32) #pragma warning(suppress : 4996) #endif - return ::close(fd); - } - + return ::close(fd); +} - int OperatingSystemImpl::closeSocket(SOCKET fd) - { +int OperatingSystemImpl::closeSocket(SOCKET fd) +{ #if defined(WIN32) || defined(__MINGW32__) - return ::closesocket(fd); + return ::closesocket(fd); #else - return ::close(fd); + return ::close(fd); #endif - } - - - SOCKET OperatingSystemImpl::socket(int af, int type, int protocol) - { - return ::socket(af, type, protocol); - } - - int OperatingSystemImpl::bind(SOCKET fd, const struct sockaddr* name, socklen_t namelen) - { - return ::bind(fd, name, namelen); - } - - SOCKET OperatingSystemImpl::accept(SOCKET fd, struct sockaddr* addr, socklen_t* addrlen) - { - return ::accept(fd, addr, addrlen); - } - - int OperatingSystemImpl::listen(SOCKET fd, int backlog) - { - return ::listen(fd, backlog); - } - - int OperatingSystemImpl::connect(SOCKET fd, const struct sockaddr* name, socklen_t namelen) - { - return ::connect(fd, name, namelen); - } - - - int OperatingSystemImpl::setsockopt(SOCKET fd, int level, int optname, const char* optval, int optlen) - { - return ::setsockopt(fd, level, optname, optval, optlen); - } - - int OperatingSystemImpl::getsockname(SOCKET fd, struct sockaddr* name, socklen_t* namelen) - { - return ::getsockname(fd, name, namelen); - } - - - int OperatingSystemImpl::write(int fd, const char* buffer, int len) - { - return ::write(fd, buffer, len); - } - - int OperatingSystemImpl::read(int fd, char* buffer, int len) - { - return ::read(fd, buffer, len); - } - - int OperatingSystemImpl::send(SOCKET fd, const char* buffer, int len, int flags) - { +} + +SOCKET OperatingSystemImpl::socket(int af, int type, int protocol) +{ + return ::socket(af, type, protocol); +} + +int OperatingSystemImpl::bind(SOCKET fd, const struct sockaddr* name, socklen_t namelen) +{ + return ::bind(fd, name, namelen); +} + +SOCKET OperatingSystemImpl::accept(SOCKET fd, struct sockaddr* addr, socklen_t* addrlen) +{ + return ::accept(fd, addr, addrlen); +} + +int OperatingSystemImpl::listen(SOCKET fd, int backlog) +{ + return ::listen(fd, backlog); +} + +int OperatingSystemImpl::connect(SOCKET fd, const struct sockaddr* name, socklen_t namelen) +{ + return ::connect(fd, name, namelen); +} + +int OperatingSystemImpl::setsockopt(SOCKET fd, int level, int optname, const char* optval, int optlen) +{ + return ::setsockopt(fd, level, optname, optval, optlen); +} + +int OperatingSystemImpl::getsockname(SOCKET fd, struct sockaddr* name, socklen_t* namelen) +{ + return ::getsockname(fd, name, namelen); +} + +int OperatingSystemImpl::write(int fd, const char* buffer, int len) +{ + return static_cast(::write(fd, buffer, static_cast(len))); +} + +int OperatingSystemImpl::read(int fd, char* buffer, int len) +{ + return static_cast(::read(fd, buffer, static_cast(len))); +} + +int OperatingSystemImpl::send(SOCKET fd, const char* buffer, int len, int flags) +{ #if defined(WIN32) || defined(__MINGW32__) - return ::send(fd, static_cast(buffer), len, flags); + return ::send(fd, static_cast(buffer), len, flags); #else - return ::send(fd, buffer, len, flags); + return static_cast(::send(fd, buffer, static_cast(len), flags)); #endif - } +} - int OperatingSystemImpl::recv(SOCKET fd, char* buffer, int len, int flags) - { +int OperatingSystemImpl::recv(SOCKET fd, char* buffer, int len, int flags) +{ #if defined(WIN32) || defined(__MINGW32__) - return ::recv(fd, static_cast(buffer), len, flags); + return ::recv(fd, static_cast(buffer), len, flags); #else - return ::recv(fd, buffer, len, flags); + return static_cast(::recv(fd, buffer, static_cast(len), flags)); #endif - } +} - int OperatingSystemImpl::getLastError() - { - int err = -1; +int OperatingSystemImpl::getLastError() +{ + int err = -1; #if defined(WIN32) || defined(__MINGW32__) - err = ::GetLastError(); + err = ::GetLastError(); #else - err = errno; + err = errno; #endif - if (err == SOCKETERROR(EINPROGRESS) || err == EAGAIN) - { - err = SOCKETERROR(EWOULDBLOCK); - } - return err; - } - - - int OperatingSystemImpl::select(int nfds, fd_set* readfds, fd_set* writefds, fd_set* exceptfds, struct timeval* timeout) + if (err == SOCKETERROR(EINPROGRESS) || err == EAGAIN) { - int err = ::select(nfds, readfds, writefds, exceptfds, timeout); - return err; + err = SOCKETERROR(EWOULDBLOCK); } + return err; +} - - - +int OperatingSystemImpl::select(int nfds, fd_set* readfds, fd_set* writefds, fd_set* exceptfds, struct timeval* timeout) +{ + int err = ::select(nfds, readfds, writefds, exceptfds, timeout); + return err; +} #if defined(WIN32) || defined(__MINGW32__) || defined(__QNX__) - int OperatingSystemImpl::makeSocketPair(SocketDescriptorPtr& socket1, SocketDescriptorPtr& socket2) - { - socket1 = nullptr; - socket2 = nullptr; - - SOCKET fdAccept = OperatingSystem::instance().socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); - if (fdAccept == -1) { - perror("socket"); - return -1; - } - SocketDescriptorPtr fileDescriptorAccept(std::make_shared(fdAccept)); - - SOCKET fdClient = OperatingSystem::instance().socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); - if (fdClient == -1) { - perror("socket"); - return -1; - } - SocketDescriptorPtr fileDescriptorClient = std::make_shared(fdClient); - setLinger(fdClient, true, 0); - setNoDelay(fdClient, true); - - int b = 1; - if (OperatingSystem::instance().setsockopt(fdAccept, SOL_SOCKET, SO_REUSEADDR, (const char*)&b, sizeof(int)) == -1) { - perror("setsockopt"); - return -1; - } - - struct sockaddr_in addrBind = { 0, 0, 0, 0,{} }; - addrBind.sin_family = AF_INET; - addrBind.sin_port = 0; - addrBind.sin_addr.s_addr = htonl(INADDR_LOOPBACK); - if (OperatingSystem::instance().bind(fdAccept, (struct sockaddr*)&addrBind, sizeof(addrBind)) == -1) { - perror("bind"); - return -1; - } - - if (OperatingSystem::instance().listen(fdAccept, 50) == -1) { - perror("listen"); - return -1; - } - - struct sockaddr addr = { 0, 0, 0, 0 }; - socklen_t lenaddr = sizeof(addr); - if (OperatingSystem::instance().getsockname(fdAccept, &addr, &lenaddr) == -1) { - perror("getsockname"); - return -1; - } - if (OperatingSystem::instance().connect(fdClient, &addr, sizeof(addr)) == -1) { - fprintf(stderr, "connect wsaerrr %d\n", OperatingSystem::instance().getLastError()); - return -1; - } - - SOCKET fdServer = OperatingSystem::instance().accept(fdAccept, &addr, &lenaddr); - if (fdServer == INVALID_SOCKET) { - perror("accept"); - return -1; - } - socket1 = std::make_shared(fdServer); - socket2 = fileDescriptorClient; - - setNonBlocking(fdClient, true); - setNonBlocking(fdServer, true); - setLinger(fdServer, true, 0); - setNoDelay(fdServer, true); - - fileDescriptorAccept = nullptr; - - return 0; - } - -#else +int OperatingSystemImpl::makeSocketPair(SocketDescriptorPtr& socket1, SocketDescriptorPtr& socket2) +{ + socket1 = nullptr; + socket2 = nullptr; - int OperatingSystemImpl::epoll_create1(int flags) + SOCKET fdAccept = OperatingSystem::instance().socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (fdAccept == -1) { - int err = ::epoll_create1(flags); - return err; + perror("socket"); + return -1; } + SocketDescriptorPtr fileDescriptorAccept(std::make_shared(fdAccept)); - int OperatingSystemImpl::epoll_ctl(int epfd, int op, int fd, struct epoll_event* event) + SOCKET fdClient = OperatingSystem::instance().socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (fdClient == -1) { - int err = ::epoll_ctl(epfd, op, fd, event); - return err; + perror("socket"); + return -1; } + SocketDescriptorPtr fileDescriptorClient = std::make_shared(fdClient); + setLinger(fdClient, true, 0); + setNoDelay(fdClient, true); - int OperatingSystemImpl::epoll_pwait(int epfd, struct epoll_event* events, int maxevents, int timeout, const sigset_t* sigmask) + int b = 1; + if (OperatingSystem::instance().setsockopt(fdAccept, SOL_SOCKET, SO_REUSEADDR, (const char*)&b, sizeof(int)) == -1) { - int err = ::epoll_pwait(epfd, events, maxevents, timeout, sigmask); - return err; + perror("setsockopt"); + return -1; } - - int OperatingSystemImpl::makeSocketPair(SocketDescriptorPtr& socket1, SocketDescriptorPtr& socket2) + struct sockaddr_in addrBind = {0, 0, 0, 0, {}}; + addrBind.sin_family = AF_INET; + addrBind.sin_port = 0; + addrBind.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + if (OperatingSystem::instance().bind(fdAccept, (struct sockaddr*)&addrBind, sizeof(addrBind)) == -1) { - int sds[2]; - int res = socketpair(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK, 0, sds); - if (res == 0) - { - setNonBlocking(sds[0], true); - setLinger(sds[0], true, 0); - setNoDelay(sds[0], true); - setNonBlocking(sds[1], true); - setLinger(sds[1], true, 0); - setNoDelay(sds[1], true); - - socket1 = std::make_shared(sds[0]); - socket2 = std::make_shared(sds[1]); - } - return res; + perror("bind"); + return -1; } - -#endif - - - - int OperatingSystemImpl::ioctlInt(SOCKET fd, unsigned long int request, int* value) + if (OperatingSystem::instance().listen(fdAccept, 50) == -1) { -#if defined(WIN32) || defined(__MINGW32__) - u_long val = 0; - int err = ioctlsocket(fd, request, &val); - *value = val; -#else - int err = ::ioctl(fd, request, value); -#endif - return err; + perror("listen"); + return -1; } - - - - int OperatingSystemImpl::setNoDelay(SOCKET fd, bool noDelay) + struct sockaddr addr = {0, 0, 0, 0}; + socklen_t lenaddr = sizeof(addr); + if (OperatingSystem::instance().getsockname(fdAccept, &addr, &lenaddr) == -1) { - int val = noDelay ? 1 : 0; - int res = setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char*)&val, sizeof(val)); - return res; + perror("getsockname"); + return -1; } - - - int OperatingSystemImpl::setNonBlocking(SOCKET fd, bool nonBlock) + if (OperatingSystem::instance().connect(fdClient, &addr, sizeof(addr)) == -1) { -#if defined(WIN32) || defined(__MINGW32__) - unsigned long val = (nonBlock) ? 1 : 0; // set non-blocking - int res = ioctlsocket(fd, FIONBIO, &val); -#else - int res = fcntl(fd, F_GETFL, 0); - if (res != -1) - { - int val = (nonBlock) ? (res | O_NONBLOCK) : (res & ~O_NONBLOCK); - res = fcntl(fd, F_SETFL, val); - } -#endif - return res; + fprintf(stderr, "connect wsaerrr %d\n", OperatingSystem::instance().getLastError()); + return -1; } - - int OperatingSystemImpl::setLinger(SOCKET fd, bool on, int timeToLinger) + SOCKET fdServer = OperatingSystem::instance().accept(fdAccept, &addr, &lenaddr); + if (fdServer == INVALID_SOCKET) { - struct linger l; - l.l_onoff = on; - l.l_linger = timeToLinger; - int res = setsockopt(fd, SOL_SOCKET, SO_LINGER, (const char*)&l, sizeof(l)); - return res; + perror("accept"); + return -1; } + socket1 = std::make_shared(fdServer); + socket2 = fileDescriptorClient; + setNonBlocking(fdClient, true); + setNonBlocking(fdServer, true); + setLinger(fdServer, true, 0); + setNoDelay(fdServer, true); + fileDescriptorAccept = nullptr; + return 0; +} - ////////////////////////////////////// - /// OperatingSystem +#else - void OperatingSystem::setInstance(std::unique_ptr&& instanceUniquePtr) - { - getStaticUniquePtrRef() = std::move(instanceUniquePtr); - getStaticInstanceRef().store(getStaticUniquePtrRef().get(), std::memory_order_release); - } +int OperatingSystemImpl::epoll_create1(int flags) +{ + int err = ::epoll_create1(flags); + return err; +} + +int OperatingSystemImpl::epoll_ctl(int epfd, int op, int fd, struct epoll_event* event) +{ + int err = ::epoll_ctl(epfd, op, fd, event); + return err; +} + +int OperatingSystemImpl::epoll_pwait(int epfd, struct epoll_event* events, int maxevents, int timeout, const sigset_t* sigmask) +{ + int err = ::epoll_pwait(epfd, events, maxevents, timeout, sigmask); + return err; +} + +int OperatingSystemImpl::makeSocketPair(SocketDescriptorPtr& socket1, SocketDescriptorPtr& socket2) +{ + int sds[2]; + int res = socketpair(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK, 0, sds); + if (res == 0) + { + setNonBlocking(sds[0], true); + setLinger(sds[0], true, 0); + setNoDelay(sds[0], true); + setNonBlocking(sds[1], true); + setLinger(sds[1], true, 0); + setNoDelay(sds[1], true); + + socket1 = std::make_shared(sds[0]); + socket2 = std::make_shared(sds[1]); + } + return res; +} - IOperatingSystem* OperatingSystem::createInstance() - { - static std::mutex mutex; - std::unique_lock lock(mutex); - IOperatingSystem* inst = getStaticInstanceRef().load(std::memory_order_relaxed); - if (!inst) - { - setInstance(std::make_unique()); - inst = getStaticInstanceRef().load(std::memory_order_relaxed); - } - return inst; - } - - std::atomic& OperatingSystem::getStaticInstanceRef() - { - static std::atomic instance; - return instance; - } +#endif - std::unique_ptr& OperatingSystem::getStaticUniquePtrRef() +int OperatingSystemImpl::ioctlInt(SOCKET fd, unsigned long int request, int* value) +{ +#if defined(WIN32) || defined(__MINGW32__) + u_long val = 0; + int err = ioctlsocket(fd, request, &val); + *value = val; +#else + int err = ::ioctl(fd, request, value); +#endif + return err; +} + +int OperatingSystemImpl::setNoDelay(SOCKET fd, bool noDelay) +{ + int val = noDelay ? 1 : 0; + int res = setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, static_cast(static_cast(&val)), sizeof(val)); + return res; +} + +int OperatingSystemImpl::setNonBlocking(SOCKET fd, bool nonBlock) +{ +#if defined(WIN32) || defined(__MINGW32__) + unsigned long val = (nonBlock) ? 1 : 0; // set non-blocking + int res = ioctlsocket(fd, FIONBIO, &val); +#else + int res = fcntl(fd, F_GETFL, 0); + if (res != -1) { - static std::unique_ptr instanceUniquePtr; - return instanceUniquePtr; + int val = (nonBlock) ? (res | O_NONBLOCK) : (res & ~O_NONBLOCK); + res = fcntl(fd, F_SETFL, val); } - -} // namespace finalmq +#endif + return res; +} + +int OperatingSystemImpl::setLinger(SOCKET fd, bool on, int timeToLinger) +{ + struct linger l; + l.l_onoff = on; + l.l_linger = timeToLinger; + int res = setsockopt(fd, SOL_SOCKET, SO_LINGER, static_cast(static_cast(&l)), sizeof(l)); + return res; +} + +////////////////////////////////////// +/// OperatingSystem + +void OperatingSystem::setInstance(std::unique_ptr&& instanceUniquePtr) +{ + getStaticUniquePtrRef() = std::move(instanceUniquePtr); + getStaticInstanceRef().store(getStaticUniquePtrRef().get(), std::memory_order_release); +} + +IOperatingSystem* OperatingSystem::createInstance() +{ + static std::mutex mutex; + std::unique_lock lock(mutex); + IOperatingSystem* inst = getStaticInstanceRef().load(std::memory_order_relaxed); + if (!inst) + { + setInstance(std::make_unique()); + inst = getStaticInstanceRef().load(std::memory_order_relaxed); + } + return inst; +} + +std::atomic& OperatingSystem::getStaticInstanceRef() +{ + static std::atomic instance; + return instance; +} + +std::unique_ptr& OperatingSystem::getStaticUniquePtrRef() +{ + static std::unique_ptr instanceUniquePtr; + return instanceUniquePtr; +} + +} // namespace finalmq diff --git a/src/helpers/Utils.cpp b/src/helpers/Utils.cpp index 838879b8..97e4c080 100644 --- a/src/helpers/Utils.cpp +++ b/src/helpers/Utils.cpp @@ -21,14 +21,14 @@ //SOFTWARE. #include "finalmq/helpers/Utils.h" -#include "finalmq/helpers/OperatingSystem.h" -#include +#include #include +#include "finalmq/helpers/OperatingSystem.h" -namespace finalmq { - +namespace finalmq +{ void Utils::split(const std::string& src, ssize_t indexBegin, ssize_t indexEnd, char delimiter, std::vector& dest) { while (indexBegin < indexEnd) @@ -48,7 +48,7 @@ void Utils::split(const std::string& src, ssize_t indexBegin, ssize_t indexEnd, std::string Utils::replaceAll(std::string str, const std::string& from, const std::string& to) { size_t start_pos = 0; - while ((start_pos = str.find(from, start_pos)) != std::string::npos) + while ((start_pos = str.find(from, start_pos)) != std::string::npos) { str.replace(start_pos, from.length(), to); start_pos += to.length(); // Handles case where 'to' is a substring of 'from' @@ -64,12 +64,12 @@ int Utils::readAll(const std::string& filename, std::string& buffer) { int fd = OperatingSystem::instance().open(filename.c_str(), O_RDONLY #if defined(WIN32) || defined(__MINGW32__) - | O_BINARY + | O_BINARY #endif ); if (fd >= 0) { - int size = s.st_size; + int size = static_cast(s.st_size); buffer.resize(size); char* buf = const_cast(buffer.data()); @@ -91,7 +91,6 @@ int Utils::readAll(const std::string& filename, std::string& buffer) } } while (size > 0 && res > 0); - OperatingSystem::instance().close(fd); } else @@ -102,6 +101,4 @@ int Utils::readAll(const std::string& filename, std::string& buffer) return res; } - - } // namespace finalmq diff --git a/src/helpers/base64.cpp b/src/helpers/base64.cpp index 3fcf94b7..c7f57cf6 100644 --- a/src/helpers/base64.cpp +++ b/src/helpers/base64.cpp @@ -26,50 +26,288 @@ */ #include "finalmq/helpers/base64.h" + +#include "assert.h" #include "ctype.h" #include "string.h" -#include "assert.h" - namespace finalmq { - -static const char* base64_chars = - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz" - "0123456789+/"; - -static const unsigned char tab[256] = { - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -// + / - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3E, 0x00, 0x00, 0x00, 0x3F, -// 0 1 2 3 4 5 6 7 8 9 - 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -// A B C D E F G H I J K L M N O - 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, -// P Q R S T U V W X Y Z - 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x00, 0x00, 0x00, 0x00, 0x00, -// a b c d e f g h i j k l m n o - 0x00, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, -// p q r s t u v w x y z - 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +static const char* base64_chars = + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789+/"; + +static const unsigned char tab[256] = { + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + // + / + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x3E, + 0x00, + 0x00, + 0x00, + 0x3F, + // 0 1 2 3 4 5 6 7 8 9 + 0x34, + 0x35, + 0x36, + 0x37, + 0x38, + 0x39, + 0x3A, + 0x3B, + 0x3C, + 0x3D, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + // A B C D E F G H I J K L M N O + 0x00, + 0x00, + 0x01, + 0x02, + 0x03, + 0x04, + 0x05, + 0x06, + 0x07, + 0x08, + 0x09, + 0x0A, + 0x0B, + 0x0C, + 0x0D, + 0x0E, + // P Q R S T U V W X Y Z + 0x0F, + 0x10, + 0x11, + 0x12, + 0x13, + 0x14, + 0x15, + 0x16, + 0x17, + 0x18, + 0x19, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + // a b c d e f g h i j k l m n o + 0x00, + 0x1A, + 0x1B, + 0x1C, + 0x1D, + 0x1E, + 0x1F, + 0x20, + 0x21, + 0x22, + 0x23, + 0x24, + 0x25, + 0x26, + 0x27, + 0x28, + // p q r s t u v w x y z + 0x29, + 0x2A, + 0x2B, + 0x2C, + 0x2D, + 0x2E, + 0x2F, + 0x30, + 0x31, + 0x32, + 0x33, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, }; -static inline bool is_base64(unsigned char c) { - return (isalnum(c) || (c == '+') || (c == '/')); +static inline bool is_base64(unsigned char c) +{ + return (isalnum(c) || (c == '+') || (c == '/')); } - - void Base64::encode(const std::vector& src, std::string& dest) { encode(src.data(), src.size(), dest); @@ -77,46 +315,48 @@ void Base64::encode(const std::vector& src, std::string& dest) void Base64::encode(const char* src, ssize_t len, std::string& dest) { - ssize_t ixDest = 0; - ssize_t i = 0; - ssize_t j = 0; - unsigned char char_array_3[3]; - unsigned char char_array_4[4] = {0}; - - dest.resize(encodeSize(len)); - - while (len--) { - char_array_3[i++] = *(src++); - if (i == 3) { - char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; - char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); - char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); - char_array_4[3] = char_array_3[2] & 0x3f; - - for(i = 0; (i <4) ; i++) - dest[ixDest++] = base64_chars[char_array_4[i]]; - i = 0; + ssize_t ixDest = 0; + ssize_t i = 0; + ssize_t j = 0; + unsigned char char_array_3[3]; + unsigned char char_array_4[4] = {0}; + + dest.resize(encodeSize(len)); + + while (len--) + { + char_array_3[i++] = *(src++); + if (i == 3) + { + char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; + char_array_4[1] = static_cast(((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4)); + char_array_4[2] = static_cast(((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6)); + char_array_4[3] = char_array_3[2] & 0x3f; + + for (i = 0; (i < 4); i++) + dest[ixDest++] = base64_chars[char_array_4[i]]; + i = 0; + } } - } - - if (i) - { - for(j = i; j < 3; j++) - char_array_3[j] = '\0'; - - char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; - char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); - char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); - char_array_4[3] = char_array_3[2] & 0x3f; - - for (j = 0; (j < i + 1); j++) - dest[ixDest++] = base64_chars[char_array_4[j]]; - - while((i++ < 3)) - dest[ixDest++] = '='; - } - assert(ixDest < (ssize_t)dest.size()); - dest.resize(ixDest); + + if (i) + { + for (j = i; j < 3; j++) + char_array_3[j] = '\0'; + + char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; + char_array_4[1] = static_cast(((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4)); + char_array_4[2] = static_cast(((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6)); + char_array_4[3] = char_array_3[2] & 0x3f; + + for (j = 0; (j < i + 1); j++) + dest[ixDest++] = base64_chars[char_array_4[j]]; + + while ((i++ < 3)) + dest[ixDest++] = '='; + } + assert(ixDest < (ssize_t)dest.size()); + dest.resize(ixDest); } ssize_t Base64::decode(const std::string& src, std::vector& dest) @@ -126,48 +366,53 @@ ssize_t Base64::decode(const std::string& src, std::vector& dest) ssize_t Base64::decode(const char* src, ssize_t len, std::vector& dest) { - ssize_t ixDest = 0; - dest.resize(decodeSize(len)); - ssize_t i = 0; - ssize_t j = 0; - ssize_t in_ = 0; - unsigned char char_array_4[4]; - unsigned char char_array_3[3] = {0}; - - while (len-- && ( src[in_] != '=') && is_base64(src[in_])) { - char_array_4[i++] = src[in_]; in_++; - if (i ==4) { - for (i = 0; i <4; i++) - char_array_4[i] = tab[char_array_4[i]]; - - char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); - char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); - char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; - - for (i = 0; (i < 3); i++) - dest[ixDest++] = char_array_3[i]; - i = 0; + ssize_t ixDest = 0; + dest.resize(decodeSize(len)); + ssize_t i = 0; + ssize_t j = 0; + ssize_t in_ = 0; + unsigned char char_array_4[4]; + unsigned char char_array_3[3] = {0}; + + while (len-- && (src[in_] != '=') && is_base64(src[in_])) + { + char_array_4[i++] = src[in_]; + in_++; + if (i == 4) + { + for (i = 0; i < 4; i++) + char_array_4[i] = tab[char_array_4[i]]; + + char_array_3[0] = static_cast((char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4)); + char_array_3[1] = static_cast(((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2)); + char_array_3[2] = static_cast(((char_array_4[2] & 0x3) << 6) + char_array_4[3]); + + for (i = 0; (i < 3); i++) + dest[ixDest++] = char_array_3[i]; + i = 0; + } } - } - if (i) { - for (j = i; j <4; j++) - char_array_4[j] = 0; + if (i) + { + for (j = i; j < 4; j++) + char_array_4[j] = 0; - for (j = 0; j <4; j++) - char_array_4[j] = tab[char_array_4[j]]; + for (j = 0; j < 4; j++) + char_array_4[j] = tab[char_array_4[j]]; - char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); - char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); - char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; + char_array_3[0] = static_cast((char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4)); + char_array_3[1] = static_cast(((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2)); + char_array_3[2] = static_cast(((char_array_4[2] & 0x3) << 6) + char_array_4[3]); - for (j = 0; (j < i - 1); j++) dest[ixDest++] = char_array_3[j]; - } + for (j = 0; (j < i - 1); j++) + dest[ixDest++] = char_array_3[j]; + } - assert(ixDest < (ssize_t)dest.size()); - dest.resize(ixDest); + assert(ixDest < (ssize_t)dest.size()); + dest.resize(ixDest); - return ixDest; + return ixDest; } -} +} // namespace finalmq diff --git a/src/hl7/Hl7Builder.cpp b/src/hl7/Hl7Builder.cpp index bab6c33f..f6478869 100644 --- a/src/hl7/Hl7Builder.cpp +++ b/src/hl7/Hl7Builder.cpp @@ -20,41 +20,38 @@ //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. - #include "finalmq/hl7/Hl7Builder.h" -#include "finalmq/conversions/itoa.h" -#include "finalmq/conversions/dtoa.h" -#include "finalmq/logger/LogStream.h" -#include -#include #include +#include +#include -namespace finalmq { +#include "finalmq/conversions/dtoa.h" +#include "finalmq/conversions/itoa.h" +#include "finalmq/logger/LogStream.h" -static const char SEGMENT_END = 0x0D; // '\r' +namespace finalmq +{ +static const char SEGMENT_END = 0x0D; // '\r' //static const char MESSAGE_START = 0x0B; //static const char MESSAGE_END1 = 0x1C; //static const char MESSAGE_END2 = 0x0D; // '\r' - Hl7Builder::Hl7Builder(IZeroCopyBuffer& buffer, int maxBlockSize, const std::string& delimiters) - : m_zeroCopybuffer(buffer) - , m_maxBlockSize(maxBlockSize) - , m_root(std::make_unique()) + : m_zeroCopybuffer(buffer), m_maxBlockSize(maxBlockSize), m_root(std::make_unique()) { assert(delimiters.size() == 5); m_delimitersForField = delimiters; - m_delimitersForField += delimiters[0]; // |^~\&| - m_delimiterField[0] = SEGMENT_END; // segment delimiter '\r', 0x0D - m_delimiterField[1] = delimiters[0]; // | - m_delimiterField[2] = delimiters[2]; // ~ - m_delimiterField[3] = delimiters[1]; // ^ - m_delimiterField[4] = delimiters[4]; // & - m_delimiterRepeat = delimiters[2]; // ~ - m_escape = delimiters[3]; // '\\' + m_delimitersForField += delimiters[0]; // |^~\&| + m_delimiterField[0] = SEGMENT_END; // segment delimiter '\r', 0x0D + m_delimiterField[1] = delimiters[0]; // | + m_delimiterField[2] = delimiters[2]; // ~ + m_delimiterField[3] = delimiters[1]; // ^ + m_delimiterField[4] = delimiters[4]; // & + m_delimiterRepeat = delimiters[2]; // ~ + m_escape = delimiters[3]; // '\\' } Hl7Builder::~Hl7Builder() @@ -62,7 +59,6 @@ Hl7Builder::~Hl7Builder() m_root.reset(); } - void Hl7Builder::reserveSpace(ssize_t space) { ssize_t sizeRemaining = m_bufferEnd - m_buffer; @@ -102,7 +98,6 @@ void Hl7Builder::resizeBuffer() } } - class Hl7Node { public: @@ -143,14 +138,13 @@ class Hl7Node } } - std::string m_segmentId; - std::vector m_nodes; - std::vector m_strings; + std::string m_segmentId{}; + std::vector m_nodes{}; + std::vector m_strings{}; }; // IJsonParserVisitor - void Hl7Builder::enterNull(const int* levelIndex, int sizeLevelIndex, int index) { m_root->enterString(levelIndex, sizeLevelIndex, index, std::string("\"\"")); @@ -186,7 +180,6 @@ void Hl7Builder::addArrayStruct(const int* levelIndex, int sizeLevelIndex, int i m_root->enterString(levelIndex, sizeLevelIndex, index, ""); } - void Hl7Builder::finished() { reserveSpace(3 + m_delimitersForField.size()); @@ -203,14 +196,13 @@ void Hl7Builder::finished() m_root.reset(); } - void Hl7Builder::serialize(const Hl7Node& node, int index, int iStart) { const std::vector& nodes = node.m_nodes; for (size_t i = iStart; i < nodes.size(); ++i) { - const Hl7Node& subNode = nodes[i]; + const Hl7Node& subNode = nodes[i]; if (i != 0 && index == 0 && !subNode.m_segmentId.empty()) { @@ -227,7 +219,7 @@ void Hl7Builder::serialize(const Hl7Node& node, int index, int iStart) if (!subNode.m_nodes.empty()) { - serialize(subNode, index + 1, (index == 0 && i == 0) ? 2 : 0); // skip MSH|^~\&| + serialize(subNode, index + 1, (index == 0 && i == 0) ? 2 : 0); // skip MSH|^~\&| } else { @@ -255,10 +247,9 @@ void Hl7Builder::serialize(const Hl7Node& node, int index, int iStart) } } - void Hl7Builder::escapeString(const char* str, ssize_t size) { - static const char hexDigits[16]{ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; + static const char hexDigits[16]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; const char* end = str + size; @@ -280,7 +271,7 @@ void Hl7Builder::escapeString(const char* str, ssize_t size) } else { - if (c == m_delimiterField[1]) // '|' + if (c == m_delimiterField[1]) // '|' { *m_buffer = m_escape; m_buffer++; @@ -289,7 +280,7 @@ void Hl7Builder::escapeString(const char* str, ssize_t size) *m_buffer = m_escape; m_buffer++; } - else if (c == m_delimiterField[3]) // '^' + else if (c == m_delimiterField[3]) // '^' { *m_buffer = m_escape; m_buffer++; @@ -298,7 +289,7 @@ void Hl7Builder::escapeString(const char* str, ssize_t size) *m_buffer = m_escape; m_buffer++; } - else if (c == m_delimiterField[4]) // '&' + else if (c == m_delimiterField[4]) // '&' { *m_buffer = m_escape; m_buffer++; @@ -307,7 +298,7 @@ void Hl7Builder::escapeString(const char* str, ssize_t size) *m_buffer = m_escape; m_buffer++; } - else if (c == m_escape) // '\\' + else if (c == m_escape) // '\\' { *m_buffer = m_escape; m_buffer++; @@ -316,7 +307,7 @@ void Hl7Builder::escapeString(const char* str, ssize_t size) *m_buffer = m_escape; m_buffer++; } - else if (c == m_delimiterRepeat) // '~' + else if (c == m_delimiterRepeat) // '~' { *m_buffer = m_escape; m_buffer++; @@ -335,4 +326,4 @@ void Hl7Builder::escapeString(const char* str, ssize_t size) } } -} // namespace finalmq +} // namespace finalmq diff --git a/src/hl7/Hl7Parser.cpp b/src/hl7/Hl7Parser.cpp index 198a4fa1..8850a288 100644 --- a/src/hl7/Hl7Parser.cpp +++ b/src/hl7/Hl7Parser.cpp @@ -21,34 +21,28 @@ //SOFTWARE. #include "finalmq/hl7/Hl7Parser.h" -#include "finalmq/helpers/FmqDefines.h" -#include #include #include -#include - - +#include -namespace finalmq { +#include -static const char SEGMENT_END = 0x0D; // '\r' +#include "finalmq/helpers/FmqDefines.h" +namespace finalmq +{ +static const char SEGMENT_END = 0x0D; // '\r' Hl7Parser::Hl7Parser() { } - char Hl7Parser::getChar(const char* str) const { return ((str < m_end) ? *str : 0); } - - - - bool Hl7Parser::startParse(const char* str, ssize_t size) { m_str = str; @@ -57,40 +51,25 @@ bool Hl7Parser::startParse(const char* str, ssize_t size) { if (size == CHECK_ON_ZEROTERM) { - m_end = (char*)nullptr - 1; // highest possible address - } - else - { - m_end = str + size; + size = strlen(str); } + m_end = str + size; + skipControlCharacters(); - if (size == CHECK_ON_ZEROTERM) - { - for (int i = 0; i < 8; ++i) - { - if (m_str[i] == 0) - { - return false; - } - } - } - else + if (size < 8) { - if (size < 8) - { - return false; - } + return false; } if (m_str[0] == 'M' && m_str[1] == 'S' && m_str[2] == 'H') { - m_delimiterField[0] = SEGMENT_END; // segment delimiter '\r', 0x0D - m_delimiterField[1] = m_str[3 + 0]; // | - m_delimiterField[2] = m_str[3 + 1]; // ^ - m_delimiterField[3] = m_str[3 + 4]; // & - m_delimiterRepeat = m_str[3 + 2]; // ~ - m_escape = m_str[3 + 3]; // '\\' + m_delimiterField[0] = SEGMENT_END; // segment delimiter '\r', 0x0D + m_delimiterField[1] = m_str[3 + 0]; // | + m_delimiterField[2] = m_str[3 + 1]; // ^ + m_delimiterField[3] = m_str[3 + 4]; // & + m_delimiterRepeat = m_str[3 + 2]; // ~ + m_escape = m_str[3 + 3]; // '\\' } else { @@ -100,7 +79,6 @@ bool Hl7Parser::startParse(const char* str, ssize_t size) return true; } - int Hl7Parser::isDelimiter(char c) const { if (c == 0) @@ -119,7 +97,6 @@ int Hl7Parser::isDelimiter(char c) const return i; } - void Hl7Parser::getSegmentId(std::string& token) const { token.clear(); @@ -139,7 +116,6 @@ void Hl7Parser::getSegmentId(std::string& token) const } } - int Hl7Parser::isNextFieldFilled(int level, bool& filled) { filled = false; @@ -167,7 +143,6 @@ int Hl7Parser::isNextFieldFilled(int level, bool& filled) return l; } - int Hl7Parser::parseToken(int level, std::string& token, bool& isarray) { token.clear(); @@ -196,7 +171,7 @@ int Hl7Parser::parseToken(int level, std::string& token, bool& isarray) token = deEscape(start, m_str); ++m_str; isarray = true; - l = 1; // array is only on level = 1 + l = 1; // array is only on level = 1 break; } else @@ -250,7 +225,7 @@ int Hl7Parser::parseTokenArray(int level, std::vector& array) l = isDelimiter(c); if (l < LAYER_MAX) { - if (filled || (l > 1)) // array/repeated (~) is on layer 1 possible + if (filled || (l > 1)) // array/repeated (~) is on layer 1 possible { array.emplace_back(deEscape(start, m_str)); } @@ -290,7 +265,6 @@ int Hl7Parser::parseTillEndOfStruct(int level) return parseTillEndOfStructIntern(level, false, isarrayDummy); } - int Hl7Parser::parseTillEndOfStructIntern(int level, bool stopOnArray, bool& isarray) { isarray = false; @@ -322,8 +296,6 @@ const char* Hl7Parser::getCurrentPosition() const return m_str; } - - void Hl7Parser::skipControlCharacters() { while (true) @@ -340,29 +312,28 @@ void Hl7Parser::skipControlCharacters() } } -static char hex2char(char c) +static unsigned char hex2char(char c) { - char num = 0; + unsigned char num = 0; if ('0' <= c && c <= '9') { - num = c - '0'; + num = static_cast(c - '0'); } else if ('a' <= c && c <= 'f') { - num = (c - 'a') + 10; - } + num = static_cast((c - 'a') + 10); + } else if ('A' <= c && c <= 'F') { - num = (c - 'A') + 10; + num = static_cast((c - 'A') + 10); } else { - num = static_cast(0xff); + num = static_cast(0xff); } return num; } - std::string Hl7Parser::deEscape(const char* start, const char* end) const { std::string dest; @@ -378,65 +349,65 @@ std::string Hl7Parser::deEscape(const char* start, const char* end) const return dest; } c = *src; - switch (c) + switch(c) { - case 'E': - dest += m_escape; - ++src; - break; - case 'F': - dest += m_delimiterField[1]; // | - ++src; - break; - case 'R': - dest += m_delimiterRepeat; // ~ - ++src; - break; - case 'S': - dest += m_delimiterField[2]; // ^ - ++src; - break; - case 'T': - dest += m_delimiterField[3]; // & - ++src; - break; - case 'X': - while (true) - { + case 'E': + dest += m_escape; ++src; - if (src >= end) - { - break; - } - c = *src; - if (c == '\\') - { - break; - } - char num = hex2char(c); - if ((unsigned char)num == 0xff) - { - return dest; - } - char d = num; + break; + case 'F': + dest += m_delimiterField[1]; // | ++src; - if (src >= end) - { - break; - } - c = *src; - num = hex2char(c); - if ((unsigned char)num == 0xff) + break; + case 'R': + dest += m_delimiterRepeat; // ~ + ++src; + break; + case 'S': + dest += m_delimiterField[2]; // ^ + ++src; + break; + case 'T': + dest += m_delimiterField[3]; // & + ++src; + break; + case 'X': + while (true) { - return dest; + ++src; + if (src >= end) + { + break; + } + c = *src; + if (c == '\\') + { + break; + } + unsigned char num = hex2char(c); + if (num == static_cast(0xff)) + { + return dest; + } + unsigned char d = num; + ++src; + if (src >= end) + { + break; + } + c = *src; + num = hex2char(c); + if (num == static_cast(0xff)) + { + return dest; + } + d = static_cast(d << 4); + d |= num; + dest += d; } - d <<= 4; - d |= num; - dest += d; - } - break; - default: - break; + break; + default: + break; } } else @@ -449,6 +420,4 @@ std::string Hl7Parser::deEscape(const char* start, const char* end) const return dest; } - - -} // namespace finalmq +} // namespace finalmq diff --git a/src/json/JsonParser.cpp b/src/json/JsonParser.cpp index e89db3a4..6c5d2ee2 100644 --- a/src/json/JsonParser.cpp +++ b/src/json/JsonParser.cpp @@ -21,73 +21,64 @@ //SOFTWARE. #include "finalmq/json/JsonParser.h" -#include "finalmq/helpers/FmqDefines.h" -#include #include #include -#include - - +#include -namespace finalmq { +#include +#include "finalmq/helpers/FmqDefines.h" +namespace finalmq +{ JsonParser::JsonParser(IJsonParserVisitor& visitor) : m_visitor(visitor) { } - char JsonParser::getChar(const char* str) const { return ((str < m_end) ? *str : 0); } - - const char* JsonParser::parseWhiteSpace(const char* str) { char c; while ((c = this->getChar(str)) != 0) { - switch (c) - { - case ' ': - case '\t': - case '\n': - case '\r': - str++; - break; - default: - return str; - break; + switch(c) + { + case ' ': + case '\t': + case '\n': + case '\r': + str++; + break; + default: + return str; + break; } } return str; } - const char* JsonParser::parse(const char* str, ssize_t size) { if (size >= CHECK_ON_ZEROTERM) { if (size == CHECK_ON_ZEROTERM) { - m_end = (char*)nullptr - 1; // highest possible address - } - else - { - m_end = str + size; + size = strlen(str); } + + m_end = str + size; } const char* ret = parseValue(str); m_visitor.finished(); return ret; } - - const char* JsonParser::parseValue(const char* str) { str = parseWhiteSpace(str); @@ -97,31 +88,31 @@ const char* JsonParser::parseValue(const char* str) m_visitor.syntaxError(str, "value expected"); return nullptr; } - switch (c) + switch(c) { - // string - case '\"': - str = parseString(str, false); - break; - // object - case '{': - str = parseObject(str); - break; - case '[': - str = parseArray(str); - break; - case 'n': - str = parseNull(str); - break; - case 't': - str = parseTrue(str); - break; - case 'f': - str = parseFalse(str); - break; - default: - str = parseNumber(str); - break; + // string + case '\"': + str = parseString(str, false); + break; + // object + case '{': + str = parseObject(str); + break; + case '[': + str = parseArray(str); + break; + case 'n': + str = parseNull(str); + break; + case 't': + str = parseTrue(str); + break; + case 'f': + str = parseFalse(str); + break; + default: + str = parseNumber(str); + break; } if (str) { @@ -131,8 +122,6 @@ const char* JsonParser::parseValue(const char* str) return nullptr; } - - const char* JsonParser::cmpString(const char* str, const char* strCmp) { char c; @@ -143,7 +132,7 @@ const char* JsonParser::cmpString(const char* str, const char* strCmp) std::string message; message += c; message += " expected"; - m_visitor.syntaxError(str, message.c_str()); + m_visitor.syntaxError(str, message.c_str()); return nullptr; } str++; @@ -153,7 +142,6 @@ const char* JsonParser::cmpString(const char* str, const char* strCmp) return str; } - const char* JsonParser::parseNull(const char* str) { str = cmpString(str, "null"); @@ -184,9 +172,6 @@ const char* JsonParser::parseFalse(const char* str) return str; } - - - const char* JsonParser::parseNumber(const char* str) { const char* first = str; @@ -203,7 +188,7 @@ const char* JsonParser::parseNumber(const char* str) } else { - m_visitor.syntaxError(str, "digit expected"); + m_visitor.syntaxError(str, "digit expected"); return nullptr; } } @@ -213,7 +198,7 @@ const char* JsonParser::parseNumber(const char* str) } else { - m_visitor.syntaxError(str, "digit expected"); + m_visitor.syntaxError(str, "digit expected"); return nullptr; } @@ -241,7 +226,7 @@ const char* JsonParser::parseNumber(const char* str) double value = strtof64(first, &res); if (res != str) { - m_visitor.syntaxError(res, "wrong number format"); + m_visitor.syntaxError(res, "wrong number format"); return nullptr; } m_visitor.enterDouble(value); @@ -251,7 +236,7 @@ const char* JsonParser::parseNumber(const char* str) long long value = strtoll(first, &res, 10); if (res != str) { - m_visitor.syntaxError(res, "wrong number format"); + m_visitor.syntaxError(res, "wrong number format"); return nullptr; } assert(value < 0); @@ -269,7 +254,7 @@ const char* JsonParser::parseNumber(const char* str) unsigned long long value = strtoull(first, &res, 10); if (res != str) { - m_visitor.syntaxError(res, "wrong number format"); + m_visitor.syntaxError(res, "wrong number format"); return nullptr; } if (value <= INT_MAX) @@ -288,7 +273,6 @@ const char* JsonParser::parseNumber(const char* str) return str; } - static std::int32_t getHexDigit(char c) { if (c >= '0' && c <= '9') @@ -306,7 +290,6 @@ static std::int32_t getHexDigit(char c) return -1; } - const char* JsonParser::parseUEscape(const char* str, std::uint32_t& value) { value = 0; @@ -318,14 +301,13 @@ const char* JsonParser::parseUEscape(const char* str, std::uint32_t& value) m_visitor.syntaxError(str, "invalid u escape"); return nullptr; } - v <<= 12 - 4*i; + v <<= 12 - 4 * i; value += v; str++; } return str; } - const char* JsonParser::parseString(const char* str, bool key) { // skip '"' @@ -388,27 +370,27 @@ const char* JsonParser::parseString(const char* str, bool key) { switch(c) { - case '\"': - case '\\': - case '/': - dest += c; - break; - case 'b': - dest += '\b'; - break; - case 'f': - dest += '\f'; - break; - case 'n': - dest += '\n'; - break; - case 'r': - dest += '\r'; - break; - case 't': - dest += '\t'; - break; - case 'u': + case '\"': + case '\\': + case '/': + dest += c; + break; + case 'b': + dest += '\b'; + break; + case 'f': + dest += '\f'; + break; + case 'n': + dest += '\n'; + break; + case 'r': + dest += '\r'; + break; + case 't': + dest += '\t'; + break; + case 'u': { str++; std::uint32_t num = 0; @@ -477,10 +459,10 @@ const char* JsonParser::parseString(const char* str, bool key) } } break; - default: - dest += '\\'; - dest += c; - break; + default: + dest += '\\'; + dest += c; + break; } } } @@ -494,7 +476,6 @@ const char* JsonParser::parseString(const char* str, bool key) return nullptr; } - const char* JsonParser::parseArray(const char* str) { m_visitor.enterArray(); @@ -531,7 +512,6 @@ const char* JsonParser::parseArray(const char* str) return nullptr; } - const char* JsonParser::parseObject(const char* str) { m_visitor.enterObject(); @@ -588,4 +568,4 @@ const char* JsonParser::parseObject(const char* str) return nullptr; } -} // namespace finalmq +} // namespace finalmq diff --git a/src/metadataserialize/MetaDataExchange.cpp b/src/metadataserialize/MetaDataExchange.cpp index 6b8244b2..50f7b463 100644 --- a/src/metadataserialize/MetaDataExchange.cpp +++ b/src/metadataserialize/MetaDataExchange.cpp @@ -21,28 +21,27 @@ //SOFTWARE. #include "finalmq/metadataserialize/MetaDataExchange.h" + +#include + +#include "finalmq/helpers/ZeroCopyBuffer.h" #include "finalmq/metadata/MetaData.h" #include "finalmq/serializejson/ParserJson.h" #include "finalmq/serializejson/SerializerJson.h" #include "finalmq/serializeproto/ParserProto.h" #include "finalmq/serializeproto/SerializerProto.h" -#include "finalmq/serializestruct/SerializerStruct.h" #include "finalmq/serializestruct/ParserStruct.h" -#include "finalmq/helpers/ZeroCopyBuffer.h" - -#include - - -namespace finalmq { - +#include "finalmq/serializestruct/SerializerStruct.h" +namespace finalmq +{ static MetaTypeId convert(SerializeMetaTypeId value) { return static_cast(static_cast(value)); } static SerializeMetaTypeId convert(MetaTypeId value) { - return static_cast(static_cast(value)); + return static_cast(value); } static bool isInData(const SerializeMetaData& metadata, const std::string& type) @@ -98,7 +97,7 @@ void MetaDataExchange::importMetaData(const SerializeMetaData& metadata) { const SerializeMetaField& fieldSource = structSource.fields[n]; int flags = 0; - std::for_each(fieldSource.flags.begin(), fieldSource.flags.end(), [&flags] (const SerializeMetaFieldFlags& flag) { + std::for_each(fieldSource.flags.begin(), fieldSource.flags.end(), [&flags](const SerializeMetaFieldFlags& flag) { flags |= flag; }); @@ -179,8 +178,6 @@ void MetaDataExchange::exportMetaData(SerializeMetaData& metadata) } } - - void MetaDataExchange::importMetaDataJson(const char* json) { SerializeMetaData root; @@ -191,7 +188,6 @@ void MetaDataExchange::importMetaDataJson(const char* json) importMetaData(root); } - void MetaDataExchange::exportMetaDataJson(std::string& json) { SerializeMetaData root; @@ -205,8 +201,6 @@ void MetaDataExchange::exportMetaDataJson(std::string& json) json = buffer.getData(); } - - void MetaDataExchange::importMetaDataProto(const char* proto, ssize_t size) { SerializeMetaData root; @@ -217,7 +211,6 @@ void MetaDataExchange::importMetaDataProto(const char* proto, ssize_t size) importMetaData(root); } - void MetaDataExchange::exportMetaDataProto(std::string& proto) { SerializeMetaData root; @@ -231,4 +224,4 @@ void MetaDataExchange::exportMetaDataProto(std::string& proto) proto = buffer.getData(); } -} // namespace finalmq +} // namespace finalmq diff --git a/src/poller/PollerImplEpoll.cpp b/src/poller/PollerImplEpoll.cpp index a5caece1..65201b36 100644 --- a/src/poller/PollerImplEpoll.cpp +++ b/src/poller/PollerImplEpoll.cpp @@ -24,20 +24,18 @@ #include "finalmq/poller/PollerImplEpoll.h" -#include "finalmq/helpers/OperatingSystem.h" -#include "finalmq/helpers/ModulenameFinalmq.h" -#include "finalmq/logger/LogStream.h" - +#include #include #include -#include - -namespace finalmq { +#include "finalmq/helpers/ModulenameFinalmq.h" +#include "finalmq/helpers/OperatingSystem.h" +#include "finalmq/logger/LogStream.h" +namespace finalmq +{ PollerImplEpoll::PollerImplEpoll() - : m_socketDescriptorsStable(ATOMIC_FLAG_INIT) { m_socketDescriptorsStable.test_and_set(); } @@ -50,8 +48,6 @@ PollerImplEpoll::~PollerImplEpoll() } } - - void PollerImplEpoll::init() { m_fdEpoll = OperatingSystem::instance().epoll_create1(EPOLL_CLOEXEC); @@ -65,7 +61,6 @@ void PollerImplEpoll::init() } } - void PollerImplEpoll::addSocket(const SocketDescriptorPtr& fd) { std::unique_lock locker(m_mutex); @@ -90,7 +85,6 @@ void PollerImplEpoll::addSocket(const SocketDescriptorPtr& fd) locker.unlock(); } - void PollerImplEpoll::addSocketEnableRead(const SocketDescriptorPtr& fd) { std::unique_lock locker(m_mutex); @@ -115,7 +109,6 @@ void PollerImplEpoll::addSocketEnableRead(const SocketDescriptorPtr& fd) locker.unlock(); } - void PollerImplEpoll::removeSocket(const SocketDescriptorPtr& fd) { std::unique_lock locker(m_mutex); @@ -141,8 +134,6 @@ void PollerImplEpoll::removeSocket(const SocketDescriptorPtr& fd) locker.unlock(); } - - void PollerImplEpoll::enableRead(const SocketDescriptorPtr& fd) { std::unique_lock locker(m_mutex); @@ -167,7 +158,6 @@ void PollerImplEpoll::enableRead(const SocketDescriptorPtr& fd) locker.unlock(); } - void PollerImplEpoll::disableRead(const SocketDescriptorPtr& fd) { std::unique_lock locker(m_mutex); @@ -192,9 +182,6 @@ void PollerImplEpoll::disableRead(const SocketDescriptorPtr& fd) locker.unlock(); } - - - void PollerImplEpoll::enableWrite(const SocketDescriptorPtr& fd) { std::unique_lock locker(m_mutex); @@ -219,7 +206,6 @@ void PollerImplEpoll::enableWrite(const SocketDescriptorPtr& fd) locker.unlock(); } - void PollerImplEpoll::disableWrite(const SocketDescriptorPtr& fd) { std::unique_lock locker(m_mutex); @@ -244,14 +230,11 @@ void PollerImplEpoll::disableWrite(const SocketDescriptorPtr& fd) locker.unlock(); } - - void PollerImplEpoll::sockedDescriptorHasChanged() { m_socketDescriptorsStable.clear(std::memory_order_release); } - void PollerImplEpoll::updateSocketDescriptors() { m_socketDescriptorsConstForEpoll.clear(); @@ -262,8 +245,6 @@ void PollerImplEpoll::updateSocketDescriptors() } } - - void PollerImplEpoll::collectSockets(int res) { m_result.clear(); @@ -316,7 +297,7 @@ void PollerImplEpoll::collectSockets(int res) { // read pending bytes from control socket std::vector buffer(countRead); - OperatingSystem::instance().recv(sd, buffer.data(), buffer.size(), 0); + OperatingSystem::instance().recv(sd, buffer.data(), static_cast(buffer.size()), 0); m_result.releaseWait = m_releaseFlags.exchange(0, std::memory_order_acq_rel); } else @@ -367,7 +348,7 @@ const PollerResult& PollerImplEpoll::wait(std::int32_t timeout) do { - res = OperatingSystem::instance().epoll_pwait(m_fdEpoll, &m_events[0], m_events.size(), timeout, nullptr); + res = OperatingSystem::instance().epoll_pwait(m_fdEpoll, &m_events[0], static_cast(m_events.size()), timeout, nullptr); if (res == -1) { @@ -401,6 +382,6 @@ void PollerImplEpoll::releaseWait(std::uint32_t info) } } -} // namespace finalmq +} // namespace finalmq #endif diff --git a/src/protocols/ProtocolHeaderBinarySize.cpp b/src/protocols/ProtocolHeaderBinarySize.cpp index 6cf8f69b..bdc2b61b 100644 --- a/src/protocols/ProtocolHeaderBinarySize.cpp +++ b/src/protocols/ProtocolHeaderBinarySize.cpp @@ -20,43 +20,38 @@ //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. - #include "finalmq/protocols/ProtocolHeaderBinarySize.h" -#include "finalmq/protocolsession/ProtocolMessage.h" -#include "finalmq/protocolsession/ProtocolRegistry.h" -#include "finalmq/streamconnection/Socket.h" #include -namespace finalmq { +#include "finalmq/protocolsession/ProtocolMessage.h" +#include "finalmq/protocolsession/ProtocolRegistry.h" +#include "finalmq/streamconnection/Socket.h" +namespace finalmq +{ const std::uint32_t ProtocolHeaderBinarySize::PROTOCOL_ID = 2; const std::string ProtocolHeaderBinarySize::PROTOCOL_NAME = "headersize"; - static const int HEADERSIZE = 4; - //--------------------------------------- // ProtocolHeaderBinarySize //--------------------------------------- - ProtocolHeaderBinarySize::ProtocolHeaderBinarySize() - : m_headerHelper(HEADERSIZE, [] (const std::string& header) { - assert(header.size() == 4); - int sizePayload = 0; - for (int i = 0; i < 4; ++i) - { - sizePayload |= ((unsigned int)header[i] & 0xff) << (8 * i); - } - return sizePayload; + : m_headerHelper(HEADERSIZE, [](const std::string& header) { + assert(header.size() == 4); + int sizePayload = 0; + for (int i = 0; i < 4; ++i) + { + sizePayload |= (static_cast(header[i]) & 0xff) << (8 * i); + } + return sizePayload; }) { - } - ProtocolHeaderBinarySize::~ProtocolHeaderBinarySize() { if (m_connection) @@ -65,7 +60,6 @@ ProtocolHeaderBinarySize::~ProtocolHeaderBinarySize() } } - // IProtocol void ProtocolHeaderBinarySize::setCallback(const std::weak_ptr& callback) { @@ -159,7 +153,7 @@ void ProtocolHeaderBinarySize::sendMessage(IMessagePtr message) char* header = buffers.begin()->first; for (int i = 0; i < HEADERSIZE; ++i) { - header[i] = (sizePayload >> (i * 8)) & 0xff; + header[i] = static_cast((sizePayload >> (i * 8)) & 0xff); } message->prepareMessageToSend(); } @@ -169,7 +163,6 @@ void ProtocolHeaderBinarySize::sendMessage(IMessagePtr message) void ProtocolHeaderBinarySize::moveOldProtocolState(IProtocol& /*protocolOld*/) { - } bool ProtocolHeaderBinarySize::received(const IStreamConnectionPtr& /*connection*/, const SocketPtr& socket, int bytesToRead) @@ -179,7 +172,7 @@ bool ProtocolHeaderBinarySize::received(const IStreamConnectionPtr& /*connection auto callback = m_callback.lock(); if (callback) { - for (const auto &message : messages) + for (const auto& message : messages) { callback->received(message); } @@ -187,7 +180,6 @@ bool ProtocolHeaderBinarySize::received(const IStreamConnectionPtr& /*connection return ok; } - hybrid_ptr ProtocolHeaderBinarySize::connected(const IStreamConnectionPtr& /*connection*/) { auto callback = m_callback.lock(); @@ -207,7 +199,6 @@ void ProtocolHeaderBinarySize::disconnected(const IStreamConnectionPtr& /*connec } } - IMessagePtr ProtocolHeaderBinarySize::pollReply(std::deque&& /*messages*/) { return {}; @@ -215,12 +206,10 @@ IMessagePtr ProtocolHeaderBinarySize::pollReply(std::deque&& /*mess void ProtocolHeaderBinarySize::subscribe(const std::vector& /*subscribtions*/) { - } void ProtocolHeaderBinarySize::cycleTime() { - } IProtocolSessionDataPtr ProtocolHeaderBinarySize::createProtocolSessionData() @@ -232,8 +221,6 @@ void ProtocolHeaderBinarySize::setProtocolSessionData(const IProtocolSessionData { } - - //--------------------------------------- // ProtocolHeaderBinarySizeFactory //--------------------------------------- @@ -246,14 +233,10 @@ struct RegisterProtocolHeaderBinarySizeFactory } } g_registerProtocolHeaderBinarySizeFactory; - - // IProtocolFactory IProtocolPtr ProtocolHeaderBinarySizeFactory::createProtocol(const Variant& /*data*/) { return std::make_shared(); } - - -} // namespace finalmq +} // namespace finalmq diff --git a/src/protocols/ProtocolHttpClient.cpp b/src/protocols/ProtocolHttpClient.cpp index 815e393e..9d6661df 100644 --- a/src/protocols/ProtocolHttpClient.cpp +++ b/src/protocols/ProtocolHttpClient.cpp @@ -20,132 +20,145 @@ //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. - #include "finalmq/protocols/ProtocolHttpClient.h" + +#include "finalmq/helpers/Utils.h" #include "finalmq/protocolsession/ProtocolMessage.h" #include "finalmq/protocolsession/ProtocolRegistry.h" #include "finalmq/protocolsession/ProtocolSession.h" #include "finalmq/streamconnection/Socket.h" -#include "finalmq/helpers/Utils.h" //#include "finalmq/helpers/ModulenameFinalmq.h" #include #include -#include #include +#include #include -namespace finalmq { - - static const char tabDecToHex[] = { - '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F' - }; - - static void encode(std::string& dest, const std::string& src) +namespace finalmq +{ +static const char tabDecToHex[] = { + '0', + '1', + '2', + '3', + '4', + '5', + '6', + '7', + '8', + '9', + 'A', + 'B', + 'C', + 'D', + 'E', + 'F'}; + +static void encode(std::string& dest, const std::string& src) +{ + dest.reserve(src.size() * 3); + char c; + unsigned char uc; + + for (size_t i = 0; i < src.size(); ++i) { - dest.reserve(src.size() * 3); - char c; - unsigned char uc; - - for (size_t i = 0; i < src.size(); ++i) + c = src[i]; + if (isalnum(c) || c == '/' || c == '-' || c == '_' || c == '.' || c == '~') { - c = src[i]; - if (isalnum(c) || c == '/' || c == '-' || c == '_' || c == '.' || c == '~') - { - dest += c; - } - else - { - uc = c; - int first = (uc >> 4) & 0x0f; - int second = uc & 0x0f; - assert(0 <= first && first < 16); - assert(0 <= second && second < 16); - dest += '%'; - dest += tabDecToHex[first]; - dest += tabDecToHex[second]; - } + dest += c; + } + else + { + uc = c; + int first = (uc >> 4) & 0x0f; + int second = uc & 0x0f; + assert(0 <= first && first < 16); + assert(0 <= second && second < 16); + dest += '%'; + dest += tabDecToHex[first]; + dest += tabDecToHex[second]; } } +} +static void decode(std::string& dest, const std::string& src) +{ + dest.reserve(src.size()); + char code[3] = {0}; + unsigned long c = 0; - static void decode(std::string& dest, const std::string& src) + for (size_t i = 0; i < src.size(); ++i) { - dest.reserve(src.size()); - char code[3] = { 0 }; - unsigned long c = 0; - - for (size_t i = 0; i < src.size(); ++i) + if (src[i] == '%') { - if (src[i] == '%') - { - ++i; - memcpy(code, &src[i], 2); - c = strtoul(code, NULL, 16); - dest += (char)c; - ++i; - } - else - { - dest += src[i]; - } + ++i; + memcpy(code, &src[i], 2); + c = strtoul(code, NULL, 16); + dest += static_cast(c); + ++i; } + else + { + dest += src[i]; + } + } +} + +//--------------------------------------- +// Cookie +//--------------------------------------- +class Cookie +{ +public: + inline Cookie() + : m_expirationDate(-1), m_secure(false), m_httpOnly(false) + { } - //--------------------------------------- - // Cookie - //--------------------------------------- - class Cookie + static std::vector parseSetCookieHeaderLine(const std::string& cookieString, const std::string& hostname) { - public: - inline Cookie() - : m_expirationDate(-1) - , m_secure(false) - , m_httpOnly(false) + // According to http://wp.netscape.com/newsref/std/cookie_spec.html,< + // the Set-Cookie response header is of the format: + // + // Set-Cookie: NAME=VALUE; expires=DATE; path=PATH; domain=DOMAIN_NAME; secure + // + // where only the NAME=VALUE part is mandatory + // + // We do not support RFC 2965 Set-Cookie2-style cookies + + std::vector result; + + int position = 0; + const int length = static_cast(cookieString.length()); + while (position < length) { - } + Cookie cookie; - static std::vector parseSetCookieHeaderLine(const std::string& cookieString, const std::string& hostname) - { - // According to http://wp.netscape.com/newsref/std/cookie_spec.html,< - // the Set-Cookie response header is of the format: - // - // Set-Cookie: NAME=VALUE; expires=DATE; path=PATH; domain=DOMAIN_NAME; secure - // - // where only the NAME=VALUE part is mandatory - // - // We do not support RFC 2965 Set-Cookie2-style cookies - - std::vector result; - - int position = 0; - const int length = static_cast(cookieString.length()); + // The first part is always the "NAME=VALUE" part + std::pair field = nextField(cookieString, position, true); + if (field.first.empty()) + // parsing error + break; + cookie.m_name = field.first; + cookie.m_value = field.second; + cookie.m_domain = hostname; + cookie.m_domainDot = false; + + position = nextNonWhitespace(cookieString, position); while (position < length) { - Cookie cookie; - - // The first part is always the "NAME=VALUE" part - std::pair field = nextField(cookieString, position, true); - if (field.first.empty()) - // parsing error - break; - cookie.m_name = field.first; - cookie.m_value = field.second; - cookie.m_domain = hostname; - cookie.m_domainDot = false; - - position = nextNonWhitespace(cookieString, position); - while (position < length) { - switch (cookieString.at(position++)) { + switch(cookieString.at(position++)) + { case ';': // new field in the cookie field = nextField(cookieString, position, false); - std::transform(field.first.begin(), field.first.end(), field.first.begin(), - [](unsigned char c) { return std::tolower(c); }); // everything but the NAME=VALUE is case-insensitive + std::transform(field.first.begin(), field.first.end(), field.first.begin(), [](unsigned char c) { return std::tolower(c); }); // everything but the NAME=VALUE is case-insensitive - if (field.first == "expires") { + if (field.first == "expires") + { position -= static_cast(field.second.length()); int end; for (end = position; end < length; ++end) @@ -156,23 +169,25 @@ namespace finalmq { int endDateStringWithoutSpace = nextNonWhitespaceReverse(cookieString, end, position); std::string dateString = cookieString.substr(position, endDateStringWithoutSpace - position); position = end; - std::transform(dateString.begin(), dateString.end(), dateString.begin(), - [](unsigned char c) { return std::tolower(c); }); + std::transform(dateString.begin(), dateString.end(), dateString.begin(), [](unsigned char c) { return std::tolower(c); }); time_t date = parseDateString(dateString); - if (date == -1) { + if (date == -1) + { return result; } cookie.m_expirationDate = date; } - else if (field.first == "domain") { + else if (field.first == "domain") + { std::string rawDomain = field.second; bool maybeLeadingDot = false; - if (!rawDomain.empty() && rawDomain[0] == '.') { + if (!rawDomain.empty() && rawDomain[0] == '.') + { maybeLeadingDot = true; rawDomain = rawDomain.substr(1); } - std::string normalizedDomain = rawDomain;// QUrl::fromAce(QUrl::toAce(rawDomain)); + std::string normalizedDomain = rawDomain; // QUrl::fromAce(QUrl::toAce(rawDomain)); if (normalizedDomain.empty() && !rawDomain.empty()) { return result; @@ -180,7 +195,8 @@ namespace finalmq { cookie.m_domain = normalizedDomain; cookie.m_domainDot = maybeLeadingDot; } - else if (field.first == "max-age") { + else if (field.first == "max-age") + { if (field.second.empty()) { return result; @@ -194,101 +210,122 @@ namespace finalmq { const time_t now = time(nullptr); cookie.m_expirationDate = now + secs; } - else if (field.first == "path") { + else if (field.first == "path") + { decode(cookie.m_path, field.second); } - else if (field.first == "secure") { + else if (field.first == "secure") + { cookie.m_secure = true; } - else if (field.first == "httponly") { + else if (field.first == "httponly") + { cookie.m_httpOnly = true; } - else if (field.first == "comment") { + else if (field.first == "comment") + { cookie.m_comment = field.second; } - else if (field.first == "version") { - if (field.second != "1") { + else if (field.first == "version") + { + if (field.second != "1") + { // oops, we don't know how to handle this cookie return result; } } - else { + else + { // got an unknown field in the cookie // what do we do? } position = nextNonWhitespace(cookieString, position); - } - } - - if (!cookie.m_name.empty()) - { - result.push_back(cookie); } } - return result; + if (!cookie.m_name.empty()) + { + result.push_back(cookie); + } } - time_t getExpirationDate() const - { - return m_expirationDate; - } + return result; + } - const std::string& getDomain() const - { - return m_domain; - } - bool getDomainDot() const - { - return m_domainDot; - } - const std::string& getPath() const - { - return m_path; - } - const std::string& getComment() const - { - return m_comment; - } - const std::string& getName() const - { - return m_name; - } - const std::string& getValue() const - { - return m_value; - } - bool getSecure() const - { - return m_secure; - } - bool getHttpOnly() const - { - return m_httpOnly; - } + time_t getExpirationDate() const + { + return m_expirationDate; + } - bool match(const std::string& domain, const std::string& path) const - { - const bool domainFits = matchDomain(domain); + const std::string& getDomain() const + { + return m_domain; + } + bool getDomainDot() const + { + return m_domainDot; + } + const std::string& getPath() const + { + return m_path; + } + const std::string& getComment() const + { + return m_comment; + } + const std::string& getName() const + { + return m_name; + } + const std::string& getValue() const + { + return m_value; + } + bool getSecure() const + { + return m_secure; + } + bool getHttpOnly() const + { + return m_httpOnly; + } + + bool match(const std::string& domain, const std::string& path) const + { + const bool domainFits = matchDomain(domain); - if (domainFits) + if (domainFits) + { + if (path == m_path) { - if (path == m_path) - { - return true; - } - else + return true; + } + else + { + if (path.size() > m_path.size()) { - if (path.size() > m_path.size()) + if (!m_path.empty() && m_path[m_path.size() - 1] == '/') { - if (!m_path.empty() && m_path[m_path.size() - 1] == '/') + if (path[m_path.size() - 1] == '/') { - if (path[m_path.size() - 1] == '/') + if (memcmp(&path[0], m_path.c_str(), m_path.size()) == 0) + { + // m_path = "/hallo/" + // path = "/hello/..." + return true; + } + } + } + else + { + if (!m_path.empty()) + { + if (path[m_path.size()] == '/') { if (memcmp(&path[0], m_path.c_str(), m_path.size()) == 0) { - // m_path = "/hallo/" + // m_path = "/hallo" // path = "/hello/..." return true; } @@ -296,313 +333,311 @@ namespace finalmq { } else { - if (!m_path.empty()) - { - if (path[m_path.size()] == '/') - { - if (memcmp(&path[0], m_path.c_str(), m_path.size()) == 0) - { - // m_path = "/hallo" - // path = "/hello/..." - return true; - } - } - } - else + if (path[0] == '/') { - if (path[0] == '/') - { - // m_path = "" - // path = "/..." - return true; - } + // m_path = "" + // path = "/..." + return true; } } } - else if (path.size() == 0 && m_path.size() == 1 && m_path[0] == '/') - { - // m_path = "/" - // path = "" - return true; - } + } + else if (path.size() == 0 && m_path.size() == 1 && m_path[0] == '/') + { + // m_path = "/" + // path = "" + return true; } } - - return false; } - bool matchExactPath(const std::string& domain, const std::string& path) const - { - const bool domainFits = matchDomain(domain); + return false; + } + + bool matchExactPath(const std::string& domain, const std::string& path) const + { + const bool domainFits = matchDomain(domain); - if (domainFits) + if (domainFits) + { + if (path == m_path) { - if (path == m_path) - { - return true; - } - else + return true; + } + else + { + if (path.size() == m_path.size() + 1) { - if (path.size() == m_path.size() + 1) + if (m_path.empty() || m_path[m_path.size() - 1] != '/') { - if (m_path.empty() || m_path[m_path.size() - 1] != '/') + if (!m_path.empty()) { - if (!m_path.empty()) + if (path[m_path.size()] == '/') { - if (path[m_path.size()] == '/') + if (memcmp(&path[0], m_path.c_str(), path.size()) == 0) { - if (memcmp(&path[0], m_path.c_str(), path.size()) == 0) - { - // m_path = "/hallo" - // path = "/hello/" - return true; - } + // m_path = "/hallo" + // path = "/hello/" + return true; } } - else + } + else + { + if (path[0] == '/') { - if (path[0] == '/') - { - // m_path = "" - // path = "/" - return true; - } + // m_path = "" + // path = "/" + return true; } } } - else if (path.size() == 0 && m_path.size() == 1 && m_path[0] == '/') - { - // m_path = "/" - // path = "" - return true; - } + } + else if (path.size() == 0 && m_path.size() == 1 && m_path[0] == '/') + { + // m_path = "/" + // path = "" + return true; } } - - return false; } - bool isExpired() const + return false; + } + + bool isExpired() const + { + const time_t now = time(nullptr); + if (m_expirationDate != -1 && now > m_expirationDate) { - const time_t now = time(nullptr); - if (m_expirationDate != -1 && now > m_expirationDate) - { - return true; - } - return false; + return true; } + return false; + } - private: - - bool matchDomain(const std::string& domain) const +private: + bool matchDomain(const std::string& domain) const + { + bool domainFits = false; + if (m_domain == domain) { - bool domainFits = false; - if (m_domain == domain) - { - domainFits = true; - } - else + domainFits = true; + } + else + { + if (m_domainDot) { - if (m_domainDot) + if (domain.size() > m_domain.size()) { - if (domain.size() > m_domain.size()) + const size_t index = domain.size() - m_domain.size() - 1; + if (domain[index] == '.') { - const size_t index = domain.size() - m_domain.size() - 1; - if (domain[index] == '.') + if (memcmp(&domain[index + 1], m_domain.c_str(), m_domain.size()) == 0) { - if (memcmp(&domain[index + 1], m_domain.c_str(), m_domain.size()) == 0) - { - domainFits = true; - } + domainFits = true; } } } } - return domainFits; } + return domainFits; + } - static bool checkStaticArray(int& val, const std::string& dateString, int at, const char* array, int size) + static bool checkStaticArray(int& val, const std::string& dateString, int at, const char* array, int size) + { + if (dateString[at] < 'a' || dateString[at] > 'z') + return false; + if (val == -1 && dateString.length() >= static_cast(at + 3)) { - if (dateString[at] < 'a' || dateString[at] > 'z') - return false; - if (val == -1 && dateString.length() >= static_cast(at + 3)) { - int j = 0; - int i = 0; - while (i <= size) { - const char* str = array + i; - if (str[0] == dateString[at] - && str[1] == dateString[at + 1] - && str[2] == dateString[at + 2]) { - val = j; - return true; - } - i += static_cast(strlen(str)) + 1; - ++j; + int j = 0; + int i = 0; + while (i <= size) + { + const char* str = array + i; + if (str[0] == dateString[at] + && str[1] == dateString[at + 1] + && str[2] == dateString[at + 2]) + { + val = j; + return true; } + i += static_cast(strlen(str)) + 1; + ++j; } - return false; } + return false; + } - static inline bool isNumber(char s) - { - return s >= '0' && s <= '9'; - } + static inline bool isNumber(char s) + { + return s >= '0' && s <= '9'; + } - static inline bool isWhitespace(char c) - { - return c == ' ' || c == '\t'; - } + static inline bool isWhitespace(char c) + { + return c == ' ' || c == '\t'; + } #ifndef WIN32 - static constexpr int SecondsPerMinute = 60; - static constexpr int SecondsPerHour = 3600; - static constexpr int SecondsPerDay = 86400; - static const int DaysOfMonth[12]; + static constexpr int SecondsPerMinute = 60; + static constexpr int SecondsPerHour = 3600; + static constexpr int SecondsPerDay = 86400; + static const int DaysOfMonth[12]; + + static bool IsLeapYear(short year) + { + if (year % 4 != 0) + return false; + if (year % 100 != 0) + return true; + return (year % 400) == 0; + } - static bool IsLeapYear(short year) + static time_t my_mkgmtime(const struct tm* ptm) + { + time_t secs = 0; + // tm_year is years since 1900 + int year = ptm->tm_year + 1900; + for (int y = 1970; y < year; ++y) { - if (year % 4 != 0) return false; - if (year % 100 != 0) return true; - return (year % 400) == 0; + secs += (IsLeapYear(static_cast(y)) ? 366 : 365) * SecondsPerDay; } - - static time_t my_mkgmtime(const struct tm* ptm) { - time_t secs = 0; - // tm_year is years since 1900 - int year = ptm->tm_year + 1900; - for (int y = 1970; y < year; ++y) { - secs += (IsLeapYear(y) ? 366 : 365) * SecondsPerDay; - } - // tm_mon is month from 0..11 - for (int m = 0; m < ptm->tm_mon; ++m) { - secs += DaysOfMonth[m] * SecondsPerDay; - if (m == 1 && IsLeapYear(year)) secs += SecondsPerDay; - } - secs += (ptm->tm_mday - 1) * SecondsPerDay; - secs += ptm->tm_hour * SecondsPerHour; - secs += ptm->tm_min * SecondsPerMinute; - secs += ptm->tm_sec; - return secs; + // tm_mon is month from 0..11 + for (int m = 0; m < ptm->tm_mon; ++m) + { + secs += DaysOfMonth[m] * SecondsPerDay; + if (m == 1 && IsLeapYear(static_cast(year))) + secs += SecondsPerDay; } + secs += (ptm->tm_mday - 1) * SecondsPerDay; + secs += ptm->tm_hour * SecondsPerHour; + secs += ptm->tm_min * SecondsPerMinute; + secs += ptm->tm_sec; + return secs; + } - // time_t my_mkgmtime(struct tm * pt) { - // time_t ret = mktime(pt); - // /* GMT and local time */ - // struct tm pgt = *gmtime(&ret); - // struct tm plt = *localtime(&ret); - // plt.tm_year -= pgt.tm_year - plt.tm_year; - // plt.tm_mon -= pgt.tm_mon - plt.tm_mon; - // plt.tm_mday -= pgt.tm_mday - plt.tm_mday; - // plt.tm_hour -= pgt.tm_hour - plt.tm_hour; - // plt.tm_min -= pgt.tm_min - plt.tm_min; - // plt.tm_sec -= pgt.tm_sec - plt.tm_sec; - // ret = mktime(&plt); - // return ret; - // } + // time_t my_mkgmtime(struct tm * pt) { + // time_t ret = mktime(pt); + // /* GMT and local time */ + // struct tm pgt = *gmtime(&ret); + // struct tm plt = *localtime(&ret); + // plt.tm_year -= pgt.tm_year - plt.tm_year; + // plt.tm_mon -= pgt.tm_mon - plt.tm_mon; + // plt.tm_mday -= pgt.tm_mday - plt.tm_mday; + // plt.tm_hour -= pgt.tm_hour - plt.tm_hour; + // plt.tm_min -= pgt.tm_min - plt.tm_min; + // plt.tm_sec -= pgt.tm_sec - plt.tm_sec; + // ret = mktime(&plt); + // return ret; + // } #endif -#define ADAY 1 +#define ADAY 1 #define AMONTH 2 -#define AYEAR 4 +#define AYEAR 4 - static time_t parseDateString(const std::string& dateString) + static time_t parseDateString(const std::string& dateString) + { + static const char zones[] = + "pst\0" // -8 + "pdt\0" + "mst\0" // -7 + "mdt\0" + "cst\0" // -6 + "cdt\0" + "est\0" // -5 + "edt\0" + "ast\0" // -4 + "nst\0" // -3 + "gmt\0" // 0 + "utc\0" + "bst\0" + "met\0" // 1 + "eet\0" // 2 + "jst\0" // 9 + "\0"; + static int zoneOffsets[] = {-8, -8, -7, -7, -6, -6, -5, -5, -4, -3, 0, 0, 0, 1, 2, 9}; + + static const char months[] = + "jan\0" + "feb\0" + "mar\0" + "apr\0" + "may\0" + "jun\0" + "jul\0" + "aug\0" + "sep\0" + "oct\0" + "nov\0" + "dec\0" + "\0"; + + struct tm tm; + tm.tm_sec = 0; + tm.tm_min = 0; + tm.tm_hour = 0; + tm.tm_mday = 0; + tm.tm_mon = 0; + tm.tm_year = 0; + tm.tm_wday = 0; + tm.tm_yday = 0; + tm.tm_isdst = 0; + + time_t time = -1; + // placeholders for values when we are not sure it is a year, month or day + int unknown[3] = {-1, -1, -1}; + int month = -1; + int day = -1; + int year = -1; + int zoneOffset = -1; + + // hour:minute:second.ms pm + //QRegExp timeRx(QLatin1String("(\\d{1,2}):(\\d{1,2})(:(\\d{1,2})|)(\\.(\\d{1,3})|)((\\s{0,}(am|pm))|)")); + + int at = 0; + while (static_cast(at) < dateString.length()) { - static const char zones[] = - "pst\0" // -8 - "pdt\0" - "mst\0" // -7 - "mdt\0" - "cst\0" // -6 - "cdt\0" - "est\0" // -5 - "edt\0" - "ast\0" // -4 - "nst\0" // -3 - "gmt\0" // 0 - "utc\0" - "bst\0" - "met\0" // 1 - "eet\0" // 2 - "jst\0" // 9 - "\0"; - static int zoneOffsets[] = { -8, -8, -7, -7, -6, -6, -5, -5, -4, -3, 0, 0, 0, 1, 2, 9 }; - - static const char months[] = - "jan\0" - "feb\0" - "mar\0" - "apr\0" - "may\0" - "jun\0" - "jul\0" - "aug\0" - "sep\0" - "oct\0" - "nov\0" - "dec\0" - "\0"; - - struct tm tm; - tm.tm_sec = 0; - tm.tm_min = 0; - tm.tm_hour = 0; - tm.tm_mday = 0; - tm.tm_mon = 0; - tm.tm_year = 0; - tm.tm_wday = 0; - tm.tm_yday = 0; - tm.tm_isdst = 0; - - time_t time = -1; - // placeholders for values when we are not sure it is a year, month or day - int unknown[3] = { -1, -1, -1 }; - int month = -1; - int day = -1; - int year = -1; - int zoneOffset = -1; - - // hour:minute:second.ms pm - //QRegExp timeRx(QLatin1String("(\\d{1,2}):(\\d{1,2})(:(\\d{1,2})|)(\\.(\\d{1,3})|)((\\s{0,}(am|pm))|)")); - - int at = 0; - while (static_cast(at) < dateString.length()) { - bool isNum = isNumber(dateString[at]); - - // Month - if (!isNum - && checkStaticArray(month, dateString, at, months, sizeof(months) - 1)) { - ++month; - at += 3; - continue; - } - // Zone - if (!isNum - && zoneOffset == -1 - && checkStaticArray(zoneOffset, dateString, at, zones, sizeof(zones) - 1)) { - int sign = (at >= 0 && dateString[at - 1] == '-') ? -1 : 1; - zoneOffset = sign * zoneOffsets[zoneOffset] * 60 * 60; - at += 3; - continue; - } - // Zone offset - if (!isNum - && (zoneOffset == -1 || zoneOffset == 0) // Can only go after gmt - && (dateString[at] == '+' || dateString[at] == '-') - && (at == 0 - || isWhitespace(dateString[at - 1]) - || dateString[at - 1] == ',' - || (at >= 3 - && (dateString[at - 3] == 'g') - && (dateString[at - 2] == 'm') - && (dateString[at - 1] == 't')))) { - - int end = 1; - while (end < 5 && dateString.length() > static_cast(at + end) - && dateString[at + end] >= '0' && dateString[at + end] <= '9') - ++end; - int minutes = 0; - int hours = 0; - switch (end - 1) { + bool isNum = isNumber(dateString[at]); + + // Month + if (!isNum + && checkStaticArray(month, dateString, at, months, sizeof(months) - 1)) + { + ++month; + at += 3; + continue; + } + // Zone + if (!isNum + && zoneOffset == -1 + && checkStaticArray(zoneOffset, dateString, at, zones, sizeof(zones) - 1)) + { + int sign = (at >= 0 && dateString[at - 1] == '-') ? -1 : 1; + zoneOffset = sign * zoneOffsets[zoneOffset] * 60 * 60; + at += 3; + continue; + } + // Zone offset + if (!isNum + && (zoneOffset == -1 || zoneOffset == 0) // Can only go after gmt + && (dateString[at] == '+' || dateString[at] == '-') + && (at == 0 + || isWhitespace(dateString[at - 1]) + || dateString[at - 1] == ',' + || (at >= 3 + && (dateString[at - 3] == 'g') + && (dateString[at - 2] == 'm') + && (dateString[at - 1] == 't')))) + { + int end = 1; + while (end < 5 && dateString.length() > static_cast(at + end) + && dateString[at + end] >= '0' && dateString[at + end] <= '9') + ++end; + int minutes = 0; + int hours = 0; + switch(end - 1) + { case 4: minutes = atoi(dateString.substr(at + 3, 2).c_str()); // fall through @@ -615,163 +650,179 @@ namespace finalmq { default: at += end; continue; - } - if (end != 1) { - int sign = dateString[at] == '-' ? -1 : 1; - zoneOffset = sign * ((minutes * 60) + (hours * 60 * 60)); - at += end; - continue; - } } + if (end != 1) + { + int sign = dateString[at] == '-' ? -1 : 1; + zoneOffset = sign * ((minutes * 60) + (hours * 60 * 60)); + at += end; + continue; + } + } - // Time hh:mm:ss.ms pm - if (isNum && time == -1) + // Time hh:mm:ss.ms pm + if (isNum && time == -1) + { + std::vector timeSplit; + Utils::split(dateString, at, dateString.length(), ':', timeSplit); + + if (timeSplit.size() >= 2 && (timeSplit[0].size() == 1 || timeSplit[0].size() == 2)) { - std::vector timeSplit; - Utils::split(dateString, at, dateString.length(), ':', timeSplit); + int h = 0; + int m = 0; + int s = 0; + // int ms = 0; - if (timeSplit.size() >= 2 && (timeSplit[0].size() == 1 || timeSplit[0].size() == 2)) + if (timeSplit.size() >= 1) { - int h = 0; - int m = 0; - int s = 0; - // int ms = 0; - - if (timeSplit.size() >= 1) - { - h = atoi(timeSplit[0].c_str()); - at += static_cast(timeSplit[0].length()); - } - if (timeSplit.size() >= 2) + h = atoi(timeSplit[0].c_str()); + at += static_cast(timeSplit[0].length()); + } + if (timeSplit.size() >= 2) + { + m = atoi(timeSplit[1].c_str()); + at += 1; // for ':' + at += static_cast(timeSplit[1].length()); + } + if (timeSplit.size() >= 3) + { + at += 1; // for ':' + std::vector secSplit; + Utils::split(timeSplit[2], 0, timeSplit[2].length(), '.', secSplit); + if (secSplit.size() >= 1) { - m = atoi(timeSplit[1].c_str()); - at += 1; // for ':' - at += static_cast(timeSplit[1].length()); + s = atoi(secSplit[0].c_str()); + at += static_cast(secSplit[0].length()); } - if (timeSplit.size() >= 3) + if (secSplit.size() >= 2) { - at += 1; // for ':' - std::vector secSplit; - Utils::split(timeSplit[2], 0, timeSplit[2].length(), '.', secSplit); - if (secSplit.size() >= 1) + at += 1; // for '.' + std::vector msSplit; + Utils::split(secSplit[1], 0, secSplit[1].length(), ' ', msSplit); + if (msSplit.size() >= 1) { - s = atoi(secSplit[0].c_str()); - at += static_cast(secSplit[0].length()); + // ms = atoi(msSplit[0].c_str()); + at += static_cast(msSplit[0].length()); } - if (secSplit.size() >= 2) + if (msSplit.size() >= 2) { - at += 1; // for '.' - std::vector msSplit; - Utils::split(secSplit[1], 0, secSplit[1].length(), ' ', msSplit); - if (msSplit.size() >= 1) - { - // ms = atoi(msSplit[0].c_str()); - at += static_cast(msSplit[0].length()); - } - if (msSplit.size() >= 2) + at += 1; // for ' ' + if (h < 12 && msSplit[1] == "pm") { - at += 1; // for ' ' - if (h < 12 && msSplit[1] == "pm") - { - h += 12; - } - at += static_cast(msSplit[1].length()); + h += 12; } + at += static_cast(msSplit[1].length()); } } - tm.tm_hour = h; - tm.tm_min = m; - tm.tm_sec = s; - continue; - } - } - - // 4 digit Year - if (isNum - && year == -1 - && dateString.length() > static_cast(at + 3)) { - if (isNumber(dateString[at + 1]) - && isNumber(dateString[at + 2]) - && isNumber(dateString[at + 3])) { - year = atoi(dateString.substr(at, 4).c_str()); - at += 4; - continue; - } - } - - // a one or two digit number - // Could be month, day or year - if (isNum) { - int length = 1; - if (dateString.length() > static_cast(at + 1) - && isNumber(dateString[at + 1])) - ++length; - int x = atoi(dateString.substr(at, length).c_str()); - if (year == -1 && (x > 31 || x == 0)) { - year = x; - } - else { - if (unknown[0] == -1) unknown[0] = x; - else if (unknown[1] == -1) unknown[1] = x; - else if (unknown[2] == -1) unknown[2] = x; } - at += length; + tm.tm_hour = h; + tm.tm_min = m; + tm.tm_sec = s; continue; } - - // Unknown character, typically a weekday such as 'Mon' - ++at; } - // Once we are done parsing the string take the digits in unknown - // and determine which is the unknown year/month/day - - int couldBe[3] = { 0, 0, 0 }; - int unknownCount = 3; - for (int i = 0; i < unknownCount; ++i) { - if (unknown[i] == -1) { - couldBe[i] = ADAY | AYEAR | AMONTH; - unknownCount = i; + // 4 digit Year + if (isNum + && year == -1 + && dateString.length() > static_cast(at + 3)) + { + if (isNumber(dateString[at + 1]) + && isNumber(dateString[at + 2]) + && isNumber(dateString[at + 3])) + { + year = atoi(dateString.substr(at, 4).c_str()); + at += 4; continue; } + } - if (unknown[i] >= 1) - couldBe[i] = ADAY; - - if (month == -1 && unknown[i] >= 1 && unknown[i] <= 12) - couldBe[i] |= AMONTH; + // a one or two digit number + // Could be month, day or year + if (isNum) + { + int length = 1; + if (dateString.length() > static_cast(at + 1) + && isNumber(dateString[at + 1])) + ++length; + int x = atoi(dateString.substr(at, length).c_str()); + if (year == -1 && (x > 31 || x == 0)) + { + year = x; + } + else + { + if (unknown[0] == -1) + unknown[0] = x; + else if (unknown[1] == -1) + unknown[1] = x; + else if (unknown[2] == -1) + unknown[2] = x; + } + at += length; + continue; + } - if (year == -1) - couldBe[i] |= AYEAR; + // Unknown character, typically a weekday such as 'Mon' + ++at; + } + + // Once we are done parsing the string take the digits in unknown + // and determine which is the unknown year/month/day + + int couldBe[3] = {0, 0, 0}; + int unknownCount = 3; + for (int i = 0; i < unknownCount; ++i) + { + if (unknown[i] == -1) + { + couldBe[i] = ADAY | AYEAR | AMONTH; + unknownCount = i; + continue; } - // For any possible day make sure one of the values that could be a month - // can contain that day. - // For any possible month make sure one of the values that can be a - // day that month can have. - // Example: 31 11 06 - // 31 can't be a day because 11 and 6 don't have 31 days - for (int i = 0; i < unknownCount; ++i) { - int currentValue = unknown[i]; - bool findMatchingMonth = couldBe[i] & ADAY && currentValue >= 29; - bool findMatchingDay = couldBe[i] & AMONTH; - if (!findMatchingMonth || !findMatchingDay) + if (unknown[i] >= 1) + couldBe[i] = ADAY; + + if (month == -1 && unknown[i] >= 1 && unknown[i] <= 12) + couldBe[i] |= AMONTH; + + if (year == -1) + couldBe[i] |= AYEAR; + } + + // For any possible day make sure one of the values that could be a month + // can contain that day. + // For any possible month make sure one of the values that can be a + // day that month can have. + // Example: 31 11 06 + // 31 can't be a day because 11 and 6 don't have 31 days + for (int i = 0; i < unknownCount; ++i) + { + int currentValue = unknown[i]; + bool findMatchingMonth = couldBe[i] & ADAY && currentValue >= 29; + bool findMatchingDay = couldBe[i] & AMONTH; + if (!findMatchingMonth || !findMatchingDay) + continue; + for (int j = 0; j < 3; ++j) + { + if (j == i) continue; - for (int j = 0; j < 3; ++j) { - if (j == i) + for (int k = 0; k < 2; ++k) + { + if (k == 0 && !(findMatchingMonth && (couldBe[j] & AMONTH))) + continue; + else if (k == 1 && !(findMatchingDay && (couldBe[j] & ADAY))) continue; - for (int k = 0; k < 2; ++k) { - if (k == 0 && !(findMatchingMonth && (couldBe[j] & AMONTH))) - continue; - else if (k == 1 && !(findMatchingDay && (couldBe[j] & ADAY))) - continue; - int m = currentValue; - int d = unknown[j]; - if (k == 0) - std::swap(m, d); - if (m == -1) m = month; - bool found = true; - switch (m) { + int m = currentValue; + int d = unknown[j]; + if (k == 0) + std::swap(m, d); + if (m == -1) + m = month; + bool found = true; + switch(m) + { case 2: // When we get 29 and the year ends up having only 28 // See date.isValid below @@ -779,957 +830,998 @@ namespace finalmq { if (d <= 29) found = false; break; - case 4: case 6: case 9: case 11: + case 4: + case 6: + case 9: + case 11: if (d <= 30) found = false; break; default: if (d > 0 && d <= 31) found = false; - } - if (k == 0) findMatchingMonth = found; - else if (k == 1) findMatchingDay = found; - } - } - if (findMatchingMonth) - couldBe[i] &= ~ADAY; - if (findMatchingDay) - couldBe[i] &= ~AMONTH; - } - - // First set the year/month/day that have been deduced - // and reduce the set as we go along to deduce more - for (int i = 0; i < unknownCount; ++i) { - int unset = 0; - for (int j = 0; j < 3; ++j) { - if (couldBe[j] == ADAY && day == -1) { - day = unknown[j]; - unset |= ADAY; - } - else if (couldBe[j] == AMONTH && month == -1) { - month = unknown[j]; - unset |= AMONTH; } - else if (couldBe[j] == AYEAR && year == -1) { - year = unknown[j]; - unset |= AYEAR; - } - else { - // common case - break; - } - couldBe[j] &= ~unset; + if (k == 0) + findMatchingMonth = found; + else if (k == 1) + findMatchingDay = found; } } - - // Now fallback to a standardized order to fill in the rest with - for (int i = 0; i < unknownCount; ++i) { - if (couldBe[i] & AMONTH && month == -1) month = unknown[i]; - else if (couldBe[i] & ADAY && day == -1) day = unknown[i]; - else if (couldBe[i] & AYEAR && year == -1) year = unknown[i]; - } - - if (year == -1 || month == -1 || day == -1) - { - return -1; - } - - // Y2k behavior - int y2k = 0; - if (year < 70) - y2k = 2000; - else if (year < 100) - y2k = 1900; - - tm.tm_year = year + y2k - 1900; - tm.tm_mon = month; - tm.tm_mday = day; - -#ifdef WIN32 - time = _mkgmtime(&tm); -#else - time = my_mkgmtime(&tm); -#endif - - if (zoneOffset != -1) { - time += zoneOffset; - } - return time; + if (findMatchingMonth) + couldBe[i] &= ~ADAY; + if (findMatchingDay) + couldBe[i] &= ~AMONTH; } - static std::pair nextField(const std::string& text, int& position, bool isNameValue) + // First set the year/month/day that have been deduced + // and reduce the set as we go along to deduce more + for (int i = 0; i < unknownCount; ++i) { - // format is one of: - // (1) token - // (2) token = token - // (3) token = quoted-string - const int length = static_cast(text.size()); - position = nextNonWhitespace(text, position); - - int semiColonPosition = static_cast(text.find_first_of(';', position)); - if (semiColonPosition < 0) - semiColonPosition = length; //no ';' means take everything to end of string - - int equalsPosition = static_cast(text.find_first_of('=', position)); - if (equalsPosition < 0 || equalsPosition > semiColonPosition) { - if (isNameValue) - return {}; //'=' is required for name-value-pair (RFC6265 section 5.2, rule 2) - equalsPosition = semiColonPosition; //no '=' means there is an attribute-name but no attribute-value - } - - // remove last spaces - int endFirstWithoutSpace = nextNonWhitespaceReverse(text, equalsPosition, position); - - std::string first = text.substr(position, endFirstWithoutSpace - position); - std::string second; - if (semiColonPosition > equalsPosition + 1) + int unset = 0; + for (int j = 0; j < 3; ++j) { - // remove last spaces - int endSecondWithoutSpace = nextNonWhitespaceReverse(text, semiColonPosition, equalsPosition + 1); - - second = text.substr(equalsPosition + 1, endSecondWithoutSpace - (equalsPosition + 1)); + if (couldBe[j] == ADAY && day == -1) + { + day = unknown[j]; + unset |= ADAY; + } + else if (couldBe[j] == AMONTH && month == -1) + { + month = unknown[j]; + unset |= AMONTH; + } + else if (couldBe[j] == AYEAR && year == -1) + { + year = unknown[j]; + unset |= AYEAR; + } + else + { + // common case + break; + } + couldBe[j] &= ~unset; } - - position = semiColonPosition; - return std::make_pair(first, second); - } - - static inline bool isTerminator(char c) - { - return c == '\n' || c == '\r'; } - static inline bool isValueSeparator(char c) + // Now fallback to a standardized order to fill in the rest with + for (int i = 0; i < unknownCount; ++i) { - return isTerminator(c) || c == ';'; + if (couldBe[i] & AMONTH && month == -1) + month = unknown[i]; + else if (couldBe[i] & ADAY && day == -1) + day = unknown[i]; + else if (couldBe[i] & AYEAR && year == -1) + year = unknown[i]; } - static inline bool isLWS(char c) + if (year == -1 || month == -1 || day == -1) { - return c == ' ' || c == '\t' || c == '\r' || c == '\n'; + return -1; } - static int nextNonWhitespace(const std::string& text, int from) - { - // RFC 2616 defines linear whitespace as: - // LWS = [CRLF] 1*( SP | HT ) - // We ignore the fact that CRLF must come as a pair at this point - // It's an invalid HTTP header if that happens. - while (static_cast(from) < text.length()) { - if (isLWS(text.at(from))) - ++from; - else - return from; // non-whitespace - } + // Y2k behavior + int y2k = 0; + if (year < 70) + y2k = 2000; + else if (year < 100) + y2k = 1900; - // reached the end - return static_cast(text.length()); - } + tm.tm_year = year + y2k - 1900; + tm.tm_mon = month; + tm.tm_mday = day; - static int nextNonWhitespaceReverse(const std::string& text, int from, int till) - { - --from; - while (from >= till) { - if (isLWS(text.at(from))) - --from; - else - return from + 1; // non-whitespace + 1 - } - - // reached the end - return till; - } - - time_t m_expirationDate; - std::string m_domain; - bool m_domainDot; - std::string m_path; - std::string m_comment; - std::string m_name; - std::string m_value; - bool m_secure; - bool m_httpOnly; - }; -#ifndef WIN32 - const int Cookie::DaysOfMonth[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; +#ifdef WIN32 + time = _mkgmtime(&tm); +#else + time = my_mkgmtime(&tm); #endif - //--------------------------------------- - // CookieStore - //--------------------------------------- - - void CookieStore::add(const Cookie& cookie) - { - std::unique_lock lock(m_mutex); - std::shared_ptr& cookieExists = getCookieInternExactPath(cookie.getDomain(), cookie.getPath()); - if (cookieExists) - { - cookieExists = std::make_shared(cookie); - } - else + if (zoneOffset != -1) { - m_cookies.push_back(std::make_shared(cookie)); + time += zoneOffset; } + return time; } - void CookieStore::add(const std::vector& cookies) + static std::pair nextField(const std::string& text, int& position, bool isNameValue) { - for (const auto& cookie : cookies) + // format is one of: + // (1) token + // (2) token = token + // (3) token = quoted-string + const int length = static_cast(text.size()); + position = nextNonWhitespace(text, position); + + int semiColonPosition = static_cast(text.find_first_of(';', position)); + if (semiColonPosition < 0) + semiColonPosition = length; //no ';' means take everything to end of string + + int equalsPosition = static_cast(text.find_first_of('=', position)); + if (equalsPosition < 0 || equalsPosition > semiColonPosition) { - add(cookie); + if (isNameValue) + return {}; //'=' is required for name-value-pair (RFC6265 section 5.2, rule 2) + equalsPosition = semiColonPosition; //no '=' means there is an attribute-name but no attribute-value } - } - - const std::vector> CookieStore::getCookies(const std::string& host, const std::string& path) const - { - std::unique_lock lock(m_mutex); - std::vector> cookies = const_cast(this)->getCookiesIntern(host, path); - return cookies; - } + // remove last spaces + int endFirstWithoutSpace = nextNonWhitespaceReverse(text, equalsPosition, position); - std::vector> CookieStore::getCookiesIntern(const std::string& host, const std::string& path) - { - std::vector> cookies; - for (auto it = m_cookies.begin(); it != m_cookies.end(); ) + std::string first = text.substr(position, endFirstWithoutSpace - position); + std::string second; + if (semiColonPosition > equalsPosition + 1) { - std::shared_ptr& cookie = *it; - if (cookie->match(host, path)) - { - if (cookie->isExpired()) - { - it = m_cookies.erase(it); - } - else - { - cookies.push_back(cookie); - ++it; - } - } - else - { - ++it; - } + // remove last spaces + int endSecondWithoutSpace = nextNonWhitespaceReverse(text, semiColonPosition, equalsPosition + 1); + + second = text.substr(equalsPosition + 1, endSecondWithoutSpace - (equalsPosition + 1)); } - return cookies; + + position = semiColonPosition; + return std::make_pair(first, second); } - std::shared_ptr& CookieStore::getCookieInternExactPath(const std::string& host, const std::string& path) + static inline bool isTerminator(char c) { - for (auto it = m_cookies.begin(); it != m_cookies.end(); ) - { - std::shared_ptr& cookie = *it; - if (cookie->matchExactPath(host, path)) - { - if (cookie->isExpired()) - { - it = m_cookies.erase(it); - } - else - { - return cookie; - } - } - else - { - ++it; - } - } - static std::shared_ptr nullPointer; - return nullPointer; + return c == '\n' || c == '\r'; } - - //--------------------------------------- - // ProtocolHttpClient - //--------------------------------------- - - - const std::uint32_t ProtocolHttpClient::PROTOCOL_ID = 7; - const std::string ProtocolHttpClient::PROTOCOL_NAME = "httpclient"; - - - const std::string ProtocolHttpClient::FMQ_HTTP = "fmq_http"; - const std::string ProtocolHttpClient::FMQ_METHOD = "fmq_method"; - const std::string ProtocolHttpClient::FMQ_PROTOCOL = "fmq_protocol"; - const std::string ProtocolHttpClient::FMQ_PATH = "fmq_path"; - const std::string ProtocolHttpClient::FMQ_QUERY_PREFIX = "QUERY_"; - const std::string ProtocolHttpClient::FMQ_HTTP_STATUS = "fmq_http_status"; - const std::string ProtocolHttpClient::FMQ_HTTP_STATUSTEXT = "fmq_http_statustext"; - const std::string ProtocolHttpClient::HTTP_REQUEST = "request"; - const std::string ProtocolHttpClient::HTTP_RESPONSE = "response"; - - static const std::string CONTENT_LENGTH = "Content-Length"; - //static const std::string FMQ_SESSIONID = "fmq_sessionid"; - static const std::string HTTP_COOKIE = "Cookie"; - - static const std::string FMQ_CREATESESSION = "fmq_createsession"; - static const std::string FMQ_SET_SESSION = "fmq_setsession"; - static const std::string HTTP_SET_COOKIE = "Set-Cookie"; - static const std::string COOKIE_PREFIX = "fmq="; - - static const std::string FMQ_PATH_POLL = "/fmq/poll"; - static const std::string FMQ_PATH_PING = "/fmq/ping"; - static const std::string FMQ_PATH_CONFIG = "/fmq/config"; - static const std::string FMQ_PATH_CREATESESSION = "/fmq/createsession"; - static const std::string FMQ_PATH_REMOVESESSION = "/fmq/removesession"; - static const std::string FMQ_MULTIPART_BOUNDARY = "B9BMAhxAhY.mQw1IDRBA"; - - - //enum ChunkedState - //{ - // STATE_STOP = 0, - // STATE_START_CHUNK_STREAM = 1, - // STATE_FIRST_CHUNK = 2, - // STATE_BEGIN_MULTIPART = 3, - // STATE_CONTINUE = 4, - //}; - - - - ProtocolHttpClient::ProtocolHttpClient() - : m_randomDevice() - , m_randomGenerator(m_randomDevice()) + static inline bool isValueSeparator(char c) { - + return isTerminator(c) || c == ';'; } - ProtocolHttpClient::~ProtocolHttpClient() + static inline bool isLWS(char c) { - if (m_connection) - { - m_connection->disconnect(); - } + return c == ' ' || c == '\t' || c == '\r' || c == '\n'; } - - // IProtocol - void ProtocolHttpClient::setCallback(const std::weak_ptr& callback) + static int nextNonWhitespace(const std::string& text, int from) { - std::unique_lock lock(m_mutex); - m_callback = callback; - std::shared_ptr cb = callback.lock(); - lock.unlock(); - if (cb) + // RFC 2616 defines linear whitespace as: + // LWS = [CRLF] 1*( SP | HT ) + // We ignore the fact that CRLF must come as a pair at this point + // It's an invalid HTTP header if that happens. + while (static_cast(from) < text.length()) { - // 5 minutes session timeout - cb->setActivityTimeout(5 * 60000); + if (isLWS(text.at(from))) + ++from; + else + return from; // non-whitespace } - } - - void ProtocolHttpClient::setConnection(const IStreamConnectionPtr& connection) - { - std::unique_lock lock(m_mutex); - m_connection = connection; - } - IStreamConnectionPtr ProtocolHttpClient::getConnection() const - { - std::unique_lock lock(m_mutex); - return m_connection; + // reached the end + return static_cast(text.length()); } - void ProtocolHttpClient::disconnect() + static int nextNonWhitespaceReverse(const std::string& text, int from, int till) { - std::unique_lock lock(m_mutex); - IStreamConnectionPtr conn = m_connection; - lock.unlock(); - if (conn) + --from; + while (from >= till) { - conn->disconnect(); + if (isLWS(text.at(from))) + --from; + else + return from + 1; // non-whitespace + 1 } - } - std::uint32_t ProtocolHttpClient::getProtocolId() const - { - return PROTOCOL_ID; + // reached the end + return till; } - bool ProtocolHttpClient::areMessagesResendable() const + time_t m_expirationDate{}; + std::string m_domain{}; + bool m_domainDot{}; + std::string m_path{}; + std::string m_comment{}; + std::string m_name{}; + std::string m_value{}; + bool m_secure{}; + bool m_httpOnly{}; +}; +#ifndef WIN32 +const int Cookie::DaysOfMonth[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; +#endif + +//--------------------------------------- +// CookieStore +//--------------------------------------- + +void CookieStore::add(const Cookie& cookie) +{ + std::unique_lock lock(m_mutex); + std::shared_ptr& cookieExists = getCookieInternExactPath(cookie.getDomain(), cookie.getPath()); + if (cookieExists) { - return false; + cookieExists = std::make_shared(cookie); } - - bool ProtocolHttpClient::doesSupportMetainfo() const + else { - return true; + m_cookies.push_back(std::make_shared(cookie)); } +} - bool ProtocolHttpClient::doesSupportSession() const +void CookieStore::add(const std::vector& cookies) +{ + for (const auto& cookie : cookies) { - return true; + add(cookie); } - - bool ProtocolHttpClient::needsReply() const +} + +const std::vector> CookieStore::getCookies(const std::string& host, const std::string& path) const +{ + std::unique_lock lock(m_mutex); + std::vector> cookies = const_cast(this)->getCookiesIntern(host, path); + return cookies; +} + +std::vector> CookieStore::getCookiesIntern(const std::string& host, const std::string& path) +{ + std::vector> cookies; + for (auto it = m_cookies.begin(); it != m_cookies.end();) { - return true; + std::shared_ptr& cookie = *it; + if (cookie->match(host, path)) + { + if (cookie->isExpired()) + { + it = m_cookies.erase(it); + } + else + { + cookies.push_back(cookie); + ++it; + } + } + else + { + ++it; + } } + return cookies; +} - bool ProtocolHttpClient::isMultiConnectionSession() const +std::shared_ptr& CookieStore::getCookieInternExactPath(const std::string& host, const std::string& path) +{ + for (auto it = m_cookies.begin(); it != m_cookies.end();) { - return true; + std::shared_ptr& cookie = *it; + if (cookie->matchExactPath(host, path)) + { + if (cookie->isExpired()) + { + it = m_cookies.erase(it); + } + else + { + return cookie; + } + } + else + { + ++it; + } } - - bool ProtocolHttpClient::isSendRequestByPoll() const + static std::shared_ptr nullPointer; + return nullPointer; +} + +//--------------------------------------- +// ProtocolHttpClient +//--------------------------------------- + +const std::uint32_t ProtocolHttpClient::PROTOCOL_ID = 7; +const std::string ProtocolHttpClient::PROTOCOL_NAME = "httpclient"; + +const std::string ProtocolHttpClient::FMQ_HTTP = "fmq_http"; +const std::string ProtocolHttpClient::FMQ_METHOD = "fmq_method"; +const std::string ProtocolHttpClient::FMQ_PROTOCOL = "fmq_protocol"; +const std::string ProtocolHttpClient::FMQ_PATH = "fmq_path"; +const std::string ProtocolHttpClient::FMQ_QUERY_PREFIX = "QUERY_"; +const std::string ProtocolHttpClient::FMQ_HTTP_STATUS = "fmq_http_status"; +const std::string ProtocolHttpClient::FMQ_HTTP_STATUSTEXT = "fmq_http_statustext"; +const std::string ProtocolHttpClient::HTTP_REQUEST = "request"; +const std::string ProtocolHttpClient::HTTP_RESPONSE = "response"; + +static const std::string CONTENT_LENGTH = "Content-Length"; +//static const std::string FMQ_SESSIONID = "fmq_sessionid"; +static const std::string HTTP_COOKIE = "Cookie"; + +static const std::string FMQ_CREATESESSION = "fmq_createsession"; +static const std::string FMQ_SET_SESSION = "fmq_setsession"; +static const std::string HTTP_SET_COOKIE = "Set-Cookie"; +static const std::string COOKIE_PREFIX = "fmq="; + +static const std::string FMQ_PATH_POLL = "/fmq/poll"; +static const std::string FMQ_PATH_PING = "/fmq/ping"; +static const std::string FMQ_PATH_CONFIG = "/fmq/config"; +static const std::string FMQ_PATH_CREATESESSION = "/fmq/createsession"; +static const std::string FMQ_PATH_REMOVESESSION = "/fmq/removesession"; +static const std::string FMQ_MULTIPART_BOUNDARY = "B9BMAhxAhY.mQw1IDRBA"; + +//enum ChunkedState +//{ +// STATE_STOP = 0, +// STATE_START_CHUNK_STREAM = 1, +// STATE_FIRST_CHUNK = 2, +// STATE_BEGIN_MULTIPART = 3, +// STATE_CONTINUE = 4, +//}; + +ProtocolHttpClient::ProtocolHttpClient() + : m_randomDevice(), m_randomGenerator(m_randomDevice()) +{ +} + +ProtocolHttpClient::~ProtocolHttpClient() +{ + if (m_connection) { - return true; + m_connection->disconnect(); } - - bool ProtocolHttpClient::doesSupportFileTransfer() const +} + +// IProtocol +void ProtocolHttpClient::setCallback(const std::weak_ptr& callback) +{ + std::unique_lock lock(m_mutex); + m_callback = callback; + std::shared_ptr cb = callback.lock(); + lock.unlock(); + if (cb) { - return true; + // 5 minutes session timeout + cb->setActivityTimeout(5 * 60000); } - - bool ProtocolHttpClient::isSynchronousRequestReply() const +} + +void ProtocolHttpClient::setConnection(const IStreamConnectionPtr& connection) +{ + std::unique_lock lock(m_mutex); + m_connection = connection; +} + +IStreamConnectionPtr ProtocolHttpClient::getConnection() const +{ + std::unique_lock lock(m_mutex); + return m_connection; +} + +void ProtocolHttpClient::disconnect() +{ + std::unique_lock lock(m_mutex); + IStreamConnectionPtr conn = m_connection; + lock.unlock(); + if (conn) { - return true; + conn->disconnect(); } +} + +std::uint32_t ProtocolHttpClient::getProtocolId() const +{ + return PROTOCOL_ID; +} + +bool ProtocolHttpClient::areMessagesResendable() const +{ + return false; +} + +bool ProtocolHttpClient::doesSupportMetainfo() const +{ + return true; +} + +bool ProtocolHttpClient::doesSupportSession() const +{ + return true; +} + +bool ProtocolHttpClient::needsReply() const +{ + return true; +} + +bool ProtocolHttpClient::isMultiConnectionSession() const +{ + return true; +} + +bool ProtocolHttpClient::isSendRequestByPoll() const +{ + return true; +} + +bool ProtocolHttpClient::doesSupportFileTransfer() const +{ + return true; +} + +bool ProtocolHttpClient::isSynchronousRequestReply() const +{ + return true; +} + +IProtocol::FuncCreateMessage ProtocolHttpClient::getMessageFactory() const +{ + return []() { + return std::make_shared(PROTOCOL_ID); + }; +} - IProtocol::FuncCreateMessage ProtocolHttpClient::getMessageFactory() const +static void splitOnce(const std::string& src, ssize_t indexBegin, ssize_t indexEnd, char delimiter, std::vector& dest) +{ + size_t pos = src.find_first_of(delimiter, indexBegin); + if (pos == std::string::npos || static_cast(pos) > indexEnd) { - return []() { - return std::make_shared(PROTOCOL_ID); - }; + pos = indexEnd; } + ssize_t len = pos - indexBegin; + assert(len >= 0); + dest.emplace_back(&src[indexBegin], len); + ++pos; - - static void splitOnce(const std::string& src, ssize_t indexBegin, ssize_t indexEnd, char delimiter, std::vector& dest) + if (static_cast(pos) < indexEnd) { - size_t pos = src.find_first_of(delimiter, indexBegin); - if (pos == std::string::npos || static_cast(pos) > indexEnd) - { - pos = indexEnd; - } - ssize_t len = pos - indexBegin; + len = indexEnd - pos; assert(len >= 0); - dest.emplace_back(&src[indexBegin], len); - ++pos; - - if (static_cast(pos) < indexEnd) - { - len = indexEnd - pos; - assert(len >= 0); - dest.emplace_back(&src[pos], len); - } + dest.emplace_back(&src[pos], len); } - - - - bool ProtocolHttpClient::receiveHeaders(ssize_t bytesReceived) +} + +bool ProtocolHttpClient::receiveHeaders(ssize_t bytesReceived) +{ + bool ok = true; + bytesReceived += m_sizeRemaining; + assert(bytesReceived <= static_cast(m_receiveBuffer.size())); + while (m_offsetRemaining < bytesReceived && ok) { - bool ok = true; - bytesReceived += m_sizeRemaining; - assert(bytesReceived <= static_cast(m_receiveBuffer.size())); - while (m_offsetRemaining < bytesReceived && ok) + size_t index = m_receiveBuffer.find_first_of('\n', m_offsetRemaining); + if (index != std::string::npos) { - size_t index = m_receiveBuffer.find_first_of('\n', m_offsetRemaining); - if (index != std::string::npos) + ssize_t indexEndLine = index; + --indexEndLine; // goto '\r' + ssize_t len = indexEndLine - m_offsetRemaining; + if (len < 0 || m_receiveBuffer[indexEndLine] != '\r') { - ssize_t indexEndLine = index; - --indexEndLine; // goto '\r' - ssize_t len = indexEndLine - m_offsetRemaining; - if (len < 0 || m_receiveBuffer[indexEndLine] != '\r') - { - ok = false; - } - if (ok) + ok = false; + } + if (ok) + { + if (m_state == State::STATE_FIND_FIRST_LINE) { - if (m_state == State::STATE_FIND_FIRST_LINE) + m_contentLength = 0; + if (len < 4) { - m_contentLength = 0; - if (len < 4) - { - ok = false; - } - else + ok = false; + } + else + { + // is response + if (m_receiveBuffer[m_offsetRemaining] == 'H' && m_receiveBuffer[m_offsetRemaining + 1] == 'T') { - // is response - if (m_receiveBuffer[m_offsetRemaining] == 'H' && m_receiveBuffer[m_offsetRemaining + 1] == 'T') + std::vector lineSplit; + Utils::split(m_receiveBuffer, m_offsetRemaining, indexEndLine, ' ', lineSplit); + if (lineSplit.size() >= 2) { - std::vector lineSplit; - Utils::split(m_receiveBuffer, m_offsetRemaining, indexEndLine, ' ', lineSplit); - if (lineSplit.size() >= 2) + m_message = std::make_shared(0); + Variant& controlData = m_message->getControlData(); + controlData.add(FMQ_HTTP, std::string(HTTP_RESPONSE)); + controlData.add(FMQ_PROTOCOL, std::move(lineSplit[0])); + controlData.add(FMQ_HTTP_STATUS, std::move(lineSplit[1])); + std::string statusText; + for (size_t i = 2; i < lineSplit.size(); ++i) { - m_message = std::make_shared(0); - Variant& controlData = m_message->getControlData(); - controlData.add(FMQ_HTTP, std::string(HTTP_RESPONSE)); - controlData.add(FMQ_PROTOCOL, std::move(lineSplit[0])); - controlData.add(FMQ_HTTP_STATUS, std::move(lineSplit[1])); - std::string statusText; - for (size_t i = 2; i < lineSplit.size(); ++i) + statusText += lineSplit[i]; + if (i < lineSplit.size() - 1) { - statusText += lineSplit[i]; - if (i < lineSplit.size() - 1) - { - statusText += ' '; - } + statusText += ' '; } - controlData.add(FMQ_HTTP_STATUSTEXT, std::move(statusText)); - m_state = State::STATE_FIND_HEADERS; - } - else - { - ok = false; } + controlData.add(FMQ_HTTP_STATUSTEXT, std::move(statusText)); + m_state = State::STATE_FIND_HEADERS; } else { ok = false; } } + else + { + ok = false; + } } - else if (m_state == State::STATE_FIND_HEADERS) + } + else if (m_state == State::STATE_FIND_HEADERS) + { + if (len == 0) { - if (len == 0) + if (m_contentLength == 0) { - if (m_contentLength == 0) - { - m_state = State::STATE_CONTENT_DONE; - } - else - { - m_state = State::STATE_CONTENT; - m_message->resizeReceiveBuffer(m_contentLength); - } - m_indexFilled = 0; - m_offsetRemaining += 2; - break; + m_state = State::STATE_CONTENT_DONE; } else { - std::vector lineSplit; - splitOnce(m_receiveBuffer, m_offsetRemaining, indexEndLine, ':', lineSplit); - if (lineSplit.size() == 2) + m_state = State::STATE_CONTENT; + m_message->resizeReceiveBuffer(m_contentLength); + } + m_indexFilled = 0; + m_offsetRemaining += 2; + break; + } + else + { + std::vector lineSplit; + splitOnce(m_receiveBuffer, m_offsetRemaining, indexEndLine, ':', lineSplit); + if (lineSplit.size() == 2) + { + std::string& value = lineSplit[1]; + if (!value.empty() && value[0] == ' ') { - std::string& value = lineSplit[1]; - if (!value.empty() && value[0] == ' ') - { - value.erase(value.begin()); - } - if (lineSplit[0] == CONTENT_LENGTH) - { - m_contentLength = std::atoll(value.c_str()); - } - else if (lineSplit[0] == HTTP_SET_COOKIE) - { - const std::vector cookies = Cookie::parseSetCookieHeaderLine(value, m_hostname); - m_cookieStore->add(cookies); - } - m_message->addMetainfo(std::move(lineSplit[0]), std::move(value)); + value.erase(value.begin()); } - else if (lineSplit.size() == 1) + if (lineSplit[0] == CONTENT_LENGTH) { - m_message->addMetainfo(std::move(lineSplit[0]), ""); + m_contentLength = std::atoll(value.c_str()); } - else + else if (lineSplit[0] == HTTP_SET_COOKIE) { - assert(false); - ok = false; + const std::vector cookies = Cookie::parseSetCookieHeaderLine(value, m_hostname); + m_cookieStore->add(cookies); } + m_message->addMetainfo(std::move(lineSplit[0]), std::move(value)); + } + else if (lineSplit.size() == 1) + { + m_message->addMetainfo(std::move(lineSplit[0]), ""); + } + else + { + assert(false); + ok = false; } } - m_offsetRemaining += len + 2; } - } - else - { - break; + m_offsetRemaining += len + 2; } } - m_sizeRemaining = bytesReceived - m_offsetRemaining; - assert(m_sizeRemaining >= 0); - return ok; + else + { + break; + } } - - - void ProtocolHttpClient::reset() + m_sizeRemaining = bytesReceived - m_offsetRemaining; + assert(m_sizeRemaining >= 0); + return ok; +} + +void ProtocolHttpClient::reset() +{ + m_offsetRemaining = 0; + m_sizeRemaining = 0; + m_contentLength = 0; + m_indexFilled = 0; + m_message = nullptr; + m_state = State::STATE_FIND_FIRST_LINE; +} + +static std::string HEADER_KEEP_ALIVE = "Connection: keep-alive\r\n"; + +void ProtocolHttpClient::sendMessage(IMessagePtr message) +{ + IStreamConnectionPtr connection = getConnection(); + if (connection == nullptr) { - m_offsetRemaining = 0; - m_sizeRemaining = 0; - m_contentLength = 0; - m_indexFilled = 0; - m_message = nullptr; - m_state = State::STATE_FIND_FIRST_LINE; + return; + } + if (message == nullptr) + { + return; + } + assert(!message->wasSent()); + std::string firstLine; + const Variant& controlData = message->getControlData(); + const std::string* filename = controlData.getData("filetransfer"); + ssize_t filesize = -1; + if (filename) + { + struct stat statdata; + memset(&statdata, 0, sizeof(statdata)); + int res = OperatingSystem::instance().stat(filename->c_str(), &statdata); + if (res == 0) + { + filesize = statdata.st_size; + message->downsizeLastSendPayload(0); + } } + if (filename && filesize == -1) + { + filesize = 0; + } + ssize_t sizeBody = message->getTotalSendPayloadSize(); + if (filesize != -1) + { + sizeBody = filesize; + } - static std::string HEADER_KEEP_ALIVE = "Connection: keep-alive\r\n"; - - void ProtocolHttpClient::sendMessage(IMessagePtr message) + static const std::string METHOD_GET = "GET"; + static const std::string METHOD_POST = "POST"; + static const std::string PATH_ROOT = "/"; + const std::string* method = controlData.getData(FMQ_METHOD); + const std::string* path = controlData.getData(FMQ_PATH); + if (method == nullptr || method->empty()) { - IStreamConnectionPtr connection = getConnection(); - if (connection == nullptr) + if (sizeBody > 0) { - return; + method = &METHOD_POST; } - if (message == nullptr) - { - return; - } - assert(!message->wasSent()); - std::string firstLine; - const Variant& controlData = message->getControlData(); - const std::string* filename = controlData.getData("filetransfer"); - ssize_t filesize = -1; - if (filename) - { - struct stat statdata; - memset(&statdata, 0, sizeof(statdata)); - int res = OperatingSystem::instance().stat(filename->c_str(), &statdata); - if (res == 0) - { - filesize = statdata.st_size; - message->downsizeLastSendPayload(0); - } - } - - if (filename && filesize == -1) + else { - filesize = 0; + method = &METHOD_GET; } + } + if (path == nullptr || path->empty()) + { + path = &PATH_ROOT; + } - ssize_t sizeBody = message->getTotalSendPayloadSize(); - if (filesize != -1) - { - sizeBody = filesize; - } + std::string pathEncode; + encode(pathEncode, *path); + firstLine = *method; + firstLine += ' '; + firstLine += pathEncode; - static const std::string METHOD_GET = "GET"; - static const std::string METHOD_POST = "POST"; - static const std::string PATH_ROOT = "/"; - const std::string* method = controlData.getData(FMQ_METHOD); - const std::string* path = controlData.getData(FMQ_PATH); - if (method == nullptr || method->empty()) + const VariantStruct* queries = controlData.getData("queries"); + if (queries) + { + for (auto it = queries->begin(); it != queries->end(); ++it) { - if (sizeBody > 0) + if (it == queries->begin()) { - method = &METHOD_POST; + firstLine += '?'; } else { - method = &METHOD_GET; - } - } - if (path == nullptr || path->empty()) - { - path = &PATH_ROOT; - } - - std::string pathEncode; - encode(pathEncode, *path); - firstLine = *method; - firstLine += ' '; - firstLine += pathEncode; - - const VariantStruct* queries = controlData.getData("queries"); - if (queries) - { - for (auto it = queries->begin(); it != queries->end(); ++it) - { - if (it == queries->begin()) - { - firstLine += '?'; - } - else - { - firstLine += '&'; - } - std::string key; - std::string value; - - encode(key, it->first); - encode(value, it->second); - firstLine += key; - firstLine += '='; - firstLine += value; + firstLine += '&'; } + std::string key; + std::string value; + + encode(key, it->first); + encode(value, it->second); + firstLine += key; + firstLine += '='; + firstLine += value; } + } - firstLine += " HTTP/1.1"; + firstLine += " HTTP/1.1"; - if (m_headerHost.empty()) - { - const ConnectionData& connectionData = connection->getConnectionData(); - m_hostname = connectionData.hostname; - m_headerHost = "Host: " + connectionData.hostname + ":" + std::to_string(connectionData.port) + "\r\n"; - } + if (m_headerHost.empty()) + { + const ConnectionData& connectionData = connection->getConnectionData(); + m_hostname = connectionData.hostname; + m_headerHost = "Host: " + connectionData.hostname + ":" + std::to_string(connectionData.port) + "\r\n"; + } - size_t sumHeaderSize = 0; - sumHeaderSize += firstLine.size() + 2 + 2; // 2 = '\r\n' and 2 = last empty line - sumHeaderSize += HEADER_KEEP_ALIVE.size(); // Connection: keep-alive\r\n + size_t sumHeaderSize = 0; + sumHeaderSize += firstLine.size() + 2 + 2; // 2 = '\r\n' and 2 = last empty line + sumHeaderSize += HEADER_KEEP_ALIVE.size(); // Connection: keep-alive\r\n - sumHeaderSize += m_headerHost.size(); // Host: hostname\r\n + sumHeaderSize += m_headerHost.size(); // Host: hostname\r\n - ProtocolMessage::Metainfo& metainfo = message->getAllMetainfo(); + ProtocolMessage::Metainfo& metainfo = message->getAllMetainfo(); - assert(m_cookieStore); - const std::vector> cookies = m_cookieStore->getCookies(m_hostname, *path); - std::string cookieString; - for (const auto& cookie : cookies) - { - cookieString += cookie->getName() + '=' + cookie->getValue() + "; "; - } - if (!cookieString.empty()) - { - metainfo[HTTP_COOKIE] = cookieString; - } + assert(m_cookieStore); + const std::vector> cookies = m_cookieStore->getCookies(m_hostname, *path); + std::string cookieString; + for (const auto& cookie : cookies) + { + cookieString += cookie->getName() + '=' + cookie->getValue() + "; "; + } + if (!cookieString.empty()) + { + metainfo[HTTP_COOKIE] = cookieString; + } - metainfo[CONTENT_LENGTH] = std::to_string(sizeBody); - if (!m_headerSendNext.empty()) - { - metainfo.insert(m_headerSendNext.begin(), m_headerSendNext.end()); - m_headerSendNext.clear(); - } - for (auto it = metainfo.begin(); it != metainfo.end(); ++it) + metainfo[CONTENT_LENGTH] = std::to_string(sizeBody); + if (!m_headerSendNext.empty()) + { + metainfo.insert(m_headerSendNext.begin(), m_headerSendNext.end()); + m_headerSendNext.clear(); + } + for (auto it = metainfo.begin(); it != metainfo.end(); ++it) + { + const std::string& key = it->first; + const std::string& value = it->second; + if (!key.empty()) { - const std::string& key = it->first; - const std::string& value = it->second; - if (!key.empty()) - { - sumHeaderSize += key.size() + value.size() + 4; // 4 = ': ' and '\r\n' - } + sumHeaderSize += key.size() + value.size() + 4; // 4 = ': ' and '\r\n' } + } - char* headerBuffer = nullptr; - size_t index = 0; - headerBuffer = message->addSendHeader(sumHeaderSize); - index = 0; - assert(index + firstLine.size() + 2 <= sumHeaderSize); - memcpy(headerBuffer + index, firstLine.data(), firstLine.size()); - index += firstLine.size(); - memcpy(headerBuffer + index, "\r\n", 2); - index += 2; - - // Host: hostname\r\n - assert(index + m_headerHost.size() <= sumHeaderSize); - memcpy(headerBuffer + index, m_headerHost.data(), m_headerHost.size()); - index += m_headerHost.size(); - - // Connection: keep-alive\r\n - assert(index + HEADER_KEEP_ALIVE.size() <= sumHeaderSize); - memcpy(headerBuffer + index, HEADER_KEEP_ALIVE.data(), HEADER_KEEP_ALIVE.size()); - index += HEADER_KEEP_ALIVE.size(); - - for (auto it = metainfo.begin(); it != metainfo.end(); ++it) + char* headerBuffer = nullptr; + size_t index = 0; + headerBuffer = message->addSendHeader(sumHeaderSize); + index = 0; + assert(index + firstLine.size() + 2 <= sumHeaderSize); + memcpy(headerBuffer + index, firstLine.data(), firstLine.size()); + index += firstLine.size(); + memcpy(headerBuffer + index, "\r\n", 2); + index += 2; + + // Host: hostname\r\n + assert(index + m_headerHost.size() <= sumHeaderSize); + memcpy(headerBuffer + index, m_headerHost.data(), m_headerHost.size()); + index += m_headerHost.size(); + + // Connection: keep-alive\r\n + assert(index + HEADER_KEEP_ALIVE.size() <= sumHeaderSize); + memcpy(headerBuffer + index, HEADER_KEEP_ALIVE.data(), HEADER_KEEP_ALIVE.size()); + index += HEADER_KEEP_ALIVE.size(); + + for (auto it = metainfo.begin(); it != metainfo.end(); ++it) + { + const std::string& key = it->first; + const std::string& value = it->second; + if (!key.empty()) { - const std::string& key = it->first; - const std::string& value = it->second; - if (!key.empty()) - { - assert(index + key.size() + value.size() + 4 <= sumHeaderSize); - memcpy(headerBuffer + index, key.data(), key.size()); - index += key.size(); - memcpy(headerBuffer + index, ": ", 2); - index += 2; - memcpy(headerBuffer + index, value.data(), value.size()); - index += value.size(); - memcpy(headerBuffer + index, "\r\n", 2); - index += 2; - } + assert(index + key.size() + value.size() + 4 <= sumHeaderSize); + memcpy(headerBuffer + index, key.data(), key.size()); + index += key.size(); + memcpy(headerBuffer + index, ": ", 2); + index += 2; + memcpy(headerBuffer + index, value.data(), value.size()); + index += value.size(); + memcpy(headerBuffer + index, "\r\n", 2); + index += 2; } - assert(index + 2 == sumHeaderSize); - memcpy(headerBuffer + index, "\r\n", 2); + } + assert(index + 2 == sumHeaderSize); + memcpy(headerBuffer + index, "\r\n", 2); - message->prepareMessageToSend(); + message->prepareMessageToSend(); - connection->sendMessage(message); + connection->sendMessage(message); - if (filename && filesize > 0) - { - std::string file = *filename; - std::weak_ptr pThisWeak = shared_from_this(); - GlobalExecutorWorker::instance().addAction([pThisWeak, file, filesize]() { - std::shared_ptr pThis = pThisWeak.lock(); - if (!pThis) - { - return; - } - int flags = O_RDONLY; + if (filename && filesize > 0) + { + std::string file = *filename; + std::weak_ptr pThisWeak = shared_from_this(); + GlobalExecutorWorker::instance().addAction([pThisWeak, file, filesize]() { + std::shared_ptr pThis = pThisWeak.lock(); + if (!pThis) + { + return; + } + int flags = O_RDONLY; #ifdef WIN32 - flags |= O_BINARY; + flags |= O_BINARY; #endif - int fd = OperatingSystem::instance().open(file.c_str(), flags); - if (fd != -1) + int fd = OperatingSystem::instance().open(file.c_str(), flags); + if (fd != -1) + { + int len = static_cast(filesize); + int err = 0; + int lenReceived = 0; + bool ex = false; + while (!ex) { - int len = static_cast(filesize); - int err = 0; - int lenReceived = 0; - bool ex = false; - while (!ex) + int size = std::min(1024, len); + IMessagePtr messageData = std::make_shared(0); + char* buf = messageData->addSendPayload(size); + do { - int size = std::min(1024, len); - IMessagePtr messageData = std::make_shared(0); - char* buf = messageData->addSendPayload(size); - do - { - err = OperatingSystem::instance().read(fd, buf, size); - } while (err == -1 && OperatingSystem::instance().getLastError() == SOCKETERROR(EINTR)); + err = OperatingSystem::instance().read(fd, buf, size); + } while (err == -1 && OperatingSystem::instance().getLastError() == SOCKETERROR(EINTR)); - if (err > 0) + if (err > 0) + { + assert(err <= size); + if (err < size) { - assert(err <= size); - if (err < size) - { - messageData->downsizeLastSendPayload(err); - } - pThis->m_connection->sendMessage(messageData); - buf += err; - len -= err; - lenReceived += err; - err = 0; - assert(len >= 0); - if (len == 0) - { - ex = true; - } + messageData->downsizeLastSendPayload(err); } - else + pThis->m_connection->sendMessage(messageData); + buf += err; + len -= err; + lenReceived += err; + err = 0; + assert(len >= 0); + if (len == 0) { ex = true; } } - if (lenReceived < filesize) + else { - pThis->m_connection->disconnect(); + ex = true; } } - else + if (lenReceived < filesize) { pThis->m_connection->disconnect(); } - }); - } + } + else + { + pThis->m_connection->disconnect(); + } + }); } - - - void ProtocolHttpClient::moveOldProtocolState(IProtocol& /*protocolOld*/) +} + +void ProtocolHttpClient::moveOldProtocolState(IProtocol& /*protocolOld*/) +{ +} + +//bool ProtocolHttpClient::handleInternalCommands(const std::shared_ptr& callback, bool& ok) +//{ +// assert(callback); +// bool handled = false; +// if (m_path) +// { +// if (*m_path == FMQ_PATH_POLL) +// { +// m_chunkedState = STATE_START_CHUNK_STREAM; +// assert(m_message); +// handled = true; +// std::int32_t timeout = -1; +// std::int32_t pollCountMax = 1; +// const std::string* strTimeout = m_message->getMetainfo("QUERY_timeout"); +// const std::string* strCount = m_message->getMetainfo("QUERY_count"); +// const std::string* strMultipart = m_message->getMetainfo("QUERY_multipart"); +// if (strTimeout) +// { +// timeout = std::atoi(strTimeout->c_str()); +// } +// if (strCount) +// { +// pollCountMax = std::atoi(strCount->c_str()); +// } +// if (strMultipart) +// { +// m_multipart = (*strMultipart == "true") ? true : false; +// } +// //if (strTimeout && !strCount) +// //{ +// // pollCountMax = -1; +// //} +// //if (!strTimeout && strCount) +// //{ +// // timeout = -1; +// //} +// IMessagePtr message = getMessageFactory()(); +// std::string contentType; +// if (m_multipart) +// { +// contentType = "multipart/x-mixed-replace; boundary="; +// contentType += FMQ_MULTIPART_BOUNDARY; +// } +// else +// { +// contentType = "text/event-stream"; +// } +// message->addMetainfo("Content-Type", contentType); +// message->addMetainfo("Transfer-Encoding", "chunked"); +// sendMessage(message); +// m_chunkedState = STATE_FIRST_CHUNK; +// callback->pollRequest(shared_from_this(), timeout, pollCountMax); +// } +// else if (*m_path == FMQ_PATH_PING) +// { +// handled = true; +// assert(m_connection); +// sendMessage(getMessageFactory()()); +// callback->activity(); +// } +// else if (*m_path == FMQ_PATH_CONFIG) +// { +// handled = true; +// const std::string* timeout = m_message->getMetainfo("QUERY_activitytimeout"); +// if (timeout) +// { +// callback->setActivityTimeout(std::atoi(timeout->c_str())); +// } +// const std::string* pollMaxRequests = m_message->getMetainfo("QUERY_pollmaxrequests"); +// if (pollMaxRequests) +// { +// callback->setPollMaxRequests(std::atoi(pollMaxRequests->c_str())); +// } +// sendMessage(getMessageFactory()()); +// callback->activity(); +// } +// else if (*m_path == FMQ_PATH_CREATESESSION) +// { +// handled = true; +// sendMessage(getMessageFactory()()); +// callback->activity(); +// } +// else if (*m_path == FMQ_PATH_REMOVESESSION) +// { +// handled = true; +// ok = false; +// sendMessage(getMessageFactory()()); +// callback->disconnected(); +// } +// } +// +// return handled; +//} + +bool ProtocolHttpClient::received(const IStreamConnectionPtr& /*connection*/, const SocketPtr& socket, int bytesToRead) +{ + bool ok = true; + + if (m_state != State::STATE_CONTENT) { - } - - - - - //bool ProtocolHttpClient::handleInternalCommands(const std::shared_ptr& callback, bool& ok) - //{ - // assert(callback); - // bool handled = false; - // if (m_path) - // { - // if (*m_path == FMQ_PATH_POLL) - // { - // m_chunkedState = STATE_START_CHUNK_STREAM; - // assert(m_message); - // handled = true; - // std::int32_t timeout = -1; - // std::int32_t pollCountMax = 1; - // const std::string* strTimeout = m_message->getMetainfo("QUERY_timeout"); - // const std::string* strCount = m_message->getMetainfo("QUERY_count"); - // const std::string* strMultipart = m_message->getMetainfo("QUERY_multipart"); - // if (strTimeout) - // { - // timeout = std::atoi(strTimeout->c_str()); - // } - // if (strCount) - // { - // pollCountMax = std::atoi(strCount->c_str()); - // } - // if (strMultipart) - // { - // m_multipart = (*strMultipart == "true") ? true : false; - // } - // //if (strTimeout && !strCount) - // //{ - // // pollCountMax = -1; - // //} - // //if (!strTimeout && strCount) - // //{ - // // timeout = -1; - // //} - // IMessagePtr message = getMessageFactory()(); - // std::string contentType; - // if (m_multipart) - // { - // contentType = "multipart/x-mixed-replace; boundary="; - // contentType += FMQ_MULTIPART_BOUNDARY; - // } - // else - // { - // contentType = "text/event-stream"; - // } - // message->addMetainfo("Content-Type", contentType); - // message->addMetainfo("Transfer-Encoding", "chunked"); - // sendMessage(message); - // m_chunkedState = STATE_FIRST_CHUNK; - // callback->pollRequest(shared_from_this(), timeout, pollCountMax); - // } - // else if (*m_path == FMQ_PATH_PING) - // { - // handled = true; - // assert(m_connection); - // sendMessage(getMessageFactory()()); - // callback->activity(); - // } - // else if (*m_path == FMQ_PATH_CONFIG) - // { - // handled = true; - // const std::string* timeout = m_message->getMetainfo("QUERY_activitytimeout"); - // if (timeout) - // { - // callback->setActivityTimeout(std::atoi(timeout->c_str())); - // } - // const std::string* pollMaxRequests = m_message->getMetainfo("QUERY_pollmaxrequests"); - // if (pollMaxRequests) - // { - // callback->setPollMaxRequests(std::atoi(pollMaxRequests->c_str())); - // } - // sendMessage(getMessageFactory()()); - // callback->activity(); - // } - // else if (*m_path == FMQ_PATH_CREATESESSION) - // { - // handled = true; - // sendMessage(getMessageFactory()()); - // callback->activity(); - // } - // else if (*m_path == FMQ_PATH_REMOVESESSION) - // { - // handled = true; - // ok = false; - // sendMessage(getMessageFactory()()); - // callback->disconnected(); - // } - // } - // - // return handled; - //} - - - - bool ProtocolHttpClient::received(const IStreamConnectionPtr& /*connection*/, const SocketPtr& socket, int bytesToRead) - { - bool ok = true; + if (m_offsetRemaining == 0 || m_sizeRemaining == 0) + { + m_receiveBuffer.resize(m_sizeRemaining + bytesToRead); + } + else + { + std::string temp = std::move(m_receiveBuffer); + m_receiveBuffer.clear(); + m_receiveBuffer.resize(m_sizeRemaining + bytesToRead); + memcpy(&m_receiveBuffer[0], &temp[m_offsetRemaining], m_sizeRemaining); + } + m_offsetRemaining = 0; - if (m_state != State::STATE_CONTENT) + ssize_t bytesReceived = 0; + int res = 0; + do { - if (m_offsetRemaining == 0 || m_sizeRemaining == 0) + res = socket->receive(const_cast(m_receiveBuffer.data() + bytesReceived + m_sizeRemaining), static_cast(bytesToRead - bytesReceived)); + if (res > 0) { - m_receiveBuffer.resize(m_sizeRemaining + bytesToRead); + bytesReceived += res; } - else + } while (res > 0 && bytesReceived < bytesToRead); + if (res >= 0) + { + assert(bytesReceived <= bytesToRead); + ok = receiveHeaders(bytesReceived); + if (ok && m_state == State::STATE_CONTENT) { - std::string temp = std::move(m_receiveBuffer); - m_receiveBuffer.clear(); - m_receiveBuffer.resize(m_sizeRemaining + bytesToRead); - memcpy(&m_receiveBuffer[0], &temp[m_offsetRemaining], m_sizeRemaining); + assert(m_message != nullptr); + BufferRef payload = m_message->getReceivePayload(); + assert(payload.second == m_contentLength); + if (m_sizeRemaining <= m_contentLength) + { + memcpy(payload.first, m_receiveBuffer.data() + m_offsetRemaining, m_sizeRemaining); + m_indexFilled = m_sizeRemaining; + assert(m_indexFilled <= m_contentLength); + if (m_indexFilled == m_contentLength) + { + m_state = State::STATE_CONTENT_DONE; + } + } + else + { + // too much content + ok = false; + } } - m_offsetRemaining = 0; - + } + } + else + { + BufferRef payload = m_message->getReceivePayload(); + assert(payload.second == m_contentLength); + ssize_t remainingContent = m_contentLength - m_indexFilled; + if (bytesToRead <= remainingContent) + { ssize_t bytesReceived = 0; int res = 0; do { - res = socket->receive(const_cast(m_receiveBuffer.data() + bytesReceived + m_sizeRemaining), static_cast(bytesToRead - bytesReceived)); + res = socket->receive(payload.first + bytesReceived + m_indexFilled, static_cast(bytesToRead - bytesReceived)); if (res > 0) { bytesReceived += res; @@ -1737,175 +1829,118 @@ namespace finalmq { } while (res > 0 && bytesReceived < bytesToRead); if (res >= 0) { - assert(bytesReceived <= bytesToRead); - ok = receiveHeaders(bytesReceived); - if (ok && m_state == State::STATE_CONTENT) + m_indexFilled += bytesReceived; + assert(m_indexFilled <= m_contentLength); + if (m_indexFilled == m_contentLength) { - assert(m_message != nullptr); - BufferRef payload = m_message->getReceivePayload(); - assert(payload.second == m_contentLength); - if (m_sizeRemaining <= m_contentLength) - { - memcpy(payload.first, m_receiveBuffer.data() + m_offsetRemaining, m_sizeRemaining); - m_indexFilled = m_sizeRemaining; - assert(m_indexFilled <= m_contentLength); - if (m_indexFilled == m_contentLength) - { - m_state = State::STATE_CONTENT_DONE; - } - } - else - { - // too much content - ok = false; - } + m_state = State::STATE_CONTENT_DONE; } } } else { - BufferRef payload = m_message->getReceivePayload(); - assert(payload.second == m_contentLength); - ssize_t remainingContent = m_contentLength - m_indexFilled; - if (bytesToRead <= remainingContent) - { - ssize_t bytesReceived = 0; - int res = 0; - do - { - res = socket->receive(const_cast(payload.first + bytesReceived + m_indexFilled), static_cast(bytesToRead - bytesReceived)); - if (res > 0) - { - bytesReceived += res; - } - } while (res > 0 && bytesReceived < bytesToRead); - if (res >= 0) - { - m_indexFilled += bytesReceived; - assert(m_indexFilled <= m_contentLength); - if (m_indexFilled == m_contentLength) - { - m_state = State::STATE_CONTENT_DONE; - } - } - } - else - { - // too much content - ok = false; - } + // too much content + ok = false; } + } - if (ok) + if (ok) + { + if (m_state == State::STATE_CONTENT_DONE) { - if (m_state == State::STATE_CONTENT_DONE) + auto callback = m_callback.lock(); + if (callback) { - auto callback = m_callback.lock(); - if (callback) + //bool handled = handleInternalCommands(callback, ok); + //if (!handled) { - //bool handled = handleInternalCommands(callback, ok); - //if (!handled) - { - callback->received(m_message, m_connectionId); - } + callback->received(m_message, m_connectionId); } - reset(); } + reset(); } - return ok; } + return ok; +} - - hybrid_ptr ProtocolHttpClient::connected(const IStreamConnectionPtr& connection) +hybrid_ptr ProtocolHttpClient::connected(const IStreamConnectionPtr& connection) +{ + ConnectionData connectionData = connection->getConnectionData(); + if (m_headerHost.empty()) { - ConnectionData connectionData = connection->getConnectionData(); - if (m_headerHost.empty()) - { - m_headerHost = "Host: " + connectionData.hostname + ":" + std::to_string(connectionData.port) + "\r\n"; - } - m_connectionId = connectionData.connectionId; - - auto callback = m_callback.lock(); - if (callback) - { - callback->connected(); - } - return nullptr; + m_headerHost = "Host: " + connectionData.hostname + ":" + std::to_string(connectionData.port) + "\r\n"; } + m_connectionId = connectionData.connectionId; - const std::string FMQ_HTTP_STATUS = "fmq_http_status"; - const std::string FMQ_HTTP_STATUSTEXT = "fmq_http_statustext"; - const std::string FMQ_DISCONNECTED = "fmq_disconnected"; - - void ProtocolHttpClient::disconnected(const IStreamConnectionPtr& connection) + auto callback = m_callback.lock(); + if (callback) { - auto callback = m_callback.lock(); - if (callback) - { - IMessagePtr message = std::make_shared(0); - IMessage::Metainfo& metainfo = message->getAllMetainfo(); - metainfo[FMQ_HTTP] = HTTP_RESPONSE; - metainfo[FMQ_PROTOCOL] = "HTTP/1.1"; - metainfo[FMQ_HTTP_STATUS] = "404"; - metainfo[FMQ_HTTP_STATUSTEXT] = "Not Found"; - metainfo[FMQ_DISCONNECTED] = true; - callback->received(message, connection->getConnectionId()); - - callback->disconnectedMultiConnection(shared_from_this()); - } + callback->connected(); } + return nullptr; +} +const std::string FMQ_HTTP_STATUS = "fmq_http_status"; +const std::string FMQ_HTTP_STATUSTEXT = "fmq_http_statustext"; +const std::string FMQ_DISCONNECTED = "fmq_disconnected"; - - IMessagePtr ProtocolHttpClient::pollReply(std::deque&& /*messages*/) +void ProtocolHttpClient::disconnected(const IStreamConnectionPtr& connection) +{ + auto callback = m_callback.lock(); + if (callback) { - return nullptr; + IMessagePtr message = std::make_shared(0); + IMessage::Metainfo& metainfo = message->getAllMetainfo(); + metainfo[FMQ_HTTP] = HTTP_RESPONSE; + metainfo[FMQ_PROTOCOL] = "HTTP/1.1"; + metainfo[FMQ_HTTP_STATUS] = "404"; + metainfo[FMQ_HTTP_STATUSTEXT] = "Not Found"; + metainfo[FMQ_DISCONNECTED] = true; + callback->received(message, connection->getConnectionId()); + + callback->disconnectedMultiConnection(shared_from_this()); } - - - void ProtocolHttpClient::subscribe(const std::vector& /*subscribtions*/) - { - - } - - - void ProtocolHttpClient::cycleTime() - { - - } - - IProtocolSessionDataPtr ProtocolHttpClient::createProtocolSessionData() - { - return std::make_shared(); - } - - void ProtocolHttpClient::setProtocolSessionData(const IProtocolSessionDataPtr& protocolSessionData) +} + +IMessagePtr ProtocolHttpClient::pollReply(std::deque&& /*messages*/) +{ + return nullptr; +} + +void ProtocolHttpClient::subscribe(const std::vector& /*subscribtions*/) +{ +} + +void ProtocolHttpClient::cycleTime() +{ +} + +IProtocolSessionDataPtr ProtocolHttpClient::createProtocolSessionData() +{ + return std::make_shared(); +} + +void ProtocolHttpClient::setProtocolSessionData(const IProtocolSessionDataPtr& protocolSessionData) +{ + m_cookieStore = std::static_pointer_cast(protocolSessionData); +} + +//--------------------------------------- +// ProtocolHttpFactory +//--------------------------------------- + +struct RegisterProtocolHttpClientFactory +{ + RegisterProtocolHttpClientFactory() { - m_cookieStore = std::static_pointer_cast(protocolSessionData); + ProtocolRegistry::instance().registerProtocolFactory(ProtocolHttpClient::PROTOCOL_NAME, ProtocolHttpClient::PROTOCOL_ID, std::make_shared()); } +} g_registerProtocolHttpClientFactory; +// IProtocolFactory +IProtocolPtr ProtocolHttpClientFactory::createProtocol(const Variant& /*data*/) +{ + return std::make_shared(); +} - //--------------------------------------- - // ProtocolHttpFactory - //--------------------------------------- - - - struct RegisterProtocolHttpClientFactory - { - RegisterProtocolHttpClientFactory() - { - ProtocolRegistry::instance().registerProtocolFactory(ProtocolHttpClient::PROTOCOL_NAME, ProtocolHttpClient::PROTOCOL_ID, std::make_shared()); - } - } g_registerProtocolHttpClientFactory; - - - // IProtocolFactory - IProtocolPtr ProtocolHttpClientFactory::createProtocol(const Variant& /*data*/) - { - return std::make_shared(); - } - - - - -} // namespace finalmq +} // namespace finalmq diff --git a/src/protocols/ProtocolHttpServer.cpp b/src/protocols/ProtocolHttpServer.cpp index 3ea29778..e1200658 100644 --- a/src/protocols/ProtocolHttpServer.cpp +++ b/src/protocols/ProtocolHttpServer.cpp @@ -20,28 +20,27 @@ //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. - #include "finalmq/protocols/ProtocolHttpServer.h" + +#include "finalmq/helpers/Utils.h" #include "finalmq/protocolsession/ProtocolMessage.h" #include "finalmq/protocolsession/ProtocolRegistry.h" #include "finalmq/protocolsession/ProtocolSession.h" #include "finalmq/streamconnection/Socket.h" -#include "finalmq/helpers/Utils.h" //#include "finalmq/helpers/ModulenameFinalmq.h" #include #include -#include #include +#include -namespace finalmq { - +namespace finalmq +{ const std::uint32_t ProtocolHttpServer::PROTOCOL_ID = 4; const std::string ProtocolHttpServer::PROTOCOL_NAME = "httpserver"; - const std::string ProtocolHttpServer::FMQ_HTTP = "fmq_http"; const std::string ProtocolHttpServer::FMQ_METHOD = "fmq_method"; const std::string ProtocolHttpServer::FMQ_PROTOCOL = "fmq_protocol"; @@ -51,7 +50,7 @@ const std::string ProtocolHttpServer::FMQ_HTTP_STATUS = "fmq_http_status"; const std::string ProtocolHttpServer::FMQ_HTTP_STATUSTEXT = "fmq_http_statustext"; const std::string ProtocolHttpServer::HTTP_REQUEST = "request"; const std::string ProtocolHttpServer::HTTP_RESPONSE = "response"; - + static const std::string CONTENT_LENGTH = "Content-Length"; static const std::string FMQ_SESSIONID = "fmq_sessionid"; static const std::string HTTP_COOKIE = "Cookie"; @@ -68,7 +67,6 @@ static const std::string FMQ_PATH_CREATESESSION = "/fmq/createsession"; static const std::string FMQ_PATH_REMOVESESSION = "/fmq/removesession"; static const std::string FMQ_MULTIPART_BOUNDARY = "B9BMAhxAhY.mQw1IDRBA"; - enum ChunkedState { STATE_STOP = 0, @@ -82,14 +80,11 @@ enum ChunkedState // ProtocolHttpServer //--------------------------------------- - -std::atomic_int64_t ProtocolHttpServer::m_nextSessionNameCounter{ 1 }; +std::atomic_int64_t ProtocolHttpServer::m_nextSessionNameCounter{1}; ProtocolHttpServer::ProtocolHttpServer() - : m_randomDevice() - , m_randomGenerator(m_randomDevice()) + : m_randomDevice(), m_randomGenerator(m_randomDevice()) { - } ProtocolHttpServer::~ProtocolHttpServer() @@ -100,7 +95,6 @@ ProtocolHttpServer::~ProtocolHttpServer() } } - // IProtocol void ProtocolHttpServer::setCallback(const std::weak_ptr& callback) { @@ -190,7 +184,6 @@ IProtocol::FuncCreateMessage ProtocolHttpServer::getMessageFactory() const }; } - static void splitOnce(const std::string& src, ssize_t indexBegin, ssize_t indexEnd, char delimiter, std::vector& dest) { size_t pos = src.find_first_of(delimiter, indexBegin); @@ -211,10 +204,23 @@ static void splitOnce(const std::string& src, ssize_t indexBegin, ssize_t indexE } } - static const char tabDecToHex[] = { - '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F' -}; + '0', + '1', + '2', + '3', + '4', + '5', + '6', + '7', + '8', + '9', + 'A', + 'B', + 'C', + 'D', + 'E', + 'F'}; static void encode(std::string& dest, const std::string& src) { @@ -222,14 +228,14 @@ static void encode(std::string& dest, const std::string& src) char c; unsigned char uc; - for (size_t i = 0; i < src.size(); ++i) + for (size_t i = 0; i < src.size(); ++i) { c = src[i]; if (isalnum(c) || c == '/' || c == '-' || c == '_' || c == '.' || c == '~') { dest += c; } - else + else { uc = c; int first = (uc >> 4) & 0x0f; @@ -243,11 +249,10 @@ static void encode(std::string& dest, const std::string& src) } } - static void decode(std::string& dest, const std::string& src) { dest.reserve(src.size()); - char code[3] = { 0 }; + char code[3] = {0}; unsigned long c = 0; for (size_t i = 0; i < src.size(); ++i) @@ -257,7 +262,7 @@ static void decode(std::string& dest, const std::string& src) ++i; memcpy(code, &src[i], 2); c = strtoul(code, NULL, 16); - dest += (char)c; + dest += static_cast(c); ++i; } else @@ -267,9 +272,6 @@ static void decode(std::string& dest, const std::string& src) } } - - - std::string ProtocolHttpServer::createSessionName() { std::uint64_t sessionCounter = m_nextSessionNameCounter.fetch_add(1); @@ -277,13 +279,11 @@ std::string ProtocolHttpServer::createSessionName() std::uint64_t v2 = m_randomVariable(m_randomGenerator); std::ostringstream oss; - oss << std::hex << v2 << v1 << '.' << std::dec <findSessionByName(m_sessionNames[i], shared_from_this()); -// streamInfo << this << " findSessionByName: " << foundInNames; + // streamInfo << this << " findSessionByName: " << foundInNames; if (foundInNames) { sessionMatched.push_back(std::move(m_sessionNames[i])); @@ -336,16 +336,16 @@ void ProtocolHttpServer::checkSessionName() found = true; if (m_sessionName != sessionFound) { -// streamInfo << this << " name before: " << m_sessionName; + // streamInfo << this << " name before: " << m_sessionName; m_sessionName = std::move(sessionFound); } } } -// streamInfo << this << " name: " << m_sessionName; + // streamInfo << this << " name: " << m_sessionName; if (m_createSession || !found) { m_sessionName = createSessionName(); -// streamInfo << this << " create session: " << m_sessionName; + // streamInfo << this << " create session: " << m_sessionName; assert(m_connection); callback->setSessionName(m_sessionName, shared_from_this(), m_connection); m_headerSendNext[FMQ_SET_SESSION] = m_sessionName; @@ -355,8 +355,6 @@ void ProtocolHttpServer::checkSessionName() m_sessionNames.clear(); } - - void ProtocolHttpServer::cookiesToSessionIds(const std::string& cookies) { m_sessionNames.clear(); @@ -380,7 +378,7 @@ void ProtocolHttpServer::cookiesToSessionIds(const std::string& cookies) if (pos != std::string::npos) { pos += 4; - std::string sessionId = { cookie, pos }; + std::string sessionId = {cookie, pos}; if (!sessionId.empty()) { m_sessionNames.emplace_back(std::move(sessionId)); @@ -389,9 +387,6 @@ void ProtocolHttpServer::cookiesToSessionIds(const std::string& cookies) } } - - - bool ProtocolHttpServer::receiveHeaders(ssize_t bytesReceived) { bool ok = true; @@ -539,10 +534,10 @@ bool ProtocolHttpServer::receiveHeaders(ssize_t bytesReceived) if (m_stateSessionId == StateSessionId::SESSIONID_NONE) { cookiesToSessionIds(value); -// if (!m_sessionNames.empty()) -// { -// streamInfo << this << " input cookie: " << m_sessionNames[0]; -// } + // if (!m_sessionNames.empty()) + // { + // streamInfo << this << " input cookie: " << m_sessionNames[0]; + // } m_stateSessionId = StateSessionId::SESSIONID_COOKIE; } } @@ -572,7 +567,6 @@ bool ProtocolHttpServer::receiveHeaders(ssize_t bytesReceived) return ok; } - void ProtocolHttpServer::reset() { m_offsetRemaining = 0; @@ -587,8 +581,6 @@ void ProtocolHttpServer::reset() m_path = nullptr; } - - static std::string HEADER_KEEP_ALIVE = "Connection: keep-alive\r\n"; void ProtocolHttpServer::sendMessage(IMessagePtr message) @@ -702,12 +694,12 @@ void ProtocolHttpServer::sendMessage(IMessagePtr message) size_t sumHeaderSize = 0; if (m_chunkedState < STATE_FIRST_CHUNK) { - sumHeaderSize += firstLine.size() + 2 + 2; // 2 = '\r\n' and 2 = last empty line - sumHeaderSize += HEADER_KEEP_ALIVE.size(); // Connection: keep-alive\r\n + sumHeaderSize += firstLine.size() + 2 + 2; // 2 = '\r\n' and 2 = last empty line + sumHeaderSize += HEADER_KEEP_ALIVE.size(); // Connection: keep-alive\r\n } if (http && *http == HTTP_REQUEST) { - sumHeaderSize += m_headerHost.size(); // Host: hostname\r\n + sumHeaderSize += m_headerHost.size(); // Host: hostname\r\n } ssize_t sizeBody = message->getTotalSendPayloadSize(); @@ -732,7 +724,7 @@ void ProtocolHttpServer::sendMessage(IMessagePtr message) const std::string& value = it->second; if (!key.empty()) { - sumHeaderSize += key.size() + value.size() + 4; // 4 = ': ' and '\r\n' + sumHeaderSize += key.size() + value.size() + 4; // 4 = ': ' and '\r\n' } } @@ -752,7 +744,7 @@ void ProtocolHttpServer::sendMessage(IMessagePtr message) } else { -// firstLine = "\r\n"; + // firstLine = "\r\n"; } char buffer[50]; #ifdef WIN32 @@ -763,9 +755,9 @@ void ProtocolHttpServer::sendMessage(IMessagePtr message) firstLine += buffer; for (auto& c : firstLine) { - c = toupper(c); + c = static_cast(toupper(c)); } - sumHeaderSize += firstLine.size() + 2; // "\r\n" + sumHeaderSize += firstLine.size() + 2; // "\r\n" } headerBuffer = message->addSendHeader(sumHeaderSize); @@ -833,7 +825,6 @@ void ProtocolHttpServer::sendMessage(IMessagePtr message) assert(m_connection); m_connection->sendMessage(message); - if (filename && filesize > 0) { std::string file = *filename; @@ -901,7 +892,6 @@ void ProtocolHttpServer::sendMessage(IMessagePtr message) } } - void ProtocolHttpServer::moveOldProtocolState(IProtocol& /*protocolOld*/) { //assert(protocolOld.getProtocolId() == PROTOCOL_ID); @@ -911,9 +901,6 @@ void ProtocolHttpServer::moveOldProtocolState(IProtocol& /*protocolOld*/) //} } - - - bool ProtocolHttpServer::handleInternalCommands(const std::shared_ptr& callback, bool& ok) { assert(callback); @@ -1008,8 +995,6 @@ bool ProtocolHttpServer::handleInternalCommands(const std::shared_ptrreceive(const_cast(payload.first + bytesReceived + m_indexFilled), static_cast(bytesToRead - bytesReceived)); + res = socket->receive(payload.first + bytesReceived + m_indexFilled, static_cast(bytesToRead - bytesReceived)); if (res > 0) { bytesReceived += res; @@ -1120,9 +1105,6 @@ bool ProtocolHttpServer::received(const IStreamConnectionPtr& /*connection*/, co return ok; } - - - hybrid_ptr ProtocolHttpServer::connected(const IStreamConnectionPtr& connection) { ConnectionData connectionData = connection->getConnectionData(); @@ -1145,8 +1127,6 @@ void ProtocolHttpServer::disconnected(const IStreamConnectionPtr& /*connection*/ } } - - IMessagePtr ProtocolHttpServer::pollReply(std::deque&& messages) { IMessagePtr message = getMessageFactory()(); @@ -1201,16 +1181,12 @@ IMessagePtr ProtocolHttpServer::pollReply(std::deque&& messages) return message; } - void ProtocolHttpServer::subscribe(const std::vector& /*subscribtions*/) { - } - void ProtocolHttpServer::cycleTime() { - } IProtocolSessionDataPtr ProtocolHttpServer::createProtocolSessionData() @@ -1222,12 +1198,10 @@ void ProtocolHttpServer::setProtocolSessionData(const IProtocolSessionDataPtr& / { } - //--------------------------------------- // ProtocolHttpFactory //--------------------------------------- - struct RegisterProtocolHttpServerFactory { RegisterProtocolHttpServerFactory() @@ -1236,14 +1210,10 @@ struct RegisterProtocolHttpServerFactory } } g_registerProtocolHttpServerFactory; - // IProtocolFactory IProtocolPtr ProtocolHttpServerFactory::createProtocol(const Variant& /*data*/) { return std::make_shared(); } - - - -} // namespace finalmq +} // namespace finalmq diff --git a/src/protocols/ProtocolMqtt5Client.cpp b/src/protocols/ProtocolMqtt5Client.cpp index 24ba7b12..e321ed36 100644 --- a/src/protocols/ProtocolMqtt5Client.cpp +++ b/src/protocols/ProtocolMqtt5Client.cpp @@ -20,16 +20,15 @@ //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. - #include "finalmq/protocols/ProtocolMqtt5Client.h" -#include "finalmq/streamconnection/Socket.h" + +#include "finalmq/helpers/ModulenameFinalmq.h" #include "finalmq/protocolsession/ProtocolMessage.h" #include "finalmq/protocolsession/ProtocolRegistry.h" +#include "finalmq/streamconnection/Socket.h" #include "finalmq/variant/VariantValueStruct.h" #include "finalmq/variant/VariantValues.h" -#include "finalmq/helpers/ModulenameFinalmq.h" - #ifdef WIN32 #include #else @@ -46,10 +45,8 @@ #endif #endif - - -namespace finalmq { - +namespace finalmq +{ const std::uint32_t ProtocolMqtt5Client::PROTOCOL_ID = 5; const std::string ProtocolMqtt5Client::PROTOCOL_NAME = "mqtt5client"; @@ -70,7 +67,6 @@ static const std::string SESSIONID_PREFIX = "/_id:"; static const std::uint8_t ReasonCodeDisconnectWithWillMessage = 0x04; - #ifdef WIN32 static std::string getUuid() { @@ -141,7 +137,7 @@ void uuid_unparse(uuid_t uu, char* out) static std::string getUuid() { std::string strUuid; - strUuid.resize(50); // 37 is the exact number + strUuid.resize(50); // 37 is the exact number uuid_t uuid; uuid_generate(uuid); uuid_unparse(uuid, const_cast(strUuid.data())); @@ -152,7 +148,7 @@ static std::string getUuid() static std::string getUuid() { std::string strUuid; - strUuid.resize(50); // 37 is the exact number + strUuid.resize(50); // 37 is the exact number uuid_t uuid; uuid_generate(uuid); uuid_unparse(uuid, const_cast(strUuid.data())); @@ -162,8 +158,6 @@ static std::string getUuid() #endif #endif - - ProtocolMqtt5Client::ProtocolMqtt5Client(const Variant& data) : m_client(std::make_unique()) { @@ -185,8 +179,6 @@ ProtocolMqtt5Client::ProtocolMqtt5Client(const Variant& data) m_client->setCallback(this); } - - ProtocolMqtt5Client::~ProtocolMqtt5Client() { if (m_connection) @@ -195,7 +187,6 @@ ProtocolMqtt5Client::~ProtocolMqtt5Client() } } - // IProtocol void ProtocolMqtt5Client::setCallback(const std::weak_ptr& callback) { @@ -211,22 +202,21 @@ void ProtocolMqtt5Client::setConnection(const IStreamConnectionPtr& connection) data.receiveMaximum = 128; data.username = m_username; data.password = m_password; - data.keepAlive = m_keepAlive; + data.keepAlive = static_cast(m_keepAlive); data.sessionExpiryInterval = m_sessionExpiryInterval; data.willMessage = std::make_unique(); data.willMessage->payload.insert(data.willMessage->payload.end(), m_virtualSessionId.begin(), m_virtualSessionId.end()); data.willMessage->qos = 2; data.willMessage->topic = TOPIC_WILLMESSAGE; data.willMessage->retain = false; - data.willMessage->delayInterval = m_sessionExpiryInterval + 1000; // the sessionExpiryInterval has priority + data.willMessage->delayInterval = m_sessionExpiryInterval + 1000; // the sessionExpiryInterval has priority m_client->startConnection(connection, data); - m_client->subscribe(connection, { {{m_virtualSessionId + "/#", 2, false, true, 2}} }); - m_client->subscribe(connection, { {{TOPIC_WILLMESSAGE, 2, false, true, 2}} }); + m_client->subscribe(connection, {{{m_virtualSessionId + "/#", 2, false, true, 2}}}); + m_client->subscribe(connection, {{{TOPIC_WILLMESSAGE, 2, false, true, 2}}}); std::unique_lock lock(m_mutex); m_connection = connection; - } IStreamConnectionPtr ProtocolMqtt5Client::getConnection() const @@ -249,7 +239,7 @@ void ProtocolMqtt5Client::disconnect() message->addSendPayload(m_virtualSessionId); m_client->publish(connection, std::move(dataWill), message); - IMqtt5Client::DisconnectData data = { ReasonCodeDisconnectWithWillMessage, "", {} }; + IMqtt5Client::DisconnectData data = {ReasonCodeDisconnectWithWillMessage, "", {}}; m_client->endConnection(connection, data); if (connection) @@ -263,37 +253,37 @@ std::uint32_t ProtocolMqtt5Client::getProtocolId() const return PROTOCOL_ID; } -bool ProtocolMqtt5Client::areMessagesResendable() const +bool ProtocolMqtt5Client::areMessagesResendable() const { return false; } -bool ProtocolMqtt5Client::doesSupportMetainfo() const +bool ProtocolMqtt5Client::doesSupportMetainfo() const { return true; } -bool ProtocolMqtt5Client::doesSupportSession() const +bool ProtocolMqtt5Client::doesSupportSession() const { return true; } -bool ProtocolMqtt5Client::needsReply() const +bool ProtocolMqtt5Client::needsReply() const { return false; } -bool ProtocolMqtt5Client::isMultiConnectionSession() const +bool ProtocolMqtt5Client::isMultiConnectionSession() const { return false; } -bool ProtocolMqtt5Client::isSendRequestByPoll() const +bool ProtocolMqtt5Client::isSendRequestByPoll() const { return false; } -bool ProtocolMqtt5Client::doesSupportFileTransfer() const +bool ProtocolMqtt5Client::doesSupportFileTransfer() const { return false; } @@ -366,17 +356,17 @@ void ProtocolMqtt5Client::sendMessage(IMessagePtr message) } } -void ProtocolMqtt5Client::moveOldProtocolState(IProtocol& /*protocolOld*/) +void ProtocolMqtt5Client::moveOldProtocolState(IProtocol& /*protocolOld*/) { } -bool ProtocolMqtt5Client::received(const IStreamConnectionPtr& connection, const SocketPtr& socket, int bytesToRead) +bool ProtocolMqtt5Client::received(const IStreamConnectionPtr& connection, const SocketPtr& socket, int bytesToRead) { bool ok = m_client->receive(connection, socket, bytesToRead); return ok; } -hybrid_ptr ProtocolMqtt5Client::connected(const IStreamConnectionPtr& /*connection*/) +hybrid_ptr ProtocolMqtt5Client::connected(const IStreamConnectionPtr& /*connection*/) { std::unique_lock lock(m_mutex); auto callback = m_callback.lock(); @@ -402,7 +392,7 @@ void ProtocolMqtt5Client::disconnected(const IStreamConnectionPtr& /*connection* } } -IMessagePtr ProtocolMqtt5Client::pollReply(std::deque&& /*messages*/) +IMessagePtr ProtocolMqtt5Client::pollReply(std::deque&& /*messages*/) { return {}; } @@ -419,7 +409,7 @@ void ProtocolMqtt5Client::subscribe(const std::vector& subscribtion { const std::string& subscription = subscribtions[i]; std::string topic = "/" + subscription; - data.subscriptions.push_back({ topic, 2, false, false, 2 }); + data.subscriptions.push_back({topic, 2, false, false, 2}); } std::unique_lock lock(m_mutex); @@ -444,7 +434,6 @@ void ProtocolMqtt5Client::cycleTime() } } - // IMqtt5ClientCallback void ProtocolMqtt5Client::receivedConnAck(const ConnAckData& data) { @@ -466,7 +455,7 @@ void ProtocolMqtt5Client::receivedConnAck(const ConnAckData& data) m_sessionExpiryInterval = data.sessionExpiryInterval; } } -// IStreamConnectionPtr connection = m_connection; + // IStreamConnectionPtr connection = m_connection; auto callback = m_callback.lock(); lock.unlock(); @@ -489,7 +478,7 @@ void ProtocolMqtt5Client::receivedConnAck(const ConnAckData& data) } else { - streamError << "Connection failed, reason code: " << (unsigned int)data.reasoncode << " (" << data.reasonString << ")"; + streamError << "Connection failed, reason code: " << static_cast(data.reasoncode) << " (" << data.reasonString << ")"; } } @@ -531,12 +520,10 @@ void ProtocolMqtt5Client::receivedPublish(const PublishData& data, const IMessag void ProtocolMqtt5Client::receivedSubAck(const std::vector& /*reasoncodes*/) { - } void ProtocolMqtt5Client::receivedUnsubAck(const std::vector& /*reasoncodes*/) { - } void ProtocolMqtt5Client::receivedPingResp() @@ -552,12 +539,11 @@ void ProtocolMqtt5Client::receivedPingResp() void ProtocolMqtt5Client::receivedDisconnect(const DisconnectData& data) { - streamInfo << "Disconnect from mqtt5 broker. Reason Code: " << (unsigned int)data.reasoncode << " (" << data.reasonString << ")"; + streamInfo << "Disconnect from mqtt5 broker. Reason Code: " << static_cast(data.reasoncode) << " (" << data.reasonString << ")"; } void ProtocolMqtt5Client::receivedAuth(const AuthData& /*data*/) { - } void ProtocolMqtt5Client::closeConnection() @@ -574,8 +560,6 @@ void ProtocolMqtt5Client::setProtocolSessionData(const IProtocolSessionDataPtr& { } - - //--------------------------------------- // ProtocolMqtt5Factory //--------------------------------------- @@ -588,13 +572,10 @@ struct RegisterProtocolMqtt5ClientFactory } } g_registerProtocolMqtt5ClientFactory; - - - // IProtocolFactory IProtocolPtr ProtocolMqtt5ClientFactory::createProtocol(const Variant& data) { return std::make_shared(data); } -} // namespace finalmq +} // namespace finalmq diff --git a/src/protocols/mqtt5/Mqtt5Client.cpp b/src/protocols/mqtt5/Mqtt5Client.cpp index cf6d77a6..aa381df5 100644 --- a/src/protocols/mqtt5/Mqtt5Client.cpp +++ b/src/protocols/mqtt5/Mqtt5Client.cpp @@ -20,21 +20,18 @@ //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. - #include "finalmq/protocols/mqtt5/Mqtt5Client.h" + #include "finalmq/protocols/mqtt5/Mqtt5Properties.h" #include "finalmq/variant/VariantValues.h" - -namespace finalmq { - - +namespace finalmq +{ Mqtt5Client::Mqtt5Client() { m_protocol->setCallback(this); } - // IMqtt5Protocol void Mqtt5Client::setCallback(hybrid_ptr callback) { @@ -46,8 +43,6 @@ bool Mqtt5Client::receive(const IStreamConnectionPtr& connection, const SocketPt return m_protocol->receive(connection, socket, bytesToRead); } - - void Mqtt5Client::startConnection(const IStreamConnectionPtr& connection, const ConnectData& data) { m_keepAlive = data.keepAlive; @@ -79,7 +74,7 @@ void Mqtt5Client::startConnection(const IStreamConnectionPtr& connection, const } if (data.receiveMaximum != 65535) { - dataInternal.properties[Mqtt5PropertyId::ReceiveMaximum] = (std::uint32_t)data.receiveMaximum; + dataInternal.properties[Mqtt5PropertyId::ReceiveMaximum] = static_cast(data.receiveMaximum); } dataInternal.clientId = data.clientId; @@ -138,7 +133,6 @@ void Mqtt5Client::unsubscribe(const IStreamConnectionPtr& connection, const std: m_protocol->sendUnsubscribe(connection, dataInternal); } - void Mqtt5Client::endConnection(const IStreamConnectionPtr& connection, const DisconnectData& data) { Mqtt5DisconnectData dataInternal; @@ -154,7 +148,6 @@ void Mqtt5Client::endConnection(const IStreamConnectionPtr& connection, const Di m_protocol->sendDisconnect(connection, dataInternal); } - void Mqtt5Client::auth(const IStreamConnectionPtr& connection, const AuthData& data) { Mqtt5AuthData dataInternal; @@ -174,8 +167,6 @@ void Mqtt5Client::auth(const IStreamConnectionPtr& connection, const AuthData& d m_protocol->sendAuth(connection, dataInternal); } - - void Mqtt5Client::cycleTime(const IStreamConnectionPtr& connection) { if (m_timerPing.isExpired()) @@ -194,18 +185,17 @@ void Mqtt5Client::cycleTime(const IStreamConnectionPtr& connection) auto callback = m_callback.lock(); if (callback) { - endConnection(connection, { ReasonKeepAliveTimeout, "Keep Alive Timeout", ""}); + endConnection(connection, {ReasonKeepAliveTimeout, "Keep Alive Timeout", ""}); callback->closeConnection(); } } } - void Mqtt5Client::setReceiveActivity() { if (m_keepAlive > 0) { - m_timerReceiveActivity.setTimeout(m_keepAlive * 1500); // x1.5 + m_timerReceiveActivity.setTimeout(m_keepAlive * 1500); // x1.5 } else { @@ -213,7 +203,6 @@ void Mqtt5Client::setReceiveActivity() } } - // IMqtt5ProtocolCallback void Mqtt5Client::receivedConnect(const Mqtt5ConnectData& /*data*/) { @@ -224,7 +213,7 @@ void Mqtt5Client::receivedConnAck(const Mqtt5ConnAckData& data) { IMqtt5ClientCallback::ConnAckData dataDest; dataDest.sessionPresent = data.sessionPresent; - dataDest.reasoncode = data.reasoncode; + dataDest.reasoncode = static_cast(data.reasoncode); dataDest.serverKeepAlive = m_keepAlive; dataDest.sessionExpiryInterval = m_sessionExpiryInterval; std::unordered_map::const_iterator it; @@ -235,11 +224,11 @@ void Mqtt5Client::receivedConnAck(const Mqtt5ConnAckData& data) } if ((it = data.properties.find(Mqtt5PropertyId::ReceiveMaximum)) != data.properties.end()) { - dataDest.receiveMaximum = static_cast(it->second); + dataDest.receiveMaximum = static_cast(it->second); } if ((it = data.properties.find(Mqtt5PropertyId::MaximumQoS)) != data.properties.end()) { - dataDest.maximumQoS = static_cast(it->second); + dataDest.maximumQoS = static_cast(it->second); } if ((it = data.properties.find(Mqtt5PropertyId::RetainAvailable)) != data.properties.end()) { @@ -273,7 +262,7 @@ void Mqtt5Client::receivedConnAck(const Mqtt5ConnAckData& data) } if ((it = data.properties.find(Mqtt5PropertyId::ServerKeepAlive)) != data.properties.end()) { - m_keepAlive = static_cast(it->second); + m_keepAlive = static_cast(it->second); dataDest.serverKeepAlive = m_keepAlive; } if ((it = data.properties.find(Mqtt5PropertyId::ServerReference)) != data.properties.end()) @@ -309,7 +298,7 @@ void Mqtt5Client::receivedPublish(Mqtt5PublishData&& data, const IMessagePtr& me { IMqtt5ClientCallback::PublishData dataDest; - dataDest.qos = data.qos; + dataDest.qos = static_cast(data.qos); dataDest.retain = data.retain; dataDest.topic = data.topic; message->getAllMetainfo() = std::move(data.metainfo); @@ -404,7 +393,7 @@ void Mqtt5Client::receivedDisconnect(const Mqtt5DisconnectData& data) { IMqtt5ClientCallback::DisconnectData dataDest; - dataDest.reasoncode = data.reasoncode; + dataDest.reasoncode = static_cast(data.reasoncode); std::unordered_map::const_iterator it; if ((it = data.properties.find(Mqtt5PropertyId::ReasonString)) != data.properties.end()) { @@ -434,7 +423,7 @@ void Mqtt5Client::receivedAuth(const Mqtt5AuthData& data) { IMqtt5ClientCallback::AuthData dataDest; - dataDest.reasoncode = data.reasoncode; + dataDest.reasoncode = static_cast(data.reasoncode); std::unordered_map::const_iterator it; if ((it = data.properties.find(Mqtt5PropertyId::ReasonString)) != data.properties.end()) { @@ -470,8 +459,4 @@ void Mqtt5Client::receivedAuth(const Mqtt5AuthData& data) } } - - - - -} // namespace finalmq +} // namespace finalmq diff --git a/src/protocols/mqtt5/Mqtt5Protocol.cpp b/src/protocols/mqtt5/Mqtt5Protocol.cpp index 1ebe7a12..f3954ec5 100644 --- a/src/protocols/mqtt5/Mqtt5Protocol.cpp +++ b/src/protocols/mqtt5/Mqtt5Protocol.cpp @@ -20,27 +20,22 @@ //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. - #include "finalmq/protocols/mqtt5/Mqtt5Protocol.h" -#include "finalmq/streamconnection/Socket.h" -#include "finalmq/protocolsession/ProtocolMessage.h" -#include "finalmq/protocols/mqtt5/Mqtt5Serialization.h" #include "finalmq/protocols/mqtt5/Mqtt5Properties.h" +#include "finalmq/protocols/mqtt5/Mqtt5Serialization.h" +#include "finalmq/protocolsession/ProtocolMessage.h" +#include "finalmq/streamconnection/Socket.h" +namespace finalmq +{ +static const int HEADERSIZE = 1; - -namespace finalmq { - -static const ssize_t HEADERSIZE = 1; - - -#define HEADER_Command(header) static_cast(((header) >> 4) & 0x0f) -#define HEADER_Dup(header) (((header) >> 3) >> 0x01) -#define HEADER_QoS(header) (((header) >> 1) >> 0x03) -#define HEADER_Retain(header) (((header) >> 0) >> 0x01) -#define HEADER_SetDup(value) (((value) & 0x01) << 3) - +#define HEADER_Command(header) static_cast(((header) >> 4) & 0x0f) +//#define HEADER_Dup(header) (((header) >> 3) >> 0x01) +//#define HEADER_QoS(header) (((header) >> 1) >> 0x03) +//#define HEADER_Retain(header) (((header) >> 0) >> 0x01) +#define HEADER_SetDup(value) static_cast((((value)&0x01) << 3)) Mqtt5Protocol::Mqtt5Protocol() { @@ -48,32 +43,30 @@ Mqtt5Protocol::Mqtt5Protocol() m_messageIdsAllocated.push_back({}); } - bool Mqtt5Protocol::receive(const IStreamConnectionPtr& connection, const SocketPtr& socket, int bytesToRead) { bool ok = true; while ((bytesToRead > 0) && ok) { - switch (m_state) + switch(m_state) { - case State::WAITFORHEADER: - ok = receiveHeader(socket, bytesToRead); - break; - case State::WAITFORLENGTH: - ok = receiveRemainingSize(connection, socket, bytesToRead); - break; - case State::WAITFORPAYLOAD: - ok = receivePayload(connection, socket, bytesToRead); - break; - default: - assert(false); - break; + case State::WAITFORHEADER: + ok = receiveHeader(socket, bytesToRead); + break; + case State::WAITFORLENGTH: + ok = receiveRemainingSize(connection, socket, bytesToRead); + break; + case State::WAITFORPAYLOAD: + ok = receivePayload(connection, socket, bytesToRead); + break; + default: + assert(false); + break; } } return ok; } - bool Mqtt5Protocol::receiveHeader(const SocketPtr& socket, int& bytesToRead) { assert(bytesToRead >= 1); @@ -127,7 +120,6 @@ bool Mqtt5Protocol::receiveRemainingSize(const IStreamConnectionPtr& connection, return ok; } - void Mqtt5Protocol::setPayloadSize() { assert(m_state == State::WAITFORLENGTH); @@ -154,7 +146,6 @@ void Mqtt5Protocol::setPayloadSize() m_sizeCurrent = 0; } - bool Mqtt5Protocol::receivePayload(const IStreamConnectionPtr& connection, const SocketPtr& socket, int& bytesToRead) { assert(m_state == State::WAITFORPAYLOAD); @@ -189,8 +180,6 @@ bool Mqtt5Protocol::receivePayload(const IStreamConnectionPtr& connection, const return ok; } - - bool Mqtt5Protocol::handleAck(const IStreamConnectionPtr& connection, Mqtt5Command command, unsigned int packetId, unsigned int reasoncode) { bool ok = true; @@ -198,11 +187,7 @@ bool Mqtt5Protocol::handleAck(const IStreamConnectionPtr& connection, Mqtt5Comma if ((packetId != 0) && (packetId < m_messageIdsAllocated.size())) { MessageStatus& status = m_messageIdsAllocated[packetId]; - if (((status.status == MessageStatus::SENDSTAT_WAITPUBACK) && (command == Mqtt5Command::COMMAND_PUBACK)) || - ((status.status == MessageStatus::SENDSTAT_WAITPUBREC) && (command == Mqtt5Command::COMMAND_PUBREC)) || - ((status.status == MessageStatus::SENDSTAT_WAITPUBCOMP) && (command == Mqtt5Command::COMMAND_PUBCOMP)) || - ((status.status == MessageStatus::SENDSTAT_WAITSUBACK) && (command == Mqtt5Command::COMMAND_SUBACK)) || - ((status.status == MessageStatus::SENDSTAT_WAITUNSUBACK) && (command == Mqtt5Command::COMMAND_UNSUBACK))) + if (((status.status == MessageStatus::SENDSTAT_WAITPUBACK) && (command == Mqtt5Command::COMMAND_PUBACK)) || ((status.status == MessageStatus::SENDSTAT_WAITPUBREC) && (command == Mqtt5Command::COMMAND_PUBREC)) || ((status.status == MessageStatus::SENDSTAT_WAITPUBCOMP) && (command == Mqtt5Command::COMMAND_PUBCOMP)) || ((status.status == MessageStatus::SENDSTAT_WAITSUBACK) && (command == Mqtt5Command::COMMAND_SUBACK)) || ((status.status == MessageStatus::SENDSTAT_WAITUNSUBACK) && (command == Mqtt5Command::COMMAND_UNSUBACK))) { assert(status.iterator != m_messagesWaitAck.end()); m_messagesWaitAck.erase(status.iterator); @@ -218,7 +203,7 @@ bool Mqtt5Protocol::handleAck(const IStreamConnectionPtr& connection, Mqtt5Comma } else { - m_messageIdsFree.push_back(packetId); + m_messageIdsFree.push_back(static_cast(packetId)); } sendPendingMessages(connection); } @@ -253,9 +238,9 @@ bool Mqtt5Protocol::processPayload(const IStreamConnectionPtr& connection) bool ok = false; Mqtt5Command command = HEADER_Command(m_header); - switch (command) + switch(command) { - case Mqtt5Command::COMMAND_CONNECT: + case Mqtt5Command::COMMAND_CONNECT: { Mqtt5ConnectData data; ok = serialization.deserializeConnect(data); @@ -265,7 +250,7 @@ bool Mqtt5Protocol::processPayload(const IStreamConnectionPtr& connection) } } break; - case Mqtt5Command::COMMAND_CONNACK: + case Mqtt5Command::COMMAND_CONNACK: { Mqtt5ConnAckData data; ok = serialization.deserializeConnAck(data); @@ -276,7 +261,7 @@ bool Mqtt5Protocol::processPayload(const IStreamConnectionPtr& connection) std::unique_lock lock(m_mutex); if (it != data.properties.end()) { - m_sendMax = static_cast(it->second); + m_sendMax = static_cast(it->second); } else { @@ -293,7 +278,7 @@ bool Mqtt5Protocol::processPayload(const IStreamConnectionPtr& connection) } } break; - case Mqtt5Command::COMMAND_PUBLISH: + case Mqtt5Command::COMMAND_PUBLISH: { Mqtt5PublishData data; ok = serialization.deserializePublish(data); @@ -310,13 +295,13 @@ bool Mqtt5Protocol::processPayload(const IStreamConnectionPtr& connection) else if (data.qos == 2) { std::unique_lock lock(m_mutex); - if (data.dup && (m_setExactlyOne.find(data.packetId) != m_setExactlyOne.end())) + if (data.dup && (m_setExactlyOne.find(static_cast(data.packetId)) != m_setExactlyOne.end())) { execute = false; } else { - m_setExactlyOne.insert(data.packetId); + m_setExactlyOne.insert(static_cast(data.packetId)); } lock.unlock(); Mqtt5PubAckData dataAck; @@ -333,7 +318,7 @@ bool Mqtt5Protocol::processPayload(const IStreamConnectionPtr& connection) } } break; - case Mqtt5Command::COMMAND_PUBACK: + case Mqtt5Command::COMMAND_PUBACK: { Mqtt5PubAckData data; ok = serialization.deserializePubAck(data, Mqtt5Command::COMMAND_PUBACK); @@ -343,7 +328,7 @@ bool Mqtt5Protocol::processPayload(const IStreamConnectionPtr& connection) } } break; - case Mqtt5Command::COMMAND_PUBREC: + case Mqtt5Command::COMMAND_PUBREC: { Mqtt5PubAckData data; ok = serialization.deserializePubAck(data, Mqtt5Command::COMMAND_PUBREC); @@ -353,14 +338,14 @@ bool Mqtt5Protocol::processPayload(const IStreamConnectionPtr& connection) } } break; - case Mqtt5Command::COMMAND_PUBREL: + case Mqtt5Command::COMMAND_PUBREL: { Mqtt5PubAckData data; ok = serialization.deserializePubAck(data, Mqtt5Command::COMMAND_PUBREL); if (ok) { std::unique_lock lock(m_mutex); - m_setExactlyOne.erase(data.packetId); + m_setExactlyOne.erase(static_cast(data.packetId)); lock.unlock(); Mqtt5PubAckData dataAck; dataAck.packetId = data.packetId; @@ -369,7 +354,7 @@ bool Mqtt5Protocol::processPayload(const IStreamConnectionPtr& connection) } } break; - case Mqtt5Command::COMMAND_PUBCOMP: + case Mqtt5Command::COMMAND_PUBCOMP: { Mqtt5PubAckData data; ok = serialization.deserializePubAck(data, Mqtt5Command::COMMAND_PUBCOMP); @@ -379,7 +364,7 @@ bool Mqtt5Protocol::processPayload(const IStreamConnectionPtr& connection) } } break; - case Mqtt5Command::COMMAND_SUBSCRIBE: + case Mqtt5Command::COMMAND_SUBSCRIBE: { Mqtt5SubscribeData data; ok = serialization.deserializeSubscribe(data); @@ -396,7 +381,7 @@ bool Mqtt5Protocol::processPayload(const IStreamConnectionPtr& connection) } } break; - case Mqtt5Command::COMMAND_SUBACK: + case Mqtt5Command::COMMAND_SUBACK: { Mqtt5SubAckData data; ok = serialization.deserializeSubAck(data); @@ -415,7 +400,7 @@ bool Mqtt5Protocol::processPayload(const IStreamConnectionPtr& connection) } } break; - case Mqtt5Command::COMMAND_UNSUBSCRIBE: + case Mqtt5Command::COMMAND_UNSUBSCRIBE: { Mqtt5UnsubscribeData data; ok = serialization.deserializeUnsubscribe(data); @@ -430,9 +415,9 @@ bool Mqtt5Protocol::processPayload(const IStreamConnectionPtr& connection) { callback->receivedUnsubscribe(data); } - } + } break; - case Mqtt5Command::COMMAND_UNSUBACK: + case Mqtt5Command::COMMAND_UNSUBACK: { Mqtt5SubAckData data; ok = serialization.deserializeSubAck(data); @@ -451,21 +436,21 @@ bool Mqtt5Protocol::processPayload(const IStreamConnectionPtr& connection) } } break; - case Mqtt5Command::COMMAND_PINGREQ: - ok = true; - if (callback) - { - callback->receivedPingReq(); - } - break; - case Mqtt5Command::COMMAND_PINGRESP: - ok = true; - if (callback) - { - callback->receivedPingResp(); - } - break; - case Mqtt5Command::COMMAND_DISCONNECT: + case Mqtt5Command::COMMAND_PINGREQ: + ok = true; + if (callback) + { + callback->receivedPingReq(); + } + break; + case Mqtt5Command::COMMAND_PINGRESP: + ok = true; + if (callback) + { + callback->receivedPingResp(); + } + break; + case Mqtt5Command::COMMAND_DISCONNECT: { Mqtt5DisconnectData data; ok = serialization.deserializeDisconnect(data); @@ -475,7 +460,7 @@ bool Mqtt5Protocol::processPayload(const IStreamConnectionPtr& connection) } } break; - case Mqtt5Command::COMMAND_AUTH: + case Mqtt5Command::COMMAND_AUTH: { Mqtt5AuthData data; ok = serialization.deserializeAuth(data); @@ -485,8 +470,8 @@ bool Mqtt5Protocol::processPayload(const IStreamConnectionPtr& connection) } } break; - default: - break; + default: + break; } clearState(); @@ -494,8 +479,6 @@ bool Mqtt5Protocol::processPayload(const IStreamConnectionPtr& connection) return ok; } - - void Mqtt5Protocol::clearState() { m_sizeCurrent = 0; @@ -506,8 +489,6 @@ void Mqtt5Protocol::clearState() m_state = State::WAITFORHEADER; } - - // IMqtt5Protocol void Mqtt5Protocol::setCallback(hybrid_ptr callback) { @@ -553,7 +534,6 @@ void Mqtt5Protocol::sendConnAck(const IStreamConnectionPtr& connection, const Mq } } - void Mqtt5Protocol::resendMessages(const IStreamConnectionPtr& connection) { if (connection) @@ -579,7 +559,6 @@ void Mqtt5Protocol::resendMessages(const IStreamConnectionPtr& connection) } } - void Mqtt5Protocol::sendPendingMessages(const IStreamConnectionPtr& connection) { if (connection) @@ -603,7 +582,6 @@ void Mqtt5Protocol::sendPendingMessages(const IStreamConnectionPtr& connection) } } - static void putPacketIdIntoMessage(std::uint8_t* bufferPacketId, unsigned int packetId) { if (bufferPacketId) @@ -613,7 +591,6 @@ static void putPacketIdIntoMessage(std::uint8_t* bufferPacketId, unsigned int pa } } - void Mqtt5Protocol::prepareForSendWithPacketId(const IMessagePtr& message, std::uint8_t* bufferPacketId, unsigned qos, Mqtt5Command command, unsigned int packetId) { assert(bufferPacketId != nullptr); @@ -623,20 +600,20 @@ void Mqtt5Protocol::prepareForSendWithPacketId(const IMessagePtr& message, std:: MessageStatus::Status status = MessageStatus::SENDSTAT_NONE; if (qos == 1) { - switch (command) + switch(command) { - case Mqtt5Command::COMMAND_PUBLISH: - status = MessageStatus::SENDSTAT_WAITPUBACK; - break; - case Mqtt5Command::COMMAND_SUBSCRIBE: - status = MessageStatus::SENDSTAT_WAITSUBACK; - break; - case Mqtt5Command::COMMAND_UNSUBSCRIBE: - status = MessageStatus::SENDSTAT_WAITUNSUBACK; - break; - default: - assert(false); - break; + case Mqtt5Command::COMMAND_PUBLISH: + status = MessageStatus::SENDSTAT_WAITPUBACK; + break; + case Mqtt5Command::COMMAND_SUBSCRIBE: + status = MessageStatus::SENDSTAT_WAITSUBACK; + break; + case Mqtt5Command::COMMAND_UNSUBSCRIBE: + status = MessageStatus::SENDSTAT_WAITUNSUBACK; + break; + default: + assert(false); + break; } } else @@ -644,10 +621,9 @@ void Mqtt5Protocol::prepareForSendWithPacketId(const IMessagePtr& message, std:: assert(qos == 2); status = MessageStatus::SENDSTAT_WAITPUBREC; } - m_messageIdsAllocated[packetId] = { status, --m_messagesWaitAck.end() }; + m_messageIdsAllocated[packetId] = {status, --m_messagesWaitAck.end()}; } - unsigned int Mqtt5Protocol::getPacketId() { unsigned int packetId = 0; @@ -669,7 +645,6 @@ unsigned int Mqtt5Protocol::getPacketId() return packetId; } - bool Mqtt5Protocol::prepareForSend(const IMessagePtr& message, std::uint8_t* bufferPacketId, unsigned qos, Mqtt5Command command) { // qos == 0 -> these messages will not be treated with ack and flow control @@ -682,7 +657,7 @@ bool Mqtt5Protocol::prepareForSend(const IMessagePtr& message, std::uint8_t* buf // when pending messages are available -> put the message to the back to keep ordering if (!m_messagesPending.empty() || m_connecting) { - m_messagesPending.emplace_back(PendingMessage{ message, bufferPacketId, qos, command }); + m_messagesPending.emplace_back(PendingMessage{message, bufferPacketId, qos, command}); return false; } @@ -694,13 +669,11 @@ bool Mqtt5Protocol::prepareForSend(const IMessagePtr& message, std::uint8_t* buf } else { - m_messagesPending.emplace_back(PendingMessage{ message, bufferPacketId, qos, command }); + m_messagesPending.emplace_back(PendingMessage{message, bufferPacketId, qos, command}); return false; } } - - void Mqtt5Protocol::sendPublish(const IStreamConnectionPtr& connection, Mqtt5PublishData& data, const IMessagePtr& message) { unsigned int sizeAppPayload = static_cast(message->getTotalSendPayloadSize()); @@ -720,7 +693,6 @@ void Mqtt5Protocol::sendPublish(const IStreamConnectionPtr& connection, Mqtt5Pub } } - void Mqtt5Protocol::sendPubAck(const IStreamConnectionPtr& connection, Mqtt5Command command, const Mqtt5PubAckData& data) { unsigned int sizePropPayload = 0; @@ -737,8 +709,6 @@ void Mqtt5Protocol::sendPubAck(const IStreamConnectionPtr& connection, Mqtt5Comm } } - - void Mqtt5Protocol::sendPubAck(const IStreamConnectionPtr& connection, const Mqtt5PubAckData& data) { sendPubAck(connection, Mqtt5Command::COMMAND_PUBACK, data); @@ -769,9 +739,6 @@ void Mqtt5Protocol::sendPubComp(const IStreamConnectionPtr& connection, const Mq sendPubAck(connection, Mqtt5Command::COMMAND_PUBCOMP, data); } - - - void Mqtt5Protocol::sendSubscribe(const IStreamConnectionPtr& connection, const Mqtt5SubscribeData& data) { unsigned int sizePropPayload = 0; @@ -799,7 +766,7 @@ void Mqtt5Protocol::sendSubAck(const IStreamConnectionPtr& connection, Mqtt5Comm IMessagePtr message = std::make_shared(0); char* buffer = message->addSendHeader(sizeMessage); Mqtt5Serialization serialization(buffer, sizeMessage, 0); - serialization.serializeSubAck(data,command, sizePayload, sizePropPayload); + serialization.serializeSubAck(data, command, sizePayload, sizePropPayload); if (connection) { @@ -807,7 +774,6 @@ void Mqtt5Protocol::sendSubAck(const IStreamConnectionPtr& connection, Mqtt5Comm } } - void Mqtt5Protocol::sendSubAck(const IStreamConnectionPtr& connection, const Mqtt5SubAckData& data) { sendSubAck(connection, Mqtt5Command::COMMAND_SUBACK, data); @@ -897,6 +863,4 @@ void Mqtt5Protocol::sendAuth(const IStreamConnectionPtr& connection, const Mqtt5 } } - - -} // namespace finalmq +} // namespace finalmq diff --git a/src/protocols/mqtt5/Mqtt5Serialization.cpp b/src/protocols/mqtt5/Mqtt5Serialization.cpp index bbe87ac2..14e17cc4 100644 --- a/src/protocols/mqtt5/Mqtt5Serialization.cpp +++ b/src/protocols/mqtt5/Mqtt5Serialization.cpp @@ -20,48 +20,43 @@ //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. - #include "finalmq/protocols/mqtt5/Mqtt5Serialization.h" + #include "finalmq/protocols/mqtt5/Mqtt5Properties.h" #include "finalmq/variant/VariantValues.h" -namespace finalmq { - +namespace finalmq +{ static const ssize_t HEADERSIZE = 1; - -#define HEADER_Low4bits(header) (((header) >> 0) & 0x0f) -#define HEADER_Dup(header) (((header) >> 3) & 0x01) -#define HEADER_QoS(header) (((header) >> 1) & 0x03) -#define HEADER_Retain(header) (((header) >> 0) & 0x01) - -#define HEADER_SetCommand(value) ((static_cast(value) & 0x0f) << 4) -#define HEADER_SetLow4bits(value) (((value) & 0x0f) << 0) -#define HEADER_SetDup(value) (((value) & 0x01) << 3) -#define HEADER_SetQoS(value) (((value) & 0x03) << 1) -#define HEADER_SetRetain(value) (((value) & 0x01) << 0) - -#define CF_UserName(flags) (((flags) >> 7) & 0x01) -#define CF_Password(flags) (((flags) >> 6) & 0x01) -#define CF_WillRetain(flags) (((flags) >> 5) & 0x01) -#define CF_WillQoS(flags) (((flags) >> 3) & 0x03) -#define CF_WillFlag(flags) (((flags) >> 2) & 0x01) -#define CF_CleanStart(flags) (((flags) >> 1) & 0x01) - -#define CF_SetUserName(value) (((value) & 0x01) << 7) -#define CF_SetPassword(value) (((value) & 0x01) << 6) -#define CF_SetWillRetain(value) (((value) & 0x01) << 5) -#define CF_SetWillQoS(value) (((value) & 0x03) << 3) -#define CF_SetWillFlag(value) (((value) & 0x01) << 2) -#define CF_SetCleanStart(value) (((value) & 0x01) << 1) - +#define HEADER_Low4bits(header) (((header) >> 0) & 0x0f) +#define HEADER_Dup(header) (((header) >> 3) & 0x01) +#define HEADER_QoS(header) (((header) >> 1) & 0x03) +#define HEADER_Retain(header) (((header) >> 0) & 0x01) + +#define HEADER_SetCommand(value) ((static_cast(value) & 0x0f) << 4) +#define HEADER_SetLow4bits(value) (((value)&0x0f) << 0) +#define HEADER_SetDup(value) (((value)&0x01) << 3) +#define HEADER_SetQoS(value) (((value)&0x03) << 1) +#define HEADER_SetRetain(value) (((value)&0x01) << 0) + +#define CF_UserName(flags) (((flags) >> 7) & 0x01) +#define CF_Password(flags) (((flags) >> 6) & 0x01) +#define CF_WillRetain(flags) (((flags) >> 5) & 0x01) +#define CF_WillQoS(flags) (((flags) >> 3) & 0x03) +#define CF_WillFlag(flags) (((flags) >> 2) & 0x01) +#define CF_CleanStart(flags) (((flags) >> 1) & 0x01) + +#define CF_SetUserName(value) (((value)&0x01) << 7) +#define CF_SetPassword(value) (((value)&0x01) << 6) +#define CF_SetWillRetain(value) (((value)&0x01) << 5) +#define CF_SetWillQoS(value) (((value)&0x03) << 3) +#define CF_SetWillFlag(value) (((value)&0x01) << 2) +#define CF_SetCleanStart(value) (((value)&0x01) << 1) Mqtt5Serialization::Mqtt5Serialization(char* buffer, unsigned int sizeBuffer, unsigned int indexBuffer) - : m_buffer(reinterpret_cast(buffer)) - , m_sizeBuffer(sizeBuffer) - , m_indexBuffer(indexBuffer) + : m_buffer(reinterpret_cast(buffer)), m_sizeBuffer(sizeBuffer), m_indexBuffer(indexBuffer) { - } unsigned int Mqtt5Serialization::getReadIndex() const @@ -69,7 +64,6 @@ unsigned int Mqtt5Serialization::getReadIndex() const return m_indexBuffer; } - bool Mqtt5Serialization::deserializeConnect(Mqtt5ConnectData& data) { if (HEADER_Low4bits(m_buffer[0]) != 0) @@ -249,7 +243,6 @@ void Mqtt5Serialization::serializeConnect(const Mqtt5ConnectData& data, unsigned } connectFlags |= CF_SetCleanStart(data.cleanStart ? 1 : 0); - write1ByteNumber(connectFlags); // keep alive @@ -289,10 +282,8 @@ void Mqtt5Serialization::serializeConnect(const Mqtt5ConnectData& data, unsigned assert(m_indexBuffer == m_sizeBuffer); } - - -#define CAF_SessionPresent(flags) (((flags) & 0x01) >> 0) -#define CAF_SetSessionPresent(value) (((value) & 0x01) << 1) +#define CAF_SessionPresent(flags) (((flags)&0x01) >> 0) +#define CAF_SetSessionPresent(value) (((value)&0x01) << 1) bool Mqtt5Serialization::deserializeConnAck(Mqtt5ConnAckData& data) { @@ -528,18 +519,15 @@ void Mqtt5Serialization::serializePubAck(const Mqtt5PubAckData& data, Mqtt5Comma assert(m_indexBuffer == m_sizeBuffer); } +#define SO_RetainHandling(flags) (((flags) >> 4) & 0x03) +#define SO_RetainAsPublished(flags) (((flags) >> 3) & 0x01) +#define SO_NoLocal(flags) (((flags) >> 2) & 0x01) +#define SO_QoS(flags) (((flags) >> 0) & 0x03) - -#define SO_RetainHandling(flags) (((flags) >> 4) & 0x03) -#define SO_RetainAsPublished(flags) (((flags) >> 3) & 0x01) -#define SO_NoLocal(flags) (((flags) >> 2) & 0x01) -#define SO_QoS(flags) (((flags) >> 0) & 0x03) - -#define SO_SetRetainHandling(value) (((value) & 0x03) << 4) -#define SO_SetRetainAsPublished(value) (((value) & 0x01) << 3) -#define SO_SetNoLocal(value) (((value) & 0x01) << 2) -#define SO_SetQoS(value) (((value) & 0x03) << 0) - +#define SO_SetRetainHandling(value) (((value)&0x03) << 4) +#define SO_SetRetainAsPublished(value) (((value)&0x01) << 3) +#define SO_SetNoLocal(value) (((value)&0x01) << 2) +#define SO_SetQoS(value) (((value)&0x03) << 0) bool Mqtt5Serialization::deserializeSubscribe(Mqtt5SubscribeData& data) { @@ -593,7 +581,6 @@ bool Mqtt5Serialization::deserializeSubscribe(Mqtt5SubscribeData& data) return ok; } - unsigned int Mqtt5Serialization::sizeSubscribe(const Mqtt5SubscribeData& data, unsigned int& sizePropPayload) { unsigned int size = 0; @@ -617,7 +604,6 @@ unsigned int Mqtt5Serialization::sizeSubscribe(const Mqtt5SubscribeData& data, u return size; } - void Mqtt5Serialization::serializeSubscribe(const Mqtt5SubscribeData& data, unsigned int sizePayload, unsigned int sizePropPayload, std::uint8_t*& bufferPacketId) { unsigned int header = 0; @@ -636,7 +622,7 @@ void Mqtt5Serialization::serializeSubscribe(const Mqtt5SubscribeData& data, unsi // at least one subscription must be available assert(!data.subscriptions.empty()); - for (const auto & entry: data.subscriptions) + for (const auto& entry : data.subscriptions) { writeString(entry.topic); unsigned int option = 0; @@ -650,8 +636,6 @@ void Mqtt5Serialization::serializeSubscribe(const Mqtt5SubscribeData& data, unsi assert(m_indexBuffer == m_sizeBuffer); } - - bool Mqtt5Serialization::deserializeSubAck(Mqtt5SubAckData& data) { if (HEADER_Low4bits(m_buffer[0]) != 0x00) @@ -687,7 +671,7 @@ bool Mqtt5Serialization::deserializeSubAck(Mqtt5SubAckData& data) { return false; } - data.reasoncodes.push_back(reasoncode); + data.reasoncodes.push_back(static_cast(reasoncode)); } return ok; @@ -699,7 +683,7 @@ unsigned int Mqtt5Serialization::sizeSubAck(const Mqtt5SubAckData& data, unsigne // packet identifier size += 2; - + // properties size += sizeProperties(data.properties, data.metainfo, sizePropPayload); @@ -726,7 +710,7 @@ void Mqtt5Serialization::serializeSubAck(const Mqtt5SubAckData& data, Mqtt5Comma // at least one ack must be available assert(!data.reasoncodes.empty()); - for (const auto reasonCode: data.reasoncodes) + for (const auto reasonCode : data.reasoncodes) { write1ByteNumber(reasonCode); } @@ -734,8 +718,6 @@ void Mqtt5Serialization::serializeSubAck(const Mqtt5SubAckData& data, Mqtt5Comma assert(m_indexBuffer == m_sizeBuffer); } - - bool Mqtt5Serialization::deserializeUnsubscribe(Mqtt5UnsubscribeData& data) { if (HEADER_Low4bits(m_buffer[0]) != 0x02) @@ -777,7 +759,6 @@ bool Mqtt5Serialization::deserializeUnsubscribe(Mqtt5UnsubscribeData& data) return ok; } - unsigned int Mqtt5Serialization::sizeUnsubscribe(const Mqtt5UnsubscribeData& data, unsigned int& sizePropPayload) { unsigned int size = 0; @@ -791,7 +772,7 @@ unsigned int Mqtt5Serialization::sizeUnsubscribe(const Mqtt5UnsubscribeData& dat // at least one unsubscription must be available assert(!data.topics.empty()); - for (const auto & topic: data.topics) + for (const auto& topic : data.topics) { size += sizeString(topic); } @@ -817,7 +798,7 @@ void Mqtt5Serialization::serializeUnsubscribe(const Mqtt5UnsubscribeData& data, // at least one unsubscription must be available assert(!data.topics.empty()); - for (const auto &topic: data.topics) + for (const auto& topic : data.topics) { writeString(topic); } @@ -825,7 +806,6 @@ void Mqtt5Serialization::serializeUnsubscribe(const Mqtt5UnsubscribeData& data, assert(m_indexBuffer == m_sizeBuffer); } - void Mqtt5Serialization::serializePingReq() { unsigned int header = HEADER_SetCommand(Mqtt5Command::COMMAND_PINGREQ); @@ -842,8 +822,6 @@ void Mqtt5Serialization::serializePingResp() assert(m_indexBuffer == m_sizeBuffer); } - - bool Mqtt5Serialization::deserializeDisconnect(Mqtt5DisconnectData& data) { if (HEADER_Low4bits(m_buffer[0]) != 0x00) @@ -970,15 +948,12 @@ void Mqtt5Serialization::serializeAuth(const Mqtt5AuthData& data, unsigned int s assert(m_indexBuffer == m_sizeBuffer); } - bool Mqtt5Serialization::doesFit(int size) const { bool ok = (m_indexBuffer + size <= m_sizeBuffer); return ok; } - - bool Mqtt5Serialization::read1ByteNumber(unsigned int& number) { if (doesFit(1)) @@ -1045,13 +1020,13 @@ bool Mqtt5Serialization::read4ByteNumber(unsigned int& number) void Mqtt5Serialization::write4ByteNumber(unsigned int number) { assert(m_indexBuffer + 4 <= m_sizeBuffer); - m_buffer[m_indexBuffer] = (number >> 24) & 0xff; + m_buffer[m_indexBuffer] = static_cast((number >> 24) & 0xff); ++m_indexBuffer; - m_buffer[m_indexBuffer] = (number >> 16) & 0xff; + m_buffer[m_indexBuffer] = static_cast((number >> 16) & 0xff); ++m_indexBuffer; - m_buffer[m_indexBuffer] = (number >> 8) & 0xff; + m_buffer[m_indexBuffer] = static_cast((number >> 8) & 0xff); ++m_indexBuffer; - m_buffer[m_indexBuffer] = (number >> 0) & 0xff; + m_buffer[m_indexBuffer] = static_cast((number >> 0) & 0xff); ++m_indexBuffer; } @@ -1146,7 +1121,6 @@ void Mqtt5Serialization::writeStringPair(const std::string& key, const std::stri writeString(value); } - bool Mqtt5Serialization::readBinary(Bytes& value) { unsigned int size = 0; @@ -1178,10 +1152,6 @@ void Mqtt5Serialization::writeBinary(const Bytes& value) m_indexBuffer += size; } - - - - bool Mqtt5Serialization::readProperties(std::unordered_map& properties, std::unordered_map& metainfo) { if (!doesFit(1)) @@ -1216,12 +1186,12 @@ bool Mqtt5Serialization::readProperties(std::unordered_map* arr = property; - if (arr == nullptr) + unsigned int value = 0; + ok = readVarByteNumber(value); + if (ok) { - property = std::vector(); + Variant& property = properties[propertyId]; + std::vector* arr = property; + if (arr == nullptr) + { + property = std::vector(); + } + arr = property; + assert(arr != nullptr); + arr->push_back(value); } - arr = property; - assert(arr != nullptr); - arr->push_back(value); } - } - break; - default: - assert(false); - ok = false; break; + default: + assert(false); + ok = false; + break; } if (m_indexBuffer == indexEndProperties) { @@ -1339,39 +1309,39 @@ unsigned int Mqtt5Serialization::sizeProperties(const std::unordered_map(id)); assert(propertyId != Mqtt5PropertyId::Invalid); Mqtt5Type type = propertyId.getPropertyType(); - switch (type) + switch(type) { - case Mqtt5Type::TypeNone: - assert(false); - break; - case Mqtt5Type::TypeByte: - sizePropertyPayload += sizeVarByteNumber(id); - sizePropertyPayload += 1; - break; - case Mqtt5Type::TypeTwoByteInteger: - sizePropertyPayload += sizeVarByteNumber(id); - sizePropertyPayload += 2; - break; - case Mqtt5Type::TypeFourByteInteger: - sizePropertyPayload += sizeVarByteNumber(id); - sizePropertyPayload += 4; - break; - case Mqtt5Type::TypeVariableByteInteger: - sizePropertyPayload += sizeVarByteNumber(id); - sizePropertyPayload += sizeVarByteNumber(value); - break; - case Mqtt5Type::TypeUTF8String: - sizePropertyPayload += sizeVarByteNumber(id); - sizePropertyPayload += sizeString(value); - break; - case Mqtt5Type::TypeUTF8StringPair: - assert(false); - break; - case Mqtt5Type::TypeBinaryData: - sizePropertyPayload += sizeVarByteNumber(id); - sizePropertyPayload += sizeBinary(value); - break; - case Mqtt5Type::TypeArrayVariableByteInteger: + case Mqtt5Type::TypeNone: + assert(false); + break; + case Mqtt5Type::TypeByte: + sizePropertyPayload += sizeVarByteNumber(id); + sizePropertyPayload += 1; + break; + case Mqtt5Type::TypeTwoByteInteger: + sizePropertyPayload += sizeVarByteNumber(id); + sizePropertyPayload += 2; + break; + case Mqtt5Type::TypeFourByteInteger: + sizePropertyPayload += sizeVarByteNumber(id); + sizePropertyPayload += 4; + break; + case Mqtt5Type::TypeVariableByteInteger: + sizePropertyPayload += sizeVarByteNumber(id); + sizePropertyPayload += sizeVarByteNumber(value); + break; + case Mqtt5Type::TypeUTF8String: + sizePropertyPayload += sizeVarByteNumber(id); + sizePropertyPayload += sizeString(value); + break; + case Mqtt5Type::TypeUTF8StringPair: + assert(false); + break; + case Mqtt5Type::TypeBinaryData: + sizePropertyPayload += sizeVarByteNumber(id); + sizePropertyPayload += sizeBinary(value); + break; + case Mqtt5Type::TypeArrayVariableByteInteger: { const std::vector* arr = value; if (arr != nullptr) @@ -1384,9 +1354,9 @@ unsigned int Mqtt5Serialization::sizeProperties(const std::unordered_map(id)); assert(propertyId != Mqtt5PropertyId::Invalid); Mqtt5Type type = propertyId.getPropertyType(); - switch (type) + switch(type) { - case Mqtt5Type::TypeNone: - assert(false); - break; - case Mqtt5Type::TypeByte: - writeVarByteNumber(id); - write1ByteNumber(value); - break; - case Mqtt5Type::TypeTwoByteInteger: - writeVarByteNumber(id); - write2ByteNumber(value); - break; - case Mqtt5Type::TypeFourByteInteger: - writeVarByteNumber(id); - write4ByteNumber(value); - break; - case Mqtt5Type::TypeVariableByteInteger: - writeVarByteNumber(id); - writeVarByteNumber(value); - break; - case Mqtt5Type::TypeUTF8String: - writeVarByteNumber(id); - writeString(value); - break; - case Mqtt5Type::TypeUTF8StringPair: - assert(false); - break; - case Mqtt5Type::TypeBinaryData: - writeVarByteNumber(id); - writeBinary(value); - break; - case Mqtt5Type::TypeArrayVariableByteInteger: + case Mqtt5Type::TypeNone: + assert(false); + break; + case Mqtt5Type::TypeByte: + writeVarByteNumber(id); + write1ByteNumber(value); + break; + case Mqtt5Type::TypeTwoByteInteger: + writeVarByteNumber(id); + write2ByteNumber(value); + break; + case Mqtt5Type::TypeFourByteInteger: + writeVarByteNumber(id); + write4ByteNumber(value); + break; + case Mqtt5Type::TypeVariableByteInteger: + writeVarByteNumber(id); + writeVarByteNumber(value); + break; + case Mqtt5Type::TypeUTF8String: + writeVarByteNumber(id); + writeString(value); + break; + case Mqtt5Type::TypeUTF8StringPair: + assert(false); + break; + case Mqtt5Type::TypeBinaryData: + writeVarByteNumber(id); + writeBinary(value); + break; + case Mqtt5Type::TypeArrayVariableByteInteger: { const std::vector* arr = value; if (arr != nullptr) @@ -1457,9 +1427,9 @@ void Mqtt5Serialization::writeProperties(const std::unordered_map& callback) { @@ -130,10 +124,6 @@ IProtocol::FuncCreateMessage ProtocolDelimiter::getMessageFactory() const }; } - - - - void ProtocolDelimiter::sendMessage(IMessagePtr message) { if (message == nullptr) @@ -155,13 +145,10 @@ void ProtocolDelimiter::sendMessage(IMessagePtr message) m_connection->sendMessage(message); } - void ProtocolDelimiter::moveOldProtocolState(IProtocol& /*protocolOld*/) { - } - bool ProtocolDelimiter::received(const IStreamConnectionPtr& /*connection*/, const SocketPtr& socket, int bytesToRead) { std::shared_ptr receiveBufferOld = m_receiveBuffer; @@ -181,7 +168,7 @@ bool ProtocolDelimiter::received(const IStreamConnectionPtr& /*connection*/, con { memcpy(const_cast(m_receiveBuffer->data()), const_cast(receiveBufferOld->data() + indexStart), sizeDelimiterPrefix); } - int res = socket->receive(const_cast(m_receiveBuffer->data()) + sizeDelimiterPrefix, static_cast(bytesToRead)); + int res = socket->receive(const_cast(m_receiveBuffer->data()) + sizeDelimiterPrefix, bytesToRead); if (res > 0) { auto callback = m_callback.lock(); @@ -228,8 +215,8 @@ bool ProtocolDelimiter::received(const IStreamConnectionPtr& /*connection*/, con const auto& receiveBufferStore = m_receiveBuffers[n]; ssize_t sizeCopy = receiveBufferStore.indexEndMessage - receiveBufferStore.indexStartMessage; memcpy(const_cast(receiveBufferHelper->data()) + offset, - const_cast(receiveBufferStore.receiveBuffer->data()) + receiveBufferStore.indexStartMessage, - sizeCopy); + const_cast(receiveBufferStore.receiveBuffer->data()) + receiveBufferStore.indexStartMessage, + sizeCopy); offset += sizeCopy; } memcpy(const_cast(receiveBufferHelper->data()) + offset, const_cast(m_receiveBuffer->data()), sizeLast); @@ -257,7 +244,7 @@ bool ProtocolDelimiter::received(const IStreamConnectionPtr& /*connection*/, con { if (m_indexStartMessage < offsetEnd) { - m_receiveBuffers.emplace_back(ReceiveBufferStore{ m_receiveBuffer, m_indexStartMessage, offsetEnd }); + m_receiveBuffers.emplace_back(ReceiveBufferStore{m_receiveBuffer, m_indexStartMessage, offsetEnd}); m_receiveBuffersTotal += offsetEnd - m_indexStartMessage; m_indexStartMessage = offsetEnd; } @@ -266,8 +253,6 @@ bool ProtocolDelimiter::received(const IStreamConnectionPtr& /*connection*/, con return (res > 0); } - - hybrid_ptr ProtocolDelimiter::connected(const IStreamConnectionPtr& /*connection*/) { auto callback = m_callback.lock(); @@ -287,7 +272,6 @@ void ProtocolDelimiter::disconnected(const IStreamConnectionPtr& /*connection*/) } } - IMessagePtr ProtocolDelimiter::pollReply(std::deque&& /*messages*/) { return {}; @@ -295,12 +279,10 @@ IMessagePtr ProtocolDelimiter::pollReply(std::deque&& /*messages*/) void ProtocolDelimiter::subscribe(const std::vector& /*subscribtions*/) { - } void ProtocolDelimiter::cycleTime() { - } IProtocolSessionDataPtr ProtocolDelimiter::createProtocolSessionData() @@ -312,4 +294,4 @@ void ProtocolDelimiter::setProtocolSessionData(const IProtocolSessionDataPtr& /* { } -} // namespace finalmq +} // namespace finalmq diff --git a/src/protocolsession/ProtocolMessage.cpp b/src/protocolsession/ProtocolMessage.cpp index 3cc1d7e3..5f75b2e4 100644 --- a/src/protocolsession/ProtocolMessage.cpp +++ b/src/protocolsession/ProtocolMessage.cpp @@ -20,23 +20,18 @@ //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. - #include "finalmq/protocolsession/ProtocolMessage.h" - -namespace finalmq { - +namespace finalmq +{ //--------------------------------------- // ProtocolMessage //--------------------------------------- const std::string ProtocolMessage::FMQ_PROTOCOLDATA = "fmq_protocoldata"; - ProtocolMessage::ProtocolMessage(std::uint32_t protocolId, ssize_t sizeHeader, ssize_t sizeTrailer) - : m_sizeHeader(sizeHeader) - , m_sizeTrailer(sizeTrailer) - , m_protocolId(protocolId) + : m_sizeHeader(sizeHeader), m_sizeTrailer(sizeTrailer), m_protocolId(protocolId) { m_itSendBufferRefsPayloadBegin = m_sendBufferRefs.end(); } @@ -171,7 +166,6 @@ ssize_t ProtocolMessage::getRemainingSize() const return 0; } - // metadata const ProtocolMessage::Metainfo& ProtocolMessage::getAllMetainfo() const { @@ -198,7 +192,6 @@ const std::string* ProtocolMessage::getMetainfo(const std::string& key) const return const_cast(this)->getMetainfo(key); } - std::string* ProtocolMessage::getMetainfo(const std::string& key) { auto it = m_metainfo.find(key); @@ -209,7 +202,6 @@ std::string* ProtocolMessage::getMetainfo(const std::string& key) return nullptr; } - // controlData Variant* ProtocolMessage::getControlDataIfAvailable() @@ -221,7 +213,6 @@ Variant* ProtocolMessage::getControlDataIfAvailable() return &m_controlData; } - Variant& ProtocolMessage::getControlData() { if (m_controlData.getType() != VARTYPE_STRUCT) @@ -240,7 +231,6 @@ const Variant& ProtocolMessage::getControlData() const return m_controlData; } - // echoData Variant& ProtocolMessage::getEchoData() { @@ -260,8 +250,6 @@ const Variant& ProtocolMessage::getEchoData() const return m_echoData; } - - // for send void ProtocolMessage::addSendPayload(const std::string& payload, ssize_t reserve) { @@ -285,15 +273,14 @@ void ProtocolMessage::downsizeLastSendPayload(ssize_t newSize) // for receive BufferRef ProtocolMessage::getReceiveHeader() const { - return { m_receiveBufferRef.first, m_sizeHeader }; + return {m_receiveBufferRef.first, m_sizeHeader}; } BufferRef ProtocolMessage::getReceivePayload() const { - return { const_cast(m_receiveBufferRef.first + m_sizeHeader), m_receiveBufferRef.second - m_sizeHeader }; + return {m_receiveBufferRef.first + m_sizeHeader, m_receiveBufferRef.second - m_sizeHeader}; } - char* ProtocolMessage::resizeReceiveBuffer(ssize_t size) { if (size < 0) @@ -310,7 +297,7 @@ char* ProtocolMessage::resizeReceiveBuffer(ssize_t size) m_receiveBufferRef.first = const_cast(m_receiveBuffer->data()); } m_receiveBufferRef.second = size; - return const_cast(m_receiveBufferRef.first); + return m_receiveBufferRef.first; } void ProtocolMessage::setReceiveBuffer(const std::shared_ptr& receiveBuffer, ssize_t offset, ssize_t size) @@ -327,7 +314,6 @@ void ProtocolMessage::setHeaderSize(ssize_t sizeHeader) m_sizeHeader = sizeHeader; } - // for the framework const std::list& ProtocolMessage::getAllSendBuffers() const { @@ -369,7 +355,6 @@ std::list& ProtocolMessage::getSendPayloadBuffers() return m_payloadBuffers; } - // for the protocol to add a header void ProtocolMessage::addSendHeader(const std::string& buffer) { @@ -416,7 +401,7 @@ void ProtocolMessage::downsizeLastSendHeader(ssize_t newSize) void ProtocolMessage::prepareMessageToSend() { m_preparedToSend = true; - for (auto it = m_sendBufferRefs.begin(); it != m_sendBufferRefs.end(); ) + for (auto it = m_sendBufferRefs.begin(); it != m_sendBufferRefs.end();) { if (it->second == 0) { @@ -455,4 +440,4 @@ IMessagePtr ProtocolMessage::getMessage(std::uint32_t protocolId) const return nullptr; } -} // namespace finalmq +} // namespace finalmq diff --git a/src/remoteentity/FileTransferReply.cpp b/src/remoteentity/FileTransferReply.cpp index f9d32dfc..85125948 100644 --- a/src/remoteentity/FileTransferReply.cpp +++ b/src/remoteentity/FileTransferReply.cpp @@ -21,18 +21,16 @@ //SOFTWARE. #include "finalmq/remoteentity/FileTransferReply.h" -#include "finalmq/remoteentity/RemoteEntity.h" -#include "finalmq/helpers/Executor.h" -#include "finalmq/variant/VariantValueStruct.h" -#include "finalmq/variant/VariantValues.h" #include +#include "finalmq/helpers/Executor.h" +#include "finalmq/remoteentity/RemoteEntity.h" +#include "finalmq/variant/VariantValueStruct.h" +#include "finalmq/variant/VariantValues.h" -namespace finalmq { - - - +namespace finalmq +{ bool FileTransferReply::replyFile(const RequestContextPtr& requestContext, const std::string& filename, IMessage::Metainfo* metainfo) { bool handeled = false; @@ -47,12 +45,12 @@ bool FileTransferReply::replyFile(const RequestContextPtr& requestContext, const if (requestContext->doesSupportFileTransfer()) { - Variant controlData = VariantStruct{ {"filetransfer", filename} }; + Variant controlData = VariantStruct{{"filetransfer", filename}}; requestContext->reply(controlData); } else { - int sizeFile = statdata.st_size; + int sizeFile = static_cast(statdata.st_size); std::shared_ptr mi; if (metainfo) @@ -118,5 +116,4 @@ bool FileTransferReply::replyFile(const RequestContextPtr& requestContext, const return handeled; } - -} // namespace finalmq +} // namespace finalmq diff --git a/src/remoteentity/RemoteEntity.cpp b/src/remoteentity/RemoteEntity.cpp index 9e242bd6..9541ae53 100644 --- a/src/remoteentity/RemoteEntity.cpp +++ b/src/remoteentity/RemoteEntity.cpp @@ -21,28 +21,27 @@ //SOFTWARE. #include "finalmq/remoteentity/RemoteEntity.h" -#include "finalmq/remoteentity/RemoteEntityContainer.h" -#include "finalmq/protocolsession/ProtocolMessage.h" -#include "finalmq/helpers/ModulenameFinalmq.h" -#include "finalmq/helpers/Utils.h" #include +#include "finalmq/helpers/ModulenameFinalmq.h" +#include "finalmq/helpers/Utils.h" +#include "finalmq/protocolsession/ProtocolMessage.h" +#include "finalmq/remoteentity/RemoteEntityContainer.h" +#include "finalmq/serializestruct/StructBase.h" -using finalmq::MsgMode; -using finalmq::Status; -using finalmq::Header; -using finalmq::ConnectEntity; -using finalmq::ConnectEntityReply; -using finalmq::DisconnectEntity; - - -namespace finalmq { +//using finalmq::ConnectEntity; +//using finalmq::ConnectEntityReply; +//using finalmq::DisconnectEntity; +//using finalmq::Header; +//using finalmq::MsgMode; +//using finalmq::Status; +namespace finalmq +{ static const std::string FMQ_METHOD = "fmq_method"; static const std::string EMPTY_PATH; - PeerEvent::PeerEvent() { } @@ -58,7 +57,7 @@ PeerEvent::operator Enum&() { return m_value; } -const PeerEvent& PeerEvent::operator =(Enum en) +const PeerEvent& PeerEvent::operator=(Enum en) { m_value = en; return *this; @@ -76,40 +75,37 @@ void PeerEvent::fromString(const std::string& name) m_value = static_cast(_enumInfo.getMetaEnum().getValueByName(name)); } const EnumInfo PeerEvent::_enumInfo = { - "PeerEvent", "", {}, { + "PeerEvent", + "", + {}, + { {"PEER_CONNECTED", 0, "", "connected"}, {"PEER_DISCONNECTED", 1, "", "disconnected"}, - } -}; - - + }}; /////////////////////////////////// - PeerManager::PeerManager() { } - std::vector PeerManager::getAllPeers() const { std::unique_lock lock(m_mutex); std::vector peers; peers.reserve(m_peers.size()); - std::for_each(m_peers.begin(), m_peers.end(), [&peers] (const auto& entry) { + std::for_each(m_peers.begin(), m_peers.end(), [&peers](const auto& entry) { peers.push_back(entry.first); }); return peers; } - std::vector PeerManager::getAllPeersWithSession(IProtocolSessionPtr session) const { std::unique_lock lock(m_mutex); std::vector peers; peers.reserve(m_peers.size()); - std::for_each(m_peers.begin(), m_peers.end(), [&peers, &session] (const auto& entry) { + std::for_each(m_peers.begin(), m_peers.end(), [&peers, &session](const auto& entry) { if (entry.second->session.getSession() == session) { peers.push_back(entry.first); @@ -132,7 +128,6 @@ std::vector PeerManager::getAllPeersWithVirtualSession(IProtocolSessionP return peers; } - void PeerManager::updatePeer(PeerId peerId, const std::string& virtualSessionId, EntityId entityId, const std::string& entityName) { std::unique_lock lock(m_mutex); @@ -172,7 +167,6 @@ void PeerManager::updatePeer(PeerId peerId, const std::string& virtualSessionId, } } - bool PeerManager::removePeer(PeerId peerId, bool& incoming) { bool found = false; @@ -201,7 +195,6 @@ bool PeerManager::removePeer(PeerId peerId, bool& incoming) return found; } - void PeerManager::removePeerFromSessionEntityToPeerId(std::int64_t sessionId, const std::string& virtualSessionId, EntityId entityId, const std::string& entityName) { // mutex already locked @@ -243,8 +236,6 @@ PeerId PeerManager::getPeerId(std::int64_t sessionId, const std::string& virtual return getPeerIdIntern(sessionId, virtualSessionId, entityId, entityName); } - - PeerId PeerManager::getPeerIdIntern(std::int64_t sessionId, const std::string& virtualSessionId, EntityId entityId, const std::string& entityName) const { // mutex already locked @@ -278,8 +269,6 @@ PeerId PeerManager::getPeerIdIntern(std::int64_t sessionId, const std::string& v return PEERID_INVALID; } - - std::shared_ptr PeerManager::getPeer(const PeerId& peerId) const { auto it = m_peers.find(peerId); @@ -290,8 +279,6 @@ std::shared_ptr PeerManager::getPeer(const PeerId& peerId) co return {}; } - - PeerManager::ReadyToSend PeerManager::getRequestHeader(const PeerId& peerId, const std::string& path, const StructBase& structBase, CorrelationId correlationId, Header& header, IProtocolSessionPtr& session, std::string& virtualSessionId) { ReadyToSend readyToSend = RTS_PEER_NOT_AVAILABLE; @@ -310,7 +297,7 @@ PeerManager::ReadyToSend PeerManager::getRequestHeader(const PeerId& peerId, con typeName = &structBase.getStructInfo().getTypeName(); } assert(typeName); - header = { peer->entityId, (peer->entityId == ENTITYID_INVALID) ? peer->entityName : std::string(), m_entityId, MsgMode::MSG_REQUEST, Status::STATUS_OK, path, *typeName, correlationId, {} }; + header = {peer->entityId, (peer->entityId == ENTITYID_INVALID) ? peer->entityName : std::string(), m_entityId, MsgMode::MSG_REQUEST, Status::STATUS_OK, path, *typeName, correlationId, {}}; readyToSend = RTS_READY; } else @@ -322,8 +309,6 @@ PeerManager::ReadyToSend PeerManager::getRequestHeader(const PeerId& peerId, con return readyToSend; } - - std::string PeerManager::getEntityName(const PeerId& peerId) { std::string entityName; @@ -337,10 +322,9 @@ std::string PeerManager::getEntityName(const PeerId& peerId) return entityName; } - PeerId PeerManager::addPeer(const SessionInfo& session, const std::string& virtualSessionId, EntityId entityId, const std::string& entityName, bool incoming, bool& added, const std::function& funcBeforeFirePeerEvent) { -// assert(entityId != ENTITYID_INVALID || !entityName.empty()); + // assert(entityId != ENTITYID_INVALID || !entityName.empty()); added = false; std::unique_lock lock(m_mutex); @@ -397,7 +381,6 @@ PeerId PeerManager::addPeer(const SessionInfo& session, const std::string& virtu return peerId; } - PeerId PeerManager::addPeer() { std::unique_lock lock(m_mutex); @@ -419,7 +402,6 @@ PeerId PeerManager::addPeer() return peerId; } - std::deque PeerManager::connect(PeerId peerId, const SessionInfo& session, EntityId entityId, const std::string& entityName) { std::deque requests; @@ -447,15 +429,11 @@ std::deque PeerManager::connect(PeerId peerId, const Sessi return requests; } - - void PeerManager::setEntityId(EntityId entityId) { m_entityId = entityId; } - - void PeerManager::setPeerEvent(const std::shared_ptr& funcPeerEvent) { std::unique_lock lock(m_mutex); @@ -474,22 +452,15 @@ const SessionInfo& PeerManager::getSession(PeerId peerId) const return sessionEmpty; } - - - - ////////////////////////////////////////////// - std::atomic RemoteEntity::m_entityIdNext{0}; - RemoteEntity::RemoteEntity() - : m_entityId(++m_entityIdNext) - , m_peerManager(std::make_shared()) + : m_entityId(++m_entityIdNext), m_peerManager(std::make_shared()) { m_peerManager->setEntityId(m_entityId); - registerCommand([this] (const RequestContextPtr& requestContext, const std::shared_ptr& request) { + registerCommand([this](const RequestContextPtr& requestContext, const std::shared_ptr& request) { assert(request); bool added{}; const std::string& virtualSessionId = requestContext->getVirtualSessionId(); @@ -502,7 +473,7 @@ RemoteEntity::RemoteEntity() { bool registered = false; ownEntityName = ec->getEntityName(m_entityId, registered); - assert(registered); // entity is already registered, otherwise the request call could not be received + assert(registered); // entity is already registered, otherwise the request call could not be received requestContext->reply(ConnectEntityReply(m_entityId, ownEntityName)); } else @@ -511,19 +482,17 @@ RemoteEntity::RemoteEntity() } }); }); - registerCommand([this] (const RequestContextPtr& requestContext, const std::shared_ptr& /*request*/) { + registerCommand([this](const RequestContextPtr& requestContext, const std::shared_ptr& /*request*/) { PeerId peerId = requestContext->peerId(); removePeer(peerId, Status::STATUS_PEER_DISCONNECTED); }); } - RemoteEntity::~RemoteEntity() { deinit(); } - // IRemoteEntity CorrelationId RemoteEntity::getNextCorrelationId() const @@ -532,8 +501,6 @@ CorrelationId RemoteEntity::getNextCorrelationId() const return id; } - - void RemoteEntity::sendEvent(const PeerId& peerId, const StructBase& structBase) { sendRequest(peerId, EMPTY_PATH, structBase, CORRELATIONID_NONE); @@ -562,7 +529,6 @@ void RemoteEntity::sendEventToAllPeers(const std::string& path, const StructBase } } - CorrelationId RemoteEntity::sendRequest(const PeerId& peerId, const StructBase& structBase, FuncReply funcReply) { CorrelationId correlationId = getNextCorrelationId(); @@ -573,7 +539,6 @@ CorrelationId RemoteEntity::sendRequest(const PeerId& peerId, const StructBase& return correlationId; } - CorrelationId RemoteEntity::sendRequest(const PeerId& peerId, const std::string& path, const StructBase& structBase, FuncReply funcReply) { CorrelationId correlationId = getNextCorrelationId(); @@ -584,7 +549,6 @@ CorrelationId RemoteEntity::sendRequest(const PeerId& peerId, const std::string& return correlationId; } - void RemoteEntity::sendRequest(const PeerId& peerId, const std::string& path, const StructBase& structBase, CorrelationId correlationId, IMessage::Metainfo* metainfo) { //// if not initialized (entity not registered) @@ -628,10 +592,9 @@ void RemoteEntity::sendRequest(const PeerId& peerId, const std::string& path, co { IExecutorPtr executor = session->getExecutor(); assert(executor); - executor->addAction([this, receiveData]() - { - receivedReply(receiveData); - }); + executor->addAction([this, receiveData]() { + receivedReply(receiveData); + }); } else { @@ -640,7 +603,6 @@ void RemoteEntity::sendRequest(const PeerId& peerId, const std::string& path, co } } - void RemoteEntity::sendEvent(const PeerId& peerId, IMessage::Metainfo&& metainfo, const StructBase& structBase) { sendRequest(peerId, EMPTY_PATH, structBase, CORRELATIONID_NONE, &metainfo); @@ -669,7 +631,6 @@ void RemoteEntity::sendEventToAllPeers(const std::string& path, IMessage::Metain } } - CorrelationId RemoteEntity::sendRequest(const PeerId& peerId, IMessage::Metainfo&& metainfo, const StructBase& structBase, FuncReplyMeta funcReply) { CorrelationId correlationId = getNextCorrelationId(); @@ -680,7 +641,6 @@ CorrelationId RemoteEntity::sendRequest(const PeerId& peerId, IMessage::Metainfo return correlationId; } - CorrelationId RemoteEntity::sendRequest(const PeerId& peerId, const std::string& path, IMessage::Metainfo&& metainfo, const StructBase& structBase, FuncReplyMeta funcReply) { CorrelationId correlationId = getNextCorrelationId(); @@ -691,7 +651,6 @@ CorrelationId RemoteEntity::sendRequest(const PeerId& peerId, const std::string& return correlationId; } - bool RemoteEntity::cancelReply(CorrelationId correlationId) { if (correlationId == CORRELATIONID_NONE) @@ -711,7 +670,6 @@ bool RemoteEntity::cancelReply(CorrelationId correlationId) } } - void RemoteEntity::replyReceived(const ReceiveData& receiveData) { std::unique_ptr request; @@ -738,7 +696,6 @@ void RemoteEntity::replyReceived(const ReceiveData& receiveData) } } - void RemoteEntity::registerReplyEvent(FuncReplyEvent funcReplyEvent) { std::unique_lock lock(m_mutex); @@ -746,8 +703,6 @@ void RemoteEntity::registerReplyEvent(FuncReplyEvent funcReplyEvent) m_funcsReplyEventChanged.fetch_add(1, std::memory_order_acq_rel); } - - PeerId RemoteEntity::createPublishPeer(const SessionInfo& session, const std::string& entityName) { bool added = false; @@ -756,9 +711,6 @@ PeerId RemoteEntity::createPublishPeer(const SessionInfo& session, const std::st return peerId; } - - - void RemoteEntity::sendConnectEntity(PeerId peerId, IRemoteEntityContainer& entityContainer, const std::shared_ptr& funcReplyConnect) { bool registered = false; @@ -767,9 +719,13 @@ void RemoteEntity::sendConnectEntity(PeerId peerId, IRemoteEntityContainer& enti if (!registered) { // entity not registered, yet - std::weak_ptr thisEntityWeak = weak_from_this(); hybrid_ptr thisEntity; - if (thisEntity.lock()) +#ifdef FINALMQ_HAS_NOT_WEAK_FROM_THIS + std::weak_ptr thisEntityWeak = *reinterpret_cast*>(static_cast*>(this)); +#else + std::weak_ptr thisEntityWeak = weak_from_this(); +#endif + if (thisEntityWeak.lock()) { thisEntity = thisEntityWeak; } @@ -780,23 +736,21 @@ void RemoteEntity::sendConnectEntity(PeerId peerId, IRemoteEntityContainer& enti entityContainer.registerEntity(thisEntity); } - requestReply(peerId, {}, ConnectEntity{ ownEntityName }, - [this, funcReplyConnect] (PeerId peerId, Status status, - IMessage::Metainfo& metainfo, const std::shared_ptr& replyReceived) { + requestReply(peerId, {}, ConnectEntity{ownEntityName}, [this, funcReplyConnect](PeerId peerId1, Status status, IMessage::Metainfo& metainfo, const std::shared_ptr& replyReceived) { if (funcReplyConnect && *funcReplyConnect) { - (*funcReplyConnect)(peerId, status); + (*funcReplyConnect)(peerId1, status); } if (replyReceived) { const std::string& virtualSessionId = metainfo[FMQ_VIRTUAL_SESSION_ID]; - m_peerManager->updatePeer(peerId, virtualSessionId, replyReceived->entityId, replyReceived->entityName); + m_peerManager->updatePeer(peerId1, virtualSessionId, replyReceived->entityId, replyReceived->entityName); } else if (status == Status::STATUS_ENTITY_NOT_FOUND) { - std::string entityName = m_peerManager->getEntityName(peerId); + std::string entityName = m_peerManager->getEntityName(peerId1); streamError << "Entity not found: " << entityName; - removePeer(peerId, status); + removePeer(peerId1, status); } }); } @@ -834,14 +788,12 @@ PeerId RemoteEntity::connect(const SessionInfo& session, EntityId entityId, Func return connectIntern(session, "", "", entityId, std::make_shared(std::move(funcReplyConnect))); } - void RemoteEntity::disconnect(PeerId peerId) { sendRequest(peerId, EMPTY_PATH, DisconnectEntity(), CORRELATIONID_NONE); removePeer(peerId, Status::STATUS_PEER_DISCONNECTED); } - void RemoteEntity::removePeer(PeerId peerId, Status status) { if (peerId != PEERID_INVALID) @@ -855,7 +807,7 @@ void RemoteEntity::removePeer(PeerId peerId, Status status) std::unique_lock lock(m_mutexRequests); std::vector> requests; requests.reserve(m_requests.size()); - for (auto it = m_requests.begin(); it != m_requests.end(); ) + for (auto it = m_requests.begin(); it != m_requests.end();) { if (it->second->peerId == peerId) { @@ -888,14 +840,11 @@ void RemoteEntity::removePeer(PeerId peerId, Status status) } } - - std::vector RemoteEntity::getAllPeers() const { return m_peerManager->getAllPeers(); } - PeerId RemoteEntity::createPeer(IRemoteEntityContainer& entityContainer, FuncReplyConnect funcReplyConnect) { PeerId peerId = m_peerManager->addPeer(); @@ -903,8 +852,6 @@ PeerId RemoteEntity::createPeer(IRemoteEntityContainer& entityContainer, FuncRep return peerId; } - - void RemoteEntity::connectIntern(PeerId peerId, const SessionInfo& session, const std::string& entityName, EntityId entityId) { // the mutex lock is important for RTS_CONNECT_NOT_AVAILABLE / RTS_READY handling. See connectIntern(PeerId ...) @@ -940,8 +887,6 @@ void RemoteEntity::connectIntern(PeerId peerId, const SessionInfo& session, cons } } - - void RemoteEntity::connect(PeerId peerId, const SessionInfo& session, const std::string& entityName) { connectIntern(peerId, session, entityName, ENTITYID_INVALID); @@ -957,7 +902,6 @@ void RemoteEntity::connect(PeerId peerId, const SessionInfo& session, const std: connectIntern(peerId, session, entityName, entityId); } - void RemoteEntity::registerCommandFunction(const std::string& path, const std::string& type, FuncCommand funcCommand) { std::shared_ptr func = std::make_shared(std::move(funcCommand)); @@ -980,11 +924,10 @@ void RemoteEntity::registerCommandFunction(const std::string& path, const std::s } else { - m_funcCommandsStatic[path] = { type, func }; + m_funcCommandsStatic[path] = {type, func}; } } - std::string RemoteEntity::getTypeOfCommandFunction(std::string& path, const std::string* method) { const RemoteEntity::Function* function = getFunction(path); @@ -1006,26 +949,22 @@ std::string RemoteEntity::getTypeOfCommandFunction(std::string& path, const std: return {}; } - void RemoteEntity::registerPeerEvent(FuncPeerEvent funcPeerEvent) { std::shared_ptr func = std::make_shared(std::move(funcPeerEvent)); m_peerManager->setPeerEvent(func); } - EntityId RemoteEntity::getEntityId() const { return m_entityId; } - SessionInfo RemoteEntity::getSession(PeerId peerId) const { return m_peerManager->getSession(peerId); } - void RemoteEntity::sessionDisconnected(const IProtocolSessionPtr& session) { std::vector peerIds = m_peerManager->getAllPeersWithSession(session); @@ -1046,7 +985,6 @@ void RemoteEntity::virtualSessionDisconnected(const IProtocolSessionPtr& session } } - const RemoteEntity::Function* RemoteEntity::getFunction(const std::string& path, IMessage::Metainfo* keys) const { std::unique_lock lock(m_mutexFunctions); @@ -1164,8 +1102,6 @@ const RemoteEntity::Function* RemoteEntity::getFunction(const std::string& path, return nullptr; } - - void RemoteEntity::receivedRequest(ReceiveData& receiveData) { if (receiveData.automaticConnect) @@ -1201,15 +1137,13 @@ void RemoteEntity::receivedRequest(ReceiveData& receiveData) } } - struct ThreadLocalDataReplyEvent { - std::int64_t changeId = 0; - std::vector funcsReplyEventNoLock; + std::int64_t changeId = 0; + std::vector funcsReplyEventNoLock{}; }; thread_local std::unordered_map t_threadLocalDataReplyEvent; - void RemoteEntity::receivedReply(const ReceiveData& receiveData) { ThreadLocalDataReplyEvent& threadLocalDataReplyEvent = t_threadLocalDataReplyEvent[m_entityId]; @@ -1236,8 +1170,7 @@ void RemoteEntity::receivedReply(const ReceiveData& receiveData) replyReceived(receiveData); } - if (receiveData.header.status == Status::STATUS_ENTITY_NOT_FOUND && - receiveData.header.srcid != ENTITYID_INVALID) + if (receiveData.header.status == Status::STATUS_ENTITY_NOT_FOUND && receiveData.header.srcid != ENTITYID_INVALID) { assert(m_peerManager); assert(receiveData.session); @@ -1247,7 +1180,6 @@ void RemoteEntity::receivedReply(const ReceiveData& receiveData) } } - void RemoteEntity::deinit() { std::vector peers = getAllPeers(); @@ -1257,6 +1189,4 @@ void RemoteEntity::deinit() } } - - -} // namespace finalmq +} // namespace finalmq diff --git a/src/remoteentity/RemoteEntityContainer.cpp b/src/remoteentity/RemoteEntityContainer.cpp index 3d7589bd..18c46b31 100644 --- a/src/remoteentity/RemoteEntityContainer.cpp +++ b/src/remoteentity/RemoteEntityContainer.cpp @@ -21,21 +21,17 @@ //SOFTWARE. #include "finalmq/remoteentity/RemoteEntityContainer.h" -#include "finalmq/helpers/ModulenameFinalmq.h" -#include "finalmq/variant/VariantValues.h" +#include "finalmq/helpers/ModulenameFinalmq.h" #include "finalmq/remoteentity/entitydata.fmq.h" +#include "finalmq/variant/VariantValues.h" - +using finalmq::Header; using finalmq::MsgMode; using finalmq::Status; -using finalmq::Header; - - -namespace finalmq { - - +namespace finalmq +{ ConnectionEvent::ConnectionEvent() { } @@ -51,7 +47,7 @@ ConnectionEvent::operator Enum&() { return m_value; } -const ConnectionEvent& ConnectionEvent::operator =(Enum en) +const ConnectionEvent& ConnectionEvent::operator=(Enum en) { m_value = en; return *this; @@ -69,24 +65,22 @@ void ConnectionEvent::fromString(const std::string& name) m_value = static_cast(_enumInfo.getMetaEnum().getValueByName(name)); } const EnumInfo ConnectionEvent::_enumInfo = { - "ConnectionEvent", "", {}, { + "ConnectionEvent", + "", + {}, + { {"CONNECTIONEVENT_CONNECTED", 0, "", "connected"}, {"CONNECTIONEVENT_DISCONNECTED", 1, "", "disconnected"}, {"CONNECTIONEVENT_SOCKET_CONNECTED", 2, "", "socket connected"}, {"CONNECTIONEVENT_SOCKET_DISCONNECTED", 3, "", "socket disconnected"}, - } -}; - - + }}; /////////////////////////////////// std::atomic_uint64_t RemoteEntityContainer::m_nextContainerId = {}; RemoteEntityContainer::RemoteEntityContainer() - : m_protocolSessionContainer(std::make_unique()) - , m_executor(m_protocolSessionContainer->getExecutor()) - , m_containerId(m_nextContainerId.fetch_add(1)) + : m_protocolSessionContainer(std::make_unique()), m_executor(m_protocolSessionContainer->getExecutor()), m_containerId(m_nextContainerId.fetch_add(1)) { } @@ -95,7 +89,6 @@ RemoteEntityContainer::~RemoteEntityContainer() deinit(); } - void RemoteEntityContainer::deinit() { std::unique_lock lock(m_mutex); @@ -120,12 +113,8 @@ void RemoteEntityContainer::deinit() } } - - // IRemoteEntityContainer - - void RemoteEntityContainer::init(const IExecutorPtr& executor, int cycleTime, FuncTimer funcTimer, bool storeRawDataInReceiveStruct, int checkReconnectInterval) { m_storeRawDataInReceiveStruct = storeRawDataInReceiveStruct; @@ -146,7 +135,6 @@ static std::string endpointToProtocolEndpoint(const std::string& endpoint, std:: return endpoint.substr(0, ixEndpoint); } - int RemoteEntityContainer::bind(const std::string& endpoint, const BindProperties& bindProperties) { std::string contentTypeName; @@ -194,14 +182,18 @@ SessionInfo RemoteEntityContainer::connect(const std::string& endpoint, const Co SessionInfo RemoteEntityContainer::createSessionInfo(const IProtocolSessionPtr& session) { +#ifdef FINALMQ_HAS_NOT_WEAK_FROM_THIS + std::weak_ptr thisEntityContainer = *reinterpret_cast*>(static_cast*>(this)); +#else std::weak_ptr thisEntityContainer = weak_from_this(); +#endif if (thisEntityContainer.lock()) { - return { thisEntityContainer, session }; + return {thisEntityContainer, session}; } else { - return { this, session }; + return {this, session}; } } @@ -240,19 +232,16 @@ void RemoteEntityContainer::subscribeSessions(std::string name) name = name + "/#"; - std::vector< IProtocolSessionPtr > sessions = m_protocolSessionContainer->getAllSessions(); + std::vector sessions = m_protocolSessionContainer->getAllSessions(); for (auto it = sessions.begin(); it != sessions.end(); ++it) { if (*it) { - (*it)->subscribe({ name }); + (*it)->subscribe({name}); } } } - - - void RemoteEntityContainer::run() { m_protocolSessionContainer->run(); @@ -269,7 +258,6 @@ IExecutorPtr RemoteEntityContainer::getExecutor() const return m_executor; } - EntityId RemoteEntityContainer::registerEntity(hybrid_ptr remoteEntity, std::string name) { // remove last '/', if available @@ -318,7 +306,6 @@ EntityId RemoteEntityContainer::registerEntity(hybrid_ptr remoteE return entityId; } - //void RemoteEntityContainer::addPureDataPaths(std::vector& paths) //{ // for (size_t i = 0; i < paths.size(); ++i) @@ -338,8 +325,6 @@ EntityId RemoteEntityContainer::registerEntity(hybrid_ptr remoteE // } //} - - void RemoteEntityContainer::unregisterEntity(EntityId entityId) { std::unique_lock lock(m_mutex); @@ -354,14 +339,12 @@ void RemoteEntityContainer::unregisterEntity(EntityId entityId) m_entityId2entity.erase(entityId); } - void RemoteEntityContainer::registerConnectionEvent(FuncConnectionEvent funcConnectionEvent) { std::unique_lock lock(m_mutex); m_funcConnectionEvent = std::make_shared(std::move(funcConnectionEvent)); } - std::vector RemoteEntityContainer::getAllEntities() const { std::unique_lock lock(m_mutex); @@ -378,7 +361,7 @@ hybrid_ptr RemoteEntityContainer::getEntity(EntityId entityId) co { std::unique_lock lock(m_mutex); auto it = m_entityId2entity.find(entityId); - if (it != m_entityId2entity.end()) + if (it != m_entityId2entity.end()) { return it->second; } @@ -398,8 +381,6 @@ std::string RemoteEntityContainer::getEntityName(EntityId entityId, bool& regist return {}; } - - inline void RemoteEntityContainer::triggerConnectionEvent(const SessionInfo& session, ConnectionEvent connectionEvent) const { std::unique_lock lock(m_mutex); @@ -411,7 +392,6 @@ inline void RemoteEntityContainer::triggerConnectionEvent(const SessionInfo& ses } } - // IProtocolSessionCallback void RemoteEntityContainer::connected(const IProtocolSessionPtr& session) { @@ -441,7 +421,6 @@ void RemoteEntityContainer::disconnected(const IProtocolSessionPtr& session) } } - void RemoteEntityContainer::disconnectedVirtualSession(const IProtocolSessionPtr& session, const std::string& virtualSessionId) { std::vector> entities; @@ -463,7 +442,6 @@ void RemoteEntityContainer::disconnectedVirtualSession(const IProtocolSessionPtr } } - //bool RemoteEntityContainer::isPureDataPath(const std::string& path) //{ // for (auto it = m_pureDataPathPrefixes.begin(); it != m_pureDataPathPrefixes.end(); ++it) @@ -485,22 +463,19 @@ void RemoteEntityContainer::disconnectedVirtualSession(const IProtocolSessionPtr // return false; //} - - struct ThreadLocalDataEntities { - std::int64_t changeId = 0; - std::unordered_map> name2entityNoLock; - std::unordered_map> entityId2entityNoLock; + std::int64_t changeId = 0; + std::unordered_map> name2entityNoLock{}; + std::unordered_map> entityId2entityNoLock{}; }; thread_local std::unordered_map t_threadLocalDataEntities; - void RemoteEntityContainer::received(const IProtocolSessionPtr& session, const IMessagePtr& message) { assert(session); assert(message); - + ThreadLocalDataEntities& threadLocalDataEntities = t_threadLocalDataEntities[m_containerId]; std::unordered_map>& name2entityNoLock = threadLocalDataEntities.name2entityNoLock; std::unordered_map>& entityId2entityNoLock = threadLocalDataEntities.entityId2entityNoLock; @@ -514,7 +489,7 @@ void RemoteEntityContainer::received(const IProtocolSessionPtr& session, const I } int formatStatus = 0; - ReceiveData receiveData{ createSessionInfo(session), {}, message, {}, false, {} }; + ReceiveData receiveData{createSessionInfo(session), {}, message, {}, false, {}}; if (!session->doesSupportMetainfo()) { receiveData.structBase = RemoteEntityFormatRegistry::instance().parse(session, *message, m_storeRawDataInReceiveStruct, name2entityNoLock, receiveData.header, formatStatus); @@ -586,7 +561,7 @@ void RemoteEntityContainer::received(const IProtocolSessionPtr& session, const I { entityId = entity->getEntityId(); } - Header headerReply{ receiveData.header.srcid, "", entityId, MsgMode::MSG_REPLY, replyStatus, {}, {}, receiveData.header.corrid, {} }; + Header headerReply{receiveData.header.srcid, "", entityId, MsgMode::MSG_REPLY, replyStatus, {}, {}, receiveData.header.corrid, {}}; RemoteEntityFormatRegistry::instance().send(session, receiveData.virtualSessionId, headerReply, std::move(message->getEchoData())); } } @@ -613,6 +588,4 @@ void RemoteEntityContainer::socketDisconnected(const IProtocolSessionPtr& sessio triggerConnectionEvent(createSessionInfo(session), ConnectionEvent::CONNECTIONEVENT_SOCKET_DISCONNECTED); } - - -} // namespace finalmq +} // namespace finalmq diff --git a/src/remoteentity/RemoteEntityFormatHl7.cpp b/src/remoteentity/RemoteEntityFormatHl7.cpp index 42b41808..062ace30 100644 --- a/src/remoteentity/RemoteEntityFormatHl7.cpp +++ b/src/remoteentity/RemoteEntityFormatHl7.cpp @@ -22,23 +22,20 @@ #include "finalmq/remoteentity/RemoteEntityFormatHl7.h" +#include "finalmq/protocolsession/ProtocolMessage.h" +#include "finalmq/remoteentity/entitydata.fmq.h" +#include "finalmq/serializehl7/ParserHl7.h" #include "finalmq/serializehl7/SerializerHl7.h" #include "finalmq/serializestruct/ParserStruct.h" -#include "finalmq/serializehl7/ParserHl7.h" #include "finalmq/serializestruct/SerializerStruct.h" #include "finalmq/serializestruct/StructFactoryRegistry.h" #include "finalmq/variant/VariantValues.h" -#include "finalmq/protocolsession/ProtocolMessage.h" -#include "finalmq/remoteentity/entitydata.fmq.h" - - -using finalmq::MsgMode; using finalmq::Header; +using finalmq::MsgMode; - -namespace finalmq { - +namespace finalmq +{ const int RemoteEntityFormatHl7::CONTENT_TYPE = 3; const std::string RemoteEntityFormatHl7::CONTENT_TYPE_NAME = "hl7"; @@ -48,8 +45,6 @@ const std::string RemoteEntityFormatHl7::PROPERTY_LINEEND = "lineend"; const std::string RemoteEntityFormatHl7::PROPERTY_MESSAGESTART = "messagestart"; const std::string RemoteEntityFormatHl7::PROPERTY_MESSAGEEND = "messageend"; - - struct RegisterFormatHl7 { RegisterFormatHl7() @@ -58,14 +53,13 @@ struct RegisterFormatHl7 } } g_registerFormatHl7; - static char* fmq_strnstr(const char* haystack, const char* needle, ssize_t len) { - ssize_t i; - ssize_t j; + ssize_t i; + ssize_t j; if (needle[0] == '\0') - return ((char*)haystack); + return (const_cast(haystack)); j = 0; while (j < len && haystack[j]) { @@ -76,14 +70,12 @@ static char* fmq_strnstr(const char* haystack, const char* needle, ssize_t len) ++j; } if (needle[i] == '\0') - return ((char*)&haystack[j - i]); + return (const_cast(&haystack[j - i])); j = j - i + 1; } return nullptr; } - - static void replaceSerialize(IMessage& source, const std::string& lineend, IMessage& destination) { static const char* SOURCE_LINEEND = "\r"; @@ -108,7 +100,7 @@ static void replaceSerialize(IMessage& source, const std::string& lineend, IMess char* buffer = destination.addSendPayload(sizeTotal, 512); memcpy(buffer, current, sizeData); memcpy(buffer + sizeData, lineend.c_str(), lineend.size()); - current = found + 1; // 1: size of character '\r' + current = found + 1; // 1: size of character '\r' sizeRest -= sizeData + 1; } @@ -120,7 +112,6 @@ static void replaceSerialize(IMessage& source, const std::string& lineend, IMess } } - static void replaceParser(const char* source, ssize_t sizeSource, const std::string& lineend, std::string& destination) { static const char DESTINATION_LINEEND = '\r'; @@ -154,8 +145,6 @@ static void replaceParser(const char* source, ssize_t sizeSource, const std::str } } - - static bool isReplaceNeeded(const IProtocolSessionPtr& session, std::string& lineend, std::string& messagestart, std::string& messageend) { lineend.clear(); @@ -172,7 +161,7 @@ static bool isReplaceNeeded(const IProtocolSessionPtr& session, std::string& lin hl7messagestart = formatData.getData(RemoteEntityFormatHl7::PROPERTY_MESSAGESTART); hl7messageend = formatData.getData(RemoteEntityFormatHl7::PROPERTY_MESSAGEEND); - replaceNeeded = ( (hl7lineend != nullptr && *hl7lineend != "\r") ); + replaceNeeded = ((hl7lineend != nullptr && *hl7lineend != "\r")); if (hl7lineend) { @@ -190,14 +179,11 @@ static bool isReplaceNeeded(const IProtocolSessionPtr& session, std::string& lin return replaceNeeded; } - - void RemoteEntityFormatHl7::serialize(const IProtocolSessionPtr& session, IMessage& message, const Header& /*header*/, const StructBase* structBase) { serializeData(session, message, structBase); } - void RemoteEntityFormatHl7::serializeData(const IProtocolSessionPtr& session, IMessage& message, const StructBase* structBase) { if (structBase) @@ -242,11 +228,6 @@ void RemoteEntityFormatHl7::serializeData(const IProtocolSessionPtr& session, IM } } - - - - - std::shared_ptr RemoteEntityFormatHl7::parse(const IProtocolSessionPtr& session, const BufferRef& bufferRef, bool storeRawData, const std::unordered_map>& /*name2Entity*/, Header& header, int& formatStatus) { formatStatus = FORMATSTATUS_HEADER_PARSED_BY_FORMAT; @@ -346,7 +327,7 @@ std::shared_ptr RemoteEntityFormatHl7::parse(const IProtocolSessionP } header.corrid = 1; - BufferRef bufferRefData = { buffer, sizeBuffer }; + BufferRef bufferRefData = {buffer, sizeBuffer}; data = parseData(session, bufferRefData, storeRawData, header.type, formatStatus); formatStatus |= FORMATSTATUS_AUTOMATIC_CONNECT; @@ -355,8 +336,6 @@ std::shared_ptr RemoteEntityFormatHl7::parse(const IProtocolSessionP return data; } - - std::shared_ptr RemoteEntityFormatHl7::parseData(const IProtocolSessionPtr& session, const BufferRef& bufferRef, bool storeRawData, std::string& type, int& formatStatus) { const char* buffer = bufferRef.first; @@ -450,8 +429,4 @@ std::shared_ptr RemoteEntityFormatHl7::parseData(const IProtocolSess return data; } - - - - -} // namespace finalmq +} // namespace finalmq diff --git a/src/remoteentity/RemoteEntityFormatProto.cpp b/src/remoteentity/RemoteEntityFormatProto.cpp index 81f0e2ea..64f26a2e 100644 --- a/src/remoteentity/RemoteEntityFormatProto.cpp +++ b/src/remoteentity/RemoteEntityFormatProto.cpp @@ -22,32 +22,24 @@ #include "finalmq/remoteentity/RemoteEntityFormatProto.h" +#include "finalmq/helpers/ModulenameFinalmq.h" +#include "finalmq/remoteentity/entitydata.fmq.h" +#include "finalmq/serializeproto/ParserProto.h" #include "finalmq/serializeproto/SerializerProto.h" #include "finalmq/serializestruct/ParserStruct.h" - -#include "finalmq/serializeproto/ParserProto.h" #include "finalmq/serializestruct/SerializerStruct.h" #include "finalmq/serializestruct/StructFactoryRegistry.h" -#include "finalmq/remoteentity/entitydata.fmq.h" - -#include "finalmq/helpers/ModulenameFinalmq.h" - - -using finalmq::MsgMode; using finalmq::Header; +using finalmq::MsgMode; - - -namespace finalmq { - - +namespace finalmq +{ const int RemoteEntityFormatProto::CONTENT_TYPE = 1; const std::string RemoteEntityFormatProto::CONTENT_TYPE_NAME = "protobuf"; //static const std::string FMQ_METHOD = "fmq_method"; - struct RegisterFormatProto { RegisterFormatProto() @@ -56,9 +48,7 @@ struct RegisterFormatProto } } g_registerFormatProto; - -#define PROTOBUFBLOCKSIZE 512 - +#define PROTOBUFBLOCKSIZE 512 void RemoteEntityFormatProto::serialize(const IProtocolSessionPtr& session, IMessage& message, const Header& header, const StructBase* structBase) { @@ -82,7 +72,6 @@ void RemoteEntityFormatProto::serialize(const IProtocolSessionPtr& session, IMes serializeData(session, message, structBase); } - void RemoteEntityFormatProto::serializeData(const IProtocolSessionPtr& /*session*/, IMessage& message, const StructBase* structBase) { char* bufferSizePayload = message.addSendPayload(4, PROTOBUFBLOCKSIZE); @@ -117,7 +106,6 @@ void RemoteEntityFormatProto::serializeData(const IProtocolSessionPtr& /*session *bufferSizePayload = static_cast(uSizePayload >> 24); } - std::shared_ptr RemoteEntityFormatProto::parse(const IProtocolSessionPtr& session, const BufferRef& bufferRef, bool storeRawData, const std::unordered_map>& name2Entity, Header& header, int& formatStatus) { formatStatus = 0; @@ -133,13 +121,13 @@ std::shared_ptr RemoteEntityFormatProto::parse(const IProtocolSessio ssize_t sizeHeader = 0; if (sizeBuffer >= 4) { - sizeHeader = (unsigned int)(unsigned char)*buffer; + sizeHeader = static_cast(static_cast(*buffer)); ++buffer; - sizeHeader |= ((unsigned int)(unsigned char)*buffer) << 8; + sizeHeader |= (static_cast(static_cast(*buffer))) << 8; ++buffer; - sizeHeader |= ((unsigned int)(unsigned char)*buffer) << 16; + sizeHeader |= (static_cast(static_cast(*buffer))) << 16; ++buffer; - sizeHeader |= ((unsigned int)(unsigned char)*buffer) << 24; + sizeHeader |= (static_cast(static_cast(*buffer))) << 24; ++buffer; } bool ok = false; @@ -175,7 +163,7 @@ std::shared_ptr RemoteEntityFormatProto::parse(const IProtocolSessio if (header.path.empty() && !header.type.empty()) { header.path = header.type; - } + } else if (!header.path.empty() && header.type.empty()) { header.type = header.path; @@ -189,15 +177,13 @@ std::shared_ptr RemoteEntityFormatProto::parse(const IProtocolSessio ssize_t sizeData = sizePayload - sizeHeader; buffer += sizeHeader; - BufferRef bufferRefData = { buffer, sizeData }; + BufferRef bufferRefData = {buffer, sizeData}; data = parseData(session, bufferRefData, storeRawData, header.type, formatStatus); } return data; } - - std::shared_ptr RemoteEntityFormatProto::parseData(const IProtocolSessionPtr& /*session*/, const BufferRef& bufferRef, bool storeRawData, std::string& type, int& formatStatus) { formatStatus = 0; @@ -224,13 +210,13 @@ std::shared_ptr RemoteEntityFormatProto::parseData(const IProtocolSe ssize_t sizeDataInStream = 0; if (ok) { - sizeDataInStream = (unsigned int)(unsigned char)*buffer; + sizeDataInStream = static_cast(static_cast(*buffer)); ++buffer; - sizeDataInStream |= ((unsigned int)(unsigned char)*buffer) << 8; + sizeDataInStream |= (static_cast(static_cast(*buffer))) << 8; ++buffer; - sizeDataInStream |= ((unsigned int)(unsigned char)*buffer) << 16; + sizeDataInStream |= (static_cast(static_cast(*buffer))) << 16; ++buffer; - sizeDataInStream |= ((unsigned int)(unsigned char)*buffer) << 24; + sizeDataInStream |= (static_cast(static_cast(*buffer))) << 24; ++buffer; sizeRemaining -= 4; } @@ -270,7 +256,4 @@ std::shared_ptr RemoteEntityFormatProto::parseData(const IProtocolSe return data; } - - - -} // namespace finalmq +} // namespace finalmq diff --git a/src/remoteentity/RemoteEntityFormatRegistry.cpp b/src/remoteentity/RemoteEntityFormatRegistry.cpp index 96f0a5c0..e0b24f52 100644 --- a/src/remoteentity/RemoteEntityFormatRegistry.cpp +++ b/src/remoteentity/RemoteEntityFormatRegistry.cpp @@ -21,27 +21,23 @@ //SOFTWARE. #include "finalmq/remoteentity/RemoteEntityFormatRegistry.h" -#include "finalmq/remoteentity/entitydata.fmq.h" + +#include +#include + +#include "finalmq/helpers/ModulenameFinalmq.h" #include "finalmq/protocolsession/ProtocolMessage.h" +#include "finalmq/remoteentity/entitydata.fmq.h" #include "finalmq/variant/Variant.h" #include "finalmq/variant/VariantValueStruct.h" #include "finalmq/variant/VariantValues.h" -#include "finalmq/helpers/ModulenameFinalmq.h" - -#include -#include - - +using finalmq::Header; using finalmq::MsgMode; using finalmq::Status; -using finalmq::Header; - - -namespace finalmq { - - +namespace finalmq +{ static const std::string FMQ_HTTP = "fmq_http"; static const std::string FMQ_METHOD = "fmq_method"; static const std::string FMQ_HTTP_STATUS = "fmq_http_status"; @@ -60,15 +56,12 @@ static const std::string MSG_REPLY = "MSG_REPLY"; static const std::string FMQ_VIRTUAL_SESSION_ID = "fmq_virtsessid"; - - void RemoteEntityFormatRegistryImpl::registerFormat(const std::string& contentTypeName, int contentType, const std::shared_ptr& format) { m_contentTypeToFormat[contentType] = format; m_contentTypeNameToContentType[contentTypeName] = contentType; } - bool RemoteEntityFormatRegistryImpl::isRegistered(int contentType) const { auto it = m_contentTypeToFormat.find(contentType); @@ -79,7 +72,6 @@ bool RemoteEntityFormatRegistryImpl::isRegistered(int contentType) const return false; } - int RemoteEntityFormatRegistryImpl::getContentType(const std::string& contentTypeName) const { auto it = m_contentTypeNameToContentType.find(contentTypeName); @@ -90,9 +82,6 @@ int RemoteEntityFormatRegistryImpl::getContentType(const std::string& contentTyp return 0; } - - - bool RemoteEntityFormatRegistryImpl::serialize(const IProtocolSessionPtr& session, IMessage& message, const Header& header, const StructBase* structBase) { int contentType = session->getContentType(); @@ -107,7 +96,6 @@ bool RemoteEntityFormatRegistryImpl::serialize(const IProtocolSessionPtr& sessio return false; } - void RemoteEntityFormatRegistryImpl::serializeHeaderToMetainfo(IMessage& message, const Header& header) { IMessage::Metainfo& metainfo = message.getAllMetainfo(); @@ -133,7 +121,6 @@ void RemoteEntityFormatRegistryImpl::serializeHeaderToMetainfo(IMessage& message metainfo[FMQ_TYPE] = header.type; } - bool RemoteEntityFormatRegistryImpl::serializeData(const IProtocolSessionPtr& session, IMessage& message, const StructBase* structBase) { int contentType = session->getContentType(); @@ -148,26 +135,21 @@ bool RemoteEntityFormatRegistryImpl::serializeData(const IProtocolSessionPtr& se return false; } - inline static bool shallSend(const Header& header, const IProtocolSessionPtr& session) { - if ((header.mode != MsgMode::MSG_REPLY) || - (header.corrid != CORRELATIONID_NONE) || - session->needsReply()) + if ((header.mode != MsgMode::MSG_REPLY) || (header.corrid != CORRELATIONID_NONE) || session->needsReply()) { return true; } return false; } - - static void statusToProtocolStatus(Status status, Variant& controlData, IMessage::Metainfo* metainfo, const IProtocolSessionPtr& session) { controlData.add(FMQ_HTTP, HTTP_RESPONSE); - switch (status) + switch(status) { - case Status::STATUS_OK: + case Status::STATUS_OK: { bool statusOk = true; if (metainfo) @@ -197,32 +179,32 @@ static void statusToProtocolStatus(Status status, Variant& controlData, IMessage } } break; - case Status::STATUS_ENTITY_NOT_FOUND: - case Status::STATUS_REQUEST_NOT_FOUND: - case Status::STATUS_REQUESTTYPE_NOT_KNOWN: - controlData.add(FMQ_HTTP_STATUS, 404); - controlData.add(FMQ_HTTP_STATUSTEXT, std::string("Not Found")); - break; - case Status::STATUS_SYNTAX_ERROR: - controlData.add(FMQ_HTTP_STATUS, 400); - controlData.add(FMQ_HTTP_STATUSTEXT, std::string("Bad Request")); - break; - case Status::STATUS_NO_REPLY: - if (session->needsReply()) - { - controlData.add(FMQ_HTTP_STATUS, 200); - controlData.add(FMQ_HTTP_STATUSTEXT, std::string("OK")); - } - else - { + case Status::STATUS_ENTITY_NOT_FOUND: + case Status::STATUS_REQUEST_NOT_FOUND: + case Status::STATUS_REQUESTTYPE_NOT_KNOWN: + controlData.add(FMQ_HTTP_STATUS, 404); + controlData.add(FMQ_HTTP_STATUSTEXT, std::string("Not Found")); + break; + case Status::STATUS_SYNTAX_ERROR: + controlData.add(FMQ_HTTP_STATUS, 400); + controlData.add(FMQ_HTTP_STATUSTEXT, std::string("Bad Request")); + break; + case Status::STATUS_NO_REPLY: + if (session->needsReply()) + { + controlData.add(FMQ_HTTP_STATUS, 200); + controlData.add(FMQ_HTTP_STATUSTEXT, std::string("OK")); + } + else + { + controlData.add(FMQ_HTTP_STATUS, 500); + controlData.add(FMQ_HTTP_STATUSTEXT, std::string("Internal Server Error")); + } + break; + default: controlData.add(FMQ_HTTP_STATUS, 500); controlData.add(FMQ_HTTP_STATUSTEXT, std::string("Internal Server Error")); - } - break; - default: - controlData.add(FMQ_HTTP_STATUS, 500); - controlData.add(FMQ_HTTP_STATUSTEXT, std::string("Internal Server Error")); - break; + break; } } @@ -237,7 +219,6 @@ static void metainfoToHeader(Header& header, IMessage::Metainfo& metainfo) metainfo.clear(); } - void RemoteEntityFormatRegistryImpl::send(const IProtocolSessionPtr& session, const std::string& virtualSessionId, Header& header, Variant&& echoData, const StructBase* structBase, IMessage::Metainfo* metainfo, Variant* controlData) { assert(session); @@ -323,15 +304,13 @@ void RemoteEntityFormatRegistryImpl::send(const IProtocolSessionPtr& session, co } if (!virtualSessionId.empty()) { - Variant& controlData = message->getControlData(); - controlData.add(FMQ_VIRTUAL_SESSION_ID, virtualSessionId); + Variant& controlData1 = message->getControlData(); + controlData1.add(FMQ_VIRTUAL_SESSION_ID, virtualSessionId); } session->sendMessage(message, (header.mode == MsgMode::MSG_REPLY)); } } - - static void metainfoToMessage(IMessage& message, std::vector& meta) { size_t size = meta.size(); @@ -347,8 +326,6 @@ static void metainfoToMessage(IMessage& message, std::vector& meta) meta.clear(); } - - //inline static bool isDestinationIdDefined(const Header& header) //{ // return (header.destid != ENTITYID_INVALID && header.destid != ENTITYID_DEFAULT); @@ -374,7 +351,6 @@ inline static bool isDestAndSubPathDefined(const Header& header) return (isDestinationDefined(header) && isSubPathDefined(header)); } - std::string RemoteEntityFormatRegistryImpl::parseMetainfo(IMessage& message, const std::unordered_map>& name2Entity, Header& header) { const IMessage::Metainfo& metainfo = message.getAllMetainfo(); @@ -454,13 +430,13 @@ std::string RemoteEntityFormatRegistryImpl::parseMetainfo(IMessage& message, con std::string pathWithoutFirstSlash; if (path[0] == '/') { - pathWithoutFirstSlash = { &path[1], path.size() - 1 }; + pathWithoutFirstSlash = {&path[1], path.size() - 1}; } else { pathWithoutFirstSlash = path; } - size_t ixEndHeader = pathWithoutFirstSlash.find_first_of('{'); //28 + size_t ixEndHeader = pathWithoutFirstSlash.find_first_of('{'); //28 if (ixEndHeader == std::string::npos) { ixEndHeader = pathWithoutFirstSlash.size(); @@ -472,10 +448,7 @@ std::string RemoteEntityFormatRegistryImpl::parseMetainfo(IMessage& message, con for (auto it = name2Entity.begin(); it != name2Entity.end() && !foundEntityName; ++it) { const std::string& prefix = it->first; - if (prefix != WILDCARD && - pathWithoutFirstSlash.size() >= prefix.size() && - pathWithoutFirstSlash.compare(0, prefix.size(), prefix) == 0 && - (pathWithoutFirstSlash.size() == prefix.size() || pathWithoutFirstSlash[prefix.size()] == '/')) + if (prefix != WILDCARD && pathWithoutFirstSlash.size() >= prefix.size() && pathWithoutFirstSlash.compare(0, prefix.size(), prefix) == 0 && (pathWithoutFirstSlash.size() == prefix.size() || pathWithoutFirstSlash[prefix.size()] == '/')) { foundEntityName = &prefix; remoteEntity = it->second; @@ -532,7 +505,6 @@ std::string RemoteEntityFormatRegistryImpl::parseMetainfo(IMessage& message, con return data; } - std::shared_ptr RemoteEntityFormatRegistryImpl::parseHeaderInMetainfo(const IProtocolSessionPtr& session, IMessage& message, bool storeRawData, const std::unordered_map>& name2Entity, Header& header, int& formatStatus) { std::string data = parseMetainfo(message, name2Entity, header); @@ -562,7 +534,7 @@ std::shared_ptr RemoteEntityFormatRegistryImpl::parseHeaderInMetainf else { std::shared_ptr structRawBytes = std::make_shared(); - structRawBytes->data = { bufferRef.first, bufferRef.first + bufferRef.second }; + structRawBytes->data = {bufferRef.first, bufferRef.first + bufferRef.second}; structBase = structRawBytes; } @@ -573,7 +545,7 @@ std::shared_ptr RemoteEntityFormatRegistryImpl::parse(const IProtoco { formatStatus = 0; BufferRef bufferRef = message.getReceivePayload(); - + std::shared_ptr structBase; int contentType = session->getContentType(); @@ -588,8 +560,6 @@ std::shared_ptr RemoteEntityFormatRegistryImpl::parse(const IProtoco return structBase; } - - //std::shared_ptr RemoteEntityFormatRegistryImpl::parsePureData(IMessage& message, Header& header) //{ // const std::unordered_map>& name2Entity; @@ -604,9 +574,6 @@ std::shared_ptr RemoteEntityFormatRegistryImpl::parse(const IProtoco // return structBytes; //} - - - ////////////////////////////////////// /// RemoteEntityFormat @@ -641,6 +608,4 @@ std::unique_ptr& RemoteEntityFormatRegistry::getSta return instanceUniquePtr; } - - -} // namespace finalmq +} // namespace finalmq diff --git a/src/serialize/ParserConverter.cpp b/src/serialize/ParserConverter.cpp index d0d551a5..f43b4be3 100644 --- a/src/serialize/ParserConverter.cpp +++ b/src/serialize/ParserConverter.cpp @@ -20,35 +20,31 @@ //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. - #include "finalmq/serialize/ParserConverter.h" -#include "finalmq/metadata/MetaData.h" -#include "finalmq/logger/LogStream.h" -#include "finalmq/helpers/ModulenameFinalmq.h" - -#include "finalmq/conversions/itoa.h" -#include "finalmq/conversions/dtoa.h" -#include -#include #include +#include +#include -namespace finalmq { - +#include "finalmq/conversions/dtoa.h" +#include "finalmq/conversions/itoa.h" +#include "finalmq/helpers/ModulenameFinalmq.h" +#include "finalmq/logger/LogStream.h" +#include "finalmq/metadata/MetaData.h" +namespace finalmq +{ ParserConverter::ParserConverter(IParserVisitor* visitor) : m_visitor(visitor) { } -void ParserConverter::setVisitor(IParserVisitor &visitor) +void ParserConverter::setVisitor(IParserVisitor& visitor) { m_visitor = &visitor; } - - // ParserConverter void ParserConverter::notifyError(const char* str, const char* message) { @@ -632,499 +628,522 @@ void ParserConverter::enterArrayEnum(const MetaField& field, const std::vector void ParserConverter::convertNumber(const MetaField& field, T value) { - switch (field.typeId) - { - case MetaTypeId::TYPE_BOOL: - m_visitor->enterBool(field, value); - break; - case MetaTypeId::TYPE_INT8: - m_visitor->enterInt8(field, static_cast(value)); - break; - case MetaTypeId::TYPE_UINT8: - m_visitor->enterUInt8(field, static_cast(value)); - break; - case MetaTypeId::TYPE_INT16: - m_visitor->enterInt16(field, static_cast(value)); - break; - case MetaTypeId::TYPE_UINT16: - m_visitor->enterUInt16(field, static_cast(value)); - break; - case MetaTypeId::TYPE_INT32: - m_visitor->enterInt32(field, static_cast(value)); - break; - case MetaTypeId::TYPE_UINT32: - m_visitor->enterUInt32(field, static_cast(value)); - break; - case MetaTypeId::TYPE_INT64: - m_visitor->enterInt64(field, static_cast(value)); - break; - case MetaTypeId::TYPE_UINT64: - m_visitor->enterUInt64(field, static_cast(value)); - break; - case MetaTypeId::TYPE_FLOAT: - m_visitor->enterFloat(field, static_cast(value)); - break; - case MetaTypeId::TYPE_DOUBLE: - m_visitor->enterDouble(field, static_cast(value)); - break; - case MetaTypeId::TYPE_STRING: - m_visitor->enterString(field, std::to_string(value)); - break; - case MetaTypeId::TYPE_ENUM: - m_visitor->enterEnum(field, static_cast(value)); - break; - case MetaTypeId::TYPE_ARRAY_BOOL: - { + switch(field.typeId) + { + case MetaTypeId::TYPE_BOOL: +#ifndef WIN32 +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wfloat-equal" +#endif + m_visitor->enterBool(field, value); +#ifndef WIN32 +#pragma GCC diagnostic pop +#endif + break; + case MetaTypeId::TYPE_INT8: + m_visitor->enterInt8(field, static_cast(value)); + break; + case MetaTypeId::TYPE_UINT8: + m_visitor->enterUInt8(field, static_cast(value)); + break; + case MetaTypeId::TYPE_INT16: + m_visitor->enterInt16(field, static_cast(value)); + break; + case MetaTypeId::TYPE_UINT16: + m_visitor->enterUInt16(field, static_cast(value)); + break; + case MetaTypeId::TYPE_INT32: + m_visitor->enterInt32(field, static_cast(value)); + break; + case MetaTypeId::TYPE_UINT32: + m_visitor->enterUInt32(field, static_cast(value)); + break; + case MetaTypeId::TYPE_INT64: + m_visitor->enterInt64(field, static_cast(value)); + break; + case MetaTypeId::TYPE_UINT64: + m_visitor->enterUInt64(field, static_cast(value)); + break; + case MetaTypeId::TYPE_FLOAT: + m_visitor->enterFloat(field, static_cast(value)); + break; + case MetaTypeId::TYPE_DOUBLE: + m_visitor->enterDouble(field, static_cast(value)); + break; + case MetaTypeId::TYPE_STRING: + m_visitor->enterString(field, std::to_string(value)); + break; + case MetaTypeId::TYPE_ENUM: + m_visitor->enterEnum(field, static_cast(value)); + break; + case MetaTypeId::TYPE_ARRAY_BOOL: + { +#ifndef WIN32 +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wfloat-equal" +#endif bool v = value; +#ifndef WIN32 +#pragma GCC diagnostic pop +#endif m_visitor->enterArrayBool(field, std::vector(&v, &v + 1)); } break; - case MetaTypeId::TYPE_ARRAY_INT8: + case MetaTypeId::TYPE_ARRAY_INT8: { std::int8_t v = static_cast(value); m_visitor->enterArrayInt8(field, &v, 1); } break; - case MetaTypeId::TYPE_ARRAY_INT16: + case MetaTypeId::TYPE_ARRAY_INT16: { std::int16_t v = static_cast(value); m_visitor->enterArrayInt16(field, &v, 1); } break; - case MetaTypeId::TYPE_ARRAY_UINT16: + case MetaTypeId::TYPE_ARRAY_UINT16: { std::uint16_t v = static_cast(value); m_visitor->enterArrayUInt16(field, &v, 1); } break; - case MetaTypeId::TYPE_ARRAY_INT32: + case MetaTypeId::TYPE_ARRAY_INT32: { std::int32_t v = static_cast(value); m_visitor->enterArrayInt32(field, &v, 1); } break; - case MetaTypeId::TYPE_ARRAY_UINT32: + case MetaTypeId::TYPE_ARRAY_UINT32: { std::uint32_t v = static_cast(value); m_visitor->enterArrayUInt32(field, &v, 1); } break; - case MetaTypeId::TYPE_ARRAY_INT64: + case MetaTypeId::TYPE_ARRAY_INT64: { std::int64_t v = static_cast(value); m_visitor->enterArrayInt64(field, &v, 1); } break; - case MetaTypeId::TYPE_ARRAY_UINT64: + case MetaTypeId::TYPE_ARRAY_UINT64: { std::uint64_t v = static_cast(value); m_visitor->enterArrayUInt64(field, &v, 1); } break; - case MetaTypeId::TYPE_ARRAY_FLOAT: + case MetaTypeId::TYPE_ARRAY_FLOAT: { float v = static_cast(value); m_visitor->enterArrayFloat(field, &v, 1); } break; - case MetaTypeId::TYPE_ARRAY_DOUBLE: + case MetaTypeId::TYPE_ARRAY_DOUBLE: { double v = static_cast(value); m_visitor->enterArrayDouble(field, &v, 1); } break; - case MetaTypeId::TYPE_ARRAY_STRING: + case MetaTypeId::TYPE_ARRAY_STRING: { m_visitor->enterArrayString(field, {std::to_string(value)}); } break; - case MetaTypeId::TYPE_ARRAY_BYTES: + case MetaTypeId::TYPE_ARRAY_BYTES: { std::string str = std::to_string(value); Bytes bytes(str.begin(), str.end()); - m_visitor->enterArrayBytes(field, { bytes }); + m_visitor->enterArrayBytes(field, {bytes}); } break; - case MetaTypeId::TYPE_ARRAY_ENUM: + case MetaTypeId::TYPE_ARRAY_ENUM: { std::int32_t v = static_cast(value); m_visitor->enterArrayEnum(field, &v, 1); } break; - default: - streamError << "number not expected"; - break; + default: + streamError << "number not expected"; + break; } } - void ParserConverter::convertString(const MetaField& field, const char* value, ssize_t size) { - switch (field.typeId) + switch(field.typeId) { - case MetaTypeId::TYPE_BOOL: + case MetaTypeId::TYPE_BOOL: { bool v = (size == 4 && (memcmp(value, "true", 4) == 0)); m_visitor->enterBool(field, v); } break; - case MetaTypeId::TYPE_INT8: + case MetaTypeId::TYPE_INT8: { std::int8_t v = static_cast(strtol(value, nullptr, 10)); m_visitor->enterInt8(field, v); } break; - case MetaTypeId::TYPE_UINT8: + case MetaTypeId::TYPE_UINT8: { std::uint8_t v = static_cast(strtoul(value, nullptr, 10)); m_visitor->enterUInt8(field, v); } break; - case MetaTypeId::TYPE_INT16: + case MetaTypeId::TYPE_INT16: { std::int16_t v = static_cast(strtol(value, nullptr, 10)); m_visitor->enterInt16(field, v); } break; - case MetaTypeId::TYPE_UINT16: + case MetaTypeId::TYPE_UINT16: { std::uint16_t v = static_cast(strtoul(value, nullptr, 10)); m_visitor->enterUInt16(field, v); } break; - case MetaTypeId::TYPE_INT32: + case MetaTypeId::TYPE_INT32: { - std::int32_t v = strtol(value, nullptr, 10); + std::int32_t v = static_cast(strtol(value, nullptr, 10)); m_visitor->enterInt32(field, v); } break; - case MetaTypeId::TYPE_UINT32: + case MetaTypeId::TYPE_UINT32: { - std::uint32_t v = strtoul(value, nullptr, 10); + std::uint32_t v = static_cast(strtoul(value, nullptr, 10)); m_visitor->enterUInt32(field, v); } break; - case MetaTypeId::TYPE_INT64: + case MetaTypeId::TYPE_INT64: { std::int64_t v = strtoll(value, nullptr, 10); m_visitor->enterInt64(field, v); } break; - case MetaTypeId::TYPE_UINT64: + case MetaTypeId::TYPE_UINT64: { std::uint64_t v = strtoull(value, nullptr, 10); m_visitor->enterUInt64(field, v); } break; - case MetaTypeId::TYPE_FLOAT: + case MetaTypeId::TYPE_FLOAT: { float v = strtof32(value, nullptr); m_visitor->enterFloat(field, v); } break; - case MetaTypeId::TYPE_DOUBLE: + case MetaTypeId::TYPE_DOUBLE: { double v = strtof64(value, nullptr); m_visitor->enterDouble(field, v); } break; - case MetaTypeId::TYPE_STRING: - m_visitor->enterString(field, value, size); - break; - case MetaTypeId::TYPE_ENUM: - m_visitor->enterEnum(field, value, size); - break; - case MetaTypeId::TYPE_ARRAY_BOOL: + case MetaTypeId::TYPE_STRING: + m_visitor->enterString(field, value, size); + break; + case MetaTypeId::TYPE_ENUM: + m_visitor->enterEnum(field, value, size); + break; + case MetaTypeId::TYPE_ARRAY_BOOL: { bool v = (size == 4 && (memcmp(value, "true", 4) == 0)); m_visitor->enterArrayBool(field, std::vector(&v, &v + 1)); } break; - case MetaTypeId::TYPE_ARRAY_INT8: + case MetaTypeId::TYPE_ARRAY_INT8: { std::int8_t v = static_cast(strtol(value, nullptr, 10)); m_visitor->enterArrayInt8(field, &v, 1); } break; - case MetaTypeId::TYPE_ARRAY_INT16: + case MetaTypeId::TYPE_ARRAY_INT16: { std::int16_t v = static_cast(strtol(value, nullptr, 10)); m_visitor->enterArrayInt16(field, &v, 1); } break; - case MetaTypeId::TYPE_ARRAY_UINT16: + case MetaTypeId::TYPE_ARRAY_UINT16: { std::uint16_t v = static_cast(strtoul(value, nullptr, 10)); m_visitor->enterArrayUInt16(field, &v, 1); } break; - case MetaTypeId::TYPE_ARRAY_INT32: + case MetaTypeId::TYPE_ARRAY_INT32: { - std::int32_t v = strtol(value, nullptr, 10); + std::int32_t v = static_cast(strtol(value, nullptr, 10)); m_visitor->enterArrayInt32(field, &v, 1); } break; - case MetaTypeId::TYPE_ARRAY_UINT32: + case MetaTypeId::TYPE_ARRAY_UINT32: { - std::uint32_t v = strtoul(value, nullptr, 10); + std::uint32_t v = static_cast(strtoul(value, nullptr, 10)); m_visitor->enterArrayUInt32(field, &v, 1); } break; - case MetaTypeId::TYPE_ARRAY_INT64: + case MetaTypeId::TYPE_ARRAY_INT64: { std::int64_t v = strtoll(value, nullptr, 10); m_visitor->enterArrayInt64(field, &v, 1); } break; - case MetaTypeId::TYPE_ARRAY_UINT64: + case MetaTypeId::TYPE_ARRAY_UINT64: { std::uint64_t v = strtoull(value, nullptr, 10); m_visitor->enterArrayUInt64(field, &v, 1); } break; - case MetaTypeId::TYPE_ARRAY_FLOAT: + case MetaTypeId::TYPE_ARRAY_FLOAT: { float v = strtof32(value, nullptr); m_visitor->enterArrayFloat(field, &v, 1); } break; - case MetaTypeId::TYPE_ARRAY_DOUBLE: + case MetaTypeId::TYPE_ARRAY_DOUBLE: { double v = strtof64(value, nullptr); m_visitor->enterArrayDouble(field, &v, 1); } break; - case MetaTypeId::TYPE_ARRAY_STRING: + case MetaTypeId::TYPE_ARRAY_STRING: { m_visitor->enterArrayString(field, {std::string(value, size)}); } break; - case MetaTypeId::TYPE_ARRAY_ENUM: + case MetaTypeId::TYPE_ARRAY_ENUM: { m_visitor->enterArrayEnum(field, {std::string(value, size)}); } break; - default: - streamError << "number not expected"; - break; + default: + streamError << "number not expected"; + break; } } - template void ParserConverter::convertArraytNumber(const MetaField& field, const T* value, ssize_t size) { - switch (field.typeId) - { - case MetaTypeId::TYPE_BOOL: - if (value && size > 0) - { - m_visitor->enterBool(field, value[0]); - } - break; - case MetaTypeId::TYPE_INT8: - if (value && size > 0) - { - m_visitor->enterInt8(field, static_cast(value[0])); - } - break; - case MetaTypeId::TYPE_UINT8: - if (value && size > 0) - { - m_visitor->enterUInt8(field, static_cast(value[0])); - } - break; - case MetaTypeId::TYPE_INT16: - if (value && size > 0) - { - m_visitor->enterInt16(field, static_cast(value[0])); - } - break; - case MetaTypeId::TYPE_UINT16: - if (value && size > 0) - { - m_visitor->enterUInt16(field, static_cast(value[0])); - } - break; - case MetaTypeId::TYPE_INT32: - if (value && size > 0) - { - m_visitor->enterInt32(field, static_cast(value[0])); - } - break; - case MetaTypeId::TYPE_UINT32: - if (value && size > 0) - { - m_visitor->enterUInt32(field, static_cast(value[0])); - } - break; - case MetaTypeId::TYPE_INT64: - if (value && size > 0) - { - m_visitor->enterInt64(field, static_cast(value[0])); - } - break; - case MetaTypeId::TYPE_UINT64: - if (value && size > 0) - { - m_visitor->enterUInt64(field, static_cast(value[0])); - } - break; - case MetaTypeId::TYPE_FLOAT: - if (value && size > 0) - { - m_visitor->enterFloat(field, static_cast(value[0])); - } - break; - case MetaTypeId::TYPE_DOUBLE: - if (value && size > 0) - { - m_visitor->enterDouble(field, static_cast(value[0])); - } - break; - case MetaTypeId::TYPE_STRING: - if (value && size > 0) - { - m_visitor->enterString(field, std::to_string(value[0])); - } - break; - case MetaTypeId::TYPE_ENUM: - if (value && size > 0) - { - m_visitor->enterEnum(field, static_cast(value[0])); - } - break; - case MetaTypeId::TYPE_ARRAY_BOOL: + switch(field.typeId) + { + case MetaTypeId::TYPE_BOOL: + if (value && size > 0) + { +#ifndef WIN32 +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wfloat-equal" +#endif + m_visitor->enterBool(field, value[0]); +#ifndef WIN32 +#pragma GCC diagnostic pop +#endif + } + break; + case MetaTypeId::TYPE_INT8: + if (value && size > 0) + { + m_visitor->enterInt8(field, static_cast(value[0])); + } + break; + case MetaTypeId::TYPE_UINT8: + if (value && size > 0) + { + m_visitor->enterUInt8(field, static_cast(value[0])); + } + break; + case MetaTypeId::TYPE_INT16: + if (value && size > 0) + { + m_visitor->enterInt16(field, static_cast(value[0])); + } + break; + case MetaTypeId::TYPE_UINT16: + if (value && size > 0) + { + m_visitor->enterUInt16(field, static_cast(value[0])); + } + break; + case MetaTypeId::TYPE_INT32: + if (value && size > 0) + { + m_visitor->enterInt32(field, static_cast(value[0])); + } + break; + case MetaTypeId::TYPE_UINT32: + if (value && size > 0) + { + m_visitor->enterUInt32(field, static_cast(value[0])); + } + break; + case MetaTypeId::TYPE_INT64: + if (value && size > 0) + { + m_visitor->enterInt64(field, static_cast(value[0])); + } + break; + case MetaTypeId::TYPE_UINT64: + if (value && size > 0) + { + m_visitor->enterUInt64(field, static_cast(value[0])); + } + break; + case MetaTypeId::TYPE_FLOAT: + if (value && size > 0) + { + m_visitor->enterFloat(field, static_cast(value[0])); + } + break; + case MetaTypeId::TYPE_DOUBLE: + if (value && size > 0) + { + m_visitor->enterDouble(field, static_cast(value[0])); + } + break; + case MetaTypeId::TYPE_STRING: + if (value && size > 0) + { + m_visitor->enterString(field, std::to_string(value[0])); + } + break; + case MetaTypeId::TYPE_ENUM: + if (value && size > 0) + { + m_visitor->enterEnum(field, static_cast(value[0])); + } + break; + case MetaTypeId::TYPE_ARRAY_BOOL: { std::vector v; v.reserve(size); - std::for_each(value, value + size, [&v] (const T& entry) { + std::for_each(value, value + size, [&v](const T& entry) { +#ifndef WIN32 +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wfloat-equal" +#endif v.push_back(entry); +#ifndef WIN32 +#pragma GCC diagnostic pop +#endif }); m_visitor->enterArrayBool(field, std::move(v)); } break; - case MetaTypeId::TYPE_ARRAY_INT8: + case MetaTypeId::TYPE_ARRAY_INT8: { std::vector v; v.reserve(size); - std::for_each(value, value + size, [&v] (const T& entry) { + std::for_each(value, value + size, [&v](const T& entry) { v.push_back(static_cast(entry)); }); m_visitor->enterArrayInt8(field, std::move(v)); } break; - case MetaTypeId::TYPE_ARRAY_INT16: + case MetaTypeId::TYPE_ARRAY_INT16: { std::vector v; v.reserve(size); std::for_each(value, value + size, [&v](const T& entry) { v.push_back(static_cast(entry)); - }); + }); m_visitor->enterArrayInt16(field, std::move(v)); } break; - case MetaTypeId::TYPE_ARRAY_UINT16: + case MetaTypeId::TYPE_ARRAY_UINT16: { std::vector v; v.reserve(size); std::for_each(value, value + size, [&v](const T& entry) { v.push_back(static_cast(entry)); - }); + }); m_visitor->enterArrayUInt16(field, std::move(v)); } break; - case MetaTypeId::TYPE_ARRAY_INT32: + case MetaTypeId::TYPE_ARRAY_INT32: { std::vector v; v.reserve(size); std::for_each(value, value + size, [&v](const T& entry) { v.push_back(static_cast(entry)); - }); + }); m_visitor->enterArrayInt32(field, std::move(v)); } break; - case MetaTypeId::TYPE_ARRAY_UINT32: + case MetaTypeId::TYPE_ARRAY_UINT32: { std::vector v; v.reserve(size); std::for_each(value, value + size, [&v](const T& entry) { v.push_back(static_cast(entry)); - }); + }); m_visitor->enterArrayUInt32(field, std::move(v)); } break; - case MetaTypeId::TYPE_ARRAY_INT64: + case MetaTypeId::TYPE_ARRAY_INT64: { std::vector v; v.reserve(size); - std::for_each(value, value + size, [&v] (const T& entry) { + std::for_each(value, value + size, [&v](const T& entry) { v.push_back(static_cast(entry)); }); m_visitor->enterArrayInt64(field, std::move(v)); } break; - case MetaTypeId::TYPE_ARRAY_UINT64: + case MetaTypeId::TYPE_ARRAY_UINT64: { std::vector v; v.reserve(size); - std::for_each(value, value + size, [&v] (const T& entry) { + std::for_each(value, value + size, [&v](const T& entry) { v.push_back(static_cast(entry)); }); m_visitor->enterArrayUInt64(field, std::move(v)); } break; - case MetaTypeId::TYPE_ARRAY_FLOAT: + case MetaTypeId::TYPE_ARRAY_FLOAT: { std::vector v; v.reserve(size); - std::for_each(value, value + size, [&v] (const T& entry) { + std::for_each(value, value + size, [&v](const T& entry) { v.push_back(static_cast(entry)); }); m_visitor->enterArrayFloat(field, std::move(v)); } break; - case MetaTypeId::TYPE_ARRAY_DOUBLE: + case MetaTypeId::TYPE_ARRAY_DOUBLE: { std::vector v; v.reserve(size); - std::for_each(value, value + size, [&v] (const T& entry) { + std::for_each(value, value + size, [&v](const T& entry) { v.push_back(static_cast(entry)); }); m_visitor->enterArrayDouble(field, std::move(v)); } break; - case MetaTypeId::TYPE_ARRAY_STRING: + case MetaTypeId::TYPE_ARRAY_STRING: { std::vector v; v.reserve(size); - std::for_each(value, value + size, [&v] (const T& entry) { + std::for_each(value, value + size, [&v](const T& entry) { v.push_back(std::to_string(entry)); }); m_visitor->enterArrayString(field, std::move(v)); } break; - case MetaTypeId::TYPE_ARRAY_ENUM: + case MetaTypeId::TYPE_ARRAY_ENUM: { std::vector v; v.reserve(size); - std::for_each(value, value + size, [&v] (const T& entry) { + std::for_each(value, value + size, [&v](const T& entry) { v.push_back(static_cast(entry)); }); m_visitor->enterArrayEnum(field, std::move(v)); } break; - default: - streamError << "array not expected"; - break; + default: + streamError << "array not expected"; + break; } } @@ -1132,428 +1151,438 @@ template void ParserConverter::convertArraytNumber(const MetaField& field, const std::vector& value) { ssize_t size = value.size(); - switch (field.typeId) - { - case MetaTypeId::TYPE_BOOL: - if (value.size() > 0) - { - m_visitor->enterBool(field, value[0]); - } - break; - case MetaTypeId::TYPE_INT8: - if (value.size() > 0) - { - m_visitor->enterInt8(field, static_cast(value[0])); - } - break; - case MetaTypeId::TYPE_UINT8: - if (value.size() > 0) - { - m_visitor->enterUInt8(field, static_cast(value[0])); - } - break; - case MetaTypeId::TYPE_INT16: - if (value.size() > 0) - { - m_visitor->enterInt16(field, static_cast(value[0])); - } - break; - case MetaTypeId::TYPE_UINT16: - if (value.size() > 0) - { - m_visitor->enterUInt16(field, static_cast(value[0])); - } - break; - case MetaTypeId::TYPE_INT32: - if (value.size() > 0) - { - m_visitor->enterInt32(field, static_cast(value[0])); - } - break; - case MetaTypeId::TYPE_UINT32: - if (value.size() > 0) - { - m_visitor->enterUInt32(field, static_cast(value[0])); - } - break; - case MetaTypeId::TYPE_INT64: - if (value.size() > 0) - { - m_visitor->enterInt64(field, static_cast(value[0])); - } - break; - case MetaTypeId::TYPE_UINT64: - if (value.size() > 0) - { - m_visitor->enterUInt64(field, static_cast(value[0])); - } - break; - case MetaTypeId::TYPE_FLOAT: - if (value.size() > 0) - { - m_visitor->enterFloat(field, static_cast(value[0])); - } - break; - case MetaTypeId::TYPE_DOUBLE: - if (value.size() > 0) - { - m_visitor->enterDouble(field, static_cast(value[0])); - } - break; - case MetaTypeId::TYPE_STRING: - if (value.size() > 0) - { - m_visitor->enterString(field, std::to_string(value[0])); - } - break; - case MetaTypeId::TYPE_ENUM: - if (value.size() > 0) - { - m_visitor->enterEnum(field, static_cast(value[0])); - } - break; - case MetaTypeId::TYPE_ARRAY_BOOL: + switch(field.typeId) + { + case MetaTypeId::TYPE_BOOL: + if (value.size() > 0) + { +#ifndef WIN32 +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wfloat-equal" +#endif + m_visitor->enterBool(field, value[0]); +#ifndef WIN32 +#pragma GCC diagnostic pop +#endif + } + break; + case MetaTypeId::TYPE_INT8: + if (value.size() > 0) + { + m_visitor->enterInt8(field, static_cast(value[0])); + } + break; + case MetaTypeId::TYPE_UINT8: + if (value.size() > 0) + { + m_visitor->enterUInt8(field, static_cast(value[0])); + } + break; + case MetaTypeId::TYPE_INT16: + if (value.size() > 0) + { + m_visitor->enterInt16(field, static_cast(value[0])); + } + break; + case MetaTypeId::TYPE_UINT16: + if (value.size() > 0) + { + m_visitor->enterUInt16(field, static_cast(value[0])); + } + break; + case MetaTypeId::TYPE_INT32: + if (value.size() > 0) + { + m_visitor->enterInt32(field, static_cast(value[0])); + } + break; + case MetaTypeId::TYPE_UINT32: + if (value.size() > 0) + { + m_visitor->enterUInt32(field, static_cast(value[0])); + } + break; + case MetaTypeId::TYPE_INT64: + if (value.size() > 0) + { + m_visitor->enterInt64(field, static_cast(value[0])); + } + break; + case MetaTypeId::TYPE_UINT64: + if (value.size() > 0) + { + m_visitor->enterUInt64(field, static_cast(value[0])); + } + break; + case MetaTypeId::TYPE_FLOAT: + if (value.size() > 0) + { + m_visitor->enterFloat(field, static_cast(value[0])); + } + break; + case MetaTypeId::TYPE_DOUBLE: + if (value.size() > 0) + { + m_visitor->enterDouble(field, static_cast(value[0])); + } + break; + case MetaTypeId::TYPE_STRING: + if (value.size() > 0) + { + m_visitor->enterString(field, std::to_string(value[0])); + } + break; + case MetaTypeId::TYPE_ENUM: + if (value.size() > 0) + { + m_visitor->enterEnum(field, static_cast(value[0])); + } + break; + case MetaTypeId::TYPE_ARRAY_BOOL: { std::vector v; v.reserve(size); - std::for_each(value.begin(), value.end(), [&v] (const T& entry) { + std::for_each(value.begin(), value.end(), [&v](const T& entry) { +#ifndef WIN32 +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wfloat-equal" +#endif v.push_back(entry); +#ifndef WIN32 +#pragma GCC diagnostic pop +#endif }); m_visitor->enterArrayBool(field, std::move(v)); } break; - case MetaTypeId::TYPE_ARRAY_INT8: + case MetaTypeId::TYPE_ARRAY_INT8: { std::vector v; v.reserve(size); - std::for_each(value.begin(), value.end(), [&v] (const T& entry) { + std::for_each(value.begin(), value.end(), [&v](const T& entry) { v.push_back(static_cast(entry)); }); m_visitor->enterArrayInt8(field, std::move(v)); } break; - case MetaTypeId::TYPE_ARRAY_INT16: + case MetaTypeId::TYPE_ARRAY_INT16: { std::vector v; v.reserve(size); - std::for_each(value.begin(), value.end(), [&v] (const T& entry) { + std::for_each(value.begin(), value.end(), [&v](const T& entry) { v.push_back(static_cast(entry)); }); m_visitor->enterArrayInt16(field, std::move(v)); } break; - case MetaTypeId::TYPE_ARRAY_UINT16: + case MetaTypeId::TYPE_ARRAY_UINT16: { std::vector v; v.reserve(size); - std::for_each(value.begin(), value.end(), [&v] (const T& entry) { + std::for_each(value.begin(), value.end(), [&v](const T& entry) { v.push_back(static_cast(entry)); }); m_visitor->enterArrayUInt16(field, std::move(v)); } break; - case MetaTypeId::TYPE_ARRAY_INT32: + case MetaTypeId::TYPE_ARRAY_INT32: { std::vector v; v.reserve(size); - std::for_each(value.begin(), value.end(), [&v] (const T& entry) { + std::for_each(value.begin(), value.end(), [&v](const T& entry) { v.push_back(static_cast(entry)); }); m_visitor->enterArrayInt32(field, std::move(v)); } break; - case MetaTypeId::TYPE_ARRAY_UINT32: + case MetaTypeId::TYPE_ARRAY_UINT32: { std::vector v; v.reserve(size); - std::for_each(value.begin(), value.end(), [&v] (const T& entry) { + std::for_each(value.begin(), value.end(), [&v](const T& entry) { v.push_back(static_cast(entry)); }); m_visitor->enterArrayUInt32(field, std::move(v)); } break; - case MetaTypeId::TYPE_ARRAY_INT64: + case MetaTypeId::TYPE_ARRAY_INT64: { std::vector v; v.reserve(size); - std::for_each(value.begin(), value.end(), [&v] (const T& entry) { + std::for_each(value.begin(), value.end(), [&v](const T& entry) { v.push_back(static_cast(entry)); }); m_visitor->enterArrayInt64(field, std::move(v)); } break; - case MetaTypeId::TYPE_ARRAY_UINT64: + case MetaTypeId::TYPE_ARRAY_UINT64: { std::vector v; v.reserve(size); - std::for_each(value.begin(), value.end(), [&v] (const T& entry) { + std::for_each(value.begin(), value.end(), [&v](const T& entry) { v.push_back(static_cast(entry)); }); m_visitor->enterArrayUInt64(field, std::move(v)); } break; - case MetaTypeId::TYPE_ARRAY_FLOAT: + case MetaTypeId::TYPE_ARRAY_FLOAT: { std::vector v; v.reserve(size); - std::for_each(value.begin(), value.end(), [&v] (const T& entry) { + std::for_each(value.begin(), value.end(), [&v](const T& entry) { v.push_back(static_cast(entry)); }); m_visitor->enterArrayFloat(field, std::move(v)); } break; - case MetaTypeId::TYPE_ARRAY_DOUBLE: + case MetaTypeId::TYPE_ARRAY_DOUBLE: { std::vector v; v.reserve(size); - std::for_each(value.begin(), value.end(), [&v] (const T& entry) { + std::for_each(value.begin(), value.end(), [&v](const T& entry) { v.push_back(static_cast(entry)); }); m_visitor->enterArrayDouble(field, std::move(v)); } break; - case MetaTypeId::TYPE_ARRAY_STRING: + case MetaTypeId::TYPE_ARRAY_STRING: { std::vector v; v.reserve(size); - std::for_each(value.begin(), value.end(), [&v] (const T& entry) { + std::for_each(value.begin(), value.end(), [&v](const T& entry) { v.push_back(std::to_string(entry)); }); m_visitor->enterArrayString(field, std::move(v)); } break; - case MetaTypeId::TYPE_ARRAY_ENUM: + case MetaTypeId::TYPE_ARRAY_ENUM: { std::vector v; v.reserve(size); - std::for_each(value.begin(), value.end(), [&v] (const T& entry) { + std::for_each(value.begin(), value.end(), [&v](const T& entry) { v.push_back(static_cast(entry)); }); m_visitor->enterArrayEnum(field, std::move(v)); } break; - default: - streamError << "array not expected"; - break; + default: + streamError << "array not expected"; + break; } } void ParserConverter::convertArraytString(const MetaField& field, const std::vector& value) { size_t size = value.size(); - switch (field.typeId) - { - case MetaTypeId::TYPE_BOOL: - if (!value.empty()) - { - bool v = (value[0].size() == 4 && (memcmp(value[0].c_str(), "true", 4) == 0)); - m_visitor->enterBool(field, v); - } - break; - case MetaTypeId::TYPE_INT8: - if (!value.empty()) - { - std::int8_t v = static_cast(strtol(value[0].c_str(), nullptr, 10)); - m_visitor->enterInt8(field, v); - } - break; - case MetaTypeId::TYPE_UINT8: - if (!value.empty()) - { - std::uint8_t v = static_cast(strtoul(value[0].c_str(), nullptr, 10)); - m_visitor->enterUInt8(field, v); - } - break; - case MetaTypeId::TYPE_INT16: - if (!value.empty()) - { - std::int16_t v = static_cast(strtol(value[0].c_str(), nullptr, 10)); - m_visitor->enterInt16(field, v); - } - break; - case MetaTypeId::TYPE_UINT16: - if (!value.empty()) - { - std::uint16_t v = static_cast(strtoul(value[0].c_str(), nullptr, 10)); - m_visitor->enterUInt16(field, v); - } - break; - case MetaTypeId::TYPE_INT32: - if (!value.empty()) - { - std::int32_t v = strtol(value[0].c_str(), nullptr, 10); - m_visitor->enterInt32(field, v); - } - break; - case MetaTypeId::TYPE_UINT32: - if (!value.empty()) - { - std::uint32_t v = strtoul(value[0].c_str(), nullptr, 10); - m_visitor->enterUInt32(field, v); - } - break; - case MetaTypeId::TYPE_INT64: - if (!value.empty()) - { - std::int64_t v = strtoll(value[0].c_str(), nullptr, 10); - m_visitor->enterInt64(field, v); - } - break; - case MetaTypeId::TYPE_UINT64: - if (!value.empty()) - { - std::uint64_t v = strtoull(value[0].c_str(), nullptr, 10); - m_visitor->enterUInt64(field, v); - } - break; - case MetaTypeId::TYPE_FLOAT: - if (!value.empty()) - { - float v = strtof32(value[0].c_str(), nullptr); - m_visitor->enterFloat(field, v); - } - break; - case MetaTypeId::TYPE_DOUBLE: - if (!value.empty()) - { - double v = strtof64(value[0].c_str(), nullptr); - m_visitor->enterDouble(field, v); - } - break; - case MetaTypeId::TYPE_STRING: - if (!value.empty()) - { - m_visitor->enterString(field, value[0].c_str(), value[0].size()); - } - break; - case MetaTypeId::TYPE_ENUM: - if (!value.empty()) - { - m_visitor->enterEnum(field, value[0].c_str(), value[0].size()); - } - break; - case MetaTypeId::TYPE_ARRAY_BOOL: + switch(field.typeId) + { + case MetaTypeId::TYPE_BOOL: + if (!value.empty()) + { + bool v = (value[0].size() == 4 && (memcmp(value[0].c_str(), "true", 4) == 0)); + m_visitor->enterBool(field, v); + } + break; + case MetaTypeId::TYPE_INT8: + if (!value.empty()) + { + std::int8_t v = static_cast(strtol(value[0].c_str(), nullptr, 10)); + m_visitor->enterInt8(field, v); + } + break; + case MetaTypeId::TYPE_UINT8: + if (!value.empty()) + { + std::uint8_t v = static_cast(strtoul(value[0].c_str(), nullptr, 10)); + m_visitor->enterUInt8(field, v); + } + break; + case MetaTypeId::TYPE_INT16: + if (!value.empty()) + { + std::int16_t v = static_cast(strtol(value[0].c_str(), nullptr, 10)); + m_visitor->enterInt16(field, v); + } + break; + case MetaTypeId::TYPE_UINT16: + if (!value.empty()) + { + std::uint16_t v = static_cast(strtoul(value[0].c_str(), nullptr, 10)); + m_visitor->enterUInt16(field, v); + } + break; + case MetaTypeId::TYPE_INT32: + if (!value.empty()) + { + std::int32_t v = static_cast(strtol(value[0].c_str(), nullptr, 10)); + m_visitor->enterInt32(field, v); + } + break; + case MetaTypeId::TYPE_UINT32: + if (!value.empty()) + { + std::uint32_t v = static_cast(strtoul(value[0].c_str(), nullptr, 10)); + m_visitor->enterUInt32(field, v); + } + break; + case MetaTypeId::TYPE_INT64: + if (!value.empty()) + { + std::int64_t v = strtoll(value[0].c_str(), nullptr, 10); + m_visitor->enterInt64(field, v); + } + break; + case MetaTypeId::TYPE_UINT64: + if (!value.empty()) + { + std::uint64_t v = strtoull(value[0].c_str(), nullptr, 10); + m_visitor->enterUInt64(field, v); + } + break; + case MetaTypeId::TYPE_FLOAT: + if (!value.empty()) + { + float v = strtof32(value[0].c_str(), nullptr); + m_visitor->enterFloat(field, v); + } + break; + case MetaTypeId::TYPE_DOUBLE: + if (!value.empty()) + { + double v = strtof64(value[0].c_str(), nullptr); + m_visitor->enterDouble(field, v); + } + break; + case MetaTypeId::TYPE_STRING: + if (!value.empty()) + { + m_visitor->enterString(field, value[0].c_str(), value[0].size()); + } + break; + case MetaTypeId::TYPE_ENUM: + if (!value.empty()) + { + m_visitor->enterEnum(field, value[0].c_str(), value[0].size()); + } + break; + case MetaTypeId::TYPE_ARRAY_BOOL: { std::vector v; v.reserve(size); - std::for_each(value.begin(), value.end(), [&v] (const std::string& entry) { + std::for_each(value.begin(), value.end(), [&v](const std::string& entry) { bool val = (entry.size() == 4 && (memcmp(entry.c_str(), "true", 4) == 0)) || (entry.size() >= 1 && (entry[0] == 1)); v.push_back(val); }); m_visitor->enterArrayBool(field, std::move(v)); } break; - case MetaTypeId::TYPE_ARRAY_INT8: + case MetaTypeId::TYPE_ARRAY_INT8: { std::vector v; v.reserve(size); - std::for_each(value.begin(), value.end(), [&v] (const std::string& entry) { + std::for_each(value.begin(), value.end(), [&v](const std::string& entry) { v.push_back(static_cast(strtol(entry.c_str(), nullptr, 10))); }); m_visitor->enterArrayInt8(field, std::move(v)); } break; - case MetaTypeId::TYPE_ARRAY_INT16: + case MetaTypeId::TYPE_ARRAY_INT16: { std::vector v; v.reserve(size); std::for_each(value.begin(), value.end(), [&v](const std::string& entry) { v.push_back(static_cast(strtol(entry.c_str(), nullptr, 10))); - }); + }); m_visitor->enterArrayInt16(field, std::move(v)); } break; - case MetaTypeId::TYPE_ARRAY_UINT16: + case MetaTypeId::TYPE_ARRAY_UINT16: { std::vector v; v.reserve(size); std::for_each(value.begin(), value.end(), [&v](const std::string& entry) { v.push_back(static_cast(strtoul(entry.c_str(), nullptr, 10))); - }); + }); m_visitor->enterArrayUInt16(field, std::move(v)); } break; - case MetaTypeId::TYPE_ARRAY_INT32: + case MetaTypeId::TYPE_ARRAY_INT32: { std::vector v; v.reserve(size); std::for_each(value.begin(), value.end(), [&v](const std::string& entry) { - v.push_back(strtol(entry.c_str(), nullptr, 10)); - }); + v.push_back(static_cast(strtol(entry.c_str(), nullptr, 10))); + }); m_visitor->enterArrayInt32(field, std::move(v)); } break; - case MetaTypeId::TYPE_ARRAY_UINT32: + case MetaTypeId::TYPE_ARRAY_UINT32: { std::vector v; v.reserve(size); std::for_each(value.begin(), value.end(), [&v](const std::string& entry) { - v.push_back(strtoul(entry.c_str(), nullptr, 10)); - }); + v.push_back(static_cast(strtoul(entry.c_str(), nullptr, 10))); + }); m_visitor->enterArrayUInt32(field, std::move(v)); } break; - case MetaTypeId::TYPE_ARRAY_INT64: + case MetaTypeId::TYPE_ARRAY_INT64: { std::vector v; v.reserve(size); - std::for_each(value.begin(), value.end(), [&v] (const std::string& entry) { + std::for_each(value.begin(), value.end(), [&v](const std::string& entry) { v.push_back(strtoll(entry.c_str(), nullptr, 10)); }); m_visitor->enterArrayInt64(field, std::move(v)); } break; - case MetaTypeId::TYPE_ARRAY_UINT64: + case MetaTypeId::TYPE_ARRAY_UINT64: { std::vector v; v.reserve(size); - std::for_each(value.begin(), value.end(), [&v] (const std::string& entry) { + std::for_each(value.begin(), value.end(), [&v](const std::string& entry) { v.push_back(strtoull(entry.c_str(), nullptr, 10)); }); m_visitor->enterArrayUInt64(field, std::move(v)); } break; - case MetaTypeId::TYPE_ARRAY_FLOAT: + case MetaTypeId::TYPE_ARRAY_FLOAT: { std::vector v; v.reserve(size); - std::for_each(value.begin(), value.end(), [&v] (const std::string& entry) { + std::for_each(value.begin(), value.end(), [&v](const std::string& entry) { v.push_back(strtof32(entry.c_str(), nullptr)); }); m_visitor->enterArrayFloat(field, std::move(v)); } break; - case MetaTypeId::TYPE_ARRAY_DOUBLE: + case MetaTypeId::TYPE_ARRAY_DOUBLE: { std::vector v; v.reserve(size); - std::for_each(value.begin(), value.end(), [&v] (const std::string& entry) { + std::for_each(value.begin(), value.end(), [&v](const std::string& entry) { v.push_back(strtof64(entry.c_str(), nullptr)); }); m_visitor->enterArrayDouble(field, std::move(v)); } break; - case MetaTypeId::TYPE_ARRAY_STRING: - m_visitor->enterArrayString(field, value); - break; - case MetaTypeId::TYPE_ARRAY_ENUM: + case MetaTypeId::TYPE_ARRAY_STRING: + m_visitor->enterArrayString(field, value); + break; + case MetaTypeId::TYPE_ARRAY_ENUM: { std::vector v; v.reserve(size); - std::for_each(value.begin(), value.end(), [&v] (const std::string& entry) { + std::for_each(value.begin(), value.end(), [&v](const std::string& entry) { v.push_back(entry); }); m_visitor->enterArrayEnum(field, std::move(v)); } break; - default: - streamError << "array not expected"; - break; + default: + streamError << "array not expected"; + break; } } - - - - -} //namespace finalmq +} //namespace finalmq diff --git a/src/serialize/ParserProcessDefaultValues.cpp b/src/serialize/ParserProcessDefaultValues.cpp index d7bddda7..686c93d9 100644 --- a/src/serialize/ParserProcessDefaultValues.cpp +++ b/src/serialize/ParserProcessDefaultValues.cpp @@ -20,29 +20,25 @@ //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. - #include "finalmq/serialize/ParserProcessDefaultValues.h" -#include "finalmq/metadata/MetaData.h" -#include -#include #include +#include +#include -namespace finalmq { - +#include "finalmq/metadata/MetaData.h" +namespace finalmq +{ static const std::string STR_VARVALUE = "finalmq.variant.VarValue"; - ParserProcessDefaultValues::ParserProcessDefaultValues(bool skipDefaultValues, IParserVisitor* visitor) - : m_visitor(visitor) - , m_skipDefaultValues(skipDefaultValues) + : m_visitor(visitor), m_skipDefaultValues(skipDefaultValues) { - } -void ParserProcessDefaultValues::setVisitor(IParserVisitor &visitor) +void ParserProcessDefaultValues::setVisitor(IParserVisitor& visitor) { m_visitor = &visitor; } @@ -52,8 +48,6 @@ void ParserProcessDefaultValues::resetVarValueActive() m_varValueActive = 0; } - - // ParserProcessDefaultValues void ParserProcessDefaultValues::notifyError(const char* str, const char* message) { @@ -61,7 +55,6 @@ void ParserProcessDefaultValues::notifyError(const char* str, const char* messag m_visitor->notifyError(str, message); } - void ParserProcessDefaultValues::startStruct(const MetaStruct& stru) { m_struct = &stru; @@ -77,7 +70,6 @@ void ParserProcessDefaultValues::startStruct(const MetaStruct& stru) m_visitor->startStruct(stru); } - void ParserProcessDefaultValues::finished() { if (!m_skipDefaultValues && m_struct) @@ -87,7 +79,7 @@ void ParserProcessDefaultValues::finished() processDefaultValues(*m_struct, fieldsDone); m_stackFieldsDone.pop_back(); } - + if (!m_stackSkipDefault.empty()) { m_stackSkipDefault.pop_back(); @@ -116,8 +108,6 @@ void ParserProcessDefaultValues::executeEnterStruct() } } - - void ParserProcessDefaultValues::enterStruct(const MetaField& field) { assert(m_visitor); @@ -204,7 +194,6 @@ void ParserProcessDefaultValues::exitStruct(const MetaField& field) } } - void ParserProcessDefaultValues::enterStructNull(const MetaField& field) { markAsDone(field); @@ -214,7 +203,6 @@ void ParserProcessDefaultValues::enterStructNull(const MetaField& field) } } - void ParserProcessDefaultValues::processDefaultValues(const MetaStruct& stru, const std::vector& fieldsDone) { assert(!m_skipDefaultValues); @@ -225,128 +213,127 @@ void ParserProcessDefaultValues::processDefaultValues(const MetaStruct& stru, co const MetaField* field = stru.getFieldByIndex(index); if (field) { - switch (field->typeId) + switch(field->typeId) { - case MetaTypeId::TYPE_NONE: - break; - case MetaTypeId::TYPE_BOOL: - m_visitor->enterBool(*field, false); - break; - case MetaTypeId::TYPE_INT8: - m_visitor->enterInt8(*field, 0); - break; - case MetaTypeId::TYPE_UINT8: - m_visitor->enterUInt8(*field, 0); - break; - case MetaTypeId::TYPE_INT16: - m_visitor->enterInt16(*field, 0); - break; - case MetaTypeId::TYPE_UINT16: - m_visitor->enterUInt16(*field, 0); - break; - case MetaTypeId::TYPE_INT32: - m_visitor->enterInt32(*field, 0); - break; - case MetaTypeId::TYPE_UINT32: - m_visitor->enterUInt32(*field, 0); - break; - case MetaTypeId::TYPE_INT64: - m_visitor->enterInt64(*field, 0); - break; - case MetaTypeId::TYPE_UINT64: - m_visitor->enterUInt64(*field, 0); - break; - case MetaTypeId::TYPE_FLOAT: - m_visitor->enterFloat(*field, 0.0); - break; - case MetaTypeId::TYPE_DOUBLE: - m_visitor->enterDouble(*field, 0.0); - break; - case MetaTypeId::TYPE_STRING: - m_visitor->enterString(*field, "", 0); - break; - case MetaTypeId::TYPE_BYTES: + case MetaTypeId::TYPE_NONE: + break; + case MetaTypeId::TYPE_BOOL: + m_visitor->enterBool(*field, false); + break; + case MetaTypeId::TYPE_INT8: + m_visitor->enterInt8(*field, 0); + break; + case MetaTypeId::TYPE_UINT8: + m_visitor->enterUInt8(*field, 0); + break; + case MetaTypeId::TYPE_INT16: + m_visitor->enterInt16(*field, 0); + break; + case MetaTypeId::TYPE_UINT16: + m_visitor->enterUInt16(*field, 0); + break; + case MetaTypeId::TYPE_INT32: + m_visitor->enterInt32(*field, 0); + break; + case MetaTypeId::TYPE_UINT32: + m_visitor->enterUInt32(*field, 0); + break; + case MetaTypeId::TYPE_INT64: + m_visitor->enterInt64(*field, 0); + break; + case MetaTypeId::TYPE_UINT64: + m_visitor->enterUInt64(*field, 0); + break; + case MetaTypeId::TYPE_FLOAT: + m_visitor->enterFloat(*field, 0.0); + break; + case MetaTypeId::TYPE_DOUBLE: + m_visitor->enterDouble(*field, 0.0); + break; + case MetaTypeId::TYPE_STRING: + m_visitor->enterString(*field, "", 0); + break; + case MetaTypeId::TYPE_BYTES: { static const BytesElement dummy{}; m_visitor->enterBytes(*field, &dummy, 0); } break; - case MetaTypeId::TYPE_STRUCT: - if (!(field->flags & METAFLAG_NULLABLE)) - { - m_visitor->enterStruct(*field); - const MetaStruct* substru = MetaDataGlobal::instance().getStruct(*field); - if (substru && (field->typeName != STR_VARVALUE)) + case MetaTypeId::TYPE_STRUCT: + if (!(field->flags & METAFLAG_NULLABLE)) { - std::vector subfieldsDone(substru->getFieldsSize(), false); - processDefaultValues(*substru, subfieldsDone); + m_visitor->enterStruct(*field); + const MetaStruct* substru = MetaDataGlobal::instance().getStruct(*field); + if (substru && (field->typeName != STR_VARVALUE)) + { + std::vector subfieldsDone(substru->getFieldsSize(), false); + processDefaultValues(*substru, subfieldsDone); + } + m_visitor->exitStruct(*field); } - m_visitor->exitStruct(*field); - } - else - { - m_visitor->enterStructNull(*field); - } - break; - case MetaTypeId::TYPE_ENUM: - m_visitor->enterEnum(*field, 0); - break; - case MetaTypeId::TYPE_ARRAY_BOOL: - m_visitor->enterArrayBoolMove(*field, {}); - break; - case MetaTypeId::TYPE_ARRAY_INT8: - m_visitor->enterArrayInt8(*field, {}); - break; - case MetaTypeId::TYPE_ARRAY_INT16: - m_visitor->enterArrayInt16(*field, {}); - break; - case MetaTypeId::TYPE_ARRAY_UINT16: - m_visitor->enterArrayUInt16(*field, {}); - break; - case MetaTypeId::TYPE_ARRAY_INT32: - m_visitor->enterArrayInt32(*field, {}); - break; - case MetaTypeId::TYPE_ARRAY_UINT32: - m_visitor->enterArrayUInt32(*field, {}); - break; - case MetaTypeId::TYPE_ARRAY_INT64: - m_visitor->enterArrayInt64(*field, {}); - break; - case MetaTypeId::TYPE_ARRAY_UINT64: - m_visitor->enterArrayUInt64(*field, {}); - break; - case MetaTypeId::TYPE_ARRAY_FLOAT: - m_visitor->enterArrayFloat(*field, {}); - break; - case MetaTypeId::TYPE_ARRAY_DOUBLE: - m_visitor->enterArrayDouble(*field, {}); - break; - case MetaTypeId::TYPE_ARRAY_STRING: - m_visitor->enterArrayStringMove(*field, {}); - break; - case MetaTypeId::TYPE_ARRAY_BYTES: - m_visitor->enterArrayBytesMove(*field, {}); - break; - case MetaTypeId::TYPE_ARRAY_STRUCT: - m_visitor->enterArrayStruct(*field); - m_visitor->exitArrayStruct(*field); - break; - case MetaTypeId::TYPE_ARRAY_ENUM: - m_visitor->enterArrayEnum(*field, std::vector()); - break; - case MetaTypeId::OFFSET_ARRAY_FLAG: - assert(false); - break; - default: - assert(false); - break; + else + { + m_visitor->enterStructNull(*field); + } + break; + case MetaTypeId::TYPE_ENUM: + m_visitor->enterEnum(*field, 0); + break; + case MetaTypeId::TYPE_ARRAY_BOOL: + m_visitor->enterArrayBoolMove(*field, {}); + break; + case MetaTypeId::TYPE_ARRAY_INT8: + m_visitor->enterArrayInt8(*field, {}); + break; + case MetaTypeId::TYPE_ARRAY_INT16: + m_visitor->enterArrayInt16(*field, {}); + break; + case MetaTypeId::TYPE_ARRAY_UINT16: + m_visitor->enterArrayUInt16(*field, {}); + break; + case MetaTypeId::TYPE_ARRAY_INT32: + m_visitor->enterArrayInt32(*field, {}); + break; + case MetaTypeId::TYPE_ARRAY_UINT32: + m_visitor->enterArrayUInt32(*field, {}); + break; + case MetaTypeId::TYPE_ARRAY_INT64: + m_visitor->enterArrayInt64(*field, {}); + break; + case MetaTypeId::TYPE_ARRAY_UINT64: + m_visitor->enterArrayUInt64(*field, {}); + break; + case MetaTypeId::TYPE_ARRAY_FLOAT: + m_visitor->enterArrayFloat(*field, {}); + break; + case MetaTypeId::TYPE_ARRAY_DOUBLE: + m_visitor->enterArrayDouble(*field, {}); + break; + case MetaTypeId::TYPE_ARRAY_STRING: + m_visitor->enterArrayStringMove(*field, {}); + break; + case MetaTypeId::TYPE_ARRAY_BYTES: + m_visitor->enterArrayBytesMove(*field, {}); + break; + case MetaTypeId::TYPE_ARRAY_STRUCT: + m_visitor->enterArrayStruct(*field); + m_visitor->exitArrayStruct(*field); + break; + case MetaTypeId::TYPE_ARRAY_ENUM: + m_visitor->enterArrayEnum(*field, std::vector()); + break; + case MetaTypeId::OFFSET_ARRAY_FLAG: + assert(false); + break; + default: + assert(false); + break; } } } } } - void ParserProcessDefaultValues::markAsDone(const MetaField& field) { if (!m_skipDefaultValues) @@ -364,7 +351,6 @@ void ParserProcessDefaultValues::markAsDone(const MetaField& field) } } - void ParserProcessDefaultValues::enterArrayStruct(const MetaField& field) { markAsDone(field); @@ -515,7 +501,14 @@ void ParserProcessDefaultValues::enterUInt64(const MetaField& field, std::uint64 void ParserProcessDefaultValues::enterFloat(const MetaField& field, float value) { markAsDone(field); +#ifndef WIN32 +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wfloat-equal" +#endif if (value != 0 || !m_skipDefaultValues) +#ifndef WIN32 +#pragma GCC diagnostic pop +#endif { if (m_skipDefaultValues) { @@ -527,7 +520,14 @@ void ParserProcessDefaultValues::enterFloat(const MetaField& field, float value) void ParserProcessDefaultValues::enterDouble(const MetaField& field, double value) { markAsDone(field); +#ifndef WIN32 +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wfloat-equal" +#endif if (value != 0 || !m_skipDefaultValues) +#ifndef WIN32 +#pragma GCC diagnostic pop +#endif { if (m_skipDefaultValues) { @@ -951,5 +951,4 @@ void ParserProcessDefaultValues::enterArrayEnum(const MetaField& field, const st } } - -} // namespace finalmq +} // namespace finalmq diff --git a/src/serializejson/ParserJson.cpp b/src/serializejson/ParserJson.cpp index 2c34c80a..00be584d 100644 --- a/src/serializejson/ParserJson.cpp +++ b/src/serializejson/ParserJson.cpp @@ -20,38 +20,27 @@ //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. - #include "finalmq/serializejson/ParserJson.h" -#include "finalmq/metadata/MetaData.h" -#include "finalmq/logger/LogStream.h" -#include "finalmq/helpers/ModulenameFinalmq.h" -#include "finalmq/helpers/base64.h" - -#include "finalmq/conversions/itoa.h" -#include "finalmq/conversions/dtoa.h" #include + +#include "finalmq/conversions/dtoa.h" +#include "finalmq/conversions/itoa.h" +#include "finalmq/helpers/ModulenameFinalmq.h" +#include "finalmq/helpers/base64.h" +#include "finalmq/logger/LogStream.h" +#include "finalmq/metadata/MetaData.h" //#include -#include #include +#include - -namespace finalmq { - - - +namespace finalmq +{ ParserJson::ParserJson(IParserVisitor& visitor, const char* ptr, ssize_t size) - : m_ptr(ptr) - , m_size(size) - , m_visitor(visitor) - , m_parser(*this) + : m_ptr(ptr), m_size(size), m_visitor(visitor), m_parser(*this) { } - - - - const char* ParserJson::parseStruct(const std::string& typeName) { assert(m_ptr); @@ -75,12 +64,8 @@ const char* ParserJson::parseStruct(const std::string& typeName) return str; } - - - void ParserJson::syntaxError(const char* /*str*/, const char* /*message*/) { - } void ParserJson::enterNull() @@ -90,8 +75,7 @@ void ParserJson::enterNull() // unknown key return; } - if (m_fieldCurrent->typeId == MetaTypeId::TYPE_STRUCT && - m_fieldCurrent->flags & METAFLAG_NULLABLE) + if (m_fieldCurrent->typeId == MetaTypeId::TYPE_STRUCT && m_fieldCurrent->flags & METAFLAG_NULLABLE) { m_visitor.enterStructNull(*m_fieldCurrent); } @@ -105,102 +89,114 @@ void ParserJson::enterNumber(T value) // unknown key return; } - switch (m_fieldCurrent->typeId) + switch(m_fieldCurrent->typeId) { - case MetaTypeId::TYPE_BOOL: - m_visitor.enterBool(*m_fieldCurrent, value); - break; - case MetaTypeId::TYPE_INT8: - m_visitor.enterInt8(*m_fieldCurrent, static_cast(value)); - break; - case MetaTypeId::TYPE_UINT8: - m_visitor.enterUInt8(*m_fieldCurrent, static_cast(value)); - break; - case MetaTypeId::TYPE_INT16: - m_visitor.enterInt16(*m_fieldCurrent, static_cast(value)); - break; - case MetaTypeId::TYPE_UINT16: - m_visitor.enterUInt16(*m_fieldCurrent, static_cast(value)); - break; - case MetaTypeId::TYPE_INT32: - m_visitor.enterInt32(*m_fieldCurrent, static_cast(value)); - break; - case MetaTypeId::TYPE_UINT32: - m_visitor.enterUInt32(*m_fieldCurrent, static_cast(value)); - break; - case MetaTypeId::TYPE_INT64: - m_visitor.enterInt64(*m_fieldCurrent, static_cast(value)); - break; - case MetaTypeId::TYPE_UINT64: - m_visitor.enterUInt64(*m_fieldCurrent, static_cast(value)); - break; - case MetaTypeId::TYPE_FLOAT: - m_visitor.enterFloat(*m_fieldCurrent, static_cast(value)); - break; - case MetaTypeId::TYPE_DOUBLE: - m_visitor.enterDouble(*m_fieldCurrent, static_cast(value)); - break; - case MetaTypeId::TYPE_STRING: - m_visitor.enterString(*m_fieldCurrent, std::to_string(value)); - break; - case MetaTypeId::TYPE_ENUM: - m_visitor.enterEnum(*m_fieldCurrent, static_cast(value)); - break; - case MetaTypeId::TYPE_ARRAY_BOOL: - m_arrayBool.push_back(value); - break; - case MetaTypeId::TYPE_ARRAY_INT8: - m_arrayInt8.push_back(static_cast(value)); - break; - case MetaTypeId::TYPE_ARRAY_INT16: - m_arrayInt16.push_back(static_cast(value)); - break; - case MetaTypeId::TYPE_ARRAY_UINT16: - m_arrayUInt16.push_back(static_cast(value)); - break; - case MetaTypeId::TYPE_ARRAY_INT32: - m_arrayInt32.push_back(static_cast(value)); - break; - case MetaTypeId::TYPE_ARRAY_UINT32: - m_arrayUInt32.push_back(static_cast(value)); - break; - case MetaTypeId::TYPE_ARRAY_INT64: - m_arrayInt64.push_back(static_cast(value)); - break; - case MetaTypeId::TYPE_ARRAY_UINT64: - m_arrayUInt64.push_back(static_cast(value)); - break; - case MetaTypeId::TYPE_ARRAY_FLOAT: - m_arrayFloat.push_back(static_cast(value)); - break; - case MetaTypeId::TYPE_ARRAY_DOUBLE: - m_arrayDouble.push_back(static_cast(value)); - break; - case MetaTypeId::TYPE_ARRAY_STRING: - m_arrayString.push_back(std::to_string(value)); - break; - case MetaTypeId::TYPE_ARRAY_BYTES: - m_arrayString.push_back(std::to_string(value)); - break; - case MetaTypeId::TYPE_ARRAY_ENUM: - if (m_arrayString.empty() || !m_arrayInt32.empty()) - { + case MetaTypeId::TYPE_BOOL: +#ifndef WIN32 +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wfloat-equal" +#endif + m_visitor.enterBool(*m_fieldCurrent, value); +#ifndef WIN32 +#pragma GCC diagnostic pop +#endif + break; + case MetaTypeId::TYPE_INT8: + m_visitor.enterInt8(*m_fieldCurrent, static_cast(value)); + break; + case MetaTypeId::TYPE_UINT8: + m_visitor.enterUInt8(*m_fieldCurrent, static_cast(value)); + break; + case MetaTypeId::TYPE_INT16: + m_visitor.enterInt16(*m_fieldCurrent, static_cast(value)); + break; + case MetaTypeId::TYPE_UINT16: + m_visitor.enterUInt16(*m_fieldCurrent, static_cast(value)); + break; + case MetaTypeId::TYPE_INT32: + m_visitor.enterInt32(*m_fieldCurrent, static_cast(value)); + break; + case MetaTypeId::TYPE_UINT32: + m_visitor.enterUInt32(*m_fieldCurrent, static_cast(value)); + break; + case MetaTypeId::TYPE_INT64: + m_visitor.enterInt64(*m_fieldCurrent, static_cast(value)); + break; + case MetaTypeId::TYPE_UINT64: + m_visitor.enterUInt64(*m_fieldCurrent, static_cast(value)); + break; + case MetaTypeId::TYPE_FLOAT: + m_visitor.enterFloat(*m_fieldCurrent, static_cast(value)); + break; + case MetaTypeId::TYPE_DOUBLE: + m_visitor.enterDouble(*m_fieldCurrent, static_cast(value)); + break; + case MetaTypeId::TYPE_STRING: + m_visitor.enterString(*m_fieldCurrent, std::to_string(value)); + break; + case MetaTypeId::TYPE_ENUM: + m_visitor.enterEnum(*m_fieldCurrent, static_cast(value)); + break; + case MetaTypeId::TYPE_ARRAY_BOOL: +#ifndef WIN32 +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wfloat-equal" +#endif + m_arrayBool.push_back(value); +#ifndef WIN32 +#pragma GCC diagnostic pop +#endif + break; + case MetaTypeId::TYPE_ARRAY_INT8: + m_arrayInt8.push_back(static_cast(value)); + break; + case MetaTypeId::TYPE_ARRAY_INT16: + m_arrayInt16.push_back(static_cast(value)); + break; + case MetaTypeId::TYPE_ARRAY_UINT16: + m_arrayUInt16.push_back(static_cast(value)); + break; + case MetaTypeId::TYPE_ARRAY_INT32: m_arrayInt32.push_back(static_cast(value)); - } - else - { - const std::string& v = MetaDataGlobal::instance().getEnumAliasByValue(*m_fieldCurrent, static_cast(value)); - m_arrayString.push_back(v); - } - break; - default: - streamError << "number not expected"; - break; + break; + case MetaTypeId::TYPE_ARRAY_UINT32: + m_arrayUInt32.push_back(static_cast(value)); + break; + case MetaTypeId::TYPE_ARRAY_INT64: + m_arrayInt64.push_back(static_cast(value)); + break; + case MetaTypeId::TYPE_ARRAY_UINT64: + m_arrayUInt64.push_back(static_cast(value)); + break; + case MetaTypeId::TYPE_ARRAY_FLOAT: + m_arrayFloat.push_back(static_cast(value)); + break; + case MetaTypeId::TYPE_ARRAY_DOUBLE: + m_arrayDouble.push_back(static_cast(value)); + break; + case MetaTypeId::TYPE_ARRAY_STRING: + m_arrayString.push_back(std::to_string(value)); + break; + case MetaTypeId::TYPE_ARRAY_BYTES: + m_arrayString.push_back(std::to_string(value)); + break; + case MetaTypeId::TYPE_ARRAY_ENUM: + if (m_arrayString.empty() || !m_arrayInt32.empty()) + { + m_arrayInt32.push_back(static_cast(value)); + } + else + { + const std::string& v = MetaDataGlobal::instance().getEnumAliasByValue(*m_fieldCurrent, static_cast(value)); + m_arrayString.push_back(v); + } + break; + default: + streamError << "number not expected"; + break; } } - - void ParserJson::enterBool(bool value) { enterNumber(value); @@ -231,7 +227,6 @@ void ParserJson::enterDouble(double value) enterNumber(value); } - template<> float ParserJson::convert(const char* value, ssize_t size) { @@ -242,11 +237,13 @@ float ParserJson::convert(const char* value, ssize_t size) } else if (size == 8 && memcmp(value, "Infinity", 8) == 0) { - v = std::numeric_limits::infinity();; + v = std::numeric_limits::infinity(); + ; } else if (size == 9 && memcmp(value, "-Infinity", 9) == 0) { - v = -std::numeric_limits::infinity();; + v = -std::numeric_limits::infinity(); + ; } else { @@ -265,11 +262,13 @@ double ParserJson::convert(const char* value, ssize_t size) } else if (size == 8 && memcmp(value, "Infinity", 8) == 0) { - v = std::numeric_limits::infinity();; + v = std::numeric_limits::infinity(); + ; } else if (size == 9 && memcmp(value, "-Infinity", 9) == 0) { - v = -std::numeric_limits::infinity();; + v = -std::numeric_limits::infinity(); + ; } else { @@ -278,7 +277,6 @@ double ParserJson::convert(const char* value, ssize_t size) return v; } - void ParserJson::enterString(const char* value, ssize_t size) { if (!m_fieldCurrent) @@ -286,78 +284,78 @@ void ParserJson::enterString(const char* value, ssize_t size) // unknown key return; } - switch (m_fieldCurrent->typeId) + switch(m_fieldCurrent->typeId) { - case MetaTypeId::TYPE_BOOL: + case MetaTypeId::TYPE_BOOL: { bool v = (size == 4 && (memcmp(value, "true", 4) == 0)); m_visitor.enterBool(*m_fieldCurrent, v); } break; - case MetaTypeId::TYPE_INT8: + case MetaTypeId::TYPE_INT8: { std::int8_t v = static_cast(strtol(value, nullptr, 10)); m_visitor.enterInt8(*m_fieldCurrent, v); } break; - case MetaTypeId::TYPE_UINT8: + case MetaTypeId::TYPE_UINT8: { std::uint8_t v = static_cast(strtoul(value, nullptr, 10)); m_visitor.enterUInt8(*m_fieldCurrent, v); } break; - case MetaTypeId::TYPE_INT16: + case MetaTypeId::TYPE_INT16: { std::int16_t v = static_cast(strtol(value, nullptr, 10)); m_visitor.enterInt16(*m_fieldCurrent, v); } break; - case MetaTypeId::TYPE_UINT16: + case MetaTypeId::TYPE_UINT16: { std::uint16_t v = static_cast(strtoul(value, nullptr, 10)); m_visitor.enterUInt16(*m_fieldCurrent, v); } break; - case MetaTypeId::TYPE_INT32: + case MetaTypeId::TYPE_INT32: { - std::int32_t v = strtol(value, nullptr, 10); + std::int32_t v = static_cast(strtol(value, nullptr, 10)); m_visitor.enterInt32(*m_fieldCurrent, v); } break; - case MetaTypeId::TYPE_UINT32: + case MetaTypeId::TYPE_UINT32: { - std::uint32_t v = strtoul(value, nullptr, 10); + std::uint32_t v = static_cast(strtoul(value, nullptr, 10)); m_visitor.enterUInt32(*m_fieldCurrent, v); } break; - case MetaTypeId::TYPE_INT64: + case MetaTypeId::TYPE_INT64: { std::int64_t v = strtoll(value, nullptr, 10); m_visitor.enterInt64(*m_fieldCurrent, v); } break; - case MetaTypeId::TYPE_UINT64: + case MetaTypeId::TYPE_UINT64: { std::uint64_t v = strtoull(value, nullptr, 10); m_visitor.enterUInt64(*m_fieldCurrent, v); } break; - case MetaTypeId::TYPE_FLOAT: + case MetaTypeId::TYPE_FLOAT: { float v = convert(value, size); m_visitor.enterFloat(*m_fieldCurrent, v); } break; - case MetaTypeId::TYPE_DOUBLE: + case MetaTypeId::TYPE_DOUBLE: { double v = convert(value, size); m_visitor.enterDouble(*m_fieldCurrent, v); } break; - case MetaTypeId::TYPE_STRING: - m_visitor.enterString(*m_fieldCurrent, value, size); - break; - case MetaTypeId::TYPE_BYTES: + case MetaTypeId::TYPE_STRING: + m_visitor.enterString(*m_fieldCurrent, value, size); + break; + case MetaTypeId::TYPE_BYTES: { // convert from base64 std::vector bin; @@ -365,73 +363,73 @@ void ParserJson::enterString(const char* value, ssize_t size) m_visitor.enterBytes(*m_fieldCurrent, std::move(bin)); } break; - case MetaTypeId::TYPE_ENUM: - m_visitor.enterEnum(*m_fieldCurrent, value, size); - break; - case MetaTypeId::TYPE_ARRAY_BOOL: + case MetaTypeId::TYPE_ENUM: + m_visitor.enterEnum(*m_fieldCurrent, value, size); + break; + case MetaTypeId::TYPE_ARRAY_BOOL: { bool v = (size == 4 && (memcmp(value, "true", 4) == 0)); m_arrayBool.push_back(v); } break; - case MetaTypeId::TYPE_ARRAY_INT8: + case MetaTypeId::TYPE_ARRAY_INT8: { std::int8_t v = static_cast(strtol(value, nullptr, 10)); m_arrayInt8.push_back(v); } break; - case MetaTypeId::TYPE_ARRAY_INT16: + case MetaTypeId::TYPE_ARRAY_INT16: { std::int16_t v = static_cast(strtol(value, nullptr, 10)); m_arrayInt16.push_back(v); } break; - case MetaTypeId::TYPE_ARRAY_UINT16: + case MetaTypeId::TYPE_ARRAY_UINT16: { std::uint16_t v = static_cast(strtoul(value, nullptr, 10)); m_arrayUInt16.push_back(v); } break; - case MetaTypeId::TYPE_ARRAY_INT32: + case MetaTypeId::TYPE_ARRAY_INT32: { - std::int32_t v = strtol(value, nullptr, 10); + std::int32_t v = static_cast(strtol(value, nullptr, 10)); m_arrayInt32.push_back(v); } break; - case MetaTypeId::TYPE_ARRAY_UINT32: + case MetaTypeId::TYPE_ARRAY_UINT32: { - std::uint32_t v = strtoul(value, nullptr, 10); + std::uint32_t v = static_cast(strtoul(value, nullptr, 10)); m_arrayUInt32.push_back(v); } break; - case MetaTypeId::TYPE_ARRAY_INT64: + case MetaTypeId::TYPE_ARRAY_INT64: { std::int64_t v = strtoll(value, nullptr, 10); m_arrayInt64.push_back(v); } break; - case MetaTypeId::TYPE_ARRAY_UINT64: + case MetaTypeId::TYPE_ARRAY_UINT64: { std::uint64_t v = strtoull(value, nullptr, 10); m_arrayUInt64.push_back(v); } break; - case MetaTypeId::TYPE_ARRAY_FLOAT: + case MetaTypeId::TYPE_ARRAY_FLOAT: { float v = convert(value, size); m_arrayFloat.push_back(v); } break; - case MetaTypeId::TYPE_ARRAY_DOUBLE: + case MetaTypeId::TYPE_ARRAY_DOUBLE: { double v = convert(value, size); m_arrayDouble.push_back(v); } break; - case MetaTypeId::TYPE_ARRAY_STRING: - m_arrayString.emplace_back(value, size); - break; - case MetaTypeId::TYPE_ARRAY_BYTES: + case MetaTypeId::TYPE_ARRAY_STRING: + m_arrayString.emplace_back(value, size); + break; + case MetaTypeId::TYPE_ARRAY_BYTES: { // convert from base64 std::vector bin; @@ -439,24 +437,23 @@ void ParserJson::enterString(const char* value, ssize_t size) m_arrayBytes.emplace_back(std::move(bin)); } break; - case MetaTypeId::TYPE_ARRAY_ENUM: - if (!m_arrayString.empty() || m_arrayInt32.empty()) - { - m_arrayString.emplace_back(value, size); - } - else - { - std::int32_t valueInt = MetaDataGlobal::instance().getEnumValueByName(*m_fieldCurrent, std::string(value, size)); - m_arrayInt32.push_back(valueInt); - } - break; - default: - streamError << "string not expected"; - break; + case MetaTypeId::TYPE_ARRAY_ENUM: + if (!m_arrayString.empty() || m_arrayInt32.empty()) + { + m_arrayString.emplace_back(value, size); + } + else + { + std::int32_t valueInt = MetaDataGlobal::instance().getEnumValueByName(*m_fieldCurrent, std::string(value, size)); + m_arrayInt32.push_back(valueInt); + } + break; + default: + streamError << "string not expected"; + break; } } - void ParserJson::enterString(std::string&& value) { if (!m_fieldCurrent) @@ -464,78 +461,78 @@ void ParserJson::enterString(std::string&& value) // unknown key return; } - switch (m_fieldCurrent->typeId) + switch(m_fieldCurrent->typeId) { - case MetaTypeId::TYPE_BOOL: + case MetaTypeId::TYPE_BOOL: { bool v = (value.size() == 4 && (memcmp(value.c_str(), "true", 4) == 0)); m_visitor.enterBool(*m_fieldCurrent, v); } break; - case MetaTypeId::TYPE_INT8: + case MetaTypeId::TYPE_INT8: { std::int8_t v = static_cast(strtol(value.c_str(), nullptr, 10)); m_visitor.enterInt8(*m_fieldCurrent, v); } break; - case MetaTypeId::TYPE_UINT8: + case MetaTypeId::TYPE_UINT8: { std::uint8_t v = static_cast(strtoul(value.c_str(), nullptr, 10)); m_visitor.enterUInt8(*m_fieldCurrent, v); } break; - case MetaTypeId::TYPE_INT16: + case MetaTypeId::TYPE_INT16: { std::int16_t v = static_cast(strtol(value.c_str(), nullptr, 10)); m_visitor.enterInt16(*m_fieldCurrent, v); } break; - case MetaTypeId::TYPE_UINT16: + case MetaTypeId::TYPE_UINT16: { std::uint16_t v = static_cast(strtoul(value.c_str(), nullptr, 10)); m_visitor.enterUInt16(*m_fieldCurrent, v); } break; - case MetaTypeId::TYPE_INT32: + case MetaTypeId::TYPE_INT32: { - std::int32_t v = strtol(value.c_str(), nullptr, 10); + std::int32_t v = static_cast(strtol(value.c_str(), nullptr, 10)); m_visitor.enterInt32(*m_fieldCurrent, v); } break; - case MetaTypeId::TYPE_UINT32: + case MetaTypeId::TYPE_UINT32: { - std::uint32_t v = strtoul(value.c_str(), nullptr, 10); + std::uint32_t v = static_cast(strtoul(value.c_str(), nullptr, 10)); m_visitor.enterUInt32(*m_fieldCurrent, v); } break; - case MetaTypeId::TYPE_INT64: + case MetaTypeId::TYPE_INT64: { std::int64_t v = strtoll(value.c_str(), nullptr, 10); m_visitor.enterInt64(*m_fieldCurrent, v); } break; - case MetaTypeId::TYPE_UINT64: + case MetaTypeId::TYPE_UINT64: { std::uint64_t v = strtoull(value.c_str(), nullptr, 10); m_visitor.enterUInt64(*m_fieldCurrent, v); } break; - case MetaTypeId::TYPE_FLOAT: + case MetaTypeId::TYPE_FLOAT: { float v = convert(value.c_str(), value.size()); m_visitor.enterFloat(*m_fieldCurrent, v); } break; - case MetaTypeId::TYPE_DOUBLE: + case MetaTypeId::TYPE_DOUBLE: { double v = convert(value.c_str(), value.size()); m_visitor.enterDouble(*m_fieldCurrent, v); } break; - case MetaTypeId::TYPE_STRING: - m_visitor.enterString(*m_fieldCurrent, std::move(value)); - break; - case MetaTypeId::TYPE_BYTES: + case MetaTypeId::TYPE_STRING: + m_visitor.enterString(*m_fieldCurrent, std::move(value)); + break; + case MetaTypeId::TYPE_BYTES: { // convert from base64 std::vector bin; @@ -543,55 +540,55 @@ void ParserJson::enterString(std::string&& value) m_visitor.enterBytes(*m_fieldCurrent, std::move(bin)); } break; - case MetaTypeId::TYPE_ENUM: - m_visitor.enterEnum(*m_fieldCurrent, std::move(value)); - break; - case MetaTypeId::TYPE_ARRAY_BOOL: + case MetaTypeId::TYPE_ENUM: + m_visitor.enterEnum(*m_fieldCurrent, std::move(value)); + break; + case MetaTypeId::TYPE_ARRAY_BOOL: { bool v = (value.size() == 4 && (memcmp(value.c_str(), "true", 4) == 0)); m_arrayBool.push_back(v); } break; - case MetaTypeId::TYPE_ARRAY_INT32: + case MetaTypeId::TYPE_ARRAY_INT32: { - std::int32_t v = strtol(value.c_str(), nullptr, 10); + std::int32_t v = static_cast(strtol(value.c_str(), nullptr, 10)); m_arrayInt32.push_back(v); } break; - case MetaTypeId::TYPE_ARRAY_UINT32: + case MetaTypeId::TYPE_ARRAY_UINT32: { - std::uint32_t v = strtoul(value.c_str(), nullptr, 10); + std::uint32_t v = static_cast(strtoul(value.c_str(), nullptr, 10)); m_arrayUInt32.push_back(v); } break; - case MetaTypeId::TYPE_ARRAY_INT64: + case MetaTypeId::TYPE_ARRAY_INT64: { std::int64_t v = strtoll(value.c_str(), nullptr, 10); m_arrayInt64.push_back(v); } break; - case MetaTypeId::TYPE_ARRAY_UINT64: + case MetaTypeId::TYPE_ARRAY_UINT64: { std::uint64_t v = strtoull(value.c_str(), nullptr, 10); m_arrayUInt64.push_back(v); } break; - case MetaTypeId::TYPE_ARRAY_FLOAT: + case MetaTypeId::TYPE_ARRAY_FLOAT: { float v = convert(value.c_str(), value.size()); m_arrayFloat.push_back(v); } break; - case MetaTypeId::TYPE_ARRAY_DOUBLE: + case MetaTypeId::TYPE_ARRAY_DOUBLE: { double v = convert(value.c_str(), value.size()); m_arrayDouble.push_back(v); } break; - case MetaTypeId::TYPE_ARRAY_STRING: - m_arrayString.push_back(std::move(value)); - break; - case MetaTypeId::TYPE_ARRAY_BYTES: + case MetaTypeId::TYPE_ARRAY_STRING: + m_arrayString.push_back(std::move(value)); + break; + case MetaTypeId::TYPE_ARRAY_BYTES: { // convert from base64 std::vector bin; @@ -599,79 +596,79 @@ void ParserJson::enterString(std::string&& value) m_arrayBytes.emplace_back(std::move(bin)); } break; - case MetaTypeId::TYPE_ARRAY_ENUM: - if (!m_arrayString.empty() || m_arrayInt32.empty()) - { - m_arrayString.push_back(std::move(value)); - } - else - { - std::int32_t valueInt = MetaDataGlobal::instance().getEnumValueByName(*m_fieldCurrent, value); - m_arrayInt32.push_back(valueInt); - } - break; - default: - streamError << "string not expected"; - break; + case MetaTypeId::TYPE_ARRAY_ENUM: + if (!m_arrayString.empty() || m_arrayInt32.empty()) + { + m_arrayString.push_back(std::move(value)); + } + else + { + std::int32_t valueInt = MetaDataGlobal::instance().getEnumValueByName(*m_fieldCurrent, value); + m_arrayInt32.push_back(valueInt); + } + break; + default: + streamError << "string not expected"; + break; } } void ParserJson::enterArray() { - if (m_fieldCurrent && ((int)m_fieldCurrent->typeId & (int)MetaTypeId::OFFSET_ARRAY_FLAG)) + if (m_fieldCurrent && (static_cast(m_fieldCurrent->typeId) & static_cast(MetaTypeId::OFFSET_ARRAY_FLAG))) { - switch (m_fieldCurrent->typeId) - { - case MetaTypeId::TYPE_ARRAY_BOOL: - m_arrayBool.clear(); - break; - case MetaTypeId::TYPE_ARRAY_INT8: - m_arrayInt8.clear(); - break; - case MetaTypeId::TYPE_ARRAY_INT16: - m_arrayInt16.clear(); - break; - case MetaTypeId::TYPE_ARRAY_UINT16: - m_arrayUInt16.clear(); - break; - case MetaTypeId::TYPE_ARRAY_INT32: - m_arrayInt32.clear(); - break; - case MetaTypeId::TYPE_ARRAY_UINT32: - m_arrayUInt32.clear(); - break; - case MetaTypeId::TYPE_ARRAY_INT64: - m_arrayInt64.clear(); - break; - case MetaTypeId::TYPE_ARRAY_UINT64: - m_arrayUInt64.clear(); - break; - case MetaTypeId::TYPE_ARRAY_FLOAT: - m_arrayFloat.clear(); - break; - case MetaTypeId::TYPE_ARRAY_DOUBLE: - m_arrayDouble.clear(); - break; - case MetaTypeId::TYPE_ARRAY_STRING: - m_arrayString.clear(); - break; - case MetaTypeId::TYPE_ARRAY_BYTES: - m_arrayString.clear(); - break; - case MetaTypeId::TYPE_ARRAY_ENUM: - m_arrayInt32.clear(); - m_arrayString.clear(); - break; - case MetaTypeId::TYPE_ARRAY_STRUCT: - m_visitor.enterArrayStruct(*m_fieldCurrent); - m_stack.emplace_back(m_fieldCurrent); - m_fieldCurrent = m_fieldCurrent->fieldWithoutArray; -// m_stack.emplace_back(m_fieldCurrent); - m_structCurrent = nullptr; - break; - default: - assert(false); - break; + switch(m_fieldCurrent->typeId) + { + case MetaTypeId::TYPE_ARRAY_BOOL: + m_arrayBool.clear(); + break; + case MetaTypeId::TYPE_ARRAY_INT8: + m_arrayInt8.clear(); + break; + case MetaTypeId::TYPE_ARRAY_INT16: + m_arrayInt16.clear(); + break; + case MetaTypeId::TYPE_ARRAY_UINT16: + m_arrayUInt16.clear(); + break; + case MetaTypeId::TYPE_ARRAY_INT32: + m_arrayInt32.clear(); + break; + case MetaTypeId::TYPE_ARRAY_UINT32: + m_arrayUInt32.clear(); + break; + case MetaTypeId::TYPE_ARRAY_INT64: + m_arrayInt64.clear(); + break; + case MetaTypeId::TYPE_ARRAY_UINT64: + m_arrayUInt64.clear(); + break; + case MetaTypeId::TYPE_ARRAY_FLOAT: + m_arrayFloat.clear(); + break; + case MetaTypeId::TYPE_ARRAY_DOUBLE: + m_arrayDouble.clear(); + break; + case MetaTypeId::TYPE_ARRAY_STRING: + m_arrayString.clear(); + break; + case MetaTypeId::TYPE_ARRAY_BYTES: + m_arrayString.clear(); + break; + case MetaTypeId::TYPE_ARRAY_ENUM: + m_arrayInt32.clear(); + m_arrayString.clear(); + break; + case MetaTypeId::TYPE_ARRAY_STRUCT: + m_visitor.enterArrayStruct(*m_fieldCurrent); + m_stack.emplace_back(m_fieldCurrent); + m_fieldCurrent = m_fieldCurrent->fieldWithoutArray; + // m_stack.emplace_back(m_fieldCurrent); + m_structCurrent = nullptr; + break; + default: + assert(false); + break; } } } @@ -684,76 +681,76 @@ void ParserJson::exitArray() return; } - if ((int)m_fieldCurrent->typeId & (int)MetaTypeId::OFFSET_ARRAY_FLAG) + if (static_cast(m_fieldCurrent->typeId) & static_cast(MetaTypeId::OFFSET_ARRAY_FLAG)) { - switch (m_fieldCurrent->typeId) - { - case MetaTypeId::TYPE_ARRAY_BOOL: - m_visitor.enterArrayBoolMove(*m_fieldCurrent, std::move(m_arrayBool)); - m_arrayBool.clear(); - break; - case MetaTypeId::TYPE_ARRAY_INT8: - m_visitor.enterArrayInt8(*m_fieldCurrent, std::move(m_arrayInt8)); - m_arrayInt8.clear(); - break; - case MetaTypeId::TYPE_ARRAY_INT16: - m_visitor.enterArrayInt16(*m_fieldCurrent, std::move(m_arrayInt16)); - m_arrayInt16.clear(); - break; - case MetaTypeId::TYPE_ARRAY_UINT16: - m_visitor.enterArrayUInt16(*m_fieldCurrent, std::move(m_arrayUInt16)); - m_arrayUInt16.clear(); - break; - case MetaTypeId::TYPE_ARRAY_INT32: - m_visitor.enterArrayInt32(*m_fieldCurrent, std::move(m_arrayInt32)); - m_arrayInt32.clear(); - break; - case MetaTypeId::TYPE_ARRAY_UINT32: - m_visitor.enterArrayUInt32(*m_fieldCurrent, std::move(m_arrayUInt32)); - m_arrayUInt32.clear(); - break; - case MetaTypeId::TYPE_ARRAY_INT64: - m_visitor.enterArrayInt64(*m_fieldCurrent, std::move(m_arrayInt64)); - m_arrayInt64.clear(); - break; - case MetaTypeId::TYPE_ARRAY_UINT64: - m_visitor.enterArrayUInt64(*m_fieldCurrent, std::move(m_arrayUInt64)); - m_arrayUInt64.clear(); - break; - case MetaTypeId::TYPE_ARRAY_FLOAT: - m_visitor.enterArrayFloat(*m_fieldCurrent, std::move(m_arrayFloat)); - m_arrayFloat.clear(); - break; - case MetaTypeId::TYPE_ARRAY_DOUBLE: - m_visitor.enterArrayDouble(*m_fieldCurrent, std::move(m_arrayDouble)); - m_arrayDouble.clear(); - break; - case MetaTypeId::TYPE_ARRAY_STRING: - m_visitor.enterArrayStringMove(*m_fieldCurrent, std::move(m_arrayString)); - m_arrayString.clear(); - break; - case MetaTypeId::TYPE_ARRAY_BYTES: - m_visitor.enterArrayBytesMove(*m_fieldCurrent, std::move(m_arrayBytes)); - m_arrayBytes.clear(); - break; - case MetaTypeId::TYPE_ARRAY_ENUM: - if (!m_arrayString.empty()) - { - m_visitor.enterArrayEnum(*m_fieldCurrent, std::move(m_arrayString)); - } - else - { - m_visitor.enterArrayEnum(*m_fieldCurrent, std::move(m_arrayInt32)); - } - m_arrayInt32.clear(); - m_arrayString.clear(); - break; - case MetaTypeId::TYPE_ARRAY_STRUCT: - assert(false); - break; - default: - assert(false); - break; + switch(m_fieldCurrent->typeId) + { + case MetaTypeId::TYPE_ARRAY_BOOL: + m_visitor.enterArrayBoolMove(*m_fieldCurrent, std::move(m_arrayBool)); + m_arrayBool.clear(); + break; + case MetaTypeId::TYPE_ARRAY_INT8: + m_visitor.enterArrayInt8(*m_fieldCurrent, std::move(m_arrayInt8)); + m_arrayInt8.clear(); + break; + case MetaTypeId::TYPE_ARRAY_INT16: + m_visitor.enterArrayInt16(*m_fieldCurrent, std::move(m_arrayInt16)); + m_arrayInt16.clear(); + break; + case MetaTypeId::TYPE_ARRAY_UINT16: + m_visitor.enterArrayUInt16(*m_fieldCurrent, std::move(m_arrayUInt16)); + m_arrayUInt16.clear(); + break; + case MetaTypeId::TYPE_ARRAY_INT32: + m_visitor.enterArrayInt32(*m_fieldCurrent, std::move(m_arrayInt32)); + m_arrayInt32.clear(); + break; + case MetaTypeId::TYPE_ARRAY_UINT32: + m_visitor.enterArrayUInt32(*m_fieldCurrent, std::move(m_arrayUInt32)); + m_arrayUInt32.clear(); + break; + case MetaTypeId::TYPE_ARRAY_INT64: + m_visitor.enterArrayInt64(*m_fieldCurrent, std::move(m_arrayInt64)); + m_arrayInt64.clear(); + break; + case MetaTypeId::TYPE_ARRAY_UINT64: + m_visitor.enterArrayUInt64(*m_fieldCurrent, std::move(m_arrayUInt64)); + m_arrayUInt64.clear(); + break; + case MetaTypeId::TYPE_ARRAY_FLOAT: + m_visitor.enterArrayFloat(*m_fieldCurrent, std::move(m_arrayFloat)); + m_arrayFloat.clear(); + break; + case MetaTypeId::TYPE_ARRAY_DOUBLE: + m_visitor.enterArrayDouble(*m_fieldCurrent, std::move(m_arrayDouble)); + m_arrayDouble.clear(); + break; + case MetaTypeId::TYPE_ARRAY_STRING: + m_visitor.enterArrayStringMove(*m_fieldCurrent, std::move(m_arrayString)); + m_arrayString.clear(); + break; + case MetaTypeId::TYPE_ARRAY_BYTES: + m_visitor.enterArrayBytesMove(*m_fieldCurrent, std::move(m_arrayBytes)); + m_arrayBytes.clear(); + break; + case MetaTypeId::TYPE_ARRAY_ENUM: + if (!m_arrayString.empty()) + { + m_visitor.enterArrayEnum(*m_fieldCurrent, std::move(m_arrayString)); + } + else + { + m_visitor.enterArrayEnum(*m_fieldCurrent, std::move(m_arrayInt32)); + } + m_arrayInt32.clear(); + m_arrayString.clear(); + break; + case MetaTypeId::TYPE_ARRAY_STRUCT: + assert(false); + break; + default: + assert(false); + break; } } else if (m_fieldCurrent->typeId == MetaTypeId::TYPE_STRUCT) @@ -762,7 +759,7 @@ void ParserJson::exitArray() m_fieldCurrent = nullptr; if (!m_stack.empty()) { -// m_stack.pop_back(); + // m_stack.pop_back(); m_fieldCurrent = m_stack.back(); if (m_fieldCurrent) { @@ -817,7 +814,7 @@ void ParserJson::exitObject() if (!m_stack.empty()) { m_fieldCurrent = m_stack.back(); - // the outer object shall not trigger exitStruct + // the outer object shall not trigger exitStruct if (m_fieldCurrent && (m_stack.size() > 1)) { m_visitor.exitStruct(*m_fieldCurrent); @@ -829,7 +826,7 @@ void ParserJson::exitObject() m_fieldCurrent = m_stack.back(); if (m_fieldCurrent) { - if ((int)m_fieldCurrent->typeId & (int)MetaTypeId::OFFSET_ARRAY_FLAG) + if (static_cast(m_fieldCurrent->typeId) & static_cast(MetaTypeId::OFFSET_ARRAY_FLAG)) { m_fieldCurrent = m_fieldCurrent->fieldWithoutArray; } @@ -859,4 +856,4 @@ void ParserJson::finished() { } -} // namespace finalmq +} // namespace finalmq diff --git a/src/serializejson/SerializerJson.cpp b/src/serializejson/SerializerJson.cpp index e3e6f09e..23f4ddc8 100644 --- a/src/serializejson/SerializerJson.cpp +++ b/src/serializejson/SerializerJson.cpp @@ -20,41 +20,33 @@ //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. - #include "finalmq/serializejson/SerializerJson.h" -#include "finalmq/serialize/ParserAbortAndIndex.h" -#include "finalmq/serialize/ParserProcessDefaultValues.h" -#include "finalmq/metadata/MetaData.h" -#include "finalmq/helpers/base64.h" -#include #include #include -namespace finalmq { +#include +#include "finalmq/helpers/base64.h" +#include "finalmq/metadata/MetaData.h" +#include "finalmq/serialize/ParserAbortAndIndex.h" +#include "finalmq/serialize/ParserProcessDefaultValues.h" +namespace finalmq +{ SerializerJson::SerializerJson(IZeroCopyBuffer& buffer, int maxBlockSize, bool enumAsString, bool skipDefaultValues) - : ParserConverter() - , m_internal(buffer, maxBlockSize, enumAsString) - , m_parserAbortAndIndex() - , m_parserProcessDefaultValues() + : ParserConverter(), m_internal(buffer, maxBlockSize, enumAsString), m_parserAbortAndIndex(), m_parserProcessDefaultValues() { m_parserAbortAndIndex = std::make_unique(&m_internal); m_parserProcessDefaultValues = std::make_unique(skipDefaultValues, m_parserAbortAndIndex.get()); ParserConverter::setVisitor(*m_parserProcessDefaultValues); } - - SerializerJson::Internal::Internal(IZeroCopyBuffer& buffer, int maxBlockSize, bool enumAsString) - : m_uniqueJsonBuilder(std::make_unique(buffer, maxBlockSize)) - , m_jsonBuilder(*m_uniqueJsonBuilder.get()) - , m_enumAsString(enumAsString) + : m_uniqueJsonBuilder(std::make_unique(buffer, maxBlockSize)), m_jsonBuilder(*m_uniqueJsonBuilder.get()), m_enumAsString(enumAsString) { } - void SerializerJson::Internal::setKey(const MetaField& field) { const std::string& name = field.name; @@ -64,7 +56,6 @@ void SerializerJson::Internal::setKey(const MetaField& field) } } - // IParserVisitor void SerializerJson::Internal::notifyError(const char* /*str*/, const char* /*message*/) { @@ -76,7 +67,6 @@ void SerializerJson::Internal::startStruct(const MetaStruct& /*stru*/) m_jsonBuilder.enterObject(); } - void SerializerJson::Internal::finished() { // outer curly brackets @@ -84,7 +74,6 @@ void SerializerJson::Internal::finished() m_jsonBuilder.finished(); } - void SerializerJson::Internal::enterStruct(const MetaField& field) { setKey(field); @@ -102,7 +91,6 @@ void SerializerJson::Internal::enterStructNull(const MetaField& field) m_jsonBuilder.enterNull(); } - void SerializerJson::Internal::enterArrayStruct(const MetaField& field) { setKey(field); @@ -114,7 +102,6 @@ void SerializerJson::Internal::exitArrayStruct(const MetaField& /*field*/) m_jsonBuilder.exitArray(); } - void SerializerJson::Internal::enterBool(const MetaField& field, bool value) { assert(field.typeId == MetaTypeId::TYPE_BOOL); @@ -180,6 +167,10 @@ void SerializerJson::Internal::enterUInt64(const MetaField& field, std::uint64_t void SerializerJson::Internal::handleDouble(double value) { +#ifndef WIN32 +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wfloat-equal" +#endif if (std::isnan(value)) { m_jsonBuilder.enterString("NaN"); @@ -196,6 +187,9 @@ void SerializerJson::Internal::handleDouble(double value) { m_jsonBuilder.enterDouble(value); } +#ifndef WIN32 +#pragma GCC diagnostic pop +#endif } void SerializerJson::Internal::enterFloat(const MetaField& field, float value) @@ -261,7 +255,6 @@ void SerializerJson::Internal::enterEnum(const MetaField& field, std::int32_t va } } - void SerializerJson::Internal::enterEnum(const MetaField& field, std::string&& value) { assert(field.typeId == MetaTypeId::TYPE_ENUM); @@ -297,7 +290,7 @@ void SerializerJson::Internal::enterArrayBoolMove(const MetaField& field, std::v assert(field.typeId == MetaTypeId::TYPE_ARRAY_BOOL); setKey(field); m_jsonBuilder.enterArray(); - std::for_each(value.begin(), value.end(), [this] (bool entry) { + std::for_each(value.begin(), value.end(), [this](bool entry) { m_jsonBuilder.enterBool(entry); }); m_jsonBuilder.exitArray(); @@ -308,7 +301,7 @@ void SerializerJson::Internal::enterArrayBool(const MetaField& field, const std: assert(field.typeId == MetaTypeId::TYPE_ARRAY_BOOL); setKey(field); m_jsonBuilder.enterArray(); - std::for_each(value.begin(), value.end(), [this] (bool entry) { + std::for_each(value.begin(), value.end(), [this](bool entry) { m_jsonBuilder.enterBool(entry); }); m_jsonBuilder.exitArray(); @@ -324,7 +317,7 @@ void SerializerJson::Internal::enterArrayInt8(const MetaField& field, const std: assert(field.typeId == MetaTypeId::TYPE_ARRAY_INT8); setKey(field); m_jsonBuilder.enterArray(); - std::for_each(value, value + size, [this] (std::int8_t entry) { + std::for_each(value, value + size, [this](std::int8_t entry) { m_jsonBuilder.enterInt32(entry); }); m_jsonBuilder.exitArray(); @@ -342,7 +335,7 @@ void SerializerJson::Internal::enterArrayInt16(const MetaField& field, const std m_jsonBuilder.enterArray(); std::for_each(value, value + size, [this](std::int16_t entry) { m_jsonBuilder.enterInt32(entry); - }); + }); m_jsonBuilder.exitArray(); } @@ -358,7 +351,7 @@ void SerializerJson::Internal::enterArrayUInt16(const MetaField& field, const st m_jsonBuilder.enterArray(); std::for_each(value, value + size, [this](std::uint16_t entry) { m_jsonBuilder.enterUInt32(entry); - }); + }); m_jsonBuilder.exitArray(); } @@ -374,7 +367,7 @@ void SerializerJson::Internal::enterArrayInt32(const MetaField& field, const std m_jsonBuilder.enterArray(); std::for_each(value, value + size, [this](std::int32_t entry) { m_jsonBuilder.enterInt32(entry); - }); + }); m_jsonBuilder.exitArray(); } @@ -390,7 +383,7 @@ void SerializerJson::Internal::enterArrayUInt32(const MetaField& field, const st m_jsonBuilder.enterArray(); std::for_each(value, value + size, [this](std::uint32_t entry) { m_jsonBuilder.enterUInt32(entry); - }); + }); m_jsonBuilder.exitArray(); } @@ -404,7 +397,7 @@ void SerializerJson::Internal::enterArrayInt64(const MetaField& field, const std assert(field.typeId == MetaTypeId::TYPE_ARRAY_INT64); setKey(field); m_jsonBuilder.enterArray(); - std::for_each(value, value + size, [this] (std::int64_t entry) { + std::for_each(value, value + size, [this](std::int64_t entry) { m_jsonBuilder.enterString(std::to_string(entry)); }); m_jsonBuilder.exitArray(); @@ -420,7 +413,7 @@ void SerializerJson::Internal::enterArrayUInt64(const MetaField& field, const st assert(field.typeId == MetaTypeId::TYPE_ARRAY_UINT64); setKey(field); m_jsonBuilder.enterArray(); - std::for_each(value, value + size, [this] (std::uint64_t entry) { + std::for_each(value, value + size, [this](std::uint64_t entry) { m_jsonBuilder.enterString(std::to_string(entry)); }); m_jsonBuilder.exitArray(); @@ -436,7 +429,7 @@ void SerializerJson::Internal::enterArrayFloat(const MetaField& field, const flo assert(field.typeId == MetaTypeId::TYPE_ARRAY_FLOAT); setKey(field); m_jsonBuilder.enterArray(); - std::for_each(value, value + size, [this] (float entry) { + std::for_each(value, value + size, [this](float entry) { handleDouble(entry); }); m_jsonBuilder.exitArray(); @@ -452,7 +445,7 @@ void SerializerJson::Internal::enterArrayDouble(const MetaField& field, const do assert(field.typeId == MetaTypeId::TYPE_ARRAY_DOUBLE); setKey(field); m_jsonBuilder.enterArray(); - std::for_each(value, value + size, [this] (double entry) { + std::for_each(value, value + size, [this](double entry) { handleDouble(entry); }); m_jsonBuilder.exitArray(); @@ -468,7 +461,7 @@ void SerializerJson::Internal::enterArrayString(const MetaField& field, const st assert(field.typeId == MetaTypeId::TYPE_ARRAY_STRING); setKey(field); m_jsonBuilder.enterArray(); - std::for_each(value.begin(), value.end(), [this] (const std::string& entry) { + std::for_each(value.begin(), value.end(), [this](const std::string& entry) { m_jsonBuilder.enterString(entry.c_str(), entry.size()); }); m_jsonBuilder.exitArray(); @@ -484,7 +477,7 @@ void SerializerJson::Internal::enterArrayBytes(const MetaField& field, const std assert(field.typeId == MetaTypeId::TYPE_ARRAY_BYTES); setKey(field); m_jsonBuilder.enterArray(); - std::for_each(value.begin(), value.end(), [this] (const Bytes& entry) { + std::for_each(value.begin(), value.end(), [this](const Bytes& entry) { // convert to base64 std::string base64; Base64::encode(entry, base64); @@ -506,14 +499,14 @@ void SerializerJson::Internal::enterArrayEnum(const MetaField& field, const std: if (m_enumAsString) { - std::for_each(value, value + size, [this, &field] (std::int32_t entry) { + std::for_each(value, value + size, [this, &field](std::int32_t entry) { const std::string& name = MetaDataGlobal::instance().getEnumAliasByValue(field, entry); m_jsonBuilder.enterString(name.c_str(), name.size()); }); } else { - std::for_each(value, value + size, [this] (std::int32_t entry) { + std::for_each(value, value + size, [this](std::int32_t entry) { m_jsonBuilder.enterInt32(entry); }); } @@ -534,20 +527,19 @@ void SerializerJson::Internal::enterArrayEnum(const MetaField& field, const std: if (m_enumAsString) { - std::for_each(value.begin(), value.end(), [this] (const std::string& entry) { + std::for_each(value.begin(), value.end(), [this](const std::string& entry) { m_jsonBuilder.enterString(entry.c_str(), entry.size()); }); } else { - std::for_each(value.begin(), value.end(), [this, &field] (const std::string& entry) { + std::for_each(value.begin(), value.end(), [this, &field](const std::string& entry) { std::int32_t v = MetaDataGlobal::instance().getEnumValueByName(field, entry); m_jsonBuilder.enterInt32(v); }); - } m_jsonBuilder.exitArray(); } -} // namespace finalmq +} // namespace finalmq diff --git a/src/serializeproto/ParserProto.cpp b/src/serializeproto/ParserProto.cpp index 21e0b223..9c2dd981 100644 --- a/src/serializeproto/ParserProto.cpp +++ b/src/serializeproto/ParserProto.cpp @@ -20,61 +20,54 @@ //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. - #include "finalmq/serializeproto/ParserProto.h" -#include "finalmq/metadata/MetaData.h" -#include "finalmq/helpers/FmqDefines.h" +#include #include #include -#include +#include "finalmq/helpers/FmqDefines.h" +#include "finalmq/metadata/MetaData.h" - -namespace finalmq { - +namespace finalmq +{ static constexpr int INDEX2ID = 1; - ParserProto::ParserProto(IParserVisitor& visitor, const char* ptr, ssize_t size) - : m_ptr(ptr) - , m_size(size) - , m_visitor(visitor) + : m_ptr(ptr), m_size(size), m_visitor(visitor) { } - template bool ParserProto::parseValue(T& value, bool zz) { bool ok = true; WireType wireType = static_cast(m_tag & 0x7); m_tag = 0; - switch (wireType) + switch(wireType) { - case WIRETYPE_VARINT: - value = static_cast(parseVarint()); - if (zz) - { - value = static_cast(zigzag(value)); - } - break; - case WIRETYPE_FIXED32: - value = static_cast(parseFixed()); - break; - case WIRETYPE_FIXED64: - value = static_cast(parseFixed()); - break; - default: - skip(wireType); - ok = false; - break; + case WIRETYPE_VARINT: + value = static_cast(parseVarint()); + if (zz) + { + value = static_cast(zigzag(value)); + } + break; + case WIRETYPE_FIXED32: + value = static_cast(parseFixed()); + break; + case WIRETYPE_FIXED64: + value = static_cast(parseFixed()); + break; + default: + skip(wireType); + ok = false; + break; } return ok; } - //template //bool ParserProto::parseZigZagValue(T& value) //{ @@ -103,8 +96,6 @@ bool ParserProto::parseValue(T& value, bool zz) // return ok; //} - - bool ParserProto::parseString(const char*& buffer, ssize_t& size) { bool ok = true; @@ -137,8 +128,6 @@ bool ParserProto::parseString(const char*& buffer, ssize_t& size) return ok; } - - void ParserProto::parseStructWire(const MetaField& field) { WireType wireType = static_cast(m_tag & 0x7); @@ -184,7 +173,6 @@ void ParserProto::parseStructWire(const MetaField& field) } } - template bool ParserProto::parseFixedValue(T& value) { @@ -214,34 +202,34 @@ bool ParserProto::parseArrayFixed(std::vector& array) WireType wireType = static_cast(m_tag & 0x7); std::uint32_t tag = m_tag; m_tag = 0; - switch (wireType) + switch(wireType) { - case WIRETYPE: - do - { - T value = parseFixed(); - if (m_ptr) + case WIRETYPE: + do { - array.push_back(value); - if (m_size > 0) + T value = parseFixed(); + if (m_ptr) { - m_tag = static_cast(parseVarint()); + array.push_back(value); + if (m_size > 0) + { + m_tag = static_cast(parseVarint()); + } + else + { + m_tag = 0; + break; + } } else { - m_tag = 0; - break; + m_ptr = nullptr; + m_size = 0; + ok = false; } - } - else - { - m_ptr = nullptr; - m_size = 0; - ok = false; - } - } while ((m_tag == tag) && m_ptr); - break; - case WIRETYPE_LENGTH_DELIMITED: + } while ((m_tag == tag) && m_ptr); + break; + case WIRETYPE_LENGTH_DELIMITED: { int sizeBuffer = static_cast(parseVarint()); if ((sizeBuffer >= 0 && sizeBuffer <= m_size) && m_ptr) @@ -267,16 +255,15 @@ bool ParserProto::parseArrayFixed(std::vector& array) } } break; - default: - skip(wireType); - ok = false; - break; + default: + skip(wireType); + ok = false; + break; } return ok; } - template bool ParserProto::parseArrayVarint(std::vector& array) { @@ -284,35 +271,35 @@ bool ParserProto::parseArrayVarint(std::vector& array) WireType wireType = static_cast(m_tag & 0x7); std::uint32_t tag = m_tag; m_tag = 0; - switch (wireType) + switch(wireType) { - case WIRETYPE_VARINT: - do - { - std::uint64_t value = parseVarint(); - if (m_ptr) + case WIRETYPE_VARINT: + do { - T v = (ZIGZAG) ? static_cast(zigzag(value)) : static_cast(value); - array.push_back(v); - if (m_size > 0) + std::uint64_t value = parseVarint(); + if (m_ptr) { - m_tag = static_cast(parseVarint()); + T v = (ZIGZAG) ? static_cast(zigzag(value)) : static_cast(value); + array.push_back(v); + if (m_size > 0) + { + m_tag = static_cast(parseVarint()); + } + else + { + m_tag = 0; + break; + } } else { - m_tag = 0; - break; + m_ptr = nullptr; + m_size = 0; + ok = false; } - } - else - { - m_ptr = nullptr; - m_size = 0; - ok = false; - } - } while ((m_tag == tag) && m_ptr); - break; - case WIRETYPE_LENGTH_DELIMITED: + } while ((m_tag == tag) && m_ptr); + break; + case WIRETYPE_LENGTH_DELIMITED: { int sizeBuffer = static_cast(parseVarint()); if ((sizeBuffer >= 0 && sizeBuffer <= m_size) && m_ptr) @@ -334,17 +321,15 @@ bool ParserProto::parseArrayVarint(std::vector& array) } } break; - default: - skip(wireType); - ok = false; - break; + default: + skip(wireType); + ok = false; + break; } return ok; } - - template bool ParserProto::parseArrayString(std::vector& array) { @@ -394,9 +379,6 @@ bool ParserProto::parseArrayString(std::vector& array) return ok; } - - - void ParserProto::parseArrayStruct(const MetaField& field) { if (m_ptr == nullptr) @@ -418,7 +400,6 @@ void ParserProto::parseArrayStruct(const MetaField& field) m_tag = 0; if (wireType == WIRETYPE_LENGTH_DELIMITED) { - const MetaField* fieldWithoutArray = field.fieldWithoutArray; assert(fieldWithoutArray); m_visitor.enterArrayStruct(field); @@ -468,7 +449,6 @@ void ParserProto::parseArrayStruct(const MetaField& field) } } - bool ParserProto::parseStruct(const std::string& typeName) { if (!m_ptr || m_size < 0) @@ -491,7 +471,6 @@ bool ParserProto::parseStruct(const std::string& typeName) return res; } - bool ParserProto::parseStructIntern(const MetaStruct& stru) { if (!m_ptr || m_size < 0) @@ -513,11 +492,11 @@ bool ParserProto::parseStructIntern(const MetaStruct& stru) const MetaField* field = stru.getFieldByIndex(index); if (field) { - switch (field->typeId) + switch(field->typeId) { - case MetaTypeId::TYPE_NONE: - break; - case MetaTypeId::TYPE_BOOL: + case MetaTypeId::TYPE_NONE: + break; + case MetaTypeId::TYPE_BOOL: { bool value = false; bool ok = parseValue(value, false); @@ -527,7 +506,7 @@ bool ParserProto::parseStructIntern(const MetaStruct& stru) } } break; - case MetaTypeId::TYPE_INT8: + case MetaTypeId::TYPE_INT8: { std::int32_t value = 0; bool zz = (field->flags & METAFLAG_PROTO_ZIGZAG); @@ -538,7 +517,7 @@ bool ParserProto::parseStructIntern(const MetaStruct& stru) } } break; - case MetaTypeId::TYPE_UINT8: + case MetaTypeId::TYPE_UINT8: { std::uint32_t value = 0; bool ok = parseValue(value, false); @@ -548,7 +527,7 @@ bool ParserProto::parseStructIntern(const MetaStruct& stru) } } break; - case MetaTypeId::TYPE_INT16: + case MetaTypeId::TYPE_INT16: { std::int32_t value = 0; bool zz = (field->flags & METAFLAG_PROTO_ZIGZAG); @@ -558,8 +537,8 @@ bool ParserProto::parseStructIntern(const MetaStruct& stru) m_visitor.enterInt16(*field, static_cast(value)); } } - break; - case MetaTypeId::TYPE_UINT16: + break; + case MetaTypeId::TYPE_UINT16: { std::uint32_t value = 0; bool ok = parseValue(value, false); @@ -569,7 +548,7 @@ bool ParserProto::parseStructIntern(const MetaStruct& stru) } } break; - case MetaTypeId::TYPE_INT32: + case MetaTypeId::TYPE_INT32: { std::int32_t value = 0; bool zz = (field->flags & METAFLAG_PROTO_ZIGZAG); @@ -580,7 +559,7 @@ bool ParserProto::parseStructIntern(const MetaStruct& stru) } } break; - case MetaTypeId::TYPE_UINT32: + case MetaTypeId::TYPE_UINT32: { std::uint32_t value = 0; bool ok = parseValue(value, false); @@ -590,7 +569,7 @@ bool ParserProto::parseStructIntern(const MetaStruct& stru) } } break; - case MetaTypeId::TYPE_INT64: + case MetaTypeId::TYPE_INT64: { std::int64_t value = 0; bool zz = (field->flags & METAFLAG_PROTO_ZIGZAG); @@ -601,7 +580,7 @@ bool ParserProto::parseStructIntern(const MetaStruct& stru) } } break; - case MetaTypeId::TYPE_UINT64: + case MetaTypeId::TYPE_UINT64: { std::uint64_t value = 0; bool ok = parseValue(value, false); @@ -611,7 +590,7 @@ bool ParserProto::parseStructIntern(const MetaStruct& stru) } } break; - case MetaTypeId::TYPE_FLOAT: + case MetaTypeId::TYPE_FLOAT: { float value = 0.0; bool ok = parseFixedValue(value); @@ -621,7 +600,7 @@ bool ParserProto::parseStructIntern(const MetaStruct& stru) } } break; - case MetaTypeId::TYPE_DOUBLE: + case MetaTypeId::TYPE_DOUBLE: { double value = 0.0; bool ok = parseFixedValue(value); @@ -631,7 +610,7 @@ bool ParserProto::parseStructIntern(const MetaStruct& stru) } } break; - case MetaTypeId::TYPE_STRING: + case MetaTypeId::TYPE_STRING: { const char* buffer = nullptr; ssize_t size = 0; @@ -642,7 +621,7 @@ bool ParserProto::parseStructIntern(const MetaStruct& stru) } } break; - case MetaTypeId::TYPE_BYTES: + case MetaTypeId::TYPE_BYTES: { const char* buffer = nullptr; ssize_t size = 0; @@ -653,10 +632,10 @@ bool ParserProto::parseStructIntern(const MetaStruct& stru) } } break; - case MetaTypeId::TYPE_STRUCT: - parseStructWire(*field); - break; - case MetaTypeId::TYPE_ENUM: + case MetaTypeId::TYPE_STRUCT: + parseStructWire(*field); + break; + case MetaTypeId::TYPE_ENUM: { std::int32_t value = 0; bool ok = parseValue(value, false); @@ -666,7 +645,7 @@ bool ParserProto::parseStructIntern(const MetaStruct& stru) } } break; - case MetaTypeId::TYPE_ARRAY_BOOL: + case MetaTypeId::TYPE_ARRAY_BOOL: { std::vector array; bool ok = parseArrayVarint(array); @@ -676,7 +655,7 @@ bool ParserProto::parseStructIntern(const MetaStruct& stru) } } break; - case MetaTypeId::TYPE_ARRAY_INT8: + case MetaTypeId::TYPE_ARRAY_INT8: { std::vector array; bool ok = false; @@ -704,7 +683,7 @@ bool ParserProto::parseStructIntern(const MetaStruct& stru) } } break; - case MetaTypeId::TYPE_ARRAY_INT16: + case MetaTypeId::TYPE_ARRAY_INT16: { std::vector array; bool ok = false; @@ -732,7 +711,7 @@ bool ParserProto::parseStructIntern(const MetaStruct& stru) } } break; - case MetaTypeId::TYPE_ARRAY_UINT16: + case MetaTypeId::TYPE_ARRAY_UINT16: { std::vector array; bool ok = false; @@ -756,7 +735,7 @@ bool ParserProto::parseStructIntern(const MetaStruct& stru) } } break; - case MetaTypeId::TYPE_ARRAY_INT32: + case MetaTypeId::TYPE_ARRAY_INT32: { std::vector array; bool ok = false; @@ -778,7 +757,7 @@ bool ParserProto::parseStructIntern(const MetaStruct& stru) } } break; - case MetaTypeId::TYPE_ARRAY_UINT32: + case MetaTypeId::TYPE_ARRAY_UINT32: { std::vector array; bool ok = false; @@ -796,7 +775,7 @@ bool ParserProto::parseStructIntern(const MetaStruct& stru) } } break; - case MetaTypeId::TYPE_ARRAY_INT64: + case MetaTypeId::TYPE_ARRAY_INT64: { std::vector array; bool ok = false; @@ -818,7 +797,7 @@ bool ParserProto::parseStructIntern(const MetaStruct& stru) } } break; - case MetaTypeId::TYPE_ARRAY_UINT64: + case MetaTypeId::TYPE_ARRAY_UINT64: { std::vector array; bool ok = false; @@ -836,7 +815,7 @@ bool ParserProto::parseStructIntern(const MetaStruct& stru) } } break; - case MetaTypeId::TYPE_ARRAY_FLOAT: + case MetaTypeId::TYPE_ARRAY_FLOAT: { std::vector array; bool ok = parseArrayFixed(array); @@ -846,7 +825,7 @@ bool ParserProto::parseStructIntern(const MetaStruct& stru) } } break; - case MetaTypeId::TYPE_ARRAY_DOUBLE: + case MetaTypeId::TYPE_ARRAY_DOUBLE: { std::vector array; bool ok = parseArrayFixed(array); @@ -856,7 +835,7 @@ bool ParserProto::parseStructIntern(const MetaStruct& stru) } } break; - case MetaTypeId::TYPE_ARRAY_STRING: + case MetaTypeId::TYPE_ARRAY_STRING: { std::vector array; bool ok = parseArrayString(array); @@ -866,7 +845,7 @@ bool ParserProto::parseStructIntern(const MetaStruct& stru) } } break; - case MetaTypeId::TYPE_ARRAY_BYTES: + case MetaTypeId::TYPE_ARRAY_BYTES: { std::vector array; bool ok = parseArrayString(array); @@ -876,10 +855,10 @@ bool ParserProto::parseStructIntern(const MetaStruct& stru) } } break; - case MetaTypeId::TYPE_ARRAY_STRUCT: - parseArrayStruct(*field); - break; - case MetaTypeId::TYPE_ARRAY_ENUM: + case MetaTypeId::TYPE_ARRAY_STRUCT: + parseArrayStruct(*field); + break; + case MetaTypeId::TYPE_ARRAY_ENUM: { std::vector array; bool ok = parseArrayVarint(array); @@ -889,12 +868,12 @@ bool ParserProto::parseStructIntern(const MetaStruct& stru) } } break; - case MetaTypeId::OFFSET_ARRAY_FLAG: - assert(false); - break; - default: - assert(false); - break; + case MetaTypeId::OFFSET_ARRAY_FLAG: + assert(false); + break; + default: + assert(false); + break; } } else @@ -909,9 +888,6 @@ bool ParserProto::parseStructIntern(const MetaStruct& stru) return (m_ptr != nullptr); } - - - std::uint64_t ParserProto::parseVarint() { std::uint64_t res = 0; @@ -949,14 +925,13 @@ std::uint64_t ParserProto::parseVarint() return 0; } - template T ParserProto::parseFixed() { T value = 0; if (m_size >= static_cast(sizeof(T))) { - EndianHelper::read(m_ptr, value); + EndianHelper(sizeof(T))>::read(m_ptr, value); m_ptr += sizeof(T); m_size -= sizeof(T); } @@ -968,7 +943,6 @@ T ParserProto::parseFixed() return value; } - //std::int32_t ParserProto::zigzag(std::uint32_t value) //{ // return static_cast((value >> 1) ^ (~(value & 1) + 1)); @@ -979,23 +953,21 @@ std::int64_t ParserProto::zigzag(std::uint64_t value) return static_cast((value >> 1) ^ (~(value & 1) + 1)); } - - void ParserProto::skip(WireType wireType) { - switch (wireType) + switch(wireType) { - case WIRETYPE_VARINT: - parseVarint(); - break; - case WIRETYPE_FIXED64: - if (m_ptr) - { - m_ptr += sizeof(std::uint64_t); - m_size -= sizeof(std::uint64_t); - } - break; - case WIRETYPE_LENGTH_DELIMITED: + case WIRETYPE_VARINT: + parseVarint(); + break; + case WIRETYPE_FIXED64: + if (m_ptr) + { + m_ptr += sizeof(std::uint64_t); + m_size -= sizeof(std::uint64_t); + } + break; + case WIRETYPE_LENGTH_DELIMITED: { std::uint64_t len = parseVarint(); if (m_ptr) @@ -1005,17 +977,17 @@ void ParserProto::skip(WireType wireType) } } break; - case WIRETYPE_FIXED32: - if (m_ptr) - { - m_ptr += sizeof(std::uint32_t); - m_size -= sizeof(std::uint32_t); - } - break; - default: - m_ptr = nullptr; - m_size = 0; - break; + case WIRETYPE_FIXED32: + if (m_ptr) + { + m_ptr += sizeof(std::uint32_t); + m_size -= sizeof(std::uint32_t); + } + break; + default: + m_ptr = nullptr; + m_size = 0; + break; } if (m_size < 0) { @@ -1024,4 +996,4 @@ void ParserProto::skip(WireType wireType) } } -} // namespace finalmq +} // namespace finalmq diff --git a/src/serializeproto/SerializerProto.cpp b/src/serializeproto/SerializerProto.cpp index 9d794da8..3596ece4 100644 --- a/src/serializeproto/SerializerProto.cpp +++ b/src/serializeproto/SerializerProto.cpp @@ -20,48 +20,37 @@ //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. - #include "finalmq/serializeproto/SerializerProto.h" -#include "finalmq/serialize/ParserAbortAndIndex.h" -#include "finalmq/metadata/MetaData.h" -#include "finalmq/helpers/FmqDefines.h" -#include "finalmq/helpers/ModulenameFinalmq.h" -#include "finalmq/logger/LogStream.h" -#include -#include #include +#include +#include -namespace finalmq { +#include "finalmq/helpers/FmqDefines.h" +#include "finalmq/helpers/ModulenameFinalmq.h" +#include "finalmq/logger/LogStream.h" +#include "finalmq/metadata/MetaData.h" +#include "finalmq/serialize/ParserAbortAndIndex.h" +namespace finalmq +{ static constexpr int INDEX2ID = 1; static constexpr int MAX_VARINT_SIZE = 10; static constexpr int STRUCT_SIZE_COPY = 128; - - - SerializerProto::SerializerProto(IZeroCopyBuffer& buffer, int maxBlockSize) - : ParserConverter() - , m_internal(buffer, maxBlockSize) - , m_parserAbortAndIndex() + : ParserConverter(), m_internal(buffer, maxBlockSize), m_parserAbortAndIndex() { m_parserAbortAndIndex = std::make_unique(&m_internal); ParserConverter::setVisitor(*m_parserAbortAndIndex); } - - SerializerProto::Internal::Internal(IZeroCopyBuffer& buffer, int maxBlockSize) - : m_zeroCopybuffer(buffer) - , m_maxBlockSize(maxBlockSize) + : m_zeroCopybuffer(buffer), m_maxBlockSize(maxBlockSize) { } - - - void SerializerProto::Internal::serializeVarint(std::uint64_t value) { while (value >= 0x80) @@ -74,8 +63,6 @@ void SerializerProto::Internal::serializeVarint(std::uint64_t value) ++m_buffer; } - - void SerializerProto::Internal::serializeVarintValue(int id, std::uint64_t value) { if (value == 0) @@ -90,10 +77,6 @@ void SerializerProto::Internal::serializeVarintValue(int id, std::uint64_t value serializeVarint(value); } - - - - void SerializerProto::Internal::serializeZigZagValue(int id, std::int64_t value) { if (value == 0) @@ -105,19 +88,22 @@ void SerializerProto::Internal::serializeZigZagValue(int id, std::int64_t value) serializeVarintValue(id, v); } - std::uint64_t SerializerProto::Internal::zigzag(std::int64_t value) { return (static_cast(value) << 1) ^ static_cast(value >> 63); } - - - template void SerializerProto::Internal::serializeFixedValue(int id, T value) { +#ifndef WIN32 +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wfloat-equal" +#endif if (value == 0) +#ifndef WIN32 +#pragma GCC diagnostic pop +#endif { return; } @@ -126,11 +112,10 @@ void SerializerProto::Internal::serializeFixedValue(int id, T value) std::uint32_t tag = (id << 3) | WIRETYPE; serializeVarint(tag); - EndianHelper::write(m_buffer, value); + EndianHelper(sizeof(T))>::write(m_buffer, value); m_buffer += sizeof(T); } - template void SerializerProto::Internal::serializeString(int id, const char* value, ssize_t size) { @@ -148,10 +133,6 @@ void SerializerProto::Internal::serializeString(int id, const char* value, ssize m_buffer += size; } - - - - template void SerializerProto::Internal::serializeArrayFixed(int id, const T* value, ssize_t size) { @@ -178,7 +159,6 @@ void SerializerProto::Internal::serializeArrayFixed(int id, const T* value, ssiz m_buffer += sizeByte; } - void SerializerProto::Internal::serializeArrayBool(int id, const std::vector& value) { if (value.size() <= 0) @@ -199,7 +179,6 @@ void SerializerProto::Internal::serializeArrayBool(int id, const std::vector& value) { ssize_t size = value.size(); @@ -215,7 +194,6 @@ void SerializerProto::Internal::serializeArrayString(int id, const std::vector& value) { ssize_t size = value.size(); @@ -227,12 +205,10 @@ void SerializerProto::Internal::serializeArrayBytes(int id, const std::vector(id, reinterpret_cast(bytes.data()), bytes.size()); + serializeString(id, bytes.data(), bytes.size()); } } - - template void SerializerProto::Internal::serializeArrayVarint(int id, const T* value, ssize_t size) { @@ -252,7 +228,6 @@ void SerializerProto::Internal::serializeArrayVarint(int id, const T* value, ssi } } - template void SerializerProto::Internal::serializeArrayZigZag(int id, const T* value, ssize_t size) { @@ -273,13 +248,9 @@ void SerializerProto::Internal::serializeArrayZigZag(int id, const T* value, ssi } } - - - static const int RESERVE_STRUCT_SIZE = 8; static const int DUMMY_ID = 2047; - char* SerializerProto::Internal::serializeStruct(int id) { reserveSpace(MAX_VARINT_SIZE + RESERVE_STRUCT_SIZE); @@ -290,9 +261,6 @@ char* SerializerProto::Internal::serializeStruct(int id) return bufferStructStart; } - - - void SerializerProto::Internal::reserveSpace(ssize_t space) { ssize_t sizeRemaining = m_bufferEnd - m_buffer; @@ -349,30 +317,20 @@ void SerializerProto::Internal::resizeBuffer() } } - - - - - // IParserVisitor void SerializerProto::Internal::notifyError(const char* /*str*/, const char* /*message*/) { - } - - void SerializerProto::Internal::startStruct(const MetaStruct& /*stru*/) { } - void SerializerProto::Internal::finished() { resizeBuffer(); } - void SerializerProto::Internal::enterStruct(const MetaField& field) { int id = field.index + INDEX2ID; @@ -446,26 +404,26 @@ ssize_t SerializerProto::Internal::calculateStructSize(ssize_t& structSize) void SerializerProto::Internal::fillRemainingStruct(ssize_t remainingSize) { - switch (remainingSize) - { - case 1: - serializeVarint(1); - break; - case 2: - serializeVarint(128); - break; - case 3: - serializeVarint(16384); - break; - case 4: - serializeVarint(2097152); - break; - case 5: - serializeVarint(268435456); - break; - default: - assert(false); - break; + switch(remainingSize) + { + case 1: + serializeVarint(1); + break; + case 2: + serializeVarint(128); + break; + case 3: + serializeVarint(16384); + break; + case 4: + serializeVarint(2097152); + break; + case 5: + serializeVarint(268435456); + break; + default: + assert(false); + break; } } @@ -545,8 +503,6 @@ void SerializerProto::Internal::enterBool(const MetaField& field, bool value) serializeVarintValue(id, value); } - - void SerializerProto::Internal::enterInt8(const MetaField& field, std::int8_t value) { enterInt32(field, value); @@ -666,8 +622,6 @@ void SerializerProto::Internal::enterEnum(const MetaField& field, const char* va enterEnum(field, std::string(value, size)); } - - void SerializerProto::Internal::enterArrayBoolMove(const MetaField& field, std::vector&& value) { int id = field.index + INDEX2ID; @@ -877,4 +831,4 @@ void SerializerProto::Internal::enterArrayEnum(const MetaField& field, const std } } -} // namespace finalmq +} // namespace finalmq diff --git a/src/serializeqt/ParserQt.cpp b/src/serializeqt/ParserQt.cpp index bd1b22c8..85063f91 100644 --- a/src/serializeqt/ParserQt.cpp +++ b/src/serializeqt/ParserQt.cpp @@ -20,103 +20,96 @@ //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. - #include "finalmq/serializeqt/ParserQt.h" -#include "finalmq/serializeqt/Qt.h" -#include "finalmq/metadata/MetaData.h" -#include "finalmq/helpers/FmqDefines.h" - -#include -#include -#include +#include #include +#include #include -#include +#include +#include -namespace finalmq { +#include "finalmq/helpers/FmqDefines.h" +#include "finalmq/metadata/MetaData.h" +#include "finalmq/serializeqt/Qt.h" +namespace finalmq +{ +ParserQt::ParserQt(IParserVisitor& visitor, const char* ptr, ssize_t size, Mode mode) + : m_ptr(reinterpret_cast(ptr)), m_size(size), m_visitor(visitor), m_mode(mode) +{ +} - ParserQt::ParserQt(IParserVisitor& visitor, const char* ptr, ssize_t size, Mode mode) - : m_ptr(reinterpret_cast(ptr)) - , m_size(size) - , m_visitor(visitor) - , m_mode(mode) +bool ParserQt::parseStruct(const std::string& typeName) +{ + if (!m_ptr || m_size < 0) { + // end of data + return false; } - - - bool ParserQt::parseStruct(const std::string& typeName) + const MetaStruct* stru = MetaDataGlobal::instance().getStruct(typeName); + if (!stru) { - if (!m_ptr || m_size < 0) - { - // end of data - return false; - } + m_visitor.notifyError(reinterpret_cast(m_ptr), "typename not found"); + m_visitor.finished(); + return false; + } - const MetaStruct* stru = MetaDataGlobal::instance().getStruct(typeName); - if (!stru) + if (m_mode == Mode::WRAPPED_BY_QVARIANTLIST) + { + const ssize_t numberOfFields = stru->getFieldsSize(); + std::uint32_t count; + bool ok = parse(count); + if (ok && count != numberOfFields) { - m_visitor.notifyError(reinterpret_cast(m_ptr), "typename not found"); + m_visitor.notifyError(reinterpret_cast(m_ptr), "number of fields does not match"); m_visitor.finished(); return false; } + } - if (m_mode == Mode::WRAPPED_BY_QVARIANTLIST) - { - const ssize_t numberOfFields = stru->getFieldsSize(); - std::uint32_t count; - bool ok = parse(count); - if (ok && count != numberOfFields) - { - m_visitor.notifyError(reinterpret_cast(m_ptr), "number of fields does not match"); - m_visitor.finished(); - return false; - } - } + m_visitor.startStruct(*stru); + bool res = parseStructIntern(*stru, m_mode != Mode::NONE); + m_visitor.finished(); + return res; +} - m_visitor.startStruct(*stru); - bool res = parseStructIntern(*stru, m_mode != Mode::NONE); - m_visitor.finished(); - return res; - } +static const std::string ENUM_BITS = "enumbits"; +static const std::string BITS_8 = "8"; +static const std::string BITS_16 = "16"; +static const std::string BITS_32 = "32"; - static const std::string ENUM_BITS = "enumbits"; - static const std::string BITS_8 = "8"; - static const std::string BITS_16 = "16"; - static const std::string BITS_32 = "32"; +static const std::string ABORTSTRUCT = "abortstruct"; +static const std::string ABORT_FALSE = "false"; +static const std::string ABORT_TRUE = "true"; - static const std::string ABORTSTRUCT = "abortstruct"; - static const std::string ABORT_FALSE = "false"; - static const std::string ABORT_TRUE = "true"; +bool ParserQt::parseStructIntern(const MetaStruct& stru, bool wrappedByQVariant) +{ + if (!m_ptr || m_size < 0) + { + // end of data + return false; + } - bool ParserQt::parseStructIntern(const MetaStruct& stru, bool wrappedByQVariant) + bool ok = true; + bool abortStruct = false; + std::int64_t index = INDEX_NOT_AVAILABLE; + + const ssize_t numberOfFields = stru.getFieldsSize(); + for (ssize_t i = 0; i < numberOfFields && ok && !abortStruct; ++i) { - if (!m_ptr || m_size < 0) + if (index >= 0) { - // end of data - return false; + i = index; + index = INDEX_ABORTSTRUCT; } + const MetaField* field = stru.getFieldByIndex(i); + assert(field); - bool ok = true; - bool abortStruct = false; - std::int64_t index = INDEX_NOT_AVAILABLE; - - const ssize_t numberOfFields = stru.getFieldsSize(); - for (ssize_t i = 0; i < numberOfFields && ok && !abortStruct; ++i) + switch(field->typeId) { - if (index >= 0) - { - i = index; - index = INDEX_ABORTSTRUCT; - } - const MetaField* field = stru.getFieldByIndex(i); - assert(field); - - switch (field->typeId) - { case MetaTypeId::TYPE_NONE: break; case MetaTypeId::TYPE_BOOL: @@ -136,8 +129,7 @@ namespace finalmq { const std::string& valueAbort = field->getProperty(ABORTSTRUCT); if (!valueAbort.empty()) { - if (((valueAbort == ABORT_TRUE) && value) || - ((valueAbort == ABORT_FALSE) && !value)) + if (((valueAbort == ABORT_TRUE) && value) || ((valueAbort == ABORT_FALSE) && !value)) { abortStruct = true; } @@ -341,8 +333,8 @@ namespace finalmq { } if (ok) { - const MetaStruct* stru = MetaDataGlobal::instance().getStruct(field->typeName); - if (!stru) + const MetaStruct* stru1 = MetaDataGlobal::instance().getStruct(field->typeName); + if (!stru1) { m_visitor.notifyError(reinterpret_cast(m_ptr), "typename not found"); m_visitor.finished(); @@ -351,7 +343,7 @@ namespace finalmq { else { m_visitor.enterStruct(*field); - ok = parseStructIntern(*stru, false); + ok = parseStructIntern(*stru1, false); m_visitor.exitStruct(*field); } } @@ -625,9 +617,9 @@ namespace finalmq { std::vector value8; ok = parse(value); value.resize(value8.size()); - for (size_t i = 0; i < value8.size(); ++i) + for (size_t n = 0; n < value8.size(); ++n) { - value[i] = static_cast(value8[i]); + value[n] = static_cast(value8[n]); } } else if (bits == BITS_16) @@ -635,9 +627,9 @@ namespace finalmq { std::vector value16; ok = parse(value); value.resize(value16.size()); - for (size_t i = 0; i < value16.size(); ++i) + for (size_t n = 0; n < value16.size(); ++n) { - value[i] = static_cast(value16[i]); + value[n] = static_cast(value16[n]); } } if (ok) @@ -657,407 +649,401 @@ namespace finalmq { default: assert(false); break; - } - - if ((index == INDEX_ABORTSTRUCT) || (index >= numberOfFields)) - { - abortStruct = true; - } } - return ok; + if ((index == INDEX_ABORTSTRUCT) || (index >= numberOfFields)) + { + abortStruct = true; + } } + return ok; +} + +bool ParserQt::parse(std::int8_t& value) +{ + return parse(*reinterpret_cast(&value)); +} - bool ParserQt::parse(std::int8_t& value) +bool ParserQt::parse(std::uint8_t& value) +{ + if (m_size >= static_cast(sizeof(std::uint8_t))) { - return parse(*reinterpret_cast(&value)); + assert(m_ptr); + value = *m_ptr; + ++m_ptr; + --m_size; + return true; } - - bool ParserQt::parse(std::uint8_t& value) + else { - if (m_size >= static_cast(sizeof(std::uint8_t))) - { - assert(m_ptr); - value = *m_ptr; - ++m_ptr; - --m_size; - return true; - } - else - { - m_ptr = nullptr; - m_size = 0; - return false; - } + m_ptr = nullptr; + m_size = 0; + return false; } +} + +bool ParserQt::parse(std::int16_t& value) +{ + return parse(*reinterpret_cast(&value)); +} - bool ParserQt::parse(std::int16_t& value) +bool ParserQt::parse(std::uint16_t& value) +{ + if (m_size >= static_cast(sizeof(std::uint16_t))) { - return parse(*reinterpret_cast(&value)); + assert(m_ptr); + value = static_cast(static_cast(*m_ptr) << 8); + ++m_ptr; + value = static_cast(value | static_cast(*m_ptr)); + ++m_ptr; + m_size -= sizeof(std::uint16_t); + return true; } - - bool ParserQt::parse(std::uint16_t& value) + else { - if (m_size >= static_cast(sizeof(std::uint16_t))) - { - assert(m_ptr); - value = static_cast(*m_ptr) << 8; - ++m_ptr; - value |= static_cast(*m_ptr); - ++m_ptr; - m_size -= sizeof(std::uint16_t); - return true; - } - else - { - m_ptr = nullptr; - m_size = 0; - return false; - } + m_ptr = nullptr; + m_size = 0; + return false; } +} + +bool ParserQt::parse(std::int32_t& value) +{ + return parse(*reinterpret_cast(&value)); +} - bool ParserQt::parse(std::int32_t& value) +bool ParserQt::parse(std::uint32_t& value) +{ + if (m_size >= static_cast(sizeof(std::uint32_t))) { - return parse(*reinterpret_cast(&value)); + assert(m_ptr); + value = static_cast(*m_ptr) << 24; + ++m_ptr; + value |= static_cast(*m_ptr) << 16; + ++m_ptr; + value |= static_cast(*m_ptr) << 8; + ++m_ptr; + value |= static_cast(*m_ptr); + ++m_ptr; + m_size -= sizeof(std::uint32_t); + return true; + } + else + { + m_ptr = nullptr; + m_size = 0; + return false; } +} - bool ParserQt::parse(std::uint32_t& value) +bool ParserQt::parse(std::int64_t& value) +{ + return parse(*reinterpret_cast(&value)); +} + +bool ParserQt::parse(std::uint64_t& value) +{ + if (m_size >= static_cast(sizeof(std::uint64_t))) { - if (m_size >= static_cast(sizeof(std::uint32_t))) - { - assert(m_ptr); - value = static_cast(*m_ptr) << 24; - ++m_ptr; - value |= static_cast(*m_ptr) << 16; - ++m_ptr; - value |= static_cast(*m_ptr) << 8; - ++m_ptr; - value |= static_cast(*m_ptr); - ++m_ptr; - m_size -= sizeof(std::uint32_t); - return true; - } - else - { - m_ptr = nullptr; - m_size = 0; - return false; - } + assert(m_ptr); + value = static_cast(*m_ptr) << 56; + ++m_ptr; + value |= static_cast(*m_ptr) << 48; + ++m_ptr; + value |= static_cast(*m_ptr) << 40; + ++m_ptr; + value |= static_cast(*m_ptr) << 32; + ++m_ptr; + value |= static_cast(*m_ptr) << 24; + ++m_ptr; + value |= static_cast(*m_ptr) << 16; + ++m_ptr; + value |= static_cast(*m_ptr) << 8; + ++m_ptr; + value |= static_cast(*m_ptr); + ++m_ptr; + m_size -= sizeof(std::uint64_t); + return true; + } + else + { + m_ptr = nullptr; + m_size = 0; + return false; } +} - bool ParserQt::parse(std::int64_t& value) +bool ParserQt::parse(float& value) +{ + union + { + std::uint64_t v; + double d; + } u; + const bool ok = parse(u.v); + value = static_cast(u.d); + return ok; +} + +bool ParserQt::parse(double& value) +{ + union + { + std::uint64_t v; + double d; + } u; + const bool ok = parse(u.v); + value = u.d; + return ok; +} + +bool ParserQt::parse(std::string& str) +{ + str.clear(); + + std::u16string utf16; + + std::uint32_t sizeBytes; + bool ok = parse(sizeBytes); + if (!ok) { - return parse(*reinterpret_cast(&value)); + return false; + } + if (sizeBytes == 0xFFFFFFFF || sizeBytes == 0) + { + return true; } - bool ParserQt::parse(std::uint64_t& value) + if (m_size >= static_cast(sizeBytes)) { - if (m_size >= static_cast(sizeof(std::uint64_t))) + std::uint32_t sizeChar = sizeBytes / 2; + utf16.resize(sizeChar); + for (std::uint32_t i = 0; i < sizeChar; ++i) { - assert(m_ptr); - value = static_cast(*m_ptr) << 56; - ++m_ptr; - value |= static_cast(*m_ptr) << 48; - ++m_ptr; - value |= static_cast(*m_ptr) << 40; - ++m_ptr; - value |= static_cast(*m_ptr) << 32; - ++m_ptr; - value |= static_cast(*m_ptr) << 24; + char16_t c = static_cast(static_cast(*m_ptr) << 8); ++m_ptr; - value |= static_cast(*m_ptr) << 16; + c = static_cast(c | static_cast(*m_ptr)); ++m_ptr; - value |= static_cast(*m_ptr) << 8; - ++m_ptr; - value |= static_cast(*m_ptr); - ++m_ptr; - m_size -= sizeof(std::uint64_t); - return true; - } - else - { - m_ptr = nullptr; - m_size = 0; - return false; + utf16[i] = c; } + str = std::wstring_convert, char16_t>{}.to_bytes(utf16); + m_size -= sizeBytes; + return true; + } + else + { + m_ptr = nullptr; + m_size = 0; + return false; } +} +bool ParserQt::parse(Bytes& value) +{ + value.clear(); - bool ParserQt::parse(float& value) + std::uint32_t size; + bool ok = parse(size); + if (!ok) { - union - { - std::uint64_t v; - double d; - } u; - const bool ok = parse(u.v); - value = static_cast(u.d); - return ok; + return false; } - - bool ParserQt::parse(double& value) + if (size == 0xFFFFFFFF || size == 0) { - union - { - std::uint64_t v; - double d; - } u; - const bool ok = parse(u.v); - value = u.d; - return ok; + return true; } - - bool ParserQt::parse(std::string& str) + if (m_size >= static_cast(size)) { - str.clear(); - - std::u16string utf16; + assert(m_ptr); + value = Bytes(m_ptr, m_ptr + size); + m_ptr += size; + m_size -= size; + return true; + } + else + { + m_ptr = nullptr; + m_size = 0; + return false; + } +} - std::uint32_t sizeBytes; - bool ok = parse(sizeBytes); - if (!ok) - { - return false; - } - if (sizeBytes == 0xFFFFFFFF || sizeBytes == 0) - { - return true; - } +bool ParserQt::parseArrayByte(const char*& buffer, ssize_t& size) +{ + buffer = nullptr; + size = 0; - if (m_size >= static_cast(sizeBytes)) - { - std::uint32_t sizeChar = sizeBytes / 2; - utf16.resize(sizeChar); - for (std::uint32_t i = 0; i < sizeChar; ++i) - { - char16_t c = static_cast(*m_ptr) << 8; - ++m_ptr; - c |= static_cast(*m_ptr); - ++m_ptr; - utf16[i] = c; - } - str = std::wstring_convert, char16_t>{}.to_bytes(utf16); - m_size -= sizeBytes; - return true; - } - else - { - m_ptr = nullptr; - m_size = 0; - return false; - } + std::uint32_t s; + bool ok = parse(s); + if (!ok) + { + return false; + } + if (s == 0xFFFFFFFF || s == 0) + { + return true; } + size = static_cast(s); - bool ParserQt::parse(Bytes& value) + if (m_size >= size) { - value.clear(); + assert(m_ptr); + buffer = reinterpret_cast(m_ptr); + m_ptr += size; + m_size -= size; + return true; + } + else + { + m_ptr = nullptr; + m_size = 0; + return false; + } +} - std::uint32_t size; - bool ok = parse(size); - if (!ok) - { - return false; - } - if (size == 0xFFFFFFFF || size == 0) - { - return true; - } +bool ParserQt::parseArrayBool(std::vector& value) +{ + value.clear(); - if (m_size >= static_cast(size)) - { - assert(m_ptr); - value = Bytes(m_ptr, m_ptr + size); - m_ptr += size; - m_size -= size; - return true; - } - else - { - m_ptr = nullptr; - m_size = 0; - return false; - } + std::uint32_t size; + bool ok = parse(size); + if (!ok) + { + return false; } - - bool ParserQt::parseArrayByte(const char*& buffer, ssize_t& size) + if (size == 0xFFFFFFFF || size == 0) { - buffer = nullptr; - size = 0; + return true; + } - std::uint32_t s; - bool ok = parse(s); - if (!ok) - { - return false; - } - if (s == 0xFFFFFFFF || s == 0) - { - return true; - } + value.resize(size); - size = static_cast(s); + const ssize_t sizeBytes = (size + 7) / 8; - if (m_size >= size) + if (m_size >= sizeBytes) + { + assert(m_ptr); + for (std::uint32_t i = 0; i < size; ++i) { - assert(m_ptr); - buffer = reinterpret_cast(m_ptr); - m_ptr += size; - m_size -= size; - return true; - } - else - { - m_ptr = nullptr; - m_size = 0; - return false; + const std::uint32_t indexBytes = i / 8; + const std::uint32_t indexBits = i % 8; + bool v = (m_ptr[indexBytes] & (1 << indexBits)) ? true : false; + value[i] = v; } + m_ptr += sizeBytes; + m_size -= sizeBytes; + return true; } - - bool ParserQt::parseArrayBool(std::vector& value) + else { - value.clear(); - - std::uint32_t size; - bool ok = parse(size); - if (!ok) - { - return false; - } - - if (size == 0xFFFFFFFF || size == 0) - { - return true; - } - - value.resize(size); + m_ptr = nullptr; + m_size = 0; + return false; + } +} - const ssize_t sizeBytes = (size + 7) / 8; +template +bool ParserQt::parse(std::vector& value) +{ + value.clear(); - if (m_size >= sizeBytes) - { - assert(m_ptr); - for (std::uint32_t i = 0; i < size; ++i) - { - const std::uint32_t indexBytes = i / 8; - const std::uint32_t indexBits = i % 8; - bool v = (m_ptr[indexBytes] & (1 << indexBits)) ? true : false; - value[i] = v; - } - m_ptr += sizeBytes; - m_size -= sizeBytes; - return true; - } - else - { - m_ptr = nullptr; - m_size = 0; - return false; - } + std::uint32_t size; + bool ok = parse(size); + if (!ok) + { + return false; } - template - bool ParserQt::parse(std::vector& value) + if (size == 0) { - value.clear(); + return true; + } + + value.resize(size); - std::uint32_t size; - bool ok = parse(size); + for (std::uint32_t i = 0; i < size; ++i) + { + ok = parse(value[i]); if (!ok) { return false; } + } + return true; +} - if (size == 0) - { - return true; - } - - value.resize(size); +bool ParserQt::parseArrayStruct(const MetaField& field) +{ + if (m_ptr == nullptr) + { + return false; + } - for (std::uint32_t i = 0; i < size; ++i) - { - bool ok = parse(value[i]); - if (!ok) - { - return false; - } - } - return true; + std::uint32_t size; + bool ok = parse(size); + if (!ok) + { + return false; } - bool ParserQt::parseArrayStruct(const MetaField& field) + const MetaStruct* stru = MetaDataGlobal::instance().getStruct(field); + if (!stru) { - if (m_ptr == nullptr) - { - return false; - } + m_visitor.notifyError(reinterpret_cast(m_ptr), "typename not found"); + return false; + } - std::uint32_t size; - bool ok = parse(size); - if (!ok) - { - return false; - } + const MetaField* fieldWithoutArray = field.fieldWithoutArray; + assert(fieldWithoutArray); + m_visitor.enterArrayStruct(field); + for (std::uint32_t i = 0; i < size && ok; ++i) + { + m_visitor.enterStruct(*fieldWithoutArray); + ok = parseStructIntern(*stru, false); + m_visitor.exitStruct(*fieldWithoutArray); + } + m_visitor.exitArrayStruct(field); - const MetaStruct* stru = MetaDataGlobal::instance().getStruct(field); - if (!stru) - { - m_visitor.notifyError(reinterpret_cast(m_ptr), "typename not found"); - return false; - } + return (m_ptr != nullptr); +} - const MetaField* fieldWithoutArray = field.fieldWithoutArray; - assert(fieldWithoutArray); - m_visitor.enterArrayStruct(field); - for (std::uint32_t i = 0; i < size && ok; ++i) - { - m_visitor.enterStruct(*fieldWithoutArray); - ok = parseStructIntern(*stru, false); - m_visitor.exitStruct(*fieldWithoutArray); - } - m_visitor.exitArrayStruct(field); - - return (m_ptr != nullptr); +bool ParserQt::parseQVariantHeader(const MetaField& /*field*/) +{ + std::uint32_t typeId; + bool ok = parse(typeId); + if (ok) + { + std::uint8_t isNull; + ok = parse(isNull); } - - bool ParserQt::parseQVariantHeader(const MetaField& /*field*/) + if (ok) { - std::uint32_t typeId; - bool ok = parse(typeId); - if (ok) + if (typeId == static_cast(QtType::User)) { - std::uint8_t isNull; - ok = parse(isNull); + Bytes typeName; + ok = parse(typeName); } - if (ok) - { - if (typeId == static_cast(QtType::User)) - { - Bytes typeName; - ok = parse(typeName); - } - } - return ok; } + return ok; +} - void ParserQt::checkIndex(const MetaField& field, std::int64_t value, std::int64_t& index) +void ParserQt::checkIndex(const MetaField& field, std::int64_t value, std::int64_t& index) +{ + if ((field.flags & MetaFieldFlags::METAFLAG_INDEX) != 0) { - if ((field.flags & MetaFieldFlags::METAFLAG_INDEX) != 0) + if (value < 0) + { + index = INDEX_ABORTSTRUCT; + } + else { - if (value < 0) - { - index = INDEX_ABORTSTRUCT; - } - else - { - index = field.index + 1 + value; - } + index = field.index + 1 + value; } } +} - -} // namespace finalmq +} // namespace finalmq diff --git a/src/serializeqt/SerializerQt.cpp b/src/serializeqt/SerializerQt.cpp index 10e370f3..a1bbe98a 100644 --- a/src/serializeqt/SerializerQt.cpp +++ b/src/serializeqt/SerializerQt.cpp @@ -20,1100 +20,1083 @@ //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. - #include "finalmq/serializeqt/SerializerQt.h" -#include "finalmq/serializeqt/Qt.h" -#include "finalmq/serialize/ParserProcessDefaultValues.h" -#include "finalmq/serialize/ParserAbortAndIndex.h" -#include "finalmq/serialize/ParserProcessValuesInOrder.h" -#include "finalmq/helpers/Utils.h" -#include "finalmq/metadata/MetaData.h" -#include "finalmq/helpers/ModulenameFinalmq.h" -#include "finalmq/logger/LogStream.h" - -#include -#include +#include #include #include -#include -namespace finalmq { +#include +#include "finalmq/helpers/ModulenameFinalmq.h" +#include "finalmq/helpers/Utils.h" +#include "finalmq/logger/LogStream.h" +#include "finalmq/metadata/MetaData.h" +#include "finalmq/serialize/ParserAbortAndIndex.h" +#include "finalmq/serialize/ParserProcessDefaultValues.h" +#include "finalmq/serialize/ParserProcessValuesInOrder.h" +#include "finalmq/serializeqt/Qt.h" - SerializerQt::SerializerQt(IZeroCopyBuffer& buffer, Mode mode, int maxBlockSize) - : ParserConverter() - , m_internal(buffer, maxBlockSize, mode) - , m_parserProcessDefaultValues() - , m_parserAbortAndIndex() - , m_parserProcessValuesInOrder() +namespace finalmq +{ +SerializerQt::SerializerQt(IZeroCopyBuffer& buffer, Mode mode, int maxBlockSize) + : ParserConverter(), m_internal(buffer, maxBlockSize, mode), m_parserProcessDefaultValues(), m_parserAbortAndIndex(), m_parserProcessValuesInOrder() +{ + m_parserProcessValuesInOrder = std::make_unique(&m_internal); + m_parserAbortAndIndex = std::make_unique(m_parserProcessValuesInOrder.get()); + m_parserProcessDefaultValues = std::make_unique(false, m_parserAbortAndIndex.get()); + ParserConverter::setVisitor(*m_parserProcessDefaultValues); +} + +SerializerQt::Internal::Internal(IZeroCopyBuffer& buffer, int maxBlockSize, Mode mode) + : m_zeroCopybuffer(buffer), m_maxBlockSize(maxBlockSize), m_mode(mode) +{ +} + +// IParserVisitor +void SerializerQt::Internal::notifyError(const char* /*str*/, const char* /*message*/) +{ +} + +void SerializerQt::Internal::startStruct(const MetaStruct& stru) +{ + if (m_mode == Mode::WRAPPED_BY_QVARIANTLIST) { - m_parserProcessValuesInOrder = std::make_unique(&m_internal); - m_parserAbortAndIndex = std::make_unique(m_parserProcessValuesInOrder.get()); - m_parserProcessDefaultValues = std::make_unique(false, m_parserAbortAndIndex.get()); - ParserConverter::setVisitor(*m_parserProcessDefaultValues); + reserveSpace(sizeof(std::uint32_t)); + const std::uint32_t count = static_cast(stru.getFieldsSize()); + serialize(count); } + m_levelState.push_back(LevelState()); +} +void SerializerQt::Internal::finished() +{ + resizeBuffer(); - SerializerQt::Internal::Internal(IZeroCopyBuffer& buffer, int maxBlockSize, Mode mode) - : m_zeroCopybuffer(buffer) - , m_maxBlockSize(maxBlockSize) - , m_mode(mode) + if (!m_levelState.empty()) { + m_levelState.pop_back(); } +} +void SerializerQt::Internal::enterStruct(const MetaField& field) +{ + assert(!m_levelState.empty()); + LevelState& levelState = m_levelState.back(); - // IParserVisitor - void SerializerQt::Internal::notifyError(const char* /*str*/, const char* /*message*/) + assert(field.typeId == MetaTypeId::TYPE_STRUCT); + if (isWrappedByQVariant()) { + serializeQVariantHeader(field); } - void SerializerQt::Internal::startStruct(const MetaStruct& stru) + if (levelState.arrayStructCounter >= 0) { - if (m_mode == Mode::WRAPPED_BY_QVARIANTLIST) - { - reserveSpace(sizeof(std::uint32_t)); - const std::uint32_t count = static_cast(stru.getFieldsSize()); - serialize(count); - } - - m_levelState.push_back(LevelState()); + ++levelState.arrayStructCounter; } + m_levelState.push_back(LevelState()); +} - void SerializerQt::Internal::finished() - { - resizeBuffer(); +void SerializerQt::Internal::exitStruct(const MetaField& /*field*/) +{ + m_levelState.pop_back(); +} - if (!m_levelState.empty()) - { - m_levelState.pop_back(); - } - } +void SerializerQt::Internal::enterStructNull(const MetaField& /*field*/) +{ +} +void SerializerQt::Internal::enterArrayStruct(const MetaField& field) +{ + assert(!m_levelState.empty()); + LevelState& levelState = m_levelState.back(); - void SerializerQt::Internal::enterStruct(const MetaField& field) + assert(field.typeId == MetaTypeId::TYPE_ARRAY_STRUCT); + if (isWrappedByQVariant()) { - assert(!m_levelState.empty()); - LevelState& levelState = m_levelState.back(); - - assert(field.typeId == MetaTypeId::TYPE_STRUCT); - if (isWrappedByQVariant()) - { - serializeQVariantHeader(field); - } - - if (levelState.arrayStructCounter >= 0) - { - ++levelState.arrayStructCounter; - } - - m_levelState.push_back(LevelState()); + serializeQVariantHeader(field); } - void SerializerQt::Internal::exitStruct(const MetaField& /*field*/) - { - m_levelState.pop_back(); - } + reserveSpace(sizeof(std::uint32_t)); + levelState.arrayStructCounterBuffer = m_buffer; + levelState.arrayStructCounter = 0; + serialize(levelState.arrayStructCounter); + levelState.arrayStructCounter = 0; - void SerializerQt::Internal::enterStructNull(const MetaField& /*field*/) - { - } + m_levelState.push_back(LevelState()); +} +void SerializerQt::Internal::exitArrayStruct(const MetaField& /*field*/) +{ + assert(!m_levelState.empty()); + LevelState& levelState = m_levelState.back(); - void SerializerQt::Internal::enterArrayStruct(const MetaField& field) + if (levelState.arrayStructCounterBuffer) { - assert(!m_levelState.empty()); - LevelState& levelState = m_levelState.back(); - - assert(field.typeId == MetaTypeId::TYPE_ARRAY_STRUCT); - if (isWrappedByQVariant()) - { - serializeQVariantHeader(field); - } - - reserveSpace(sizeof(std::uint32_t)); - levelState.arrayStructCounterBuffer = m_buffer; - levelState.arrayStructCounter = 0; + char* buffer = m_buffer; + m_buffer = levelState.arrayStructCounterBuffer; serialize(levelState.arrayStructCounter); - levelState.arrayStructCounter = 0; - - m_levelState.push_back(LevelState()); + m_buffer = buffer; + levelState.arrayStructCounter = -1; } - void SerializerQt::Internal::exitArrayStruct(const MetaField& /*field*/) - { - assert(!m_levelState.empty()); - LevelState& levelState = m_levelState.back(); - - if (levelState.arrayStructCounterBuffer) - { - char* buffer = m_buffer; - m_buffer = levelState.arrayStructCounterBuffer; - serialize(levelState.arrayStructCounter); - m_buffer = buffer; - levelState.arrayStructCounter = -1; - } - - m_levelState.pop_back(); - } + m_levelState.pop_back(); +} - static const std::string ABORTSTRUCT = "abortstruct"; - static const std::string ABORT_FALSE = "false"; - static const std::string ABORT_TRUE = "true"; +static const std::string ABORTSTRUCT = "abortstruct"; +static const std::string ABORT_FALSE = "false"; +static const std::string ABORT_TRUE = "true"; - void SerializerQt::Internal::enterBool(const MetaField& field, bool value) +void SerializerQt::Internal::enterBool(const MetaField& field, bool value) +{ + assert(field.typeId == MetaTypeId::TYPE_BOOL); + if (isWrappedByQVariant()) { - assert(field.typeId == MetaTypeId::TYPE_BOOL); - if (isWrappedByQVariant()) - { - serializeQVariantHeader(field); - } - reserveSpace(sizeof(std::uint8_t)); - serialize(static_cast(value ? 1 : 0)); + serializeQVariantHeader(field); } + reserveSpace(sizeof(std::uint8_t)); + serialize(static_cast(value ? 1 : 0)); +} - void SerializerQt::Internal::enterInt8(const MetaField& field, std::int8_t value) +void SerializerQt::Internal::enterInt8(const MetaField& field, std::int8_t value) +{ + assert(field.typeId == MetaTypeId::TYPE_INT8); + if (isWrappedByQVariant()) { - assert(field.typeId == MetaTypeId::TYPE_INT8); - if (isWrappedByQVariant()) - { - serializeQVariantHeader(field); - } - reserveSpace(sizeof(std::int8_t)); - serialize(value); + serializeQVariantHeader(field); } + reserveSpace(sizeof(std::int8_t)); + serialize(value); +} - void SerializerQt::Internal::enterUInt8(const MetaField& field, std::uint8_t value) +void SerializerQt::Internal::enterUInt8(const MetaField& field, std::uint8_t value) +{ + assert(field.typeId == MetaTypeId::TYPE_UINT8); + if (isWrappedByQVariant()) { - assert(field.typeId == MetaTypeId::TYPE_UINT8); - if (isWrappedByQVariant()) - { - serializeQVariantHeader(field); - } - reserveSpace(sizeof(std::uint8_t)); - serialize(value); + serializeQVariantHeader(field); } + reserveSpace(sizeof(std::uint8_t)); + serialize(value); +} - void SerializerQt::Internal::enterInt16(const MetaField& field, std::int16_t value) +void SerializerQt::Internal::enterInt16(const MetaField& field, std::int16_t value) +{ + assert(field.typeId == MetaTypeId::TYPE_INT16); + if (isWrappedByQVariant()) { - assert(field.typeId == MetaTypeId::TYPE_INT16); - if (isWrappedByQVariant()) - { - serializeQVariantHeader(field); - } - reserveSpace(sizeof(std::int16_t)); - serialize(value); + serializeQVariantHeader(field); } + reserveSpace(sizeof(std::int16_t)); + serialize(value); +} - void SerializerQt::Internal::enterUInt16(const MetaField& field, std::uint16_t value) +void SerializerQt::Internal::enterUInt16(const MetaField& field, std::uint16_t value) +{ + assert(field.typeId == MetaTypeId::TYPE_UINT16); + if (isWrappedByQVariant()) { - assert(field.typeId == MetaTypeId::TYPE_UINT16); - if (isWrappedByQVariant()) - { - serializeQVariantHeader(field); - } - reserveSpace(sizeof(std::uint16_t)); - serialize(value); + serializeQVariantHeader(field); } + reserveSpace(sizeof(std::uint16_t)); + serialize(value); +} - void SerializerQt::Internal::enterInt32(const MetaField& field, std::int32_t value) +void SerializerQt::Internal::enterInt32(const MetaField& field, std::int32_t value) +{ + assert(field.typeId == MetaTypeId::TYPE_INT32); + if (isWrappedByQVariant()) { - assert(field.typeId == MetaTypeId::TYPE_INT32); - if (isWrappedByQVariant()) - { - serializeQVariantHeader(field); - } - reserveSpace(sizeof(std::int32_t)); - serialize(value); + serializeQVariantHeader(field); } + reserveSpace(sizeof(std::int32_t)); + serialize(value); +} - void SerializerQt::Internal::enterUInt32(const MetaField& field, std::uint32_t value) +void SerializerQt::Internal::enterUInt32(const MetaField& field, std::uint32_t value) +{ + assert(field.typeId == MetaTypeId::TYPE_UINT32); + if (isWrappedByQVariant()) { - assert(field.typeId == MetaTypeId::TYPE_UINT32); - if (isWrappedByQVariant()) - { - serializeQVariantHeader(field); - } - reserveSpace(sizeof(std::uint32_t)); - serialize(value); + serializeQVariantHeader(field); } + reserveSpace(sizeof(std::uint32_t)); + serialize(value); +} - void SerializerQt::Internal::enterInt64(const MetaField& field, std::int64_t value) +void SerializerQt::Internal::enterInt64(const MetaField& field, std::int64_t value) +{ + assert(field.typeId == MetaTypeId::TYPE_INT64); + if (isWrappedByQVariant()) { - assert(field.typeId == MetaTypeId::TYPE_INT64); - if (isWrappedByQVariant()) - { - serializeQVariantHeader(field); - } - reserveSpace(sizeof(std::int64_t)); - serialize(value); + serializeQVariantHeader(field); } + reserveSpace(sizeof(std::int64_t)); + serialize(value); +} - void SerializerQt::Internal::enterUInt64(const MetaField& field, std::uint64_t value) +void SerializerQt::Internal::enterUInt64(const MetaField& field, std::uint64_t value) +{ + assert(field.typeId == MetaTypeId::TYPE_UINT64); + if (isWrappedByQVariant()) { - assert(field.typeId == MetaTypeId::TYPE_UINT64); - if (isWrappedByQVariant()) - { - serializeQVariantHeader(field); - } - reserveSpace(sizeof(std::uint64_t)); - serialize(value); + serializeQVariantHeader(field); } + reserveSpace(sizeof(std::uint64_t)); + serialize(value); +} - void SerializerQt::Internal::enterFloat(const MetaField& field, float value) +void SerializerQt::Internal::enterFloat(const MetaField& field, float value) +{ + assert(field.typeId == MetaTypeId::TYPE_FLOAT); + if (isWrappedByQVariant()) { - assert(field.typeId == MetaTypeId::TYPE_FLOAT); - if (isWrappedByQVariant()) - { - serializeQVariantHeader(field); - } - reserveSpace(sizeof(double)); - serialize(value); - } - - void SerializerQt::Internal::enterDouble(const MetaField& field, double value) - { - assert(field.typeId == MetaTypeId::TYPE_DOUBLE); - if (isWrappedByQVariant()) - { - serializeQVariantHeader(field); - } - reserveSpace(sizeof(double)); - serialize(value); - } - - void SerializerQt::Internal::enterString(const MetaField& field, std::string&& value) - { - assert(field.typeId == MetaTypeId::TYPE_STRING); - if (isWrappedByQVariant()) - { - serializeQVariantHeader(field); - } - reserveSpace(sizeof(std::uint32_t) + 2 * value.size()); - serializeString(value); - } - - void SerializerQt::Internal::enterString(const MetaField& field, const char* value, ssize_t size) - { - assert(field.typeId == MetaTypeId::TYPE_STRING); - if (isWrappedByQVariant()) - { - serializeQVariantHeader(field); - } - reserveSpace(sizeof(std::uint32_t) + 2 * size); - serializeString(value, size); - } - - void SerializerQt::Internal::enterBytes(const MetaField& field, Bytes&& value) - { - assert(field.typeId == MetaTypeId::TYPE_BYTES); - enterBytes(field, value.data(), value.size()); - } - - void SerializerQt::Internal::enterBytes(const MetaField& field, const BytesElement* value, ssize_t size) - { - assert(field.typeId == MetaTypeId::TYPE_BYTES); - if (isWrappedByQVariant()) - { - serializeQVariantHeader(field); - } - reserveSpace(sizeof(std::uint32_t) + size); - serialize(value, size); + serializeQVariantHeader(field); } + reserveSpace(sizeof(double)); + serialize(value); +} - static const std::string QT_ENUM_BITS = "enumbits"; - static const std::string BITS_8 = "8"; - static const std::string BITS_16 = "16"; - static const std::string BITS_32 = "32"; - - void SerializerQt::Internal::enterEnum(const MetaField& field, std::int32_t value) +void SerializerQt::Internal::enterDouble(const MetaField& field, double value) +{ + assert(field.typeId == MetaTypeId::TYPE_DOUBLE); + if (isWrappedByQVariant()) { - assert(field.typeId == MetaTypeId::TYPE_ENUM); - if (isWrappedByQVariant()) - { - serializeQVariantHeader(field); - } - reserveSpace(sizeof(std::int32_t)); - const std::string* bits = &field.getProperty(QT_ENUM_BITS); - const MetaEnum* en = MetaDataGlobal::instance().getEnum(field.typeName); - if (en == nullptr) - { - streamError << "enum not found " << field.typeName; - } - if (bits->empty()) - { - if (en) - { - bits = &en->getProperty(QT_ENUM_BITS); - } - } - if (*bits == BITS_8) - { - serialize(static_cast(value)); - } - else if (*bits == BITS_16) - { - serialize(static_cast(value)); - } - else - { - serialize(value); - } + serializeQVariantHeader(field); } + reserveSpace(sizeof(double)); + serialize(value); +} - void SerializerQt::Internal::enterEnum(const MetaField& field, std::string&& value) +void SerializerQt::Internal::enterString(const MetaField& field, std::string&& value) +{ + assert(field.typeId == MetaTypeId::TYPE_STRING); + if (isWrappedByQVariant()) { - std::int32_t enumValue = MetaDataGlobal::instance().getEnumValueByName(field, value); - enterEnum(field, enumValue); + serializeQVariantHeader(field); } + reserveSpace(sizeof(std::uint32_t) + 2 * value.size()); + serializeString(value); +} - void SerializerQt::Internal::enterEnum(const MetaField& field, const char* value, ssize_t size) +void SerializerQt::Internal::enterString(const MetaField& field, const char* value, ssize_t size) +{ + assert(field.typeId == MetaTypeId::TYPE_STRING); + if (isWrappedByQVariant()) { - enterEnum(field, std::string(value, size)); + serializeQVariantHeader(field); } + reserveSpace(sizeof(std::uint32_t) + 2 * size); + serializeString(value, size); +} - void SerializerQt::Internal::enterArrayBoolMove(const MetaField& field, std::vector&& value) - { - enterArrayBool(field, value); - } +void SerializerQt::Internal::enterBytes(const MetaField& field, Bytes&& value) +{ + assert(field.typeId == MetaTypeId::TYPE_BYTES); + enterBytes(field, value.data(), value.size()); +} - void SerializerQt::Internal::enterArrayBool(const MetaField& field, const std::vector& value) +void SerializerQt::Internal::enterBytes(const MetaField& field, const BytesElement* value, ssize_t size) +{ + assert(field.typeId == MetaTypeId::TYPE_BYTES); + if (isWrappedByQVariant()) { - assert(field.typeId == MetaTypeId::TYPE_ARRAY_BOOL); - if (isWrappedByQVariant()) - { - serializeQVariantHeader(field); - } - const ssize_t sizeBytes = (value.size() + 7) / 8; - reserveSpace(sizeof(std::int32_t) + sizeBytes); - serializeArrayBool(value); + serializeQVariantHeader(field); } + reserveSpace(sizeof(std::uint32_t) + size); + serialize(value, size); +} - void SerializerQt::Internal::enterArrayInt8(const MetaField& field, std::vector&& value) - { - enterArrayInt8(field, value.data(), value.size()); - } +static const std::string QT_ENUM_BITS = "enumbits"; +static const std::string BITS_8 = "8"; +static const std::string BITS_16 = "16"; +static const std::string BITS_32 = "32"; - void SerializerQt::Internal::enterArrayInt8(const MetaField& field, const std::int8_t* value, ssize_t size) +void SerializerQt::Internal::enterEnum(const MetaField& field, std::int32_t value) +{ + assert(field.typeId == MetaTypeId::TYPE_ENUM); + if (isWrappedByQVariant()) { - assert(field.typeId == MetaTypeId::TYPE_ARRAY_INT8); - if (isWrappedByQVariant()) - { - serializeQVariantHeader(field); - } - reserveSpace(sizeof(std::int32_t) + size * sizeof(std::int8_t)); - serialize(value, size); + serializeQVariantHeader(field); } - - void SerializerQt::Internal::enterArrayInt16(const MetaField& field, std::vector&& value) + reserveSpace(sizeof(std::int32_t)); + const std::string* bits = &field.getProperty(QT_ENUM_BITS); + const MetaEnum* en = MetaDataGlobal::instance().getEnum(field.typeName); + if (en == nullptr) { - enterArrayInt16(field, value.data(), value.size()); + streamError << "enum not found " << field.typeName; } - - void SerializerQt::Internal::enterArrayInt16(const MetaField& field, const std::int16_t* value, ssize_t size) + if (bits->empty()) { - assert(field.typeId == MetaTypeId::TYPE_ARRAY_INT16); - if (isWrappedByQVariant()) + if (en) { - serializeQVariantHeader(field); + bits = &en->getProperty(QT_ENUM_BITS); } - reserveSpace(sizeof(std::int32_t) + size * sizeof(std::int16_t)); - serialize(value, size); } - - void SerializerQt::Internal::enterArrayUInt16(const MetaField& field, std::vector&& value) + if (*bits == BITS_8) { - enterArrayUInt16(field, value.data(), value.size()); + serialize(static_cast(value)); } - - void SerializerQt::Internal::enterArrayUInt16(const MetaField& field, const std::uint16_t* value, ssize_t size) + else if (*bits == BITS_16) { - assert(field.typeId == MetaTypeId::TYPE_ARRAY_UINT16); - if (isWrappedByQVariant()) - { - serializeQVariantHeader(field); - } - reserveSpace(sizeof(std::int32_t) + size * sizeof(std::uint16_t)); - serialize(value, size); + serialize(static_cast(value)); } - - void SerializerQt::Internal::enterArrayInt32(const MetaField& field, std::vector&& value) - { - enterArrayInt32(field, value.data(), value.size()); - } - - void SerializerQt::Internal::enterArrayInt32(const MetaField& field, const std::int32_t* value, ssize_t size) + else { - assert(field.typeId == MetaTypeId::TYPE_ARRAY_INT32); - if (isWrappedByQVariant()) - { - serializeQVariantHeader(field); - } - reserveSpace(sizeof(std::int32_t) + size * sizeof(std::int32_t)); - serialize(value, size); - } - - void SerializerQt::Internal::enterArrayUInt32(const MetaField& field, std::vector&& value) - { - enterArrayUInt32(field, value.data(), value.size()); - } - - void SerializerQt::Internal::enterArrayUInt32(const MetaField& field, const std::uint32_t* value, ssize_t size) - { - assert(field.typeId == MetaTypeId::TYPE_ARRAY_UINT32); - if (isWrappedByQVariant()) - { - serializeQVariantHeader(field); - } - reserveSpace(sizeof(std::int32_t) + size * sizeof(std::uint32_t)); - serialize(value, size); - } - - void SerializerQt::Internal::enterArrayInt64(const MetaField& field, std::vector&& value) - { - enterArrayInt64(field, value.data(), value.size()); - } - - void SerializerQt::Internal::enterArrayInt64(const MetaField& field, const std::int64_t* value, ssize_t size) - { - assert(field.typeId == MetaTypeId::TYPE_ARRAY_INT64); - if (isWrappedByQVariant()) - { - serializeQVariantHeader(field); - } - reserveSpace(sizeof(std::int32_t) + size * sizeof(std::int64_t)); - serialize(value, size); + serialize(value); } +} - void SerializerQt::Internal::enterArrayUInt64(const MetaField& field, std::vector&& value) - { - enterArrayUInt64(field, value.data(), value.size()); - } +void SerializerQt::Internal::enterEnum(const MetaField& field, std::string&& value) +{ + std::int32_t enumValue = MetaDataGlobal::instance().getEnumValueByName(field, value); + enterEnum(field, enumValue); +} - void SerializerQt::Internal::enterArrayUInt64(const MetaField& field, const std::uint64_t* value, ssize_t size) - { - assert(field.typeId == MetaTypeId::TYPE_ARRAY_UINT64); - if (isWrappedByQVariant()) - { - serializeQVariantHeader(field); - } - reserveSpace(sizeof(std::int32_t) + size * sizeof(std::uint64_t)); - serialize(value, size); - } +void SerializerQt::Internal::enterEnum(const MetaField& field, const char* value, ssize_t size) +{ + enterEnum(field, std::string(value, size)); +} - void SerializerQt::Internal::enterArrayFloat(const MetaField& field, std::vector&& value) - { - enterArrayFloat(field, value.data(), value.size()); - } +void SerializerQt::Internal::enterArrayBoolMove(const MetaField& field, std::vector&& value) +{ + enterArrayBool(field, value); +} - void SerializerQt::Internal::enterArrayFloat(const MetaField& field, const float* value, ssize_t size) +void SerializerQt::Internal::enterArrayBool(const MetaField& field, const std::vector& value) +{ + assert(field.typeId == MetaTypeId::TYPE_ARRAY_BOOL); + if (isWrappedByQVariant()) { - assert(field.typeId == MetaTypeId::TYPE_ARRAY_FLOAT); - if (isWrappedByQVariant()) - { - serializeQVariantHeader(field); - } - reserveSpace(sizeof(std::int32_t) + size * sizeof(double)); - serialize(value, size); + serializeQVariantHeader(field); } + const ssize_t sizeBytes = (value.size() + 7) / 8; + reserveSpace(sizeof(std::int32_t) + sizeBytes); + serializeArrayBool(value); +} - void SerializerQt::Internal::enterArrayDouble(const MetaField& field, std::vector&& value) +void SerializerQt::Internal::enterArrayInt8(const MetaField& field, std::vector&& value) +{ + enterArrayInt8(field, value.data(), value.size()); +} + +void SerializerQt::Internal::enterArrayInt8(const MetaField& field, const std::int8_t* value, ssize_t size) +{ + assert(field.typeId == MetaTypeId::TYPE_ARRAY_INT8); + if (isWrappedByQVariant()) { - enterArrayDouble(field, value.data(), value.size()); + serializeQVariantHeader(field); } + reserveSpace(sizeof(std::int32_t) + size * sizeof(std::int8_t)); + serialize(value, size); +} - void SerializerQt::Internal::enterArrayDouble(const MetaField& field, const double* value, ssize_t size) +void SerializerQt::Internal::enterArrayInt16(const MetaField& field, std::vector&& value) +{ + enterArrayInt16(field, value.data(), value.size()); +} + +void SerializerQt::Internal::enterArrayInt16(const MetaField& field, const std::int16_t* value, ssize_t size) +{ + assert(field.typeId == MetaTypeId::TYPE_ARRAY_INT16); + if (isWrappedByQVariant()) { - assert(field.typeId == MetaTypeId::TYPE_ARRAY_DOUBLE); - if (isWrappedByQVariant()) - { - serializeQVariantHeader(field); - } - reserveSpace(sizeof(std::int32_t) + size * sizeof(double)); - serialize(value, size); + serializeQVariantHeader(field); } + reserveSpace(sizeof(std::int32_t) + size * sizeof(std::int16_t)); + serialize(value, size); +} - void SerializerQt::Internal::enterArrayStringMove(const MetaField& field, std::vector&& value) +void SerializerQt::Internal::enterArrayUInt16(const MetaField& field, std::vector&& value) +{ + enterArrayUInt16(field, value.data(), value.size()); +} + +void SerializerQt::Internal::enterArrayUInt16(const MetaField& field, const std::uint16_t* value, ssize_t size) +{ + assert(field.typeId == MetaTypeId::TYPE_ARRAY_UINT16); + if (isWrappedByQVariant()) { - enterArrayString(field, value); + serializeQVariantHeader(field); } + reserveSpace(sizeof(std::int32_t) + size * sizeof(std::uint16_t)); + serialize(value, size); +} - void SerializerQt::Internal::enterArrayString(const MetaField& field, const std::vector& value) +void SerializerQt::Internal::enterArrayInt32(const MetaField& field, std::vector&& value) +{ + enterArrayInt32(field, value.data(), value.size()); +} + +void SerializerQt::Internal::enterArrayInt32(const MetaField& field, const std::int32_t* value, ssize_t size) +{ + assert(field.typeId == MetaTypeId::TYPE_ARRAY_INT32); + if (isWrappedByQVariant()) { - assert(field.typeId == MetaTypeId::TYPE_ARRAY_STRING); - if (isWrappedByQVariant()) - { - serializeQVariantHeader(field); - } - std::uint32_t len = sizeof(std::uint32_t); - for (size_t i = 0; i < value.size(); ++i) - { - len += sizeof(std::uint32_t) + 2 * static_cast(value.size()); - } - reserveSpace(len); - serializeArrayString(value); + serializeQVariantHeader(field); } + reserveSpace(sizeof(std::int32_t) + size * sizeof(std::int32_t)); + serialize(value, size); +} - void SerializerQt::Internal::enterArrayBytesMove(const MetaField& field, std::vector&& value) - { - enterArrayBytes(field, value); - } +void SerializerQt::Internal::enterArrayUInt32(const MetaField& field, std::vector&& value) +{ + enterArrayUInt32(field, value.data(), value.size()); +} - void SerializerQt::Internal::enterArrayBytes(const MetaField& field, const std::vector& value) - { - assert(field.typeId == MetaTypeId::TYPE_ARRAY_BYTES); - if (isWrappedByQVariant()) - { - serializeQVariantHeader(field); - } - std::uint32_t len = sizeof(std::uint32_t); - for (size_t i = 0; i < value.size(); ++i) - { - len += sizeof(std::uint32_t) + static_cast(value.size()); - } - reserveSpace(len); - serializeArrayBytes(value); +void SerializerQt::Internal::enterArrayUInt32(const MetaField& field, const std::uint32_t* value, ssize_t size) +{ + assert(field.typeId == MetaTypeId::TYPE_ARRAY_UINT32); + if (isWrappedByQVariant()) + { + serializeQVariantHeader(field); } + reserveSpace(sizeof(std::int32_t) + size * sizeof(std::uint32_t)); + serialize(value, size); +} - void SerializerQt::Internal::enterArrayEnum(const MetaField& field, std::vector&& value) - { - enterArrayEnum(field, value.data(), value.size()); - } +void SerializerQt::Internal::enterArrayInt64(const MetaField& field, std::vector&& value) +{ + enterArrayInt64(field, value.data(), value.size()); +} - void SerializerQt::Internal::enterArrayEnum(const MetaField& field, const std::int32_t* value, ssize_t size) +void SerializerQt::Internal::enterArrayInt64(const MetaField& field, const std::int64_t* value, ssize_t size) +{ + assert(field.typeId == MetaTypeId::TYPE_ARRAY_INT64); + if (isWrappedByQVariant()) { - assert(field.typeId == MetaTypeId::TYPE_ARRAY_ENUM); - if (isWrappedByQVariant()) - { - serializeQVariantHeader(field); - } - reserveSpace(sizeof(std::int32_t) + size * sizeof(std::int32_t)); - - const std::string* bits = &field.getProperty(QT_ENUM_BITS); - if (bits->empty()) - { - const MetaEnum* en = MetaDataGlobal::instance().getEnum(field.typeName); - if (en) - { - bits = &en->getProperty(QT_ENUM_BITS); - } - } - if (*bits == BITS_8) - { - std::vector value8; - value8.resize(size); - for (ssize_t i = 0; i < size; ++i) - { - value8[i] = static_cast(value[i]); - } - serialize(value8.data(), size); - } - else if (*bits == BITS_16) - { - std::vector value16; - value16.resize(size); - for (ssize_t i = 0; i < size; ++i) - { - value16[i] = static_cast(value[i]); - } - serialize(value16.data(), size); - } - else - { - serialize(value, size); - } + serializeQVariantHeader(field); } + reserveSpace(sizeof(std::int32_t) + size * sizeof(std::int64_t)); + serialize(value, size); +} - void SerializerQt::Internal::enterArrayEnumMove(const MetaField& field, std::vector&& value) - { - enterArrayEnum(field, value); - } +void SerializerQt::Internal::enterArrayUInt64(const MetaField& field, std::vector&& value) +{ + enterArrayUInt64(field, value.data(), value.size()); +} - void SerializerQt::Internal::enterArrayEnum(const MetaField& field, const std::vector& value) +void SerializerQt::Internal::enterArrayUInt64(const MetaField& field, const std::uint64_t* value, ssize_t size) +{ + assert(field.typeId == MetaTypeId::TYPE_ARRAY_UINT64); + if (isWrappedByQVariant()) { - std::vector enums; - enums.resize(value.size()); - for (size_t i = 0; i < value.size(); ++i) - { - const std::int32_t enumValue = MetaDataGlobal::instance().getEnumValueByName(field, value[i]); - enums[i] = enumValue; - } - enterArrayEnum(field, enums.data(), enums.size()); + serializeQVariantHeader(field); } + reserveSpace(sizeof(std::int32_t) + size * sizeof(std::uint64_t)); + serialize(value, size); +} +void SerializerQt::Internal::enterArrayFloat(const MetaField& field, std::vector&& value) +{ + enterArrayFloat(field, value.data(), value.size()); +} - void SerializerQt::Internal::serialize(char value) - { - serialize(static_cast(value)); - } - - void SerializerQt::Internal::serialize(std::int8_t value) +void SerializerQt::Internal::enterArrayFloat(const MetaField& field, const float* value, ssize_t size) +{ + assert(field.typeId == MetaTypeId::TYPE_ARRAY_FLOAT); + if (isWrappedByQVariant()) { - serialize(static_cast(value)); + serializeQVariantHeader(field); } + reserveSpace(sizeof(std::int32_t) + size * sizeof(double)); + serialize(value, size); +} - void SerializerQt::Internal::serialize(std::uint8_t value) - { - *m_buffer = value; - ++m_buffer; - } +void SerializerQt::Internal::enterArrayDouble(const MetaField& field, std::vector&& value) +{ + enterArrayDouble(field, value.data(), value.size()); +} - void SerializerQt::Internal::serialize(std::int16_t value) +void SerializerQt::Internal::enterArrayDouble(const MetaField& field, const double* value, ssize_t size) +{ + assert(field.typeId == MetaTypeId::TYPE_ARRAY_DOUBLE); + if (isWrappedByQVariant()) { - serialize(static_cast(value)); + serializeQVariantHeader(field); } + reserveSpace(sizeof(std::int32_t) + size * sizeof(double)); + serialize(value, size); +} - void SerializerQt::Internal::serialize(std::uint16_t value) - { - *m_buffer = (value >> 8) & 0xff; - ++m_buffer; - *m_buffer = (value) & 0xff; - ++m_buffer; - } +void SerializerQt::Internal::enterArrayStringMove(const MetaField& field, std::vector&& value) +{ + enterArrayString(field, value); +} - void SerializerQt::Internal::serialize(std::int32_t value) +void SerializerQt::Internal::enterArrayString(const MetaField& field, const std::vector& value) +{ + assert(field.typeId == MetaTypeId::TYPE_ARRAY_STRING); + if (isWrappedByQVariant()) { - serialize(static_cast(value)); + serializeQVariantHeader(field); } - - void SerializerQt::Internal::serialize(std::uint32_t value) + std::uint32_t len = sizeof(std::uint32_t); + for (size_t i = 0; i < value.size(); ++i) { - *m_buffer = (value >> 24) & 0xff; - ++m_buffer; - *m_buffer = (value >> 16) & 0xff; - ++m_buffer; - *m_buffer = (value >> 8) & 0xff; - ++m_buffer; - *m_buffer = (value) & 0xff; - ++m_buffer; + len += static_cast(sizeof(std::uint32_t) + 2 * static_cast(value.size())); } + reserveSpace(len); + serializeArrayString(value); +} - void SerializerQt::Internal::serialize(std::int64_t value) - { - serialize(static_cast(value)); - } +void SerializerQt::Internal::enterArrayBytesMove(const MetaField& field, std::vector&& value) +{ + enterArrayBytes(field, value); +} - void SerializerQt::Internal::serialize(std::uint64_t value) +void SerializerQt::Internal::enterArrayBytes(const MetaField& field, const std::vector& value) +{ + assert(field.typeId == MetaTypeId::TYPE_ARRAY_BYTES); + if (isWrappedByQVariant()) { - *m_buffer = (value >> 56) & 0xff; - ++m_buffer; - *m_buffer = (value >> 48) & 0xff; - ++m_buffer; - *m_buffer = (value >> 40) & 0xff; - ++m_buffer; - *m_buffer = (value >> 32) & 0xff; - ++m_buffer; - *m_buffer = (value >> 24) & 0xff; - ++m_buffer; - *m_buffer = (value >> 16) & 0xff; - ++m_buffer; - *m_buffer = (value >> 8) & 0xff; - ++m_buffer; - *m_buffer = (value) & 0xff; - ++m_buffer; + serializeQVariantHeader(field); } - - void SerializerQt::Internal::serialize(float value) + std::uint32_t len = sizeof(std::uint32_t); + for (size_t i = 0; i < value.size(); ++i) { - union - { - std::uint64_t v; - double d; - } u; - u.d = static_cast(value); - serialize(u.v); + len += static_cast(sizeof(std::uint32_t) + static_cast(value.size())); } + reserveSpace(len); + serializeArrayBytes(value); +} - void SerializerQt::Internal::serialize(double value) - { - union - { - std::uint64_t v; - double d; - } u; - u.d = value; - serialize(u.v); - } +void SerializerQt::Internal::enterArrayEnum(const MetaField& field, std::vector&& value) +{ + enterArrayEnum(field, value.data(), value.size()); +} - void SerializerQt::Internal::serializeString(const std::string& value) +void SerializerQt::Internal::enterArrayEnum(const MetaField& field, const std::int32_t* value, ssize_t size) +{ + assert(field.typeId == MetaTypeId::TYPE_ARRAY_ENUM); + if (isWrappedByQVariant()) { - std::u16string u16 = std::wstring_convert, char16_t>{}.from_bytes(value); - assert(u16.size() <= value.size()); - serialize((std::int16_t*)(u16.data()), u16.size(), true); - } - - void SerializerQt::Internal::serializeString(const char* value, ssize_t size) - { - serializeString(std::string(value, value + size)); + serializeQVariantHeader(field); } + reserveSpace(sizeof(std::int32_t) + size * sizeof(std::int32_t)); - template - void SerializerQt::Internal::serialize(const T* value, ssize_t size, bool sizeTimesTwo) + const std::string* bits = &field.getProperty(QT_ENUM_BITS); + if (bits->empty()) { - std::uint32_t s = static_cast(size); - if (sizeTimesTwo) - { - serialize(s * 2); - } - else - { - serialize(s); - } - - for (std::uint32_t i = 0; i < s; ++i) + const MetaEnum* en = MetaDataGlobal::instance().getEnum(field.typeName); + if (en) { - serialize(value[i]); + bits = &en->getProperty(QT_ENUM_BITS); } } - - void SerializerQt::Internal::serializeArrayBool(const std::vector& value) + if (*bits == BITS_8) { - std::uint32_t s = static_cast(value.size()); - serialize(s); - const ssize_t sizeBytes = (value.size() + 7) / 8; - for (ssize_t i = 0; i < sizeBytes; ++i) + std::vector value8; + value8.resize(size); + for (ssize_t i = 0; i < size; ++i) { - m_buffer[i] = 0; + value8[i] = static_cast(value[i]); } - for (std::uint32_t i = 0; i < s; ++i) - { - if (value[i]) - { - const std::uint32_t indexBytes = i / 8; - const std::uint32_t indexBits = i % 8; - m_buffer[indexBytes] |= (1 << indexBits); - } - } - m_buffer += sizeBytes; + serialize(value8.data(), size); } - - void SerializerQt::Internal::serializeArrayString(const std::vector& value) + else if (*bits == BITS_16) { - std::uint32_t s = static_cast(value.size()); - serialize(s); - for (std::uint32_t i = 0; i < s; ++i) + std::vector value16; + value16.resize(size); + for (ssize_t i = 0; i < size; ++i) { - serializeString(value[i]); + value16[i] = static_cast(value[i]); } + serialize(value16.data(), size); } - - void SerializerQt::Internal::serializeArrayBytes(const std::vector& value) + else { - std::uint32_t s = static_cast(value.size()); - serialize(s); - for (std::uint32_t i = 0; i < s; ++i) - { - serialize(value[i].data(), value[i].size()); - } + serialize(value, size); } - - - - void SerializerQt::Internal::serializeQVariantHeader(const MetaField& field) +} + +void SerializerQt::Internal::enterArrayEnumMove(const MetaField& field, std::vector&& value) +{ + enterArrayEnum(field, value); +} + +void SerializerQt::Internal::enterArrayEnum(const MetaField& field, const std::vector& value) +{ + std::vector enums; + enums.resize(value.size()); + for (size_t i = 0; i < value.size(); ++i) + { + const std::int32_t enumValue = MetaDataGlobal::instance().getEnumValueByName(field, value[i]); + enums[i] = enumValue; + } + enterArrayEnum(field, enums.data(), enums.size()); +} + +void SerializerQt::Internal::serialize(char value) +{ + serialize(static_cast(value)); +} + +void SerializerQt::Internal::serialize(std::int8_t value) +{ + serialize(static_cast(value)); +} + +void SerializerQt::Internal::serialize(std::uint8_t value) +{ + *m_buffer = value; + ++m_buffer; +} + +void SerializerQt::Internal::serialize(std::int16_t value) +{ + serialize(static_cast(value)); +} + +void SerializerQt::Internal::serialize(std::uint16_t value) +{ + *m_buffer = static_cast((value >> 8) & 0xff); + ++m_buffer; + *m_buffer = static_cast((value)&0xff); + ++m_buffer; +} + +void SerializerQt::Internal::serialize(std::int32_t value) +{ + serialize(static_cast(value)); +} + +void SerializerQt::Internal::serialize(std::uint32_t value) +{ + *m_buffer = static_cast((value >> 24) & 0xff); + ++m_buffer; + *m_buffer = static_cast((value >> 16) & 0xff); + ++m_buffer; + *m_buffer = static_cast((value >> 8) & 0xff); + ++m_buffer; + *m_buffer = static_cast((value)&0xff); + ++m_buffer; +} + +void SerializerQt::Internal::serialize(std::int64_t value) +{ + serialize(static_cast(value)); +} + +void SerializerQt::Internal::serialize(std::uint64_t value) +{ + *m_buffer = static_cast((value >> 56) & 0xff); + ++m_buffer; + *m_buffer = static_cast((value >> 48) & 0xff); + ++m_buffer; + *m_buffer = static_cast((value >> 40) & 0xff); + ++m_buffer; + *m_buffer = static_cast((value >> 32) & 0xff); + ++m_buffer; + *m_buffer = static_cast((value >> 24) & 0xff); + ++m_buffer; + *m_buffer = static_cast((value >> 16) & 0xff); + ++m_buffer; + *m_buffer = static_cast((value >> 8) & 0xff); + ++m_buffer; + *m_buffer = static_cast(value & 0xff); + ++m_buffer; +} + +void SerializerQt::Internal::serialize(float value) +{ + union + { + std::uint64_t v; + double d; + } u; + u.d = static_cast(value); + serialize(u.v); +} + +void SerializerQt::Internal::serialize(double value) +{ + union + { + std::uint64_t v; + double d; + } u; + u.d = value; + serialize(u.v); +} + +void SerializerQt::Internal::serializeString(const std::string& value) +{ + std::u16string u16 = std::wstring_convert, char16_t>{}.from_bytes(value); + assert(u16.size() <= value.size()); + serialize(reinterpret_cast(const_cast(u16.data())), u16.size(), true); +} + +void SerializerQt::Internal::serializeString(const char* value, ssize_t size) +{ + serializeString(std::string(value, value + size)); +} + +template +void SerializerQt::Internal::serialize(const T* value, ssize_t size, bool sizeTimesTwo) +{ + std::uint32_t s = static_cast(size); + if (sizeTimesTwo) + { + serialize(s * 2); + } + else { - std::uint32_t typeId; - std::string typeName; - getQVariantType(field, typeId, typeName); - - reserveSpace(sizeof(std::int32_t) + sizeof(std::int8_t) + ((typeId == static_cast(QtType::User)) ? typeName.size() : 0)); - - serialize(typeId); - serialize(static_cast(0)); - - if (typeId == static_cast(QtType::User)) - { - serialize(typeName.data(), typeName.size() + 1); - } + serialize(s); } - bool SerializerQt::Internal::isWrappedByQVariant() const + for (std::uint32_t i = 0; i < s; ++i) { - return (m_levelState.size() == 1 && (m_mode != Mode::NONE)); + serialize(value[i]); } +} - bool SerializerQt::Internal::getQVariantTypeFromMetaTypeId(const MetaField& field, std::uint32_t& typeId, std::string& typeName) +void SerializerQt::Internal::serializeArrayBool(const std::vector& value) +{ + std::uint32_t s = static_cast(value.size()); + serialize(s); + const ssize_t sizeBytes = (value.size() + 7) / 8; + for (ssize_t i = 0; i < sizeBytes; ++i) { - typeId = static_cast(QtType::UnknownType); - typeName.clear(); - - switch (field.typeId) - { - case MetaTypeId::TYPE_BOOL: - typeId = static_cast(QtType::Bool); - break; - case MetaTypeId::TYPE_INT8: - typeId = static_cast(QtType::Char); - break; - case MetaTypeId::TYPE_UINT8: - typeId = static_cast(QtType::UChar); - break; - case MetaTypeId::TYPE_INT16: - typeId = static_cast(QtType::Short); - break; - case MetaTypeId::TYPE_UINT16: - typeId = static_cast(QtType::UShort); - break; - case MetaTypeId::TYPE_INT32: - typeId = static_cast(QtType::Int); - break; - case MetaTypeId::TYPE_UINT32: - typeId = static_cast(QtType::UInt); - break; - case MetaTypeId::TYPE_INT64: - typeId = static_cast(QtType::LongLong); - break; - case MetaTypeId::TYPE_UINT64: - typeId = static_cast(QtType::ULongLong); - break; - case MetaTypeId::TYPE_FLOAT: - typeId = static_cast(QtType::Float); - break; - case MetaTypeId::TYPE_DOUBLE: - typeId = static_cast(QtType::Double); - break; - case MetaTypeId::TYPE_STRING: - typeId = static_cast(QtType::QString); - break; - case MetaTypeId::TYPE_BYTES: - typeId = static_cast(QtType::QByteArray); - break; - case MetaTypeId::TYPE_STRUCT: - typeId = static_cast(QtType::User); - typeName = Utils::replaceAll(field.typeName, ".", "::"); - break; - case MetaTypeId::TYPE_ENUM: - typeId = static_cast(QtType::User); - typeName = Utils::replaceAll(field.typeName, ".", "::"); - break; - case MetaTypeId::TYPE_ARRAY_BOOL: - typeId = static_cast(QtType::QBitArray); - break; - case MetaTypeId::TYPE_ARRAY_INT8: - typeId = static_cast(QtType::User); - typeName = "QVector"; - break; - case MetaTypeId::TYPE_ARRAY_INT16: - typeId = static_cast(QtType::User); - typeName = "QVector"; - break; - case MetaTypeId::TYPE_ARRAY_UINT16: - typeId = static_cast(QtType::User); - typeName = "QVector"; - break; - case MetaTypeId::TYPE_ARRAY_INT32: - typeId = static_cast(QtType::User); - typeName = "QVector"; - break; - case MetaTypeId::TYPE_ARRAY_UINT32: - typeId = static_cast(QtType::User); - typeName = "QVector"; - break; - case MetaTypeId::TYPE_ARRAY_INT64: - typeId = static_cast(QtType::User); - typeName = "QVector"; - break; - case MetaTypeId::TYPE_ARRAY_UINT64: - typeId = static_cast(QtType::User); - typeName = "QVector"; - break; - case MetaTypeId::TYPE_ARRAY_FLOAT: - typeId = static_cast(QtType::User); - typeName = "QVector"; - break; - case MetaTypeId::TYPE_ARRAY_DOUBLE: - typeId = static_cast(QtType::User); - typeName = "QVector"; - break; - case MetaTypeId::TYPE_ARRAY_STRING: - typeId = static_cast(QtType::QStringList); - break; - case MetaTypeId::TYPE_ARRAY_BYTES: - typeId = static_cast(QtType::QByteArrayList); - break; - case MetaTypeId::TYPE_ARRAY_STRUCT: - typeId = static_cast(QtType::User); - typeName = "QList<" + Utils::replaceAll(field.typeName, ".", "::") + ">"; - break; - case MetaTypeId::TYPE_ARRAY_ENUM: - typeId = static_cast(QtType::User); - typeName = "QList<" + Utils::replaceAll(field.typeName, ".", "::") + ">"; - break; - default: - break; - } - - return (typeId != static_cast(QtType::UnknownType)); + m_buffer[i] = 0; } - - std::uint32_t SerializerQt::Internal::getTypeIdByName(const std::string& typeName) + for (std::uint32_t i = 0; i < s; ++i) { - std::unordered_map table{ - { "bool", static_cast(QtType::Bool) }, - { "int", static_cast(QtType::Int) }, - { "uint", static_cast(QtType::UInt) }, - { "qlonglong", static_cast(QtType::LongLong) }, - { "qulonglong", static_cast(QtType::ULongLong) }, - { "double", static_cast(QtType::Double) }, - { "long", static_cast(QtType::Long) }, - { "short", static_cast(QtType::Short) }, - { "char", static_cast(QtType::Char) }, - { "ulong", static_cast(QtType::ULong) }, - { "ushort", static_cast(QtType::UShort) }, - { "uchar", static_cast(QtType::UChar) }, - { "float", static_cast(QtType::Float) }, - { "QChar", static_cast(QtType::QChar) }, - { "QString", static_cast(QtType::QString) }, - { "QStringList", static_cast(QtType::QStringList) }, - { "QByteArray", static_cast(QtType::QByteArray) }, - { "QBitArray", static_cast(QtType::QBitArray) }, - { "QDate", static_cast(QtType::QDate) }, - { "QTime", static_cast(QtType::QTime) }, - { "QDateTime", static_cast(QtType::QDateTime) }, - { "QUrl", static_cast(QtType::QUrl) }, - { "QLocale", static_cast(QtType::QLocale) }, - { "QRect", static_cast(QtType::QRect) }, - { "QRectF", static_cast(QtType::QRectF) }, - { "QSize", static_cast(QtType::QSize) }, - { "QSizeF", static_cast(QtType::QSizeF) }, - { "QLine", static_cast(QtType::QLine) }, - { "QLineF", static_cast(QtType::QLineF) }, - { "QPoint", static_cast(QtType::QPoint) }, - { "QPointF", static_cast(QtType::QPointF) }, - { "QRegExp", static_cast(QtType::QRegExp) }, - { "QEasingCurve", static_cast(QtType::QEasingCurve) }, - { "QUuid", static_cast(QtType::QUuid) }, - { "QVariant", static_cast(QtType::QVariant) }, - { "QModelIndex", static_cast(QtType::QModelIndex) }, - { "QPersistentModelIndex", static_cast(QtType::QPersistentModelIndex) }, - { "QRegularExpression", static_cast(QtType::QRegularExpression) }, - { "QJsonValue", static_cast(QtType::QJsonValue) }, - { "QJsonObject", static_cast(QtType::QJsonObject) }, - { "QJsonArray", static_cast(QtType::QJsonArray) }, - { "QJsonDocument", static_cast(QtType::QJsonDocument) }, - { "QByteArrayList", static_cast(QtType::QByteArrayList) }, - { "QObjectStar", static_cast(QtType::QObjectStar) }, - { "SChar", static_cast(QtType::SChar) }, - { "Void", static_cast(QtType::Void) }, - { "Nullptr", static_cast(QtType::Nullptr) }, - { "QVariantMap", static_cast(QtType::QVariantMap) }, - { "QVariantList", static_cast(QtType::QVariantList) }, - { "QVariantHash", static_cast(QtType::QVariantHash) }, - { "QCborSimpleType", static_cast(QtType::QCborSimpleType) }, - { "QCborValue", static_cast(QtType::QCborValue) }, - { "QCborArray", static_cast(QtType::QCborArray) }, - { "QCborMap", static_cast(QtType::QCborMap) }, - { "QFont", static_cast(QtType::QFont) }, - { "QPixmap", static_cast(QtType::QPixmap) }, - { "QBrush", static_cast(QtType::QBrush) }, - { "QColor", static_cast(QtType::QColor) }, - { "QPalette", static_cast(QtType::QPalette) }, - { "QIcon", static_cast(QtType::QIcon) }, - { "QImage", static_cast(QtType::QImage) }, - { "QPolygon", static_cast(QtType::QPolygon) }, - { "QRegion", static_cast(QtType::QRegion) }, - { "QBitmap", static_cast(QtType::QBitmap) }, - { "QCursor", static_cast(QtType::QCursor) }, - { "QKeySequence", static_cast(QtType::QKeySequence) }, - { "QPen", static_cast(QtType::QPen) }, - { "QTextLength", static_cast(QtType::QTextLength) }, - { "QTextFormat", static_cast(QtType::QTextFormat) }, - { "QMatrix", static_cast(QtType::QMatrix) }, - { "QTransform", static_cast(QtType::QTransform) }, - { "QMatrix4x4", static_cast(QtType::QMatrix4x4) }, - { "QVector2D", static_cast(QtType::QVector2D) }, - { "QVector3D", static_cast(QtType::QVector3D) }, - { "QVector4D", static_cast(QtType::QVector4D) }, - { "QQuaternion", static_cast(QtType::QQuaternion) }, - { "QPolygonF", static_cast(QtType::QPolygonF) }, - { "QColorSpace", static_cast(QtType::QColorSpace) }, - { "QSizePolicy", static_cast(QtType::QSizePolicy) }, - }; - - const auto it = table.find(typeName); - if (it != table.end()) + if (value[i]) { - return it->second; + const std::uint32_t indexBytes = i / 8; + const std::uint32_t indexBits = i % 8; + m_buffer[indexBytes] |= static_cast(1 << indexBits); } - return static_cast(QtType::User); } - - void SerializerQt::Internal::getQVariantType(const MetaField& field, std::uint32_t& typeId, std::string& typeName) - { - typeName.clear(); - - static const std::string KEY_QTTYPE = "qttype"; - typeName = field.getProperty(KEY_QTTYPE); - - if (typeName.empty()) + m_buffer += sizeBytes; +} + +void SerializerQt::Internal::serializeArrayString(const std::vector& value) +{ + std::uint32_t s = static_cast(value.size()); + serialize(s); + for (std::uint32_t i = 0; i < s; ++i) + { + serializeString(value[i]); + } +} + +void SerializerQt::Internal::serializeArrayBytes(const std::vector& value) +{ + std::uint32_t s = static_cast(value.size()); + serialize(s); + for (std::uint32_t i = 0; i < s; ++i) + { + serialize(value[i].data(), value[i].size()); + } +} + +void SerializerQt::Internal::serializeQVariantHeader(const MetaField& field) +{ + std::uint32_t typeId; + std::string typeName; + getQVariantType(field, typeId, typeName); + + reserveSpace(sizeof(std::int32_t) + sizeof(std::int8_t) + ((typeId == static_cast(QtType::User)) ? typeName.size() : 0)); + + serialize(typeId); + serialize(static_cast(0)); + + if (typeId == static_cast(QtType::User)) + { + serialize(typeName.data(), typeName.size() + 1); + } +} + +bool SerializerQt::Internal::isWrappedByQVariant() const +{ + return (m_levelState.size() == 1 && (m_mode != Mode::NONE)); +} + +bool SerializerQt::Internal::getQVariantTypeFromMetaTypeId(const MetaField& field, std::uint32_t& typeId, std::string& typeName) +{ + typeId = static_cast(QtType::UnknownType); + typeName.clear(); + + switch(field.typeId) + { + case MetaTypeId::TYPE_BOOL: + typeId = static_cast(QtType::Bool); + break; + case MetaTypeId::TYPE_INT8: + typeId = static_cast(QtType::Char); + break; + case MetaTypeId::TYPE_UINT8: + typeId = static_cast(QtType::UChar); + break; + case MetaTypeId::TYPE_INT16: + typeId = static_cast(QtType::Short); + break; + case MetaTypeId::TYPE_UINT16: + typeId = static_cast(QtType::UShort); + break; + case MetaTypeId::TYPE_INT32: + typeId = static_cast(QtType::Int); + break; + case MetaTypeId::TYPE_UINT32: + typeId = static_cast(QtType::UInt); + break; + case MetaTypeId::TYPE_INT64: + typeId = static_cast(QtType::LongLong); + break; + case MetaTypeId::TYPE_UINT64: + typeId = static_cast(QtType::ULongLong); + break; + case MetaTypeId::TYPE_FLOAT: + typeId = static_cast(QtType::Float); + break; + case MetaTypeId::TYPE_DOUBLE: + typeId = static_cast(QtType::Double); + break; + case MetaTypeId::TYPE_STRING: + typeId = static_cast(QtType::QString); + break; + case MetaTypeId::TYPE_BYTES: + typeId = static_cast(QtType::QByteArray); + break; + case MetaTypeId::TYPE_STRUCT: + typeId = static_cast(QtType::User); + typeName = Utils::replaceAll(field.typeName, ".", "::"); + break; + case MetaTypeId::TYPE_ENUM: + typeId = static_cast(QtType::User); + typeName = Utils::replaceAll(field.typeName, ".", "::"); + break; + case MetaTypeId::TYPE_ARRAY_BOOL: + typeId = static_cast(QtType::QBitArray); + break; + case MetaTypeId::TYPE_ARRAY_INT8: + typeId = static_cast(QtType::User); + typeName = "QVector"; + break; + case MetaTypeId::TYPE_ARRAY_INT16: + typeId = static_cast(QtType::User); + typeName = "QVector"; + break; + case MetaTypeId::TYPE_ARRAY_UINT16: + typeId = static_cast(QtType::User); + typeName = "QVector"; + break; + case MetaTypeId::TYPE_ARRAY_INT32: + typeId = static_cast(QtType::User); + typeName = "QVector"; + break; + case MetaTypeId::TYPE_ARRAY_UINT32: + typeId = static_cast(QtType::User); + typeName = "QVector"; + break; + case MetaTypeId::TYPE_ARRAY_INT64: + typeId = static_cast(QtType::User); + typeName = "QVector"; + break; + case MetaTypeId::TYPE_ARRAY_UINT64: + typeId = static_cast(QtType::User); + typeName = "QVector"; + break; + case MetaTypeId::TYPE_ARRAY_FLOAT: + typeId = static_cast(QtType::User); + typeName = "QVector"; + break; + case MetaTypeId::TYPE_ARRAY_DOUBLE: + typeId = static_cast(QtType::User); + typeName = "QVector"; + break; + case MetaTypeId::TYPE_ARRAY_STRING: + typeId = static_cast(QtType::QStringList); + break; + case MetaTypeId::TYPE_ARRAY_BYTES: + typeId = static_cast(QtType::QByteArrayList); + break; + case MetaTypeId::TYPE_ARRAY_STRUCT: + typeId = static_cast(QtType::User); + typeName = "QList<" + Utils::replaceAll(field.typeName, ".", "::") + ">"; + break; + case MetaTypeId::TYPE_ARRAY_ENUM: + typeId = static_cast(QtType::User); + typeName = "QList<" + Utils::replaceAll(field.typeName, ".", "::") + ">"; + break; + default: + break; + } + + return (typeId != static_cast(QtType::UnknownType)); +} + +std::uint32_t SerializerQt::Internal::getTypeIdByName(const std::string& typeName) +{ + std::unordered_map table{ + {"bool", static_cast(QtType::Bool)}, + {"int", static_cast(QtType::Int)}, + {"uint", static_cast(QtType::UInt)}, + {"qlonglong", static_cast(QtType::LongLong)}, + {"qulonglong", static_cast(QtType::ULongLong)}, + {"double", static_cast(QtType::Double)}, + {"long", static_cast(QtType::Long)}, + {"short", static_cast(QtType::Short)}, + {"char", static_cast(QtType::Char)}, + {"ulong", static_cast(QtType::ULong)}, + {"ushort", static_cast(QtType::UShort)}, + {"uchar", static_cast(QtType::UChar)}, + {"float", static_cast(QtType::Float)}, + {"QChar", static_cast(QtType::QChar)}, + {"QString", static_cast(QtType::QString)}, + {"QStringList", static_cast(QtType::QStringList)}, + {"QByteArray", static_cast(QtType::QByteArray)}, + {"QBitArray", static_cast(QtType::QBitArray)}, + {"QDate", static_cast(QtType::QDate)}, + {"QTime", static_cast(QtType::QTime)}, + {"QDateTime", static_cast(QtType::QDateTime)}, + {"QUrl", static_cast(QtType::QUrl)}, + {"QLocale", static_cast(QtType::QLocale)}, + {"QRect", static_cast(QtType::QRect)}, + {"QRectF", static_cast(QtType::QRectF)}, + {"QSize", static_cast(QtType::QSize)}, + {"QSizeF", static_cast(QtType::QSizeF)}, + {"QLine", static_cast(QtType::QLine)}, + {"QLineF", static_cast(QtType::QLineF)}, + {"QPoint", static_cast(QtType::QPoint)}, + {"QPointF", static_cast(QtType::QPointF)}, + {"QRegExp", static_cast(QtType::QRegExp)}, + {"QEasingCurve", static_cast(QtType::QEasingCurve)}, + {"QUuid", static_cast(QtType::QUuid)}, + {"QVariant", static_cast(QtType::QVariant)}, + {"QModelIndex", static_cast(QtType::QModelIndex)}, + {"QPersistentModelIndex", static_cast(QtType::QPersistentModelIndex)}, + {"QRegularExpression", static_cast(QtType::QRegularExpression)}, + {"QJsonValue", static_cast(QtType::QJsonValue)}, + {"QJsonObject", static_cast(QtType::QJsonObject)}, + {"QJsonArray", static_cast(QtType::QJsonArray)}, + {"QJsonDocument", static_cast(QtType::QJsonDocument)}, + {"QByteArrayList", static_cast(QtType::QByteArrayList)}, + {"QObjectStar", static_cast(QtType::QObjectStar)}, + {"SChar", static_cast(QtType::SChar)}, + {"Void", static_cast(QtType::Void)}, + {"Nullptr", static_cast(QtType::Nullptr)}, + {"QVariantMap", static_cast(QtType::QVariantMap)}, + {"QVariantList", static_cast(QtType::QVariantList)}, + {"QVariantHash", static_cast(QtType::QVariantHash)}, + {"QCborSimpleType", static_cast(QtType::QCborSimpleType)}, + {"QCborValue", static_cast(QtType::QCborValue)}, + {"QCborArray", static_cast(QtType::QCborArray)}, + {"QCborMap", static_cast(QtType::QCborMap)}, + {"QFont", static_cast(QtType::QFont)}, + {"QPixmap", static_cast(QtType::QPixmap)}, + {"QBrush", static_cast(QtType::QBrush)}, + {"QColor", static_cast(QtType::QColor)}, + {"QPalette", static_cast(QtType::QPalette)}, + {"QIcon", static_cast(QtType::QIcon)}, + {"QImage", static_cast(QtType::QImage)}, + {"QPolygon", static_cast(QtType::QPolygon)}, + {"QRegion", static_cast(QtType::QRegion)}, + {"QBitmap", static_cast(QtType::QBitmap)}, + {"QCursor", static_cast(QtType::QCursor)}, + {"QKeySequence", static_cast(QtType::QKeySequence)}, + {"QPen", static_cast(QtType::QPen)}, + {"QTextLength", static_cast(QtType::QTextLength)}, + {"QTextFormat", static_cast(QtType::QTextFormat)}, + {"QMatrix", static_cast(QtType::QMatrix)}, + {"QTransform", static_cast(QtType::QTransform)}, + {"QMatrix4x4", static_cast(QtType::QMatrix4x4)}, + {"QVector2D", static_cast(QtType::QVector2D)}, + {"QVector3D", static_cast(QtType::QVector3D)}, + {"QVector4D", static_cast(QtType::QVector4D)}, + {"QQuaternion", static_cast(QtType::QQuaternion)}, + {"QPolygonF", static_cast(QtType::QPolygonF)}, + {"QColorSpace", static_cast(QtType::QColorSpace)}, + {"QSizePolicy", static_cast(QtType::QSizePolicy)}, + }; + + const auto it = table.find(typeName); + if (it != table.end()) + { + return it->second; + } + return static_cast(QtType::User); +} + +void SerializerQt::Internal::getQVariantType(const MetaField& field, std::uint32_t& typeId, std::string& typeName) +{ + typeName.clear(); + + static const std::string KEY_QTTYPE = "qttype"; + typeName = field.getProperty(KEY_QTTYPE); + + if (typeName.empty()) + { + if (field.typeId == MetaTypeId::TYPE_STRUCT) { - if (field.typeId == MetaTypeId::TYPE_STRUCT) - { - const MetaStruct* stru = MetaDataGlobal::instance().getStruct(field); - if (stru) - { - typeName = stru->getProperty(KEY_QTTYPE); - } - } - else if (field.typeId == MetaTypeId::TYPE_ENUM) + const MetaStruct* stru = MetaDataGlobal::instance().getStruct(field); + if (stru) { - const MetaEnum* enu = MetaDataGlobal::instance().getEnum(field); - if (enu) - { - typeName = enu->getProperty(KEY_QTTYPE); - } + typeName = stru->getProperty(KEY_QTTYPE); } } - - if (!typeName.empty()) - { - typeId = getTypeIdByName(typeName); - } - else + else if (field.typeId == MetaTypeId::TYPE_ENUM) { - getQVariantTypeFromMetaTypeId(field, typeId, typeName); + const MetaEnum* enu = MetaDataGlobal::instance().getEnum(field); + if (enu) + { + typeName = enu->getProperty(KEY_QTTYPE); + } } } - void SerializerQt::Internal::reserveSpace(ssize_t space) + if (!typeName.empty()) { - ssize_t sizeRemaining = m_bufferEnd - m_buffer; - if (sizeRemaining < space) - { - if (m_buffer != nullptr) - { - ssize_t size = m_buffer - m_bufferStart; - assert(size >= 0); - m_zeroCopybuffer.downsizeLastBuffer(size); - } - - const ssize_t sizeRemainingZeroCopyBuffer = m_zeroCopybuffer.getRemainingSize(); - ssize_t sizeNew = m_maxBlockSize; - if (space <= sizeRemainingZeroCopyBuffer) - { - sizeNew = sizeRemainingZeroCopyBuffer; - } - sizeNew = std::max(sizeNew, space); - char* bufferStartNew = m_zeroCopybuffer.addBuffer(sizeNew); - - m_bufferStart = bufferStartNew; - m_bufferEnd = m_bufferStart + sizeNew; - m_buffer = m_bufferStart; - } + typeId = getTypeIdByName(typeName); } + else + { + getQVariantTypeFromMetaTypeId(field, typeId, typeName); + } +} - void SerializerQt::Internal::resizeBuffer() +void SerializerQt::Internal::reserveSpace(ssize_t space) +{ + ssize_t sizeRemaining = m_bufferEnd - m_buffer; + if (sizeRemaining < space) { if (m_buffer != nullptr) { ssize_t size = m_buffer - m_bufferStart; assert(size >= 0); m_zeroCopybuffer.downsizeLastBuffer(size); - m_bufferStart = nullptr; - m_bufferEnd = nullptr; - m_buffer = nullptr; } + + const ssize_t sizeRemainingZeroCopyBuffer = m_zeroCopybuffer.getRemainingSize(); + ssize_t sizeNew = m_maxBlockSize; + if (space <= sizeRemainingZeroCopyBuffer) + { + sizeNew = sizeRemainingZeroCopyBuffer; + } + sizeNew = std::max(sizeNew, space); + char* bufferStartNew = m_zeroCopybuffer.addBuffer(sizeNew); + + m_bufferStart = bufferStartNew; + m_bufferEnd = m_bufferStart + sizeNew; + m_buffer = m_bufferStart; + } +} + +void SerializerQt::Internal::resizeBuffer() +{ + if (m_buffer != nullptr) + { + ssize_t size = m_buffer - m_bufferStart; + assert(size >= 0); + m_zeroCopybuffer.downsizeLastBuffer(size); + m_bufferStart = nullptr; + m_bufferEnd = nullptr; + m_buffer = nullptr; } +} -} // namespace finalmq +} // namespace finalmq diff --git a/src/serializestruct/SerializerStruct.cpp b/src/serializestruct/SerializerStruct.cpp index bf6ca61d..5fea05b2 100644 --- a/src/serializestruct/SerializerStruct.cpp +++ b/src/serializestruct/SerializerStruct.cpp @@ -20,50 +20,43 @@ //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. - #include "finalmq/serializestruct/SerializerStruct.h" -#include "finalmq/serializevariant/VarValueToVariant.h" -#include "finalmq/serialize/ParserProcessDefaultValues.h" -#include "finalmq/metadata/MetaData.h" -#include "finalmq/variant/VariantValueStruct.h" -#include "finalmq/variant/VariantValueList.h" -#include "finalmq/variant/VariantValues.h" -#include "finalmq/logger/LogStream.h" -#include "finalmq/helpers/ModulenameFinalmq.h" -#include #include +#include -namespace finalmq { - +#include "finalmq/helpers/ModulenameFinalmq.h" +#include "finalmq/logger/LogStream.h" +#include "finalmq/metadata/MetaData.h" +#include "finalmq/serialize/ParserProcessDefaultValues.h" +#include "finalmq/serializevariant/VarValueToVariant.h" +#include "finalmq/variant/VariantValueList.h" +#include "finalmq/variant/VariantValueStruct.h" +#include "finalmq/variant/VariantValues.h" +namespace finalmq +{ static const std::string STR_VARVALUE = "finalmq.variant.VarValue"; - SerializerStruct::SerializerStruct(StructBase& root) - : IParserVisitor() - , m_root(root) + : IParserVisitor(), m_root(root) { m_root.clear(); - m_stack.push_back({ &m_root, -1 }); + m_stack.push_back({&m_root, -1}); m_current = &m_stack.back(); } - void SerializerStruct::setExitNotification(std::function funcExit) { m_funcExit = std::move(funcExit); } - - // IParserVisitor void SerializerStruct::notifyError(const char* /*str*/, const char* /*message*/) { } - void SerializerStruct::startStruct(const MetaStruct& /*stru*/) { m_wasStartStructCalled = true; @@ -73,7 +66,6 @@ void SerializerStruct::finished() { } - void SerializerStruct::enterStruct(const MetaField& field) { if (field.typeId != MetaTypeId::TYPE_STRUCT && field.typeId != MetaTypeId::TYPE_ARRAY_STRUCT) @@ -142,7 +134,7 @@ void SerializerStruct::enterStruct(const MetaField& field) sub = m_current->structBase->add(m_current->structArrayIndex); } } - m_stack.push_back({ sub, -1 }); + m_stack.push_back({sub, -1}); m_current = &m_stack.back(); } } @@ -235,9 +227,7 @@ void SerializerStruct::exitArrayStruct(const MetaField& field) m_current->structArrayIndex = -1; } - - -template +template void SerializerStruct::setValue(StructBase& structBase, const FieldInfo& fieldInfoDest, const T& value) { T* pval = structBase.getData(fieldInfoDest); @@ -247,7 +237,7 @@ void SerializerStruct::setValue(StructBase& structBase, const FieldInfo& fieldIn } } -template +template void SerializerStruct::setValue(StructBase& structBase, const FieldInfo& fieldInfoDest, T&& value) { T* pval = structBase.getData(fieldInfoDest); @@ -257,7 +247,6 @@ void SerializerStruct::setValue(StructBase& structBase, const FieldInfo& fieldIn } } - const FieldInfo* SerializerStruct::getFieldInfoDest(const MetaField& field) { assert(m_current); @@ -270,7 +259,6 @@ const FieldInfo* SerializerStruct::getFieldInfoDest(const MetaField& field) return nullptr; } - template void SerializerStruct::convertNumber(StructBase& structBase, const FieldInfo& fieldInfoDest, T value) { @@ -279,142 +267,155 @@ void SerializerStruct::convertNumber(StructBase& structBase, const FieldInfo& fi { return; } - switch (fieldDest->typeId) - { - case MetaTypeId::TYPE_BOOL: - setValue(structBase, fieldInfoDest, static_cast(value)); + switch(fieldDest->typeId) + { + case MetaTypeId::TYPE_BOOL: +#ifndef WIN32 +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wfloat-equal" +#endif + setValue(structBase, fieldInfoDest, static_cast(value)); +#ifndef WIN32 +#pragma GCC diagnostic pop +#endif + break; + case MetaTypeId::TYPE_INT8: + setValue(structBase, fieldInfoDest, static_cast(value)); + break; + case MetaTypeId::TYPE_UINT8: + setValue(structBase, fieldInfoDest, static_cast(value)); + break; + case MetaTypeId::TYPE_INT16: + setValue(structBase, fieldInfoDest, static_cast(value)); + break; + case MetaTypeId::TYPE_UINT16: + setValue(structBase, fieldInfoDest, static_cast(value)); + break; + case MetaTypeId::TYPE_INT32: + setValue(structBase, fieldInfoDest, static_cast(value)); + break; + case MetaTypeId::TYPE_UINT32: + setValue(structBase, fieldInfoDest, static_cast(value)); + break; + case MetaTypeId::TYPE_INT64: + setValue(structBase, fieldInfoDest, static_cast(value)); + break; + case MetaTypeId::TYPE_UINT64: + setValue(structBase, fieldInfoDest, static_cast(value)); + break; + case MetaTypeId::TYPE_FLOAT: + setValue(structBase, fieldInfoDest, static_cast(value)); + break; + case MetaTypeId::TYPE_DOUBLE: + setValue(structBase, fieldInfoDest, static_cast(value)); + break; + case MetaTypeId::TYPE_STRING: + setValue(structBase, fieldInfoDest, std::to_string(value)); + break; + case MetaTypeId::TYPE_BYTES: + { + std::string str = std::to_string(value); + Bytes bytes(str.begin(), str.end()); + setValue(structBase, fieldInfoDest, std::move(bytes)); + } break; - case MetaTypeId::TYPE_INT8: - setValue(structBase, fieldInfoDest, static_cast(value)); + case MetaTypeId::TYPE_ENUM: + { + bool validEnum = MetaDataGlobal::instance().isEnumValue(*fieldDest, static_cast(value)); + setValue(structBase, fieldInfoDest, static_cast(validEnum ? value : 0)); + } + break; + case MetaTypeId::TYPE_ARRAY_BOOL: + { +#ifndef WIN32 +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wfloat-equal" +#endif + bool v = static_cast(value); +#ifndef WIN32 +#pragma GCC diagnostic pop +#endif + setValue>(structBase, fieldInfoDest, {v}); + } + break; + case MetaTypeId::TYPE_ARRAY_INT8: + { + std::int8_t v = static_cast(value); + setValue>(structBase, fieldInfoDest, {v}); + } break; - case MetaTypeId::TYPE_UINT8: - setValue(structBase, fieldInfoDest, static_cast(value)); + case MetaTypeId::TYPE_ARRAY_INT16: + { + std::int16_t v = static_cast(value); + setValue>(structBase, fieldInfoDest, {v}); + } break; - case MetaTypeId::TYPE_INT16: - setValue(structBase, fieldInfoDest, static_cast(value)); + case MetaTypeId::TYPE_ARRAY_UINT16: + { + std::uint16_t v = static_cast(value); + setValue>(structBase, fieldInfoDest, {v}); + } break; - case MetaTypeId::TYPE_UINT16: - setValue(structBase, fieldInfoDest, static_cast(value)); + case MetaTypeId::TYPE_ARRAY_INT32: + { + std::int32_t v = static_cast(value); + setValue>(structBase, fieldInfoDest, {v}); + } break; - case MetaTypeId::TYPE_INT32: - setValue(structBase, fieldInfoDest, static_cast(value)); + case MetaTypeId::TYPE_ARRAY_UINT32: + { + std::uint32_t v = static_cast(value); + setValue>(structBase, fieldInfoDest, {v}); + } break; - case MetaTypeId::TYPE_UINT32: - setValue(structBase, fieldInfoDest, static_cast(value)); + case MetaTypeId::TYPE_ARRAY_INT64: + { + std::int64_t v = static_cast(value); + setValue>(structBase, fieldInfoDest, {v}); + } break; - case MetaTypeId::TYPE_INT64: - setValue(structBase, fieldInfoDest, static_cast(value)); + case MetaTypeId::TYPE_ARRAY_UINT64: + { + std::uint64_t v = static_cast(value); + setValue>(structBase, fieldInfoDest, {v}); + } break; - case MetaTypeId::TYPE_UINT64: - setValue(structBase, fieldInfoDest, static_cast(value)); + case MetaTypeId::TYPE_ARRAY_FLOAT: + { + float v = static_cast(value); + setValue>(structBase, fieldInfoDest, {v}); + } break; - case MetaTypeId::TYPE_FLOAT: - setValue(structBase, fieldInfoDest, static_cast(value)); + case MetaTypeId::TYPE_ARRAY_DOUBLE: + { + double v = static_cast(value); + setValue>(structBase, fieldInfoDest, {v}); + } break; - case MetaTypeId::TYPE_DOUBLE: - setValue(structBase, fieldInfoDest, static_cast(value)); + case MetaTypeId::TYPE_ARRAY_STRING: + { + setValue>(structBase, fieldInfoDest, {std::to_string(value)}); + } break; - case MetaTypeId::TYPE_STRING: - setValue(structBase, fieldInfoDest, std::to_string(value)); + case MetaTypeId::TYPE_ARRAY_BYTES: + { + std::string str = std::to_string(value); + Bytes bytes(str.begin(), str.end()); + setValue>(structBase, fieldInfoDest, {bytes}); + } break; - case MetaTypeId::TYPE_BYTES: - { - std::string str = std::to_string(value); - Bytes bytes(str.begin(), str.end()); - setValue(structBase, fieldInfoDest, std::move(bytes)); - } - break; - case MetaTypeId::TYPE_ENUM: - { - bool validEnum = MetaDataGlobal::instance().isEnumValue(*fieldDest, static_cast(value)); - setValue(structBase, fieldInfoDest, static_cast(validEnum ? value : 0)); - } - break; - case MetaTypeId::TYPE_ARRAY_BOOL: - { - bool v = static_cast(value); - setValue>(structBase, fieldInfoDest, { v }); - } - break; - case MetaTypeId::TYPE_ARRAY_INT8: - { - std::int8_t v = static_cast(value); - setValue>(structBase, fieldInfoDest, { v }); - } - break; - case MetaTypeId::TYPE_ARRAY_INT16: - { - std::int16_t v = static_cast(value); - setValue>(structBase, fieldInfoDest, { v }); - } - break; - case MetaTypeId::TYPE_ARRAY_UINT16: - { - std::uint16_t v = static_cast(value); - setValue>(structBase, fieldInfoDest, { v }); - } - break; - case MetaTypeId::TYPE_ARRAY_INT32: - { - std::int32_t v = static_cast(value); - setValue>(structBase, fieldInfoDest, { v }); - } - break; - case MetaTypeId::TYPE_ARRAY_UINT32: - { - std::uint32_t v = static_cast(value); - setValue>(structBase, fieldInfoDest, { v }); - } - break; - case MetaTypeId::TYPE_ARRAY_INT64: - { - std::int64_t v = static_cast(value); - setValue>(structBase, fieldInfoDest, { v }); - } - break; - case MetaTypeId::TYPE_ARRAY_UINT64: - { - std::uint64_t v = static_cast(value); - setValue>(structBase, fieldInfoDest, { v }); - } - break; - case MetaTypeId::TYPE_ARRAY_FLOAT: - { - float v = static_cast(value); - setValue>(structBase, fieldInfoDest, { v }); - } - break; - case MetaTypeId::TYPE_ARRAY_DOUBLE: - { - double v = static_cast(value); - setValue>(structBase, fieldInfoDest, { v }); - } - break; - case MetaTypeId::TYPE_ARRAY_STRING: - { - setValue>(structBase, fieldInfoDest, { std::to_string(value) }); - } - break; - case MetaTypeId::TYPE_ARRAY_BYTES: - { - std::string str = std::to_string(value); - Bytes bytes(str.begin(), str.end()); - setValue>(structBase, fieldInfoDest, { bytes }); - } - break; - case MetaTypeId::TYPE_ARRAY_ENUM: - { - std::int32_t v = static_cast(value); - setValue>(structBase, fieldInfoDest, { v }); - } - break; - default: - streamError << "number not expected"; + case MetaTypeId::TYPE_ARRAY_ENUM: + { + std::int32_t v = static_cast(value); + setValue>(structBase, fieldInfoDest, {v}); + } break; + default: + streamError << "number not expected"; + break; } } - void SerializerStruct::convertString(StructBase& structBase, const FieldInfo& fieldInfoDest, const char* value, ssize_t size) { const MetaField* fieldDest = fieldInfoDest.getField(); @@ -427,409 +428,423 @@ void SerializerStruct::convertString(StructBase& structBase, const FieldInfo& fi { str = std::string(value, value + size); } - switch (fieldDest->typeId) - { - case MetaTypeId::TYPE_BOOL: - { - bool v = (str.size() == 4 && (memcmp(str.c_str(), "true", 4) == 0)); - setValue(structBase, fieldInfoDest, v); - } - break; - case MetaTypeId::TYPE_INT8: - { - std::int8_t v = static_cast(strtol(str.c_str(), nullptr, 10)); - setValue(structBase, fieldInfoDest, v); - } - break; - case MetaTypeId::TYPE_UINT8: - { - std::uint8_t v = static_cast(strtoul(str.c_str(), nullptr, 10)); - setValue(structBase, fieldInfoDest, v); - } - break; - case MetaTypeId::TYPE_INT16: - { - std::int16_t v = static_cast(strtol(str.c_str(), nullptr, 10)); - setValue(structBase, fieldInfoDest, v); - } - break; - case MetaTypeId::TYPE_UINT16: - { - std::uint16_t v = static_cast(strtoul(str.c_str(), nullptr, 10)); - setValue(structBase, fieldInfoDest, v); - } - break; - case MetaTypeId::TYPE_INT32: - { - std::int32_t v = strtol(str.c_str(), nullptr, 10); - setValue(structBase, fieldInfoDest, v); - } - break; - case MetaTypeId::TYPE_UINT32: - { - std::uint32_t v = strtoul(str.c_str(), nullptr, 10); - setValue(structBase, fieldInfoDest, v); - } - break; - case MetaTypeId::TYPE_INT64: + switch(fieldDest->typeId) { - std::int64_t v = strtoll(str.c_str(), nullptr, 10); - setValue(structBase, fieldInfoDest, v); - } - break; - case MetaTypeId::TYPE_UINT64: - { - std::uint64_t v = strtoull(str.c_str(), nullptr, 10); - setValue(structBase, fieldInfoDest, v); - } - break; - case MetaTypeId::TYPE_FLOAT: - { - float v = strtof32(str.c_str(), nullptr); - setValue(structBase, fieldInfoDest, v); - } - break; - case MetaTypeId::TYPE_DOUBLE: - { - double v = strtof64(str.c_str(), nullptr); - setValue(structBase, fieldInfoDest, v); - } - break; - case MetaTypeId::TYPE_STRING: - setValue(structBase, fieldInfoDest, str); + case MetaTypeId::TYPE_BOOL: + { + bool v = (str.size() == 4 && (memcmp(str.c_str(), "true", 4) == 0)); + setValue(structBase, fieldInfoDest, v); + } break; - case MetaTypeId::TYPE_BYTES: - { - Bytes bytes(str.c_str(), str.c_str() + str.size()); - setValue(structBase, fieldInfoDest, std::move(bytes)); - } - break; - case MetaTypeId::TYPE_ENUM: - { - std::int32_t v = MetaDataGlobal::instance().getEnumValueByName(*fieldDest, str); - setValue(structBase, fieldInfoDest, v); - } - break; - case MetaTypeId::TYPE_ARRAY_BOOL: - { - bool v = (str.size() == 4 && (memcmp(str.c_str(), "true", 4) == 0)); - setValue>(structBase, fieldInfoDest, { v }); - } - break; - case MetaTypeId::TYPE_ARRAY_INT8: - { - std::int8_t v = static_cast(strtol(str.c_str(), nullptr, 10)); - setValue< std::vector>(structBase, fieldInfoDest, { v }); - } - break; - case MetaTypeId::TYPE_ARRAY_INT16: - { - std::int16_t v = static_cast(strtol(str.c_str(), nullptr, 10)); - setValue< std::vector>(structBase, fieldInfoDest, { v }); - } - break; - case MetaTypeId::TYPE_ARRAY_UINT16: - { - std::uint16_t v = static_cast(strtoul(str.c_str(), nullptr, 10)); - setValue< std::vector>(structBase, fieldInfoDest, { v }); - } - break; - case MetaTypeId::TYPE_ARRAY_INT32: - { - std::int32_t v = strtol(str.c_str(), nullptr, 10); - setValue< std::vector>(structBase, fieldInfoDest, { v }); - } - break; - case MetaTypeId::TYPE_ARRAY_UINT32: - { - std::uint32_t v = strtoul(str.c_str(), nullptr, 10); - setValue< std::vector>(structBase, fieldInfoDest, { v }); - } - break; - case MetaTypeId::TYPE_ARRAY_INT64: - { - std::int64_t v = strtoll(str.c_str(), nullptr, 10); - setValue< std::vector>(structBase, fieldInfoDest, { v }); - } - break; - case MetaTypeId::TYPE_ARRAY_UINT64: - { - std::uint64_t v = strtoull(str.c_str(), nullptr, 10); - setValue< std::vector>(structBase, fieldInfoDest, { v }); - } - break; - case MetaTypeId::TYPE_ARRAY_FLOAT: - { - float v = strtof32(str.c_str(), nullptr); - setValue>(structBase, fieldInfoDest, { v }); - } - break; - case MetaTypeId::TYPE_ARRAY_DOUBLE: - { - double v = strtof64(str.c_str(), nullptr); - setValue>(structBase, fieldInfoDest, { v }); - } - break; - case MetaTypeId::TYPE_ARRAY_STRING: - { - setValue>(structBase, fieldInfoDest, { str }); - } - break; - case MetaTypeId::TYPE_ARRAY_BYTES: - { - Bytes bytes(str.c_str(), str.c_str() + str.size()); - setValue>(structBase, fieldInfoDest, { std::move(bytes) }); - } - break; - case MetaTypeId::TYPE_ARRAY_ENUM: - { - std::int32_t v = MetaDataGlobal::instance().getEnumValueByName(*fieldDest, str); - setValue>(structBase, fieldInfoDest, { v }); - } - break; - default: - streamError << "number not expected"; + case MetaTypeId::TYPE_INT8: + { + std::int8_t v = static_cast(strtol(str.c_str(), nullptr, 10)); + setValue(structBase, fieldInfoDest, v); + } break; - } -} - -template -void SerializerStruct::convertArrayNumber(StructBase& structBase, const FieldInfo& fieldInfoDest, const T* value, ssize_t size) -{ - const MetaField* fieldDest = fieldInfoDest.getField(); - if (fieldDest == nullptr) - { - return; - } - switch (fieldDest->typeId) - { - case MetaTypeId::TYPE_BOOL: - if (size >= 1) + case MetaTypeId::TYPE_UINT8: { - setValue(structBase, fieldInfoDest, static_cast(value[0])); + std::uint8_t v = static_cast(strtoul(str.c_str(), nullptr, 10)); + setValue(structBase, fieldInfoDest, v); } break; - case MetaTypeId::TYPE_INT8: - if (size >= 1) + case MetaTypeId::TYPE_INT16: { - setValue(structBase, fieldInfoDest, static_cast(value[0])); + std::int16_t v = static_cast(strtol(str.c_str(), nullptr, 10)); + setValue(structBase, fieldInfoDest, v); } break; - case MetaTypeId::TYPE_UINT8: - if (size >= 1) + case MetaTypeId::TYPE_UINT16: { - setValue(structBase, fieldInfoDest, static_cast(value[0])); + std::uint16_t v = static_cast(strtoul(str.c_str(), nullptr, 10)); + setValue(structBase, fieldInfoDest, v); } break; - case MetaTypeId::TYPE_INT16: - if (size >= 1) + case MetaTypeId::TYPE_INT32: { - setValue(structBase, fieldInfoDest, static_cast(value[0])); + std::int32_t v = static_cast(strtol(str.c_str(), nullptr, 10)); + setValue(structBase, fieldInfoDest, v); } break; - case MetaTypeId::TYPE_UINT16: - if (size >= 1) + case MetaTypeId::TYPE_UINT32: { - setValue(structBase, fieldInfoDest, static_cast(value[0])); + std::uint32_t v = static_cast(strtoul(str.c_str(), nullptr, 10)); + setValue(structBase, fieldInfoDest, v); } break; - case MetaTypeId::TYPE_INT32: - if (size >= 1) + case MetaTypeId::TYPE_INT64: { - setValue(structBase, fieldInfoDest, static_cast(value[0])); + std::int64_t v = strtoll(str.c_str(), nullptr, 10); + setValue(structBase, fieldInfoDest, v); } break; - case MetaTypeId::TYPE_UINT32: - if (size >= 1) + case MetaTypeId::TYPE_UINT64: { - setValue(structBase, fieldInfoDest, static_cast(value[0])); + std::uint64_t v = strtoull(str.c_str(), nullptr, 10); + setValue(structBase, fieldInfoDest, v); } break; - case MetaTypeId::TYPE_INT64: - if (size >= 1) + case MetaTypeId::TYPE_FLOAT: { - setValue(structBase, fieldInfoDest, static_cast(value[0])); + float v = strtof32(str.c_str(), nullptr); + setValue(structBase, fieldInfoDest, v); } break; - case MetaTypeId::TYPE_UINT64: - if (size >= 1) + case MetaTypeId::TYPE_DOUBLE: { - setValue(structBase, fieldInfoDest, static_cast(value[0])); + double v = strtof64(str.c_str(), nullptr); + setValue(structBase, fieldInfoDest, v); } break; - case MetaTypeId::TYPE_FLOAT: - if (size >= 1) + case MetaTypeId::TYPE_STRING: + setValue(structBase, fieldInfoDest, str); + break; + case MetaTypeId::TYPE_BYTES: { - setValue(structBase, fieldInfoDest, static_cast(value[0])); + Bytes bytes(str.c_str(), str.c_str() + str.size()); + setValue(structBase, fieldInfoDest, std::move(bytes)); } break; - case MetaTypeId::TYPE_DOUBLE: - if (size >= 1) + case MetaTypeId::TYPE_ENUM: { - setValue(structBase, fieldInfoDest, static_cast(value[0])); + std::int32_t v = MetaDataGlobal::instance().getEnumValueByName(*fieldDest, str); + setValue(structBase, fieldInfoDest, v); } break; - case MetaTypeId::TYPE_STRING: - if (size >= 1) + case MetaTypeId::TYPE_ARRAY_BOOL: { - setValue(structBase, fieldInfoDest, std::to_string(value[0])); + bool v = (str.size() == 4 && (memcmp(str.c_str(), "true", 4) == 0)); + setValue>(structBase, fieldInfoDest, {v}); } break; - case MetaTypeId::TYPE_BYTES: - { - if (size >= 1) + case MetaTypeId::TYPE_ARRAY_INT8: { - std::string str = std::to_string(value[0]); - Bytes bytes(str.begin(), str.end()); - setValue(structBase, fieldInfoDest, std::move(bytes)); + std::int8_t v = static_cast(strtol(str.c_str(), nullptr, 10)); + setValue>(structBase, fieldInfoDest, {v}); } - } - break; - case MetaTypeId::TYPE_ENUM: - { - if (size >= 1) + break; + case MetaTypeId::TYPE_ARRAY_INT16: + { + std::int16_t v = static_cast(strtol(str.c_str(), nullptr, 10)); + setValue>(structBase, fieldInfoDest, {v}); + } + break; + case MetaTypeId::TYPE_ARRAY_UINT16: { - bool validEnum = MetaDataGlobal::instance().isEnumValue(*fieldDest, static_cast(value[0])); - setValue(structBase, fieldInfoDest, static_cast(validEnum ? value[0] : 0)); + std::uint16_t v = static_cast(strtoul(str.c_str(), nullptr, 10)); + setValue>(structBase, fieldInfoDest, {v}); } + break; + case MetaTypeId::TYPE_ARRAY_INT32: + { + std::int32_t v = static_cast(strtol(str.c_str(), nullptr, 10)); + setValue>(structBase, fieldInfoDest, {v}); + } + break; + case MetaTypeId::TYPE_ARRAY_UINT32: + { + std::uint32_t v = static_cast(strtoul(str.c_str(), nullptr, 10)); + setValue>(structBase, fieldInfoDest, {v}); + } + break; + case MetaTypeId::TYPE_ARRAY_INT64: + { + std::int64_t v = strtoll(str.c_str(), nullptr, 10); + setValue>(structBase, fieldInfoDest, {v}); + } + break; + case MetaTypeId::TYPE_ARRAY_UINT64: + { + std::uint64_t v = strtoull(str.c_str(), nullptr, 10); + setValue>(structBase, fieldInfoDest, {v}); + } + break; + case MetaTypeId::TYPE_ARRAY_FLOAT: + { + float v = strtof32(str.c_str(), nullptr); + setValue>(structBase, fieldInfoDest, {v}); + } + break; + case MetaTypeId::TYPE_ARRAY_DOUBLE: + { + double v = strtof64(str.c_str(), nullptr); + setValue>(structBase, fieldInfoDest, {v}); + } + break; + case MetaTypeId::TYPE_ARRAY_STRING: + { + setValue>(structBase, fieldInfoDest, {str}); + } + break; + case MetaTypeId::TYPE_ARRAY_BYTES: + { + Bytes bytes(str.c_str(), str.c_str() + str.size()); + setValue>(structBase, fieldInfoDest, {std::move(bytes)}); + } + break; + case MetaTypeId::TYPE_ARRAY_ENUM: + { + std::int32_t v = MetaDataGlobal::instance().getEnumValueByName(*fieldDest, str); + setValue>(structBase, fieldInfoDest, {v}); + } + break; + default: + streamError << "number not expected"; + break; } - break; - case MetaTypeId::TYPE_ARRAY_BOOL: +} + +template +void SerializerStruct::convertArrayNumber(StructBase& structBase, const FieldInfo& fieldInfoDest, const T* value, ssize_t size) +{ + const MetaField* fieldDest = fieldInfoDest.getField(); + if (fieldDest == nullptr) { - std::vector v; - v.reserve(size); - std::for_each(value, value + size, [&v](const T& entry) { - v.push_back(entry); - }); - setValue>(structBase, fieldInfoDest, std::move(v)); + return; } - break; - case MetaTypeId::TYPE_ARRAY_INT8: + switch(fieldDest->typeId) { - std::vector v; - v.reserve(size); - std::for_each(value, value + size, [&v](const T& entry) { - v.push_back(static_cast(entry)); + case MetaTypeId::TYPE_BOOL: + if (size >= 1) + { +#ifndef WIN32 +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wfloat-equal" +#endif + setValue(structBase, fieldInfoDest, static_cast(value[0])); +#ifndef WIN32 +#pragma GCC diagnostic pop +#endif + } + break; + case MetaTypeId::TYPE_INT8: + if (size >= 1) + { + setValue(structBase, fieldInfoDest, static_cast(value[0])); + } + break; + case MetaTypeId::TYPE_UINT8: + if (size >= 1) + { + setValue(structBase, fieldInfoDest, static_cast(value[0])); + } + break; + case MetaTypeId::TYPE_INT16: + if (size >= 1) + { + setValue(structBase, fieldInfoDest, static_cast(value[0])); + } + break; + case MetaTypeId::TYPE_UINT16: + if (size >= 1) + { + setValue(structBase, fieldInfoDest, static_cast(value[0])); + } + break; + case MetaTypeId::TYPE_INT32: + if (size >= 1) + { + setValue(structBase, fieldInfoDest, static_cast(value[0])); + } + break; + case MetaTypeId::TYPE_UINT32: + if (size >= 1) + { + setValue(structBase, fieldInfoDest, static_cast(value[0])); + } + break; + case MetaTypeId::TYPE_INT64: + if (size >= 1) + { + setValue(structBase, fieldInfoDest, static_cast(value[0])); + } + break; + case MetaTypeId::TYPE_UINT64: + if (size >= 1) + { + setValue(structBase, fieldInfoDest, static_cast(value[0])); + } + break; + case MetaTypeId::TYPE_FLOAT: + if (size >= 1) + { + setValue(structBase, fieldInfoDest, static_cast(value[0])); + } + break; + case MetaTypeId::TYPE_DOUBLE: + if (size >= 1) + { + setValue(structBase, fieldInfoDest, static_cast(value[0])); + } + break; + case MetaTypeId::TYPE_STRING: + if (size >= 1) + { + setValue(structBase, fieldInfoDest, std::to_string(value[0])); + } + break; + case MetaTypeId::TYPE_BYTES: + { + if (size >= 1) + { + std::string str = std::to_string(value[0]); + Bytes bytes(str.begin(), str.end()); + setValue(structBase, fieldInfoDest, std::move(bytes)); + } + } + break; + case MetaTypeId::TYPE_ENUM: + { + if (size >= 1) + { + bool validEnum = MetaDataGlobal::instance().isEnumValue(*fieldDest, static_cast(value[0])); + setValue(structBase, fieldInfoDest, static_cast(validEnum ? value[0] : 0)); + } + } + break; + case MetaTypeId::TYPE_ARRAY_BOOL: + { + std::vector v; + v.reserve(size); + std::for_each(value, value + size, [&v](const T& entry) { +#ifndef WIN32 +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wfloat-equal" +#endif + v.push_back(entry); +#ifndef WIN32 +#pragma GCC diagnostic pop +#endif }); - setValue>(structBase, fieldInfoDest, std::move(v)); - } - break; - case MetaTypeId::TYPE_ARRAY_INT16: - { - std::vector v; - v.reserve(size); - std::for_each(value, value + size, [&v](const T& entry) { - v.push_back(static_cast(entry)); + setValue>(structBase, fieldInfoDest, std::move(v)); + } + break; + case MetaTypeId::TYPE_ARRAY_INT8: + { + std::vector v; + v.reserve(size); + std::for_each(value, value + size, [&v](const T& entry) { + v.push_back(static_cast(entry)); }); - setValue>(structBase, fieldInfoDest, std::move(v)); - } - break; - case MetaTypeId::TYPE_ARRAY_UINT16: - { - std::vector v; - v.reserve(size); - std::for_each(value, value + size, [&v](const T& entry) { - v.push_back(static_cast(entry)); + setValue>(structBase, fieldInfoDest, std::move(v)); + } + break; + case MetaTypeId::TYPE_ARRAY_INT16: + { + std::vector v; + v.reserve(size); + std::for_each(value, value + size, [&v](const T& entry) { + v.push_back(static_cast(entry)); }); - setValue>(structBase, fieldInfoDest, std::move(v)); - } - break; - case MetaTypeId::TYPE_ARRAY_INT32: - { - std::vector v; - v.reserve(size); - std::for_each(value, value + size, [&v](const T& entry) { - v.push_back(static_cast(entry)); + setValue>(structBase, fieldInfoDest, std::move(v)); + } + break; + case MetaTypeId::TYPE_ARRAY_UINT16: + { + std::vector v; + v.reserve(size); + std::for_each(value, value + size, [&v](const T& entry) { + v.push_back(static_cast(entry)); }); - setValue>(structBase, fieldInfoDest, std::move(v)); - } - break; - case MetaTypeId::TYPE_ARRAY_UINT32: - { - std::vector v; - v.reserve(size); - std::for_each(value, value + size, [&v](const T& entry) { - v.push_back(static_cast(entry)); + setValue>(structBase, fieldInfoDest, std::move(v)); + } + break; + case MetaTypeId::TYPE_ARRAY_INT32: + { + std::vector v; + v.reserve(size); + std::for_each(value, value + size, [&v](const T& entry) { + v.push_back(static_cast(entry)); }); - setValue>(structBase, fieldInfoDest, std::move(v)); - } - break; - case MetaTypeId::TYPE_ARRAY_INT64: - { - std::vector v; - v.reserve(size); - std::for_each(value, value + size, [&v](const T& entry) { - v.push_back(static_cast(entry)); + setValue>(structBase, fieldInfoDest, std::move(v)); + } + break; + case MetaTypeId::TYPE_ARRAY_UINT32: + { + std::vector v; + v.reserve(size); + std::for_each(value, value + size, [&v](const T& entry) { + v.push_back(static_cast(entry)); }); - setValue>(structBase, fieldInfoDest, std::move(v)); - } - break; - case MetaTypeId::TYPE_ARRAY_UINT64: - { - std::vector v; - v.reserve(size); - std::for_each(value, value + size, [&v](const T& entry) { - v.push_back(static_cast(entry)); + setValue>(structBase, fieldInfoDest, std::move(v)); + } + break; + case MetaTypeId::TYPE_ARRAY_INT64: + { + std::vector v; + v.reserve(size); + std::for_each(value, value + size, [&v](const T& entry) { + v.push_back(static_cast(entry)); }); - setValue>(structBase, fieldInfoDest, std::move(v)); - } - break; - case MetaTypeId::TYPE_ARRAY_FLOAT: - { - std::vector v; - v.reserve(size); - std::for_each(value, value + size, [&v](const T& entry) { - v.push_back(static_cast(entry)); + setValue>(structBase, fieldInfoDest, std::move(v)); + } + break; + case MetaTypeId::TYPE_ARRAY_UINT64: + { + std::vector v; + v.reserve(size); + std::for_each(value, value + size, [&v](const T& entry) { + v.push_back(static_cast(entry)); }); - setValue>(structBase, fieldInfoDest, std::move(v)); - } - break; - case MetaTypeId::TYPE_ARRAY_DOUBLE: - { - std::vector v; - v.reserve(size); - std::for_each(value, value + size, [&v](const T& entry) { - v.push_back(static_cast(entry)); + setValue>(structBase, fieldInfoDest, std::move(v)); + } + break; + case MetaTypeId::TYPE_ARRAY_FLOAT: + { + std::vector v; + v.reserve(size); + std::for_each(value, value + size, [&v](const T& entry) { + v.push_back(static_cast(entry)); }); - setValue>(structBase, fieldInfoDest, std::move(v)); - } - break; - case MetaTypeId::TYPE_ARRAY_STRING: - { - std::vector v; - v.reserve(size); - std::for_each(value, value + size, [&v](const T& entry) { - v.push_back(std::to_string(entry)); + setValue>(structBase, fieldInfoDest, std::move(v)); + } + break; + case MetaTypeId::TYPE_ARRAY_DOUBLE: + { + std::vector v; + v.reserve(size); + std::for_each(value, value + size, [&v](const T& entry) { + v.push_back(static_cast(entry)); }); - setValue>(structBase, fieldInfoDest, std::move(v)); - } - break; - case MetaTypeId::TYPE_ARRAY_BYTES: - { - std::vector v; - v.reserve(size); - std::for_each(value, value + size, [&v](const T& entry) { - std::string str = std::to_string(entry); - Bytes bytes(str.begin(), str.end()); - v.push_back(bytes); - }); - setValue>(structBase, fieldInfoDest, std::move(v)); - } - break; - case MetaTypeId::TYPE_ARRAY_ENUM: - { - std::vector v; - v.reserve(size); - std::for_each(value, value + size, [&v, fieldDest](const T& entry) { - bool validEnum = MetaDataGlobal::instance().isEnumValue(*fieldDest, static_cast(entry)); - v.push_back(static_cast(validEnum ? entry : 0)); + setValue>(structBase, fieldInfoDest, std::move(v)); + } + break; + case MetaTypeId::TYPE_ARRAY_STRING: + { + std::vector v; + v.reserve(size); + std::for_each(value, value + size, [&v](const T& entry) { + v.push_back(std::to_string(entry)); }); - setValue>(structBase, fieldInfoDest, std::move(v)); - } - break; - default: - streamError << "array not expected"; + setValue>(structBase, fieldInfoDest, std::move(v)); + } break; + case MetaTypeId::TYPE_ARRAY_BYTES: + { + std::vector v; + v.reserve(size); + std::for_each(value, value + size, [&v](const T& entry) { + std::string str = std::to_string(entry); + Bytes bytes(str.begin(), str.end()); + v.push_back(bytes); + }); + setValue>(structBase, fieldInfoDest, std::move(v)); + } + break; + case MetaTypeId::TYPE_ARRAY_ENUM: + { + std::vector v; + v.reserve(size); + std::for_each(value, value + size, [&v, fieldDest](const T& entry) { + bool validEnum = MetaDataGlobal::instance().isEnumValue(*fieldDest, static_cast(entry)); + v.push_back(static_cast(validEnum ? entry : 0)); + }); + setValue>(structBase, fieldInfoDest, std::move(v)); + } + break; + default: + streamError << "array not expected"; + break; } } @@ -841,233 +856,232 @@ void SerializerStruct::convertArrayString(StructBase& structBase, const FieldInf { return; } - switch (fieldDest->typeId) + switch(fieldDest->typeId) { - case MetaTypeId::TYPE_BOOL: - if (size >= 1) + case MetaTypeId::TYPE_BOOL: + if (size >= 1) + { + bool val = (value[0].size() == 4 && (memcmp(value[0].c_str(), "true", 4) == 0)); + setValue>(structBase, fieldInfoDest, {val}); + } + break; + case MetaTypeId::TYPE_INT8: + if (size >= 1) + { + setValue(structBase, fieldInfoDest, static_cast(strtol(value[0].c_str(), nullptr, 10))); + } + break; + case MetaTypeId::TYPE_UINT8: + if (size >= 1) + { + setValue(structBase, fieldInfoDest, static_cast(strtoul(value[0].c_str(), nullptr, 10))); + } + break; + case MetaTypeId::TYPE_INT16: + if (size >= 1) + { + setValue(structBase, fieldInfoDest, static_cast(strtol(value[0].c_str(), nullptr, 10))); + } + break; + case MetaTypeId::TYPE_UINT16: + if (size >= 1) + { + setValue(structBase, fieldInfoDest, static_cast(strtoul(value[0].c_str(), nullptr, 10))); + } + break; + case MetaTypeId::TYPE_INT32: + if (size >= 1) + { + setValue(structBase, fieldInfoDest, static_cast(strtol(value[0].c_str(), nullptr, 10))); + } + break; + case MetaTypeId::TYPE_UINT32: + if (size >= 1) + { + setValue(structBase, fieldInfoDest, static_cast(strtoul(value[0].c_str(), nullptr, 10))); + } + break; + case MetaTypeId::TYPE_INT64: + if (size >= 1) + { + setValue(structBase, fieldInfoDest, static_cast(strtoll(value[0].c_str(), nullptr, 10))); + } + break; + case MetaTypeId::TYPE_UINT64: + if (size >= 1) + { + setValue(structBase, fieldInfoDest, static_cast(strtoull(value[0].c_str(), nullptr, 10))); + } + break; + case MetaTypeId::TYPE_FLOAT: + if (size >= 1) + { + setValue(structBase, fieldInfoDest, strtof32(value[0].c_str(), nullptr)); + } + break; + case MetaTypeId::TYPE_DOUBLE: + if (size >= 1) + { + setValue(structBase, fieldInfoDest, strtof64(value[0].c_str(), nullptr)); + } + break; + case MetaTypeId::TYPE_STRING: + if (size >= 1) + { + setValue(structBase, fieldInfoDest, value[0]); + } + break; + case MetaTypeId::TYPE_BYTES: { - bool val = (value[0].size() == 4 && (memcmp(value[0].c_str(), "true", 4) == 0)); - setValue>(structBase, fieldInfoDest, { val }); + if (size >= 1) + { + Bytes bytes(value[0].begin(), value[0].end()); + setValue(structBase, fieldInfoDest, std::move(bytes)); + } } break; - case MetaTypeId::TYPE_INT8: - if (size >= 1) + case MetaTypeId::TYPE_ENUM: { - setValue(structBase, fieldInfoDest, static_cast(strtol(value[0].c_str(), nullptr, 10))); + if (size >= 1) + { + std::int32_t enumValue = MetaDataGlobal::instance().getEnumValueByName(*fieldDest, value[0]); + setValue(structBase, fieldInfoDest, enumValue); + } } break; - case MetaTypeId::TYPE_UINT8: - if (size >= 1) + case MetaTypeId::TYPE_ARRAY_BOOL: { - setValue(structBase, fieldInfoDest, static_cast(strtoul(value[0].c_str(), nullptr, 10))); + std::vector v; + v.reserve(size); + std::for_each(value.begin(), value.end(), [&v](const std::string& entry) { + bool val = (entry.size() == 4 && (memcmp(entry.c_str(), "true", 4) == 0)) || (entry.size() >= 1 && (entry[0] == 1)); + v.push_back(val); + }); + setValue>(structBase, fieldInfoDest, std::move(v)); } break; - case MetaTypeId::TYPE_INT16: - if (size >= 1) + case MetaTypeId::TYPE_ARRAY_INT8: { - setValue(structBase, fieldInfoDest, static_cast(strtol(value[0].c_str(), nullptr, 10))); + std::vector v; + v.reserve(size); + std::for_each(value.begin(), value.end(), [&v](const std::string& entry) { + v.push_back(static_cast(strtol(entry.c_str(), nullptr, 10))); + }); + setValue>(structBase, fieldInfoDest, std::move(v)); } break; - case MetaTypeId::TYPE_UINT16: - if (size >= 1) + case MetaTypeId::TYPE_ARRAY_INT16: { - setValue(structBase, fieldInfoDest, static_cast(strtoul(value[0].c_str(), nullptr, 10))); + std::vector v; + v.reserve(size); + std::for_each(value.begin(), value.end(), [&v](const std::string& entry) { + v.push_back(static_cast(strtol(entry.c_str(), nullptr, 10))); + }); + setValue>(structBase, fieldInfoDest, std::move(v)); } break; - case MetaTypeId::TYPE_INT32: - if (size >= 1) + case MetaTypeId::TYPE_ARRAY_UINT16: { - setValue(structBase, fieldInfoDest, static_cast(strtol(value[0].c_str(), nullptr, 10))); + std::vector v; + v.reserve(size); + std::for_each(value.begin(), value.end(), [&v](const std::string& entry) { + v.push_back(static_cast(strtoul(entry.c_str(), nullptr, 10))); + }); + setValue>(structBase, fieldInfoDest, std::move(v)); } break; - case MetaTypeId::TYPE_UINT32: - if (size >= 1) + case MetaTypeId::TYPE_ARRAY_INT32: { - setValue(structBase, fieldInfoDest, static_cast(strtoul(value[0].c_str(), nullptr, 10))); + std::vector v; + v.reserve(size); + std::for_each(value.begin(), value.end(), [&v](const std::string& entry) { + v.push_back(static_cast(strtol(entry.c_str(), nullptr, 10))); + }); + setValue>(structBase, fieldInfoDest, std::move(v)); } break; - case MetaTypeId::TYPE_INT64: - if (size >= 1) + case MetaTypeId::TYPE_ARRAY_UINT32: { - setValue(structBase, fieldInfoDest, static_cast(strtoll(value[0].c_str(), nullptr, 10))); + std::vector v; + v.reserve(size); + std::for_each(value.begin(), value.end(), [&v](const std::string& entry) { + v.push_back(static_cast(strtoul(entry.c_str(), nullptr, 10))); + }); + setValue>(structBase, fieldInfoDest, std::move(v)); } break; - case MetaTypeId::TYPE_UINT64: - if (size >= 1) + case MetaTypeId::TYPE_ARRAY_INT64: { - setValue(structBase, fieldInfoDest, static_cast(strtoull(value[0].c_str(), nullptr, 10))); + std::vector v; + v.reserve(size); + std::for_each(value.begin(), value.end(), [&v](const std::string& entry) { + v.push_back(strtoll(entry.c_str(), nullptr, 10)); + }); + setValue>(structBase, fieldInfoDest, std::move(v)); } break; - case MetaTypeId::TYPE_FLOAT: - if (size >= 1) + case MetaTypeId::TYPE_ARRAY_UINT64: { - setValue(structBase, fieldInfoDest, static_cast(strtof32(value[0].c_str(), nullptr))); + std::vector v; + v.reserve(size); + std::for_each(value.begin(), value.end(), [&v](const std::string& entry) { + v.push_back(strtoull(entry.c_str(), nullptr, 10)); + }); + setValue>(structBase, fieldInfoDest, std::move(v)); } break; - case MetaTypeId::TYPE_DOUBLE: - if (size >= 1) + case MetaTypeId::TYPE_ARRAY_FLOAT: { - setValue(structBase, fieldInfoDest, static_cast(strtof64(value[0].c_str(), nullptr))); + std::vector v; + v.reserve(size); + std::for_each(value.begin(), value.end(), [&v](const std::string& entry) { + v.push_back(strtof32(entry.c_str(), nullptr)); + }); + setValue>(structBase, fieldInfoDest, std::move(v)); } break; - case MetaTypeId::TYPE_STRING: - if (size >= 1) + case MetaTypeId::TYPE_ARRAY_DOUBLE: { - setValue(structBase, fieldInfoDest, value[0]); + std::vector v; + v.reserve(size); + std::for_each(value.begin(), value.end(), [&v](const std::string& entry) { + v.push_back(strtof64(entry.c_str(), nullptr)); + }); + setValue>(structBase, fieldInfoDest, std::move(v)); } break; - case MetaTypeId::TYPE_BYTES: - { - if (size >= 1) + case MetaTypeId::TYPE_ARRAY_STRING: + setValue>(structBase, fieldInfoDest, value); + break; + case MetaTypeId::TYPE_ARRAY_BYTES: { - Bytes bytes(value[0].begin(), value[0].end()); - setValue(structBase, fieldInfoDest, std::move(bytes)); - } - } - break; - case MetaTypeId::TYPE_ENUM: - { - if (size >= 1) - { - std::int32_t enumValue = MetaDataGlobal::instance().getEnumValueByName(*fieldDest, value[0]); - setValue(structBase, fieldInfoDest, enumValue); - } - } - break; - case MetaTypeId::TYPE_ARRAY_BOOL: - { - std::vector v; - v.reserve(size); - std::for_each(value.begin(), value.end(), [&v](const std::string& entry) { - bool val = (entry.size() == 4 && (memcmp(entry.c_str(), "true", 4) == 0)) || (entry.size() >= 1 && (entry[0] == 1)); - v.push_back(val); - }); - setValue>(structBase, fieldInfoDest, std::move(v)); - } - break; - case MetaTypeId::TYPE_ARRAY_INT8: - { - std::vector v; - v.reserve(size); - std::for_each(value.begin(), value.end(), [&v](const std::string& entry) { - v.push_back(static_cast(strtol(entry.c_str(), nullptr, 10))); - }); - setValue>(structBase, fieldInfoDest, std::move(v)); - } - break; - case MetaTypeId::TYPE_ARRAY_INT16: - { - std::vector v; - v.reserve(size); - std::for_each(value.begin(), value.end(), [&v](const std::string& entry) { - v.push_back(static_cast(strtol(entry.c_str(), nullptr, 10))); - }); - setValue>(structBase, fieldInfoDest, std::move(v)); - } - break; - case MetaTypeId::TYPE_ARRAY_UINT16: - { - std::vector v; - v.reserve(size); - std::for_each(value.begin(), value.end(), [&v](const std::string& entry) { - v.push_back(static_cast(strtoul(entry.c_str(), nullptr, 10))); - }); - setValue>(structBase, fieldInfoDest, std::move(v)); - } - break; - case MetaTypeId::TYPE_ARRAY_INT32: - { - std::vector v; - v.reserve(size); - std::for_each(value.begin(), value.end(), [&v](const std::string& entry) { - v.push_back(strtol(entry.c_str(), nullptr, 10)); - }); - setValue>(structBase, fieldInfoDest, std::move(v)); - } - break; - case MetaTypeId::TYPE_ARRAY_UINT32: - { - std::vector v; - v.reserve(size); - std::for_each(value.begin(), value.end(), [&v](const std::string& entry) { - v.push_back(strtoul(entry.c_str(), nullptr, 10)); - }); - setValue>(structBase, fieldInfoDest, std::move(v)); - } - break; - case MetaTypeId::TYPE_ARRAY_INT64: - { - std::vector v; - v.reserve(size); - std::for_each(value.begin(), value.end(), [&v](const std::string& entry) { - v.push_back(strtoll(entry.c_str(), nullptr, 10)); + std::vector v; + v.reserve(size); + std::for_each(value.begin(), value.end(), [&v](const std::string& entry) { + std::string str(entry.begin(), entry.end()); + Bytes bytes(str.begin(), str.end()); + v.push_back(bytes); }); - setValue>(structBase, fieldInfoDest, std::move(v)); - } - break; - case MetaTypeId::TYPE_ARRAY_UINT64: - { - std::vector v; - v.reserve(size); - std::for_each(value.begin(), value.end(), [&v](const std::string& entry) { - v.push_back(strtoull(entry.c_str(), nullptr, 10)); - }); - setValue>(structBase, fieldInfoDest, std::move(v)); - } - break; - case MetaTypeId::TYPE_ARRAY_FLOAT: - { - std::vector v; - v.reserve(size); - std::for_each(value.begin(), value.end(), [&v](const std::string& entry) { - v.push_back(strtof32(entry.c_str(), nullptr)); - }); - setValue>(structBase, fieldInfoDest, std::move(v)); - } - break; - case MetaTypeId::TYPE_ARRAY_DOUBLE: - { - std::vector v; - v.reserve(size); - std::for_each(value.begin(), value.end(), [&v](const std::string& entry) { - v.push_back(strtof64(entry.c_str(), nullptr)); - }); - setValue>(structBase, fieldInfoDest, std::move(v)); - } - break; - case MetaTypeId::TYPE_ARRAY_STRING: - setValue>(structBase, fieldInfoDest, value); + setValue>(structBase, fieldInfoDest, std::move(v)); + } break; - case MetaTypeId::TYPE_ARRAY_BYTES: - { - std::vector v; - v.reserve(size); - std::for_each(value.begin(), value.end(), [&v](const std::string& entry) { - std::string str(entry.begin(), entry.end()); - Bytes bytes(str.begin(), str.end()); - v.push_back(bytes); + case MetaTypeId::TYPE_ARRAY_ENUM: + { + std::vector v; + v.reserve(size); + std::for_each(value.begin(), value.end(), [&v, fieldDest](const std::string& entry) { + std::int32_t enumValue = MetaDataGlobal::instance().getEnumValueByName(*fieldDest, entry); + v.push_back(enumValue); }); - setValue>(structBase, fieldInfoDest, std::move(v)); - } - break; - case MetaTypeId::TYPE_ARRAY_ENUM: - { - std::vector v; - v.reserve(size); - std::for_each(value.begin(), value.end(), [&v, fieldDest](const std::string& entry) { - std::int32_t enumValue = MetaDataGlobal::instance().getEnumValueByName(*fieldDest, entry); - v.push_back(enumValue); - }); - setValue>(structBase, fieldInfoDest, std::move(v)); - } - break; - default: - streamError << "array not expected"; + setValue>(structBase, fieldInfoDest, std::move(v)); + } break; + default: + streamError << "array not expected"; + break; } } - template void SerializerStruct::setValueNumber(const MetaField& field, T value) { @@ -1183,7 +1197,6 @@ void SerializerStruct::setValueArrayNumber(const MetaField& field, std::vector& value) { const FieldInfo* fieldInfoDest = getFieldInfoDest(field); @@ -1240,8 +1253,6 @@ void SerializerStruct::setValueArrayString(const MetaField& field, std::vector -namespace finalmq { - +#include "finalmq/metadata/MetaData.h" +#include "finalmq/serializevariant/VariantToVarValue.h" +#include "finalmq/variant/VariantValueList.h" +#include "finalmq/variant/VariantValueStruct.h" +#include "finalmq/variant/VariantValues.h" +namespace finalmq +{ static const std::string STR_VARVALUE = "finalmq.variant.VarValue"; - - ParserVariant::ParserVariant(IParserVisitor& visitor, const Variant& variant) - : m_visitor(visitor) - , m_root(variant) + : m_visitor(visitor), m_root(variant) { } - - - - bool ParserVariant::parseStruct(const std::string& typeName) { bool ok = false; @@ -66,47 +58,44 @@ bool ParserVariant::parseStruct(const std::string& typeName) return ok; } - - void ParserVariant::processField(const Variant* sub, const MetaField* field) { - - switch (field->typeId) + switch(field->typeId) { - case TYPE_BOOL: - m_visitor.enterBool(*field, *sub); - break; - case TYPE_INT8: - m_visitor.enterInt8(*field, *sub); - break; - case TYPE_UINT8: - m_visitor.enterUInt8(*field, *sub); - break; - case TYPE_INT16: - m_visitor.enterInt16(*field, *sub); - break; - case TYPE_UINT16: - m_visitor.enterUInt16(*field, *sub); - break; - case TYPE_INT32: - m_visitor.enterInt32(*field, *sub); - break; - case TYPE_UINT32: - m_visitor.enterUInt32(*field, *sub); - break; - case TYPE_INT64: - m_visitor.enterInt64(*field, *sub); - break; - case TYPE_UINT64: - m_visitor.enterUInt64(*field, *sub); - break; - case TYPE_FLOAT: - m_visitor.enterFloat(*field, *sub); - break; - case TYPE_DOUBLE: - m_visitor.enterDouble(*field, *sub); - break; - case TYPE_STRING: + case TYPE_BOOL: + m_visitor.enterBool(*field, *sub); + break; + case TYPE_INT8: + m_visitor.enterInt8(*field, *sub); + break; + case TYPE_UINT8: + m_visitor.enterUInt8(*field, *sub); + break; + case TYPE_INT16: + m_visitor.enterInt16(*field, *sub); + break; + case TYPE_UINT16: + m_visitor.enterUInt16(*field, *sub); + break; + case TYPE_INT32: + m_visitor.enterInt32(*field, *sub); + break; + case TYPE_UINT32: + m_visitor.enterUInt32(*field, *sub); + break; + case TYPE_INT64: + m_visitor.enterInt64(*field, *sub); + break; + case TYPE_UINT64: + m_visitor.enterUInt64(*field, *sub); + break; + case TYPE_FLOAT: + m_visitor.enterFloat(*field, *sub); + break; + case TYPE_DOUBLE: + m_visitor.enterDouble(*field, *sub); + break; + case TYPE_STRING: { const std::string* str = *sub; if (str) @@ -119,48 +108,48 @@ void ParserVariant::processField(const Variant* sub, const MetaField* field) } } break; - case TYPE_BYTES: - { - const Bytes* bytes = *sub; - if (bytes) - { - m_visitor.enterBytes(*field, bytes->data(), bytes->size()); - } - else - { - m_visitor.enterBytes(*field, *sub); - } - } - break; - case TYPE_STRUCT: - if ((sub->getType() != VARTYPE_NONE) || !(field->flags & METAFLAG_NULLABLE)) + case TYPE_BYTES: { - m_visitor.enterStruct(*field); - if (field->typeName == STR_VARVALUE) + const Bytes* bytes = *sub; + if (bytes) { - VariantToVarValue variantToVarValue(*sub, m_visitor); - variantToVarValue.convert(); + m_visitor.enterBytes(*field, bytes->data(), bytes->size()); } else { - const MetaStruct* stru = MetaDataGlobal::instance().getStruct(*field); - if (stru) + m_visitor.enterBytes(*field, *sub); + } + } + break; + case TYPE_STRUCT: + if ((sub->getType() != VARTYPE_NONE) || !(field->flags & METAFLAG_NULLABLE)) + { + m_visitor.enterStruct(*field); + if (field->typeName == STR_VARVALUE) { - parseStruct(*stru, *sub); + VariantToVarValue variantToVarValue(*sub, m_visitor); + variantToVarValue.convert(); } else { - m_visitor.notifyError(nullptr, "typename not found"); + const MetaStruct* stru = MetaDataGlobal::instance().getStruct(*field); + if (stru) + { + parseStruct(*stru, *sub); + } + else + { + m_visitor.notifyError(nullptr, "typename not found"); + } } + m_visitor.exitStruct(*field); } - m_visitor.exitStruct(*field); - } - else - { - m_visitor.enterStructNull(*field); - } - break; - case TYPE_ENUM: + else + { + m_visitor.enterStructNull(*field); + } + break; + case TYPE_ENUM: { const std::string* str = *sub; if (str) @@ -174,7 +163,7 @@ void ParserVariant::processField(const Variant* sub, const MetaField* field) } } break; - case TYPE_ARRAY_BOOL: + case TYPE_ARRAY_BOOL: { const std::vector* value = *sub; if (value) @@ -187,7 +176,7 @@ void ParserVariant::processField(const Variant* sub, const MetaField* field) } } break; - case TYPE_ARRAY_INT8: + case TYPE_ARRAY_INT8: { const std::vector* value = *sub; if (value) @@ -200,7 +189,7 @@ void ParserVariant::processField(const Variant* sub, const MetaField* field) } } break; - case TYPE_ARRAY_INT16: + case TYPE_ARRAY_INT16: { const std::vector* value = *sub; if (value) @@ -213,7 +202,7 @@ void ParserVariant::processField(const Variant* sub, const MetaField* field) } } break; - case TYPE_ARRAY_UINT16: + case TYPE_ARRAY_UINT16: { const std::vector* value = *sub; if (value) @@ -226,7 +215,7 @@ void ParserVariant::processField(const Variant* sub, const MetaField* field) } } break; - case TYPE_ARRAY_INT32: + case TYPE_ARRAY_INT32: { const std::vector* value = *sub; if (value) @@ -239,7 +228,7 @@ void ParserVariant::processField(const Variant* sub, const MetaField* field) } } break; - case TYPE_ARRAY_UINT32: + case TYPE_ARRAY_UINT32: { const std::vector* value = *sub; if (value) @@ -252,7 +241,7 @@ void ParserVariant::processField(const Variant* sub, const MetaField* field) } } break; - case TYPE_ARRAY_INT64: + case TYPE_ARRAY_INT64: { const std::vector* value = *sub; if (value) @@ -265,7 +254,7 @@ void ParserVariant::processField(const Variant* sub, const MetaField* field) } } break; - case TYPE_ARRAY_UINT64: + case TYPE_ARRAY_UINT64: { const std::vector* value = *sub; if (value) @@ -278,7 +267,7 @@ void ParserVariant::processField(const Variant* sub, const MetaField* field) } } break; - case TYPE_ARRAY_FLOAT: + case TYPE_ARRAY_FLOAT: { const std::vector* value = *sub; if (value) @@ -291,7 +280,7 @@ void ParserVariant::processField(const Variant* sub, const MetaField* field) } } break; - case TYPE_ARRAY_DOUBLE: + case TYPE_ARRAY_DOUBLE: { const std::vector* value = *sub; if (value) @@ -304,7 +293,7 @@ void ParserVariant::processField(const Variant* sub, const MetaField* field) } } break; - case TYPE_ARRAY_STRING: + case TYPE_ARRAY_STRING: { const std::vector* value = *sub; if (value) @@ -317,7 +306,7 @@ void ParserVariant::processField(const Variant* sub, const MetaField* field) } } break; - case TYPE_ARRAY_BYTES: + case TYPE_ARRAY_BYTES: { const std::vector* value = *sub; if (value) @@ -330,7 +319,7 @@ void ParserVariant::processField(const Variant* sub, const MetaField* field) } } break; - case TYPE_ARRAY_STRUCT: + case TYPE_ARRAY_STRUCT: { m_visitor.enterArrayStruct(*field); const VariantList* list = *sub; @@ -348,14 +337,13 @@ void ParserVariant::processField(const Variant* sub, const MetaField* field) m_visitor.enterStruct(*fieldWithoutArray); parseStruct(*stru, element); m_visitor.exitStruct(*fieldWithoutArray); - } } } m_visitor.exitArrayStruct(*field); } break; - case TYPE_ARRAY_ENUM: + case TYPE_ARRAY_ENUM: { bool done = false; const std::vector* value = *sub; @@ -366,10 +354,10 @@ void ParserVariant::processField(const Variant* sub, const MetaField* field) } else { - const std::vector* value = *sub; - if (value) + const std::vector* v = *sub; + if (v) { - m_visitor.enterArrayEnum(*field, value->data(), value->size()); + m_visitor.enterArrayEnum(*field, v->data(), v->size()); done = true; } } @@ -379,139 +367,135 @@ void ParserVariant::processField(const Variant* sub, const MetaField* field) } } break; - default: - assert(false); - break; + default: + assert(false); + break; } } - - void ParserVariant::processEmptyField(const MetaField* field) { - - switch (field->typeId) + switch(field->typeId) { - case TYPE_BOOL: - m_visitor.enterBool(*field, bool()); - break; - case TYPE_INT8: - m_visitor.enterInt8(*field, std::int8_t()); - break; - case TYPE_UINT8: - m_visitor.enterUInt8(*field, std::uint8_t()); - break; - case TYPE_INT16: - m_visitor.enterInt16(*field, std::int16_t()); - break; - case TYPE_UINT16: - m_visitor.enterUInt16(*field, std::uint16_t()); - break; - case TYPE_INT32: - m_visitor.enterInt32(*field, std::int32_t()); - break; - case TYPE_UINT32: - m_visitor.enterUInt32(*field, std::uint32_t()); - break; - case TYPE_INT64: - m_visitor.enterInt64(*field, std::int64_t()); - break; - case TYPE_UINT64: - m_visitor.enterUInt64(*field, std::uint64_t()); - break; - case TYPE_FLOAT: - m_visitor.enterFloat(*field, float()); - break; - case TYPE_DOUBLE: - m_visitor.enterDouble(*field, double()); - break; - case TYPE_STRING: - m_visitor.enterString(*field, std::string()); - break; - case TYPE_BYTES: - m_visitor.enterBytes(*field, Bytes()); - break; - case TYPE_STRUCT: - if (!(field->flags & METAFLAG_NULLABLE)) - { - m_visitor.enterStruct(*field); - if (field->typeName == STR_VARVALUE) - { - VariantToVarValue variantToVarValue(Variant(), m_visitor); - variantToVarValue.convert(); - } - else - { - const MetaStruct* stru = MetaDataGlobal::instance().getStruct(*field); - if (stru) + case TYPE_BOOL: + m_visitor.enterBool(*field, bool()); + break; + case TYPE_INT8: + m_visitor.enterInt8(*field, std::int8_t()); + break; + case TYPE_UINT8: + m_visitor.enterUInt8(*field, std::uint8_t()); + break; + case TYPE_INT16: + m_visitor.enterInt16(*field, std::int16_t()); + break; + case TYPE_UINT16: + m_visitor.enterUInt16(*field, std::uint16_t()); + break; + case TYPE_INT32: + m_visitor.enterInt32(*field, std::int32_t()); + break; + case TYPE_UINT32: + m_visitor.enterUInt32(*field, std::uint32_t()); + break; + case TYPE_INT64: + m_visitor.enterInt64(*field, std::int64_t()); + break; + case TYPE_UINT64: + m_visitor.enterUInt64(*field, std::uint64_t()); + break; + case TYPE_FLOAT: + m_visitor.enterFloat(*field, float()); + break; + case TYPE_DOUBLE: + m_visitor.enterDouble(*field, double()); + break; + case TYPE_STRING: + m_visitor.enterString(*field, std::string()); + break; + case TYPE_BYTES: + m_visitor.enterBytes(*field, Bytes()); + break; + case TYPE_STRUCT: + if (!(field->flags & METAFLAG_NULLABLE)) + { + m_visitor.enterStruct(*field); + if (field->typeName == STR_VARVALUE) { - parseStruct(*stru); + VariantToVarValue variantToVarValue(Variant(), m_visitor); + variantToVarValue.convert(); } else { - m_visitor.notifyError(nullptr, "typename not found"); + const MetaStruct* stru = MetaDataGlobal::instance().getStruct(*field); + if (stru) + { + parseStruct(*stru); + } + else + { + m_visitor.notifyError(nullptr, "typename not found"); + } } + m_visitor.exitStruct(*field); } - m_visitor.exitStruct(*field); - } - else - { - m_visitor.enterStructNull(*field); - } - break; - case TYPE_ENUM: - m_visitor.enterEnum(*field, std::int32_t()); - break; - case TYPE_ARRAY_BOOL: - m_visitor.enterArrayBool(*field, std::vector()); - break; - case TYPE_ARRAY_INT8: - m_visitor.enterArrayInt8(*field, std::vector()); - break; - case TYPE_ARRAY_INT16: - m_visitor.enterArrayInt16(*field, std::vector()); - break; - case TYPE_ARRAY_UINT16: - m_visitor.enterArrayUInt16(*field, std::vector()); - break; - case TYPE_ARRAY_INT32: - m_visitor.enterArrayInt32(*field, std::vector()); - break; - case TYPE_ARRAY_UINT32: - m_visitor.enterArrayUInt32(*field, std::vector()); - break; - case TYPE_ARRAY_INT64: - m_visitor.enterArrayInt64(*field, std::vector()); - break; - case TYPE_ARRAY_UINT64: - m_visitor.enterArrayUInt64(*field, std::vector()); - break; - case TYPE_ARRAY_FLOAT: - m_visitor.enterArrayFloat(*field, std::vector()); - break; - case TYPE_ARRAY_DOUBLE: - m_visitor.enterArrayDouble(*field, std::vector()); - break; - case TYPE_ARRAY_STRING: - m_visitor.enterArrayString(*field, std::vector()); - break; - case TYPE_ARRAY_BYTES: - m_visitor.enterArrayBytes(*field, std::vector()); - break; - case TYPE_ARRAY_STRUCT: - m_visitor.enterArrayStruct(*field); - m_visitor.exitArrayStruct(*field); - break; - case TYPE_ARRAY_ENUM: - m_visitor.enterArrayEnum(*field, std::vector()); - break; - default: - assert(false); - break; + else + { + m_visitor.enterStructNull(*field); + } + break; + case TYPE_ENUM: + m_visitor.enterEnum(*field, std::int32_t()); + break; + case TYPE_ARRAY_BOOL: + m_visitor.enterArrayBool(*field, std::vector()); + break; + case TYPE_ARRAY_INT8: + m_visitor.enterArrayInt8(*field, std::vector()); + break; + case TYPE_ARRAY_INT16: + m_visitor.enterArrayInt16(*field, std::vector()); + break; + case TYPE_ARRAY_UINT16: + m_visitor.enterArrayUInt16(*field, std::vector()); + break; + case TYPE_ARRAY_INT32: + m_visitor.enterArrayInt32(*field, std::vector()); + break; + case TYPE_ARRAY_UINT32: + m_visitor.enterArrayUInt32(*field, std::vector()); + break; + case TYPE_ARRAY_INT64: + m_visitor.enterArrayInt64(*field, std::vector()); + break; + case TYPE_ARRAY_UINT64: + m_visitor.enterArrayUInt64(*field, std::vector()); + break; + case TYPE_ARRAY_FLOAT: + m_visitor.enterArrayFloat(*field, std::vector()); + break; + case TYPE_ARRAY_DOUBLE: + m_visitor.enterArrayDouble(*field, std::vector()); + break; + case TYPE_ARRAY_STRING: + m_visitor.enterArrayString(*field, std::vector()); + break; + case TYPE_ARRAY_BYTES: + m_visitor.enterArrayBytes(*field, std::vector()); + break; + case TYPE_ARRAY_STRUCT: + m_visitor.enterArrayStruct(*field); + m_visitor.exitArrayStruct(*field); + break; + case TYPE_ARRAY_ENUM: + m_visitor.enterArrayEnum(*field, std::vector()); + break; + default: + assert(false); + break; } } - void ParserVariant::parseStruct(const MetaStruct& stru, const Variant& variant) { ssize_t size = stru.getFieldsSize(); @@ -531,7 +515,6 @@ void ParserVariant::parseStruct(const MetaStruct& stru, const Variant& variant) } } - void ParserVariant::parseStruct(const MetaStruct& stru) { ssize_t size = stru.getFieldsSize(); @@ -543,4 +526,4 @@ void ParserVariant::parseStruct(const MetaStruct& stru) } } -} // namespace finalmq +} // namespace finalmq diff --git a/src/streamconnection/AddressHelpers.cpp b/src/streamconnection/AddressHelpers.cpp index 260d2ac6..1169ca9a 100644 --- a/src/streamconnection/AddressHelpers.cpp +++ b/src/streamconnection/AddressHelpers.cpp @@ -21,27 +21,29 @@ //SOFTWARE. #include "finalmq/streamconnection/AddressHelpers.h" -#include "finalmq/logger/LogStream.h" -#include "finalmq/helpers/ModulenameFinalmq.h" + #include +#include "finalmq/helpers/ModulenameFinalmq.h" +#include "finalmq/logger/LogStream.h" + #if defined(WIN32) || defined(__MINGW32__) -#pragma warning(disable: 4996) +#pragma warning(disable : 4996) #else -#include #include + +#include #endif #ifdef __QNX__ -#include #include +#include #endif #include - -namespace finalmq { - +namespace finalmq +{ int AddressHelpers::parseEndpoint(const std::string& endpoint, std::string& protocol, std::string& address) { if (endpoint.empty()) @@ -96,7 +98,6 @@ int AddressHelpers::parseTcpAddress(const std::string& address, std::string& hos return 0; } - ConnectionData AddressHelpers::endpoint2ConnectionData(const std::string& endpoint) { ConnectionData connectionData; @@ -143,9 +144,6 @@ ConnectionData AddressHelpers::endpoint2ConnectionData(const std::string& endpoi return connectionData; } - - - std::string AddressHelpers::makeSocketAddress(const std::string& hostname, int port, int af, bool asyncGetHostByName, bool& doAsyncGetHostByName) { const sockaddr* addr = nullptr; @@ -156,9 +154,9 @@ std::string AddressHelpers::makeSocketAddress(const std::string& hostname, int p #ifndef WIN32 struct sockaddr_un addrUnix; #endif - switch (af) + switch(af) { - case AF_INET: + case AF_INET: { assert(!hostname.empty()); addrlen = 0; @@ -178,30 +176,34 @@ std::string AddressHelpers::makeSocketAddress(const std::string& hostname, int p if (hp) { memset(&addrTcp, 0, addrlen); - addrTcp.sin_family = af; - addrTcp.sin_addr.s_addr = ((struct in_addr *)(hp->h_addr))->s_addr; - addrTcp.sin_port = htons(port); - addr = (sockaddr*)&addrTcp; +#ifdef WIN32 + addrTcp.sin_family = static_cast(af); +#else + addrTcp.sin_family = static_cast(af); +#endif + addrTcp.sin_addr.s_addr = reinterpret_cast(hp->h_addr)->s_addr; + addrTcp.sin_port = htons(static_cast(port)); + addr = reinterpret_cast(&addrTcp); } } } break; #ifndef WIN32 - case AF_UNIX: - addrlen = sizeof(addrUnix); - memset(&addrUnix, 0, sizeof(addrUnix)); - addrUnix.sun_family = af; - strcpy(addrUnix.sun_path, hostname.c_str()); - addr = (sockaddr*)&addrUnix; - break; + case AF_UNIX: + addrlen = sizeof(addrUnix); + memset(&addrUnix, 0, sizeof(addrUnix)); + addrUnix.sun_family = static_cast(af); + strcpy(addrUnix.sun_path, hostname.c_str()); + addr = reinterpret_cast(&addrUnix); + break; #endif - default: - streamError << "protocol not supported"; - break; + default: + streamError << "protocol not supported"; + break; } if (addr) { - return std::string((char*)addr, addrlen); + return std::string(reinterpret_cast(addr), addrlen); } else { @@ -209,16 +211,14 @@ std::string AddressHelpers::makeSocketAddress(const std::string& hostname, int p } } - - void AddressHelpers::addr2peer(sockaddr* addr, ConnectionData& connectionData) { - switch (addr->sa_family) + switch(addr->sa_family) { #ifndef WIN32 - case AF_UNIX: + case AF_UNIX: { - struct sockaddr_un* a = (struct sockaddr_un*)addr; + struct sockaddr_un* a = reinterpret_cast(addr); std::string endpoint = "icp://"; endpoint += a->sun_path; connectionData.endpointPeer = std::move(endpoint); @@ -227,11 +227,11 @@ void AddressHelpers::addr2peer(sockaddr* addr, ConnectionData& connectionData) } break; #endif - case AF_INET: + case AF_INET: { - struct sockaddr_in* a = (struct sockaddr_in*)addr; + struct sockaddr_in* a = reinterpret_cast(addr); int port = ntohs(a->sin_port); - unsigned char* ipaddr = (unsigned char*)&a->sin_addr.s_addr; + unsigned char* ipaddr = reinterpret_cast(&a->sin_addr.s_addr); std::string address; address += std::to_string(ipaddr[0]); address += '.'; @@ -249,12 +249,12 @@ void AddressHelpers::addr2peer(sockaddr* addr, ConnectionData& connectionData) connectionData.portPeer = port; } break; - default: - connectionData.endpointPeer.clear(); - connectionData.addressPeer.clear(); - connectionData.portPeer = 0; - break; + default: + connectionData.endpointPeer.clear(); + connectionData.addressPeer.clear(); + connectionData.portPeer = 0; + break; } } -} // namespace finalmq +} // namespace finalmq diff --git a/src/streamconnection/Socket.cpp b/src/streamconnection/Socket.cpp index 23caf969..a8f0a9bc 100644 --- a/src/streamconnection/Socket.cpp +++ b/src/streamconnection/Socket.cpp @@ -20,31 +20,28 @@ //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. - #include "finalmq/streamconnection/Socket.h" -#include "finalmq/helpers/OperatingSystem.h" -#include "finalmq/logger/LogStream.h" -#include "finalmq/helpers/ModulenameFinalmq.h" - +#include #include #include -#include + +#include "finalmq/helpers/ModulenameFinalmq.h" +#include "finalmq/helpers/OperatingSystem.h" +#include "finalmq/logger/LogStream.h" #if defined(WIN32) || defined(__MINGW32__) -#pragma warning(disable: 4996) +#pragma warning(disable : 4996) //#include #else -#include #include + +#include #ifndef __QNX__ #include #endif #endif - - - class InitWinSocket { public: @@ -65,22 +62,17 @@ class InitWinSocket }; static InitWinSocket g_initWinSocket; - - -namespace finalmq { - - +namespace finalmq +{ Socket::Socket() { } - Socket::~Socket() { destroy(); } - bool Socket::create(int af, int type, int protocol) { destroy(); @@ -102,8 +94,6 @@ bool Socket::create(int af, int type, int protocol) return ok; } - - #ifdef USE_OPENSSL bool Socket::createSslServer(int af, int type, int protocol, const CertificateData& certificateData) { @@ -142,7 +132,6 @@ bool Socket::createSslClient(int af, int type, int protocol, const CertificateDa } #endif - bool Socket::isValid() const { return (m_sd != nullptr); @@ -168,7 +157,7 @@ bool Socket::accept(sockaddr* addr, socklen_t* addrlen, SocketPtr& socketAccept) bool ok = false; socketAccept = nullptr; assert(m_sd); - SOCKET sd = OperatingSystem::instance().accept(m_sd->getDescriptor(), addr, (socklen_t*)addrlen); + SOCKET sd = OperatingSystem::instance().accept(m_sd->getDescriptor(), addr, addrlen); if (sd != INVALID_SOCKET) { ok = true; @@ -184,13 +173,12 @@ bool Socket::accept(sockaddr* addr, socklen_t* addrlen, SocketPtr& socketAccept) return ok; } - int Socket::bind(const sockaddr* addr, int addrlen) { #if !defined(WIN32) && !defined(__MINGW32__) if (m_af == AF_UNIX) { - struct sockaddr_un* addrunix = (sockaddr_un*)addr; + const struct sockaddr_un* addrunix = reinterpret_cast(addr); if (addrunix) { m_name = addrunix->sun_path; @@ -210,7 +198,6 @@ int Socket::bind(const sockaddr* addr, int addrlen) return err; } - int Socket::listen(int backlog) { assert(m_sd); @@ -219,9 +206,6 @@ int Socket::listen(int backlog) return err; } - - - int Socket::send(const char* buf, int len, int flags) { assert(m_sd); @@ -254,7 +238,7 @@ int Socket::send(const char* buf, int len, int flags) do { err = OperatingSystem::instance().send(m_sd->getDescriptor(), buf, len, flags); - } while(err == -1 && getLastError() == SOCKETERROR(EINTR)); + } while (err == -1 && getLastError() == SOCKETERROR(EINTR)); } if (err > 0) @@ -282,8 +266,6 @@ int Socket::send(const char* buf, int len, int flags) return err; } - - int Socket::receive(char* buf, int len, int flags) { assert(m_sd); @@ -316,7 +298,7 @@ int Socket::receive(char* buf, int len, int flags) do { err = OperatingSystem::instance().recv(m_sd->getDescriptor(), buf, len, flags); - } while(err == -1 && getLastError() == SOCKETERROR(EINTR)); + } while (err == -1 && getLastError() == SOCKETERROR(EINTR)); } if (err > 0) @@ -344,7 +326,6 @@ int Socket::receive(char* buf, int len, int flags) return err; } - void Socket::destroy() { if (m_sd) @@ -357,17 +338,11 @@ void Socket::destroy() } } - - SocketDescriptorPtr Socket::getSocketDescriptor() const { return m_sd; } - - - - void Socket::attach(SOCKET sd) { if (sd != INVALID_SOCKET) @@ -382,7 +357,6 @@ void Socket::attach(SOCKET sd) } } - int Socket::pendingRead() const { assert(m_sd); @@ -395,7 +369,6 @@ int Socket::pendingRead() const return countRead; } - int Socket::getLastError() { int errorNumber = OperatingSystem::instance().getLastError(); @@ -406,7 +379,6 @@ int Socket::getLastError() return errorNumber; } - int Socket::handleError(int err, const char* funcName) { if (err == -1) @@ -423,7 +395,6 @@ int Socket::handleError(int err, const char* funcName) return err; } - #ifdef USE_OPENSSL SSL_CTX* Socket::getSslCtx() @@ -462,23 +433,18 @@ int Socket::sslPending() return m_sslSocket->sslPending(); } - - SslSocket::IoState Socket::sslAccepting() { assert(m_sslSocket); return m_sslSocket->accepting(); } - SslSocket::IoState Socket::sslConnecting() { assert(m_sslSocket); return m_sslSocket->connecting(); } - #endif - -} // namespace finalmq +} // namespace finalmq diff --git a/src/streamconnection/StreamConnection.cpp b/src/streamconnection/StreamConnection.cpp index 2a804f15..4bbb3482 100644 --- a/src/streamconnection/StreamConnection.cpp +++ b/src/streamconnection/StreamConnection.cpp @@ -20,32 +20,24 @@ //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. - #include "finalmq/streamconnection/StreamConnection.h" -#include "finalmq/streamconnection/AddressHelpers.h" -#include - -namespace finalmq { +#include +#include "finalmq/streamconnection/AddressHelpers.h" +namespace finalmq +{ StreamConnection::StreamConnection(const ConnectionData& connectionData, std::shared_ptr socket, const IPollerPtr& poller, hybrid_ptr callback) - : m_connectionId(connectionData.connectionId) - , m_connectionData(connectionData) - , m_socketPrivate(socket) - , m_socket(socket) - , m_poller(poller) - , m_callback(callback) + : m_connectionId(connectionData.connectionId), m_connectionData(connectionData), m_socketPrivate(socket), m_socket(socket), m_poller(poller), m_callback(callback) { m_lastReconnectTime = std::chrono::steady_clock::now(); } - StreamConnection::~StreamConnection() { } - // IStreamConnection void StreamConnection::sendMessage(const IMessagePtr& msg) { @@ -60,8 +52,7 @@ void StreamConnection::sendMessage(const IMessagePtr& msg) if (size > 0) { const auto& payloads = msg->getAllSendBuffers(); - if (!m_pendingMessages.empty() || - m_connectionData.connectionState != ConnectionState::CONNECTIONSTATE_CONNECTED) + if (!m_pendingMessages.empty() || m_connectionData.connectionState != ConnectionState::CONNECTIONSTATE_CONNECTED) { m_pendingMessages.push_back({msg, payloads.begin(), 0}); } @@ -78,15 +69,15 @@ void StreamConnection::sendMessage(const IMessagePtr& msg) const BufferRef& payload = *it; ++it; -#if __QNX__ +#ifdef __QNX__ int flags = 0; #else bool last = (it == payloads.end()); - int flags = last ? 0 : MSG_MORE; // win32: MSG_PARTIAL + int flags = last ? 0 : MSG_MORE; // win32: MSG_PARTIAL #endif #if !defined WIN32 - flags |= MSG_NOSIGNAL; // no sigpipe + flags |= MSG_NOSIGNAL; // no sigpipe #endif int err = m_socketPrivate->send(payload.first, static_cast(payload.second), flags); if (err != payload.second) @@ -109,14 +100,12 @@ void StreamConnection::sendMessage(const IMessagePtr& msg) lock.unlock(); } - ConnectionData StreamConnection::getConnectionData() const { std::unique_lock lock(m_mutex); return m_connectionData; } - ConnectionState StreamConnection::getConnectionState() const { std::unique_lock lock(m_mutex); @@ -128,37 +117,31 @@ std::int64_t StreamConnection::getConnectionId() const return m_connectionId; } - - SocketPtr StreamConnection::getSocketPrivate() { // do not mutex lock here, because the removeSocket and getSocketPrivate will be called from same thread. return m_socketPrivate; } - SocketPtr StreamConnection::getSocket() { std::unique_lock lock(m_mutex); return m_socket; } - void StreamConnection::disconnect() { m_disconnectFlag = true; m_poller->releaseWait(RELEASE_DISCONNECT); } - bool StreamConnection::connect() { bool connecting = false; std::unique_lock lock(m_mutex); - if ((m_connectionData.connectionState == ConnectionState::CONNECTIONSTATE_CREATED || m_connectionData.connectionState == ConnectionState::CONNECTIONSTATE_CONNECTING_FAILED) && - m_socketPrivate) + if ((m_connectionData.connectionState == ConnectionState::CONNECTIONSTATE_CREATED || m_connectionData.connectionState == ConnectionState::CONNECTIONSTATE_CONNECTING_FAILED) && m_socketPrivate) { - int ret = m_socketPrivate->connect((const sockaddr*)m_connectionData.sockaddr.c_str(), (int)m_connectionData.sockaddr.size()); + int ret = m_socketPrivate->connect(reinterpret_cast(m_connectionData.sockaddr.c_str()), static_cast(m_connectionData.sockaddr.size())); if (ret == 0) { connecting = true; @@ -172,9 +155,6 @@ bool StreamConnection::connect() return connecting; } - - - bool StreamConnection::sendPendingMessages() { bool pending = false; @@ -189,18 +169,18 @@ bool StreamConnection::sendPendingMessages() IMessagePtr& msg = messageSendState.msg; assert(msg); const auto& payloads = msg->getAllSendBuffers(); - for (auto it = messageSendState.it ; it != payloads.end() && !pending; ) + for (auto it = messageSendState.it; it != payloads.end() && !pending;) { const BufferRef& payload = *it; ++it; -#if __QNX__ +#ifdef __QNX__ int flags = 0; #else bool last = ((it == payloads.end()) && (m_pendingMessages.size() == 1)); - int flags = last ? 0 : MSG_MORE; // win32: MSG_PARTIAL + int flags = last ? 0 : MSG_MORE; // win32: MSG_PARTIAL #endif #if !defined WIN32 - flags |= MSG_NOSIGNAL; // no sigpipe + flags |= MSG_NOSIGNAL; // no sigpipe #endif ssize_t size = payload.second - messageSendState.offset; assert((payload.second == 0 && size == 0) || (size > 0)); @@ -237,10 +217,6 @@ bool StreamConnection::sendPendingMessages() return pending; } - - - - bool StreamConnection::checkEdgeConnected() { std::unique_lock lock(m_mutex); @@ -253,13 +229,10 @@ bool StreamConnection::checkEdgeConnected() return edgeConnected; } - bool StreamConnection::doReconnect() { bool reconnecting = false; - if (!m_connectionData.incomingConnection && - m_connectionData.connectionState == ConnectionState::CONNECTIONSTATE_CONNECTING_FAILED && - m_connectionData.reconnectInterval >= 0) + if (!m_connectionData.incomingConnection && m_connectionData.connectionState == ConnectionState::CONNECTIONSTATE_CONNECTING_FAILED && m_connectionData.reconnectInterval >= 0) { std::chrono::time_point now = std::chrono::steady_clock::now(); std::chrono::duration dur = now - m_lastReconnectTime; @@ -273,7 +246,6 @@ bool StreamConnection::doReconnect() return reconnecting; } - bool StreamConnection::changeStateForDisconnect() { std::unique_lock lock(m_mutex); @@ -308,13 +280,11 @@ bool StreamConnection::changeStateForDisconnect() return removeConnection; } - bool StreamConnection::getDisconnectFlag() const { return m_disconnectFlag; } - void StreamConnection::updateConnectionData(const ConnectionData& connectionData) { std::unique_lock lock(m_mutex); @@ -323,7 +293,6 @@ void StreamConnection::updateConnectionData(const ConnectionData& connectionData lock.unlock(); } - void StreamConnection::connected(const IStreamConnectionPtr& connection) { auto callback = m_callback.lock(); @@ -363,4 +332,4 @@ bool StreamConnection::received(const IStreamConnectionPtr& connection, const So return ok; } -} // namespace finalmq +} // namespace finalmq diff --git a/src/streamconnection/StreamConnectionContainer.cpp b/src/streamconnection/StreamConnectionContainer.cpp index 6a597ebe..0f3ae0c6 100644 --- a/src/streamconnection/StreamConnectionContainer.cpp +++ b/src/streamconnection/StreamConnectionContainer.cpp @@ -20,12 +20,11 @@ //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. - #include "finalmq/streamconnection/StreamConnectionContainer.h" -#include "finalmq/streamconnection/Socket.h" -#include "finalmq/streamconnection/AddressHelpers.h" -#include "finalmq/helpers/Executor.h" +#include "finalmq/helpers/Executor.h" +#include "finalmq/streamconnection/AddressHelpers.h" +#include "finalmq/streamconnection/Socket.h" #if defined(WIN32) || defined(__MINGW32__) || defined(__QNX__) #include "finalmq/poller/PollerImplSelect.h" @@ -34,8 +33,9 @@ #endif #if !defined(WIN32) && !defined(__MINGW32__) -#include #include + +#include #include #ifndef __QNX__ #include @@ -43,23 +43,21 @@ #endif #include -#include - - -namespace finalmq { +#include +namespace finalmq +{ std::atomic_int64_t StreamConnectionContainer::m_nextConnectionId{1}; - StreamConnectionContainer::StreamConnectionContainer() #if defined(WIN32) || defined(__MINGW32__) || defined(__QNX__) : m_poller(std::make_shared()) #else : m_poller(std::make_shared()) #endif - , m_executorPollerThread(std::make_shared()) - , m_executorWorker(std::make_unique>(1)) + , + m_executorPollerThread(std::make_shared()), m_executorWorker(std::make_unique>(1)) { m_executorPollerThread->registerActionNotification([this]() { m_poller->releaseWait(RELEASE_EXECUTEINPOLLERTHREAD); @@ -76,8 +74,6 @@ StreamConnectionContainer::~StreamConnectionContainer() } } - - std::unordered_map::iterator StreamConnectionContainer::findBindByEndpoint(const std::string& endpoint) { // mutex already locked @@ -91,7 +87,6 @@ std::unordered_map::iterator Stream return m_sd2binds.end(); } - IStreamConnectionPrivatePtr StreamConnectionContainer::findConnectionBySdOnlyForPollerLoop(SOCKET sd) { // m_sd2ConnectionPollerLoop is only used at poller loop thread @@ -104,7 +99,6 @@ IStreamConnectionPrivatePtr StreamConnectionContainer::findConnectionBySdOnlyFor return connection; } - IStreamConnectionPrivatePtr StreamConnectionContainer::findConnectionById(std::int64_t connectionId) { std::unique_lock lock(m_mutex); @@ -118,10 +112,6 @@ IStreamConnectionPrivatePtr StreamConnectionContainer::findConnectionById(std::i return connection; } - - - - // IStreamConnectionContainer void StreamConnectionContainer::init(int cycleTime, FuncPollerLoopTimer funcTimer, int checkReconnectInterval) @@ -131,10 +121,10 @@ void StreamConnectionContainer::init(int cycleTime, FuncPollerLoopTimer funcTime m_cycleTime = cycleTime; m_checkReconnectInterval = checkReconnectInterval; m_poller->init(); - m_threadTimer = std::thread([this](){ + m_threadTimer = std::thread([this]() { while (!m_terminatePollerLoop) { - m_executorPollerThread->addAction([this](){ + m_executorPollerThread->addAction([this]() { // this is the poller thread if (isTimerExpired(m_lastReconnectTime, m_checkReconnectInterval)) { @@ -150,7 +140,6 @@ void StreamConnectionContainer::init(int cycleTime, FuncPollerLoopTimer funcTime }); } - int StreamConnectionContainer::bind(const std::string& endpoint, hybrid_ptr callbackDefault, const BindProperties& bindProperties) { ConnectionData connectionData = AddressHelpers::endpoint2ConnectionData(endpoint); @@ -174,7 +163,7 @@ int StreamConnectionContainer::bind(const std::string& endpoint, hybrid_ptrbind((const sockaddr*)addr.c_str(), (int)addr.size()); + err = socket->bind(reinterpret_cast(addr.c_str()), static_cast(addr.size())); } if (err == 0) { @@ -204,8 +193,6 @@ int StreamConnectionContainer::bind(const std::string& endpoint, hybrid_ptr locker(m_mutex); @@ -235,9 +222,6 @@ IStreamConnectionPtr StreamConnectionContainer::connect(const std::string& endpo return connection; } - - - IStreamConnectionPtr StreamConnectionContainer::createConnection(hybrid_ptr callback) { ConnectionData connectionData; @@ -254,8 +238,6 @@ IStreamConnectionPtr StreamConnectionContainer::createConnection(hybrid_ptrgetSocket(); @@ -279,14 +261,14 @@ bool StreamConnectionContainer::createSocket(const IStreamConnectionPtr& streamC ret = socket->create(connectionData.af, connectionData.type, connectionData.protocol); } - (void) connectionProperties; + (void)connectionProperties; if (ret) { SocketDescriptorPtr sd = socket->getSocketDescriptor(); assert(sd); connectionData.sd = sd->getDescriptor(); - AddressHelpers::addr2peer((sockaddr*)connectionData.sockaddr.c_str(), connectionData); + AddressHelpers::addr2peer(reinterpret_cast(const_cast(connectionData.sockaddr.c_str())), connectionData); IStreamConnectionPrivatePtr streamConnectionPrivate; std::unique_lock lock(m_mutex); @@ -313,8 +295,6 @@ bool StreamConnectionContainer::createSocket(const IStreamConnectionPtr& streamC return ret; } - - bool StreamConnectionContainer::connect(const std::string& endpoint, const IStreamConnectionPtr& streamConnection, const ConnectProperties& connectionProperties) { assert(streamConnection); @@ -342,24 +322,28 @@ bool StreamConnectionContainer::connect(const std::string& endpoint, const IStre std::string hostname = connectionData.hostname; m_executorWorker->addAction([this, connectionData, connection, connectionProperties]() mutable { bool ok = false; - struct in_addr addr; + struct in_addr addr1; struct hostent* hp = gethostbyname(connectionData.hostname.c_str()); if (hp) { - addr = *((struct in_addr*)(hp->h_addr)); + addr1 = *(reinterpret_cast(hp->h_addr)); struct sockaddr_in addrTcp; memset(&addrTcp, 0, sizeof(sockaddr_in)); - addrTcp.sin_family = connectionData.af; - addrTcp.sin_addr.s_addr = addr.s_addr; - addrTcp.sin_port = htons(connectionData.port); - connectionData.sockaddr = std::string((const char*)&addrTcp, sizeof(sockaddr_in)); +#ifdef WIN32 + addrTcp.sin_family = static_cast(connectionData.af); +#else + addrTcp.sin_family = static_cast(connectionData.af); +#endif + addrTcp.sin_addr.s_addr = addr1.s_addr; + addrTcp.sin_port = htons(static_cast(connectionData.port)); + connectionData.sockaddr = std::string(reinterpret_cast(&addrTcp), sizeof(sockaddr_in)); ok = createSocket(connection, connectionData, connectionProperties); if (ok) { ok = connection->connect(); } } - if(!ok) + if (!ok) { connection->disconnect(); } @@ -381,12 +365,9 @@ bool StreamConnectionContainer::connect(const std::string& endpoint, const IStre return ret; } - - - -std::vector< IStreamConnectionPtr > StreamConnectionContainer::getAllConnections() const +std::vector StreamConnectionContainer::getAllConnections() const { - std::vector< IStreamConnectionPtr > connections; + std::vector connections; std::unique_lock lock(m_mutex); connections.reserve(m_connectionId2Connection.size()); @@ -414,9 +395,6 @@ IStreamConnectionPtr StreamConnectionContainer::getConnection(std::int64_t conne return connection; } - - - ////////////// void StreamConnectionContainer::removeConnection(const SocketDescriptorPtr& sd, std::int64_t connectionId) @@ -431,7 +409,6 @@ void StreamConnectionContainer::removeConnection(const SocketDescriptorPtr& sd, lock.unlock(); } - void StreamConnectionContainer::disconnectIntern(const IStreamConnectionPrivatePtr& connectionDisconnect, const SocketDescriptorPtr& sd) { bool removeConn = connectionDisconnect->changeStateForDisconnect(); @@ -444,29 +421,22 @@ void StreamConnectionContainer::disconnectIntern(const IStreamConnectionPrivateP ////////////// - - - void StreamConnectionContainer::run() { pollerLoop(); } - void StreamConnectionContainer::terminatePollerLoop() { m_terminatePollerLoop = true; m_poller->releaseWait(RELEASE_TERMINATE); } - IExecutorPtr StreamConnectionContainer::getPollerThreadExecutor() const { return m_executorPollerThread; } - - IStreamConnectionPrivatePtr StreamConnectionContainer::addConnection(const SocketPtr& socket, ConnectionData& connectionData, hybrid_ptr callback) { std::unique_lock lock(m_mutex); @@ -484,7 +454,6 @@ IStreamConnectionPrivatePtr StreamConnectionContainer::addConnection(const Socke return connection; } - void StreamConnectionContainer::handleReceive(const IStreamConnectionPrivatePtr& connection, const SocketPtr& socket, int bytesToRead) { #ifdef USE_OPENSSL @@ -518,10 +487,10 @@ void StreamConnectionContainer::handleReceive(const IStreamConnectionPrivatePtr& if (!ok) { - SocketPtr socket = connection->getSocketPrivate(); - if (socket) + SocketPtr socket1 = connection->getSocketPrivate(); + if (socket1) { - SocketDescriptorPtr sd = socket->getSocketDescriptor(); + SocketDescriptorPtr sd = socket1->getSocketDescriptor(); disconnectIntern(connection, sd); } } @@ -536,8 +505,6 @@ void StreamConnectionContainer::handleReceive(const IStreamConnectionPrivatePtr& #endif } - - void StreamConnectionContainer::handleConnectionEvents(const IStreamConnectionPrivatePtr& connection, const SocketPtr& socket, const DescriptorInfo& info) { bool disconnected = (info.disconnected || (info.readable && info.bytesToRead == 0)); @@ -641,7 +608,7 @@ void StreamConnectionContainer::handleBindEvents(const DescriptorInfo& info) addr.resize(400); socklen_t addrlen = static_cast(addr.size()); SocketPtr socketAccept; - bindData.socket->accept((sockaddr*)addr.c_str(), &addrlen, socketAccept); + bindData.socket->accept(reinterpret_cast(const_cast(addr.c_str())), &addrlen, socketAccept); if (socketAccept) { ConnectionData connectionData = bindData.connectionData; @@ -665,7 +632,7 @@ void StreamConnectionContainer::handleBindEvents(const DescriptorInfo& info) SocketDescriptorPtr sd = socketAccept->getSocketDescriptor(); assert(sd); connectionData.sd = sd->getDescriptor(); - AddressHelpers::addr2peer((sockaddr*)connectionData.sockaddr.c_str(), connectionData); + AddressHelpers::addr2peer(reinterpret_cast(const_cast(connectionData.sockaddr.c_str())), connectionData); IStreamConnectionPrivatePtr connection = addConnection(socketAccept, connectionData, bindData.callback); connection->connected(connection); @@ -695,7 +662,6 @@ void StreamConnectionContainer::handleBindEvents(const DescriptorInfo& info) } } - #ifdef USE_OPENSSL bool StreamConnectionContainer::sslAccepting(SslAcceptingData& sslAcceptingData) { @@ -717,7 +683,7 @@ bool StreamConnectionContainer::sslAccepting(SslAcceptingData& sslAcceptingData) if (state == SslSocket::IoState::SUCCESS) { sslAcceptingData.connectionData.sd = sd->getDescriptor(); - AddressHelpers::addr2peer((sockaddr*)sslAcceptingData.connectionData.sockaddr.c_str(), sslAcceptingData.connectionData); + AddressHelpers::addr2peer(reinterpret_cast(const_cast(sslAcceptingData.connectionData.sockaddr.c_str())), sslAcceptingData.connectionData); IStreamConnectionPrivatePtr connection = addConnection(sslAcceptingData.socket, sslAcceptingData.connectionData, sslAcceptingData.callback); connection->connected(connection); @@ -738,7 +704,7 @@ bool StreamConnectionContainer::sslAccepting(SslAcceptingData& sslAcceptingData) void StreamConnectionContainer::doReconnect() { - std::vector< IStreamConnectionPrivatePtr > connections; + std::vector connections; std::unique_lock lock(m_mutex); connections.reserve(m_connectionId2Connection.size()); for (auto it = m_connectionId2Connection.begin(); it != m_connectionId2Connection.end(); ++it) @@ -753,8 +719,6 @@ void StreamConnectionContainer::doReconnect() } } - - bool StreamConnectionContainer::isTimerExpired(std::chrono::time_point& lastTime, int interval) { bool expired = false; @@ -775,9 +739,6 @@ bool StreamConnectionContainer::isTimerExpired(std::chrono::time_pointsecond); if (success) { - IStreamConnectionPrivatePtr connection = findConnectionBySdOnlyForPollerLoop(info.sd); - if (connection) + IStreamConnectionPrivatePtr connection1 = findConnectionBySdOnlyForPollerLoop(info.sd); + if (connection1) { - SocketPtr socket = connection->getSocketPrivate(); + SocketPtr socket = connection1->getSocketPrivate(); if (socket) { - handleConnectionEvents(connection, socket, info); + handleConnectionEvents(connection1, socket, info); } } } @@ -884,5 +843,4 @@ void StreamConnectionContainer::pollerLoop() } } - -} // namespace finalmq +} // namespace finalmq diff --git a/src/variant/VariantValueRegisterConversions.cpp b/src/variant/VariantValueRegisterConversions.cpp index c52b732e..7b28706f 100644 --- a/src/variant/VariantValueRegisterConversions.cpp +++ b/src/variant/VariantValueRegisterConversions.cpp @@ -20,39 +20,40 @@ //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. - - #include "finalmq/variant/VariantValueRegisterConversions.h" -#include "finalmq/variant/VariantValues.h" #include "finalmq/conversions/Conversions.h" +#include "finalmq/variant/VariantValues.h" - -namespace finalmq { - - +namespace finalmq +{ static VariantValueRegisterConversions g_registerConversions; - template class FunctionConvert { public: - TO operator ()(const Variant& variant) + TO operator()(const Variant& variant) { assert(variant.getType() == MetaTypeInfo::TypeId); const FROM* data = variant; assert(data); +#ifndef WIN32 +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wfloat-equal" +#endif return static_cast(*data); +#ifndef WIN32 +#pragma GCC diagnostic pop +#endif } }; - template class FunctionConvertStringToNumber { public: - TO operator ()(const Variant& variant) + TO operator()(const Variant& variant) { assert(variant.getType() == MetaTypeId::TYPE_STRING); const std::string* data = variant; @@ -62,12 +63,11 @@ class FunctionConvertStringToNumber } }; - template class FunctionConvertNumberToString { public: - std::string operator ()(const Variant& variant) + std::string operator()(const Variant& variant) { assert(variant.getType() == MetaTypeInfo::TypeId); const FROM* data = variant; @@ -79,7 +79,7 @@ template<> class FunctionConvertNumberToString { public: - std::string operator ()(const Variant& variant) + std::string operator()(const Variant& variant) { assert(variant.getType() == MetaTypeInfo::TypeId); const bool* data = variant; @@ -88,7 +88,6 @@ class FunctionConvertNumberToString } }; - template void VariantValueRegisterConversions::registerConversionsTo() { @@ -105,8 +104,6 @@ void VariantValueRegisterConversions::registerConversionsTo() Convert::registerConversion(MetaTypeId::TYPE_DOUBLE, FunctionConvert()); } - - VariantValueRegisterConversions::VariantValueRegisterConversions() { registerConversionsTo(); @@ -121,29 +118,29 @@ VariantValueRegisterConversions::VariantValueRegisterConversions() registerConversionsTo(); registerConversionsTo(); - Convert::registerConversion(MetaTypeId::TYPE_BOOL, FunctionConvertNumberToString()); - Convert::registerConversion(MetaTypeId::TYPE_INT8, FunctionConvertNumberToString()); - Convert::registerConversion(MetaTypeId::TYPE_UINT8, FunctionConvertNumberToString()); - Convert::registerConversion(MetaTypeId::TYPE_INT16, FunctionConvertNumberToString()); - Convert::registerConversion(MetaTypeId::TYPE_UINT16, FunctionConvertNumberToString()); - Convert::registerConversion(MetaTypeId::TYPE_INT32, FunctionConvertNumberToString()); - Convert::registerConversion(MetaTypeId::TYPE_UINT32, FunctionConvertNumberToString()); - Convert::registerConversion(MetaTypeId::TYPE_INT64, FunctionConvertNumberToString()); - Convert::registerConversion(MetaTypeId::TYPE_UINT64, FunctionConvertNumberToString()); - Convert::registerConversion(MetaTypeId::TYPE_FLOAT, FunctionConvertNumberToString()); - Convert::registerConversion(MetaTypeId::TYPE_DOUBLE, FunctionConvertNumberToString()); - - Convert::registerConversion(MetaTypeId::TYPE_STRING, FunctionConvertStringToNumber()); + Convert::registerConversion(MetaTypeId::TYPE_BOOL, FunctionConvertNumberToString()); + Convert::registerConversion(MetaTypeId::TYPE_INT8, FunctionConvertNumberToString()); + Convert::registerConversion(MetaTypeId::TYPE_UINT8, FunctionConvertNumberToString()); + Convert::registerConversion(MetaTypeId::TYPE_INT16, FunctionConvertNumberToString()); + Convert::registerConversion(MetaTypeId::TYPE_UINT16, FunctionConvertNumberToString()); + Convert::registerConversion(MetaTypeId::TYPE_INT32, FunctionConvertNumberToString()); + Convert::registerConversion(MetaTypeId::TYPE_UINT32, FunctionConvertNumberToString()); + Convert::registerConversion(MetaTypeId::TYPE_INT64, FunctionConvertNumberToString()); + Convert::registerConversion(MetaTypeId::TYPE_UINT64, FunctionConvertNumberToString()); + Convert::registerConversion(MetaTypeId::TYPE_FLOAT, FunctionConvertNumberToString()); + Convert::registerConversion(MetaTypeId::TYPE_DOUBLE, FunctionConvertNumberToString()); + + Convert::registerConversion(MetaTypeId::TYPE_STRING, FunctionConvertStringToNumber()); Convert::registerConversion(MetaTypeId::TYPE_STRING, FunctionConvertStringToNumber()); Convert::registerConversion(MetaTypeId::TYPE_STRING, FunctionConvertStringToNumber()); Convert::registerConversion(MetaTypeId::TYPE_STRING, FunctionConvertStringToNumber()); Convert::registerConversion(MetaTypeId::TYPE_STRING, FunctionConvertStringToNumber()); Convert::registerConversion(MetaTypeId::TYPE_STRING, FunctionConvertStringToNumber()); Convert::registerConversion(MetaTypeId::TYPE_STRING, FunctionConvertStringToNumber()); - Convert::registerConversion(MetaTypeId::TYPE_STRING, FunctionConvertStringToNumber()); + Convert::registerConversion(MetaTypeId::TYPE_STRING, FunctionConvertStringToNumber()); Convert::registerConversion(MetaTypeId::TYPE_STRING, FunctionConvertStringToNumber()); - Convert::registerConversion(MetaTypeId::TYPE_STRING, FunctionConvertStringToNumber()); - Convert::registerConversion(MetaTypeId::TYPE_STRING, FunctionConvertStringToNumber()); + Convert::registerConversion(MetaTypeId::TYPE_STRING, FunctionConvertStringToNumber()); + Convert::registerConversion(MetaTypeId::TYPE_STRING, FunctionConvertStringToNumber()); } -} // namespace finalmq +} // namespace finalmq