From 13d480796cb8c86d2f97acacf08b16a6766f31b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stanislav=20Angelovi=C4=8D?= Date: Sat, 3 May 2025 18:44:33 +0200 Subject: [PATCH 01/13] fix: address clang-tidy warnings in the library code --- .clang-tidy | 58 +++++++++ CMakeLists.txt | 20 ++- include/sdbus-c++/sdbus-c++.h | 2 + src/Connection.cpp | 128 ++++++++++++------- src/Connection.h | 16 +-- src/Error.cpp | 6 +- src/Flags.cpp | 8 +- src/Message.cpp | 227 ++++++++++++++++++---------------- src/Object.cpp | 24 ++-- src/Object.h | 10 +- src/Proxy.cpp | 36 +++--- src/SdBus.cpp | 185 +++++++++++++-------------- src/SdBus.h | 4 +- src/Types.cpp | 8 +- 14 files changed, 436 insertions(+), 296 deletions(-) create mode 100644 .clang-tidy diff --git a/.clang-tidy b/.clang-tidy new file mode 100644 index 00000000..e95c3235 --- /dev/null +++ b/.clang-tidy @@ -0,0 +1,58 @@ +--- +# TODO: enable -llvm-include-order in the end, after clang-format +Checks: "*,\ + -llvmlibc-*,\ + -altera-*,\ + -fuchsia-*, + -modernize-use-trailing-return-type,\ + -readability-braces-around-statements,\ + -google-readability-braces-around-statements,\ + -hicpp-braces-around-statements,\ + -hicpp-signed-bitwise,\ + -llvm-include-order,\ + -google-runtime-int,\ + -hicpp-named-parameter,\ + -readability-named-parameter,\ + -bugprone-macro-parentheses,\ + -google-readability-todo,\ + -cppcoreguidelines-pro-type-reinterpret-cast,\ + -cppcoreguidelines-pro-bounds-array-to-pointer-decay,\ + -hicpp-no-array-decay,\ + -cppcoreguidelines-avoid-c-arrays,\ + -hicpp-avoid-c-arrays,\ + -modernize-avoid-c-arrays" + +HeaderFilterRegex: 'src|sdbus-c++' +FormatStyle: file +WarningsAsErrors: "*" +CheckOptions: + - key: misc-non-private-member-variables-in-classes.IgnoreClassesWithAllMemberVariablesBeingPublic + value: '1' + - key: readability-implicit-bool-conversion.AllowPointerConditions + value: '1' + - key: readability-implicit-bool-conversion.AllowIntegerConditions + value: '1' + - key: readability-redundant-member-init.IgnoreBaseInCopyConstructors + value: '1' + - key: cppcoreguidelines-special-member-functions.AllowSoleDefaultDtor + value: '1' + - key: hicpp-special-member-functions.AllowSoleDefaultDtor + value: '1' + - key: readability-identifier-length.IgnoredVariableNames + value: 'r|fd|id|ok|it' + - key: readability-identifier-length.IgnoredParameterNames + value: 'fd|id|b' + - key: performance-move-const-arg.CheckTriviallyCopyableMove + value: '0' + - key: hicpp-move-const-arg.CheckTriviallyCopyableMove + value: '0' + - key: misc-include-cleaner.IgnoreHeaders + value: 'systemd/.*|gtest/.*|gmock/.*|bits/chrono.h|bits/basic_string.h|time.h|poll.h' + - key: readability-simplify-boolean-expr.IgnoreMacros + value: '1' + - key: cppcoreguidelines-rvalue-reference-param-not-moved.IgnoreUnnamedParams + value: '1' +# - key: bugprone-easily-swappable-parameters.MinimumLength +# value: '3' +# - key: readability-braces-around-statements.ShortStatementLines +# value: '3' diff --git a/CMakeLists.txt b/CMakeLists.txt index 1888ea98..a5b83f6e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -35,7 +35,7 @@ option(SDBUSCPP_BUILD_DOCS "Build documentation for sdbus-c++" ON) if(SDBUSCPP_BUILD_DOCS) option(SDBUSCPP_BUILD_DOXYGEN_DOCS "Build doxygen documentation for sdbus-c++ API" OFF) endif() -#option(SDBUSCPP_CLANG_TIDY "Co-compile with clang-tidy static analyzer" OFF) +option(SDBUSCPP_CLANG_TIDY "Co-compile with clang-tidy static analyzer" OFF) #option(SDBUSCPP_COVERAGE "Build sdbus-c++ with code coverage instrumentation" OFF) # We promote the BUILD_SHARED_LIBS flag to a (global) option only if we are the main project if(CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR) @@ -265,6 +265,24 @@ if(SDBUSCPP_BUILD_DOCS) add_subdirectory("${CMAKE_CURRENT_SOURCE_DIR}/docs") endif() +#---------------------------------- +# STATIC ANALYSIS +#---------------------------------- + +if(SDBUSCPP_CLANG_TIDY) + message(STATUS "Building with static analysis") + find_program(CLANG_TIDY NAMES clang-tidy) + if(NOT CLANG_TIDY) + message(STATUS "clang-tidy not found") + else() + message(STATUS "clang-tidy found: ${CLANG_TIDY}") + set_target_properties(sdbus-c++-objlib PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY}") + set_target_properties(sdbus-c++ PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY}") + set_target_properties(sdbus-c++-unit-tests PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY}") + set_target_properties(sdbus-c++-integration-tests PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY}") + endif() +endif() + #---------------------------------- # CMAKE CONFIG & PACKAGE CONFIG #---------------------------------- diff --git a/include/sdbus-c++/sdbus-c++.h b/include/sdbus-c++/sdbus-c++.h index 8bc3fe69..787d8054 100644 --- a/include/sdbus-c++/sdbus-c++.h +++ b/include/sdbus-c++/sdbus-c++.h @@ -24,6 +24,7 @@ * along with sdbus-c++. If not, see . */ +// IWYU pragma: begin_exports #include #include #include @@ -36,3 +37,4 @@ #include #include #include +// IWYU pragma: end_exports diff --git a/src/Connection.cpp b/src/Connection.cpp index 7c667b55..cc05ac08 100644 --- a/src/Connection.cpp +++ b/src/Connection.cpp @@ -27,21 +27,34 @@ #include "Connection.h" #include "sdbus-c++/Error.h" +#include "sdbus-c++/IConnection.h" #include "sdbus-c++/Message.h" #include "sdbus-c++/Types.h" +#include "sdbus-c++/TypeTraits.h" +#include "ISdBus.h" #include "MessageUtils.h" #include "ScopeGuard.h" #include "SdBus.h" #include "Utils.h" +#include +#include +#include +#include +#include +#include +#include #include +#include #include #include SDBUS_HEADER #ifndef SDBUS_basu // sd_event integration is not supported in basu-based sdbus-c++ #include #endif #include +#include +#include namespace sdbus::internal { @@ -105,9 +118,19 @@ Connection::Connection(std::unique_ptr&& interface, pseudo_bus_t) } Connection::~Connection() +try { Connection::leaveEventLoop(); } +catch (...) // NOLINT(bugprone-empty-catch) +{ + // Theoretically, we can fail to notify the event fd or join with the joinable thread... + // What to do now here in the destructor? That is the question: + // 1. Report the problem... but how, where? + // 2. Terminate immediately... too harsh? + // 3. Ignore and go on... even when some resources may be lingering? + // Since the failure here is expected to be very unlikely, we choose the defensive approach of (3). +} void Connection::requestName(const ServiceName& name) { @@ -194,7 +217,7 @@ Slot Connection::addObjectManager(const ObjectPath& objectPath, return_slot_t) SDBUS_THROW_ERROR_IF(r < 0, "Failed to add object manager", -r); - return {slot, [this](void *slot){ sdbus_->sd_bus_slot_unref((sd_bus_slot*)slot); }}; + return {slot, [this](void *slot){ sdbus_->sd_bus_slot_unref(static_cast(slot)); }}; } void Connection::setMethodCallTimeout(uint64_t timeout) @@ -206,7 +229,7 @@ void Connection::setMethodCallTimeout(uint64_t timeout) uint64_t Connection::getMethodCallTimeout() const { - uint64_t timeout; + uint64_t timeout{}; auto r = sdbus_->sd_bus_get_method_call_timeout(bus_.get(), &timeout); @@ -230,9 +253,9 @@ Slot Connection::addMatch(const std::string& match, message_handler callback, re auto r = sdbus_->sd_bus_add_match(bus_.get(), &slot, match.c_str(), &Connection::sdbus_match_callback, matchInfo.get()); SDBUS_THROW_ERROR_IF(r < 0, "Failed to add match", -r); - matchInfo->slot = {slot, [this](void *slot){ sdbus_->sd_bus_slot_unref((sd_bus_slot*)slot); }}; + matchInfo->slot = {slot, [this](void *slot){ sdbus_->sd_bus_slot_unref(static_cast(slot)); }}; - return {matchInfo.release(), [](void *ptr){ delete static_cast(ptr); }}; + return {matchInfo.release(), [](void *ptr){ delete static_cast(ptr); }}; // NOLINT(cppcoreguidelines-owning-memory) } void Connection::addMatchAsync(const std::string& match, message_handler callback, message_handler installCallback) @@ -259,9 +282,9 @@ Slot Connection::addMatchAsync( const std::string& match , matchInfo.get()); SDBUS_THROW_ERROR_IF(r < 0, "Failed to add match", -r); - matchInfo->slot = {slot, [this](void *slot){ sdbus_->sd_bus_slot_unref((sd_bus_slot*)slot); }}; + matchInfo->slot = {slot, [this](void *slot){ sdbus_->sd_bus_slot_unref(static_cast(slot)); }}; - return {matchInfo.release(), [](void *ptr){ delete static_cast(ptr); }}; + return {matchInfo.release(), [](void *ptr){ delete static_cast(ptr); }}; // NOLINT(cppcoreguidelines-owning-memory) } void Connection::attachSdEventLoop(sd_event *event, int priority) @@ -306,7 +329,7 @@ Slot Connection::createSdEventSlot(sd_event *event) (void)sd_event_default(&event); SDBUS_THROW_ERROR_IF(!event, "Invalid sd_event handle", EINVAL); - return Slot{event, [](void* event){ sd_event_unref((sd_event*)event); }}; + return Slot{event, [](void* event){ sd_event_unref(static_cast(event)); }}; } Slot Connection::createSdTimeEventSourceSlot(sd_event *event, int priority) @@ -314,7 +337,7 @@ Slot Connection::createSdTimeEventSourceSlot(sd_event *event, int priority) sd_event_source *timeEventSource{}; auto r = sd_event_add_time(event, &timeEventSource, CLOCK_MONOTONIC, 0, 0, onSdTimerEvent, this); SDBUS_THROW_ERROR_IF(r < 0, "Failed to add timer event", -r); - Slot sdTimeEventSource{timeEventSource, [](void* source){ deleteSdEventSource((sd_event_source*)source); }}; + Slot sdTimeEventSource{timeEventSource, [](void* source){ deleteSdEventSource(static_cast(source)); }}; r = sd_event_source_set_priority(timeEventSource, priority); SDBUS_THROW_ERROR_IF(r < 0, "Failed to set time event priority", -r); @@ -325,12 +348,12 @@ Slot Connection::createSdTimeEventSourceSlot(sd_event *event, int priority) return sdTimeEventSource; } -Slot Connection::createSdIoEventSourceSlot(sd_event *event, int fd, int priority) +Slot Connection::createSdIoEventSourceSlot(sd_event *event, int fd, int priority) // NOLINT(bugprone-easily-swappable-parameters) { sd_event_source *ioEventSource{}; auto r = sd_event_add_io(event, &ioEventSource, fd, 0, onSdIoEvent, this); SDBUS_THROW_ERROR_IF(r < 0, "Failed to add io event", -r); - Slot sdIoEventSource{ioEventSource, [](void* source){ deleteSdEventSource((sd_event_source*)source); }}; + Slot sdIoEventSource{ioEventSource, [](void* source){ deleteSdEventSource(static_cast(source)); }}; r = sd_event_source_set_prepare(ioEventSource, onSdEventPrepare); SDBUS_THROW_ERROR_IF(r < 0, "Failed to set prepare callback for IO event", -r); @@ -344,12 +367,12 @@ Slot Connection::createSdIoEventSourceSlot(sd_event *event, int fd, int priority return sdIoEventSource; } -Slot Connection::createSdInternalEventSourceSlot(sd_event *event, int fd, int priority) +Slot Connection::createSdInternalEventSourceSlot(sd_event *event, int fd, int priority) // NOLINT(bugprone-easily-swappable-parameters) { sd_event_source *internalEventSource{}; auto r = sd_event_add_io(event, &internalEventSource, fd, 0, onSdInternalEvent, this); SDBUS_THROW_ERROR_IF(r < 0, "Failed to add internal event", -r); - Slot sdInternalEventSource{internalEventSource, [](void* source){ deleteSdEventSource((sd_event_source*)source); }}; + Slot sdInternalEventSource{internalEventSource, [](void* source){ deleteSdEventSource(static_cast(source)); }}; // sd-event loop calls prepare callbacks for all event sources, not just for the one that fired now. // So since onSdEventPrepare is already registered on ioEventSource, we don't need to duplicate it here. @@ -367,7 +390,7 @@ Slot Connection::createSdInternalEventSourceSlot(sd_event *event, int fd, int pr int Connection::onSdTimerEvent(sd_event_source */*s*/, uint64_t /*usec*/, void *userdata) { - auto connection = static_cast(userdata); + auto *connection = static_cast(userdata); assert(connection != nullptr); (void)connection->processPendingEvent(); @@ -377,7 +400,7 @@ int Connection::onSdTimerEvent(sd_event_source */*s*/, uint64_t /*usec*/, void * int Connection::onSdIoEvent(sd_event_source */*s*/, int /*fd*/, uint32_t /*revents*/, void *userdata) { - auto connection = static_cast(userdata); + auto *connection = static_cast(userdata); assert(connection != nullptr); (void)connection->processPendingEvent(); @@ -387,7 +410,7 @@ int Connection::onSdIoEvent(sd_event_source */*s*/, int /*fd*/, uint32_t /*reven int Connection::onSdInternalEvent(sd_event_source */*s*/, int /*fd*/, uint32_t /*revents*/, void *userdata) { - auto connection = static_cast(userdata); + auto *connection = static_cast(userdata); assert(connection != nullptr); // It's not really necessary to processPendingEvent() here. We just clear the event fd. @@ -410,7 +433,7 @@ int Connection::onSdInternalEvent(sd_event_source */*s*/, int /*fd*/, uint32_t / int Connection::onSdEventPrepare(sd_event_source */*s*/, void *userdata) { - auto connection = static_cast(userdata); + auto *connection = static_cast(userdata); assert(connection != nullptr); auto sdbusPollData = connection->getEventLoopPollData(); @@ -432,16 +455,16 @@ int Connection::onSdEventPrepare(sd_event_source */*s*/, void *userdata) // In case the timeout is infinite, we disable the timer in the sd_event loop. // This prevents a syscall error, where `timerfd_settime` returns `EINVAL`, // because the value is too big. See #324 for details - r = sd_event_source_set_enabled(sdTimeEventSource, sdbusPollData.timeout != sdbusPollData.timeout.max() ? SD_EVENT_ONESHOT : SD_EVENT_OFF); + r = sd_event_source_set_enabled(sdTimeEventSource, sdbusPollData.timeout != std::chrono::microseconds::max() ? SD_EVENT_ONESHOT : SD_EVENT_OFF); SDBUS_THROW_ERROR_IF(r < 0, "Failed to enable time event source", -r); return 1; } -void Connection::deleteSdEventSource(sd_event_source *s) +void Connection::deleteSdEventSource(sd_event_source *source) { #if LIBSYSTEMD_VERSION>=243 - sd_event_source_disable_unref(s); + sd_event_source_disable_unref(source); #else sd_event_source_set_enabled(s, SD_EVENT_OFF); sd_event_source_unref(s); @@ -467,7 +490,7 @@ Slot Connection::addObjectVTable( const ObjectPath& objectPath SDBUS_THROW_ERROR_IF(r < 0, "Failed to register object vtable", -r); - return {slot, [this](void *slot){ sdbus_->sd_bus_slot_unref((sd_bus_slot*)slot); }}; + return {slot, [this](void *slot){ sdbus_->sd_bus_slot_unref(static_cast(slot)); }}; } PlainMessage Connection::createPlainMessage() const @@ -478,6 +501,8 @@ PlainMessage Connection::createPlainMessage() const SDBUS_THROW_ERROR_IF(r < 0, "Failed to create a plain message", -r); + // TODO: const_cast..? Finish the const correctness design + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) return Message::Factory::create(sdbusMsg, const_cast(this), adopt_message); } @@ -498,13 +523,15 @@ MethodCall Connection::createMethodCall( const char* destination auto r = sdbus_->sd_bus_message_new_method_call( bus_.get() , &sdbusMsg - , !*destination ? nullptr : destination + , *destination == '\0' ? nullptr : destination , objectPath , interfaceName , methodName); SDBUS_THROW_ERROR_IF(r < 0, "Failed to create method call", -r); + // TODO: const_cast..? Finish the const correctness design + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) return Message::Factory::create(sdbusMsg, const_cast(this), adopt_message); } @@ -525,6 +552,8 @@ Signal Connection::createSignal( const char* objectPath SDBUS_THROW_ERROR_IF(r < 0, "Failed to create signal", -r); + // TODO: const_cast..? Finish the const correctness design + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) return Message::Factory::create(sdbusMsg, const_cast(this), adopt_message); } @@ -544,7 +573,7 @@ void Connection::emitPropertiesChangedSignal( const char* objectPath auto r = sdbus_->sd_bus_emit_properties_changed_strv( bus_.get() , objectPath , interfaceName - , propNames.empty() ? nullptr : &names[0] ); + , propNames.empty() ? nullptr : names.data() ); SDBUS_THROW_ERROR_IF(r < 0, "Failed to emit PropertiesChanged signal", -r); } @@ -563,7 +592,7 @@ void Connection::emitInterfacesAddedSignal( const ObjectPath& objectPath auto r = sdbus_->sd_bus_emit_interfaces_added_strv( bus_.get() , objectPath.c_str() - , interfaces.empty() ? nullptr : &names[0] ); + , interfaces.empty() ? nullptr : names.data() ); SDBUS_THROW_ERROR_IF(r < 0, "Failed to emit InterfacesAdded signal", -r); } @@ -582,7 +611,7 @@ void Connection::emitInterfacesRemovedSignal( const ObjectPath& objectPath auto r = sdbus_->sd_bus_emit_interfaces_removed_strv( bus_.get() , objectPath.c_str() - , interfaces.empty() ? nullptr : &names[0] ); + , interfaces.empty() ? nullptr : names.data() ); SDBUS_THROW_ERROR_IF(r < 0, "Failed to emit InterfacesRemoved signal", -r); } @@ -599,16 +628,16 @@ Slot Connection::registerSignalHandler( const char* sender auto r = sdbus_->sd_bus_match_signal( bus_.get() , &slot - , !*sender ? nullptr : sender - , !*objectPath ? nullptr : objectPath - , !*interfaceName ? nullptr : interfaceName - , !*signalName ? nullptr : signalName + , *sender == '\0' ? nullptr : sender + , *objectPath == '\0' ? nullptr : objectPath + , *interfaceName == '\0' ? nullptr : interfaceName + , *signalName == '\0' ? nullptr : signalName , callback , userData ); SDBUS_THROW_ERROR_IF(r < 0, "Failed to register signal handler", -r); - return {slot, [this](void *slot){ sdbus_->sd_bus_slot_unref((sd_bus_slot*)slot); }}; + return {slot, [this](void *slot){ sdbus_->sd_bus_slot_unref(static_cast(slot)); }}; } sd_bus_message* Connection::incrementMessageRefCount(sd_bus_message* sdbusMsg) @@ -646,7 +675,7 @@ sd_bus_message* Connection::callMethod(sd_bus_message* sdbusMsg, uint64_t timeou sd_bus_message* sdbusReply{}; auto r = sdbus_->sd_bus_call(nullptr, sdbusMsg, timeout, &sdbusError, &sdbusReply); - if (sd_bus_error_is_set(&sdbusError)) + if (sd_bus_error_is_set(&sdbusError) != 0) throw Error(Error::Name{sdbusError.name}, sdbusError.message); SDBUS_THROW_ERROR_IF(r < 0, "Failed to call method", -r); @@ -664,7 +693,7 @@ Slot Connection::callMethodAsync(sd_bus_message* sdbusMsg, sd_bus_message_handle // TODO: Think of ways of optimizing these three locking/unlocking of sdbus mutex (merge into one call?) auto timeoutBefore = getEventLoopPollData().timeout; - auto r = sdbus_->sd_bus_call_async(nullptr, &slot, sdbusMsg, (sd_bus_message_handler_t)callback, userData, timeout); + auto r = sdbus_->sd_bus_call_async(nullptr, &slot, sdbusMsg, callback, userData, timeout); SDBUS_THROW_ERROR_IF(r < 0, "Failed to call method asynchronously", -r); auto timeoutAfter = getEventLoopPollData().timeout; @@ -674,7 +703,7 @@ Slot Connection::callMethodAsync(sd_bus_message* sdbusMsg, sd_bus_message_handle if (timeoutAfter < timeoutBefore || arePendingMessagesInQueues()) notifyEventLoopToWakeUpFromPoll(); - return {slot, [this](void *slot){ sdbus_->sd_bus_slot_unref((sd_bus_slot*)slot); }}; + return {slot, [this](void *slot){ sdbus_->sd_bus_slot_unref(static_cast(slot)); }}; } void Connection::sendMessage(sd_bus_message* sdbusMsg) @@ -713,7 +742,7 @@ sd_bus_message* Connection::createErrorReplyMessage(sd_bus_message* sdbusMsg, co Connection::BusPtr Connection::openBus(const BusFactory& busFactory) { sd_bus* bus{}; - int r = busFactory(&bus); + const int r = busFactory(&bus); SDBUS_THROW_ERROR_IF(r < 0, "Failed to open bus", -r); BusPtr busPtr{bus, [this](sd_bus* bus){ return sdbus_->sd_bus_flush_close_unref(bus); }}; @@ -725,7 +754,7 @@ Connection::BusPtr Connection::openPseudoBus() { sd_bus* bus{}; - int r = sdbus_->sd_bus_new(&bus); + const int r = sdbus_->sd_bus_new(&bus); SDBUS_THROW_ERROR_IF(r < 0, "Failed to open pseudo bus", -r); (void)sdbus_->sd_bus_start(bus); @@ -783,10 +812,10 @@ void Connection::joinWithEventLoop() bool Connection::processPendingEvent() { - auto bus = bus_.get(); + auto *bus = bus_.get(); assert(bus != nullptr); - int r = sdbus_->sd_bus_process(bus, nullptr); + const int r = sdbus_->sd_bus_process(bus, nullptr); SDBUS_THROW_ERROR_IF(r < 0, "Failed to process bus requests", -r); // In correct use of sdbus-c++ API, r can be 0 only when processPendingEvent() @@ -798,7 +827,7 @@ bool Connection::processPendingEvent() return r > 0; } -bool Connection::waitForNextEvent() +bool Connection::waitForNextEvent() // NOLINT(misc-no-recursion) { assert(bus_ != nullptr); assert(loopExitFd_.fd >= 0); @@ -821,7 +850,7 @@ bool Connection::waitForNextEvent() SDBUS_THROW_ERROR_IF(r < 0, "Failed to wait on the bus", -errno); // Wake up notification, in order that we re-enter poll with freshly read PollData (namely, new poll timeout thereof) - if (fds[1].revents & POLLIN) + if (fds[1].revents & POLLIN) // NOLINT(readability-implicit-bool-conversion) { auto cleared = eventFd_.clear(); SDBUS_THROW_ERROR_IF(!cleared, "Failed to read from the event descriptor", -errno); @@ -829,7 +858,7 @@ bool Connection::waitForNextEvent() return waitForNextEvent(); } // Loop exit notification - if (fds[2].revents & POLLIN) + if (fds[2].revents & POLLIN) // NOLINT(readability-implicit-bool-conversion) { auto cleared = loopExitFd_.clear(); SDBUS_THROW_ERROR_IF(!cleared, "Failed to read from the loop exit descriptor", -errno); @@ -854,6 +883,8 @@ Message Connection::getCurrentlyProcessedMessage() const { auto* sdbusMsg = sdbus_->sd_bus_get_current_message(bus_.get()); + // TODO: const_cast..? Finish the const correctness design + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) return Message::Factory::create(sdbusMsg, const_cast(this)); } @@ -861,8 +892,9 @@ template std::vector Connection::to_strv(const std::vector& strings) { std::vector strv; + strv.reserve(strings.size()); for (auto& str : strings) - strv.push_back(const_cast(str.c_str())); + strv.push_back(const_cast(str.c_str())); // NOLINT(cppcoreguidelines-pro-type-const-cast) strv.push_back(nullptr); return strv; } @@ -894,8 +926,8 @@ int Connection::sdbus_match_install_callback(sd_bus_message *sdbusMessage, void } Connection::EventFd::EventFd() + : fd(eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK)) { - fd = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK); SDBUS_THROW_ERROR_IF(fd < 0, "Failed to create event object", -errno); } @@ -905,14 +937,14 @@ Connection::EventFd::~EventFd() close(fd); } -void Connection::EventFd::notify() +void Connection::EventFd::notify() const { assert(fd >= 0); auto r = eventfd_write(fd, 1); SDBUS_THROW_ERROR_IF(r < 0, "Failed to notify event descriptor", -errno); } -bool Connection::EventFd::clear() +bool Connection::EventFd::clear() const { assert(fd >= 0); @@ -933,10 +965,10 @@ std::chrono::microseconds IConnection::PollData::getRelativeTimeout() const if (timeout == zero) return zero; - else if (timeout == max) + if (timeout == max) return max; - else - return std::max(std::chrono::duration_cast(timeout - now()), zero); + + return std::max(std::chrono::duration_cast(timeout - now()), zero); } int IConnection::PollData::getPollTimeout() const @@ -945,8 +977,8 @@ int IConnection::PollData::getPollTimeout() const if (relativeTimeout == decltype(relativeTimeout)::max()) return -1; - else - return static_cast(std::chrono::ceil(relativeTimeout).count()); + + return static_cast(std::chrono::ceil(relativeTimeout).count()); } } // namespace sdbus diff --git a/src/Connection.h b/src/Connection.h index ed28bf4d..cbd05393 100644 --- a/src/Connection.h +++ b/src/Connection.h @@ -202,24 +202,24 @@ namespace sdbus::internal { private: #ifndef SDBUS_basu // sd_event integration is not supported if instead of libsystemd we are based on basu - Slot createSdEventSlot(sd_event *event); + static Slot createSdEventSlot(sd_event *event); Slot createSdTimeEventSourceSlot(sd_event *event, int priority); Slot createSdIoEventSourceSlot(sd_event *event, int fd, int priority); Slot createSdInternalEventSourceSlot(sd_event *event, int fd, int priority); - static void deleteSdEventSource(sd_event_source *s); + static void deleteSdEventSource(sd_event_source *source); - static int onSdTimerEvent(sd_event_source *s, uint64_t usec, void *userdata); - static int onSdIoEvent(sd_event_source *s, int fd, uint32_t revents, void *userdata); - static int onSdInternalEvent(sd_event_source *s, int fd, uint32_t revents, void *userdata); - static int onSdEventPrepare(sd_event_source *s, void *userdata); + static int onSdTimerEvent(sd_event_source *source, uint64_t usec, void *userdata); + static int onSdIoEvent(sd_event_source *source, int fd, uint32_t revents, void *userdata); + static int onSdInternalEvent(sd_event_source *source, int fd, uint32_t revents, void *userdata); + static int onSdEventPrepare(sd_event_source *source, void *userdata); #endif struct EventFd { EventFd(); ~EventFd(); - void notify(); - bool clear(); + void notify() const; + bool clear() const; int fd{-1}; }; diff --git a/src/Error.cpp b/src/Error.cpp index b93df38c..66b48031 100644 --- a/src/Error.cpp +++ b/src/Error.cpp @@ -29,6 +29,8 @@ #include "ScopeGuard.h" #include SDBUS_HEADER +#include +#include namespace sdbus { @@ -38,7 +40,7 @@ namespace sdbus sd_bus_error_set_errno(&sdbusError, errNo); SCOPE_EXIT{ sd_bus_error_free(&sdbusError); }; - Error::Name name(sd_bus_error_is_set(&sdbusError) ? sdbusError.name : ""); + Error::Name name(sd_bus_error_is_set(&sdbusError) != 0 ? sdbusError.name : ""); std::string message(std::move(customMsg)); if (!message.empty() && sdbusError.message != nullptr) { @@ -51,6 +53,6 @@ namespace sdbus message = sdbusError.message; } - return Error(std::move(name), std::move(message)); + return {std::move(name), std::move(message)}; } } // namespace sdbus diff --git a/src/Flags.cpp b/src/Flags.cpp index ef943b06..b97ac7fd 100644 --- a/src/Flags.cpp +++ b/src/Flags.cpp @@ -26,6 +26,7 @@ #include #include SDBUS_HEADER +#include namespace sdbus { @@ -33,7 +34,6 @@ namespace sdbus { uint64_t sdbusFlags{}; - using namespace sdbus; if (flags_.test(Flags::DEPRECATED)) sdbusFlags |= SD_BUS_VTABLE_DEPRECATED; if (!flags_.test(Flags::PRIVILEGED)) @@ -55,7 +55,6 @@ namespace sdbus { uint64_t sdbusFlags{}; - using namespace sdbus; if (flags_.test(Flags::DEPRECATED)) sdbusFlags |= SD_BUS_VTABLE_DEPRECATED; if (!flags_.test(Flags::PRIVILEGED)) @@ -70,7 +69,6 @@ namespace sdbus { uint64_t sdbusFlags{}; - using namespace sdbus; if (flags_.test(Flags::DEPRECATED)) sdbusFlags |= SD_BUS_VTABLE_DEPRECATED; @@ -81,7 +79,6 @@ namespace sdbus { uint64_t sdbusFlags{}; - using namespace sdbus; if (flags_.test(Flags::DEPRECATED)) sdbusFlags |= SD_BUS_VTABLE_DEPRECATED; //if (!flags_.test(Flags::PRIVILEGED)) @@ -103,10 +100,9 @@ namespace sdbus { auto sdbusFlags = toSdBusPropertyFlags(); - using namespace sdbus; if (!flags_.test(Flags::PRIVILEGED)) sdbusFlags |= SD_BUS_VTABLE_UNPRIVILEGED; return sdbusFlags; } -} +} // namespace sdbus diff --git a/src/Message.cpp b/src/Message.cpp index 4ccf89ae..99d03996 100644 --- a/src/Message.cpp +++ b/src/Message.cpp @@ -28,13 +28,23 @@ #include "sdbus-c++/Error.h" #include "sdbus-c++/Types.h" +#include "sdbus-c++/TypeTraits.h" #include "IConnection.h" #include "MessageUtils.h" #include "ScopeGuard.h" #include +#include // int16_t, uint64_t, ... +#include // atexit #include +#include +#include +#include // pid_t, gid_t, ... +#include // std::ignore +#include // std::unique_ptr +#include // std::move +#include #include SDBUS_HEADER namespace sdbus { @@ -51,7 +61,7 @@ Message::Message(void *msg, internal::IConnection* connection) noexcept { assert(msg_ != nullptr); assert(connection_ != nullptr); - connection_->incrementMessageRefCount((sd_bus_message*)msg_); + connection_->incrementMessageRefCount(static_cast(msg_)); } Message::Message(void *msg, internal::IConnection* connection, adopt_message_t) noexcept @@ -69,14 +79,17 @@ Message::Message(const Message& other) noexcept Message& Message::operator=(const Message& other) noexcept { + if (this == &other) + return *this; + if (msg_) - connection_->decrementMessageRefCount((sd_bus_message*)msg_); + connection_->decrementMessageRefCount(static_cast(msg_)); msg_ = other.msg_; connection_ = other.connection_; ok_ = other.ok_; - connection_->incrementMessageRefCount((sd_bus_message*)msg_); + connection_->incrementMessageRefCount(static_cast(msg_)); return *this; } @@ -89,7 +102,7 @@ Message::Message(Message&& other) noexcept Message& Message::operator=(Message&& other) noexcept { if (msg_) - connection_->decrementMessageRefCount((sd_bus_message*)msg_); + connection_->decrementMessageRefCount(static_cast(msg_)); msg_ = other.msg_; other.msg_ = nullptr; @@ -104,18 +117,18 @@ Message& Message::operator=(Message&& other) noexcept Message::~Message() { if (msg_) - connection_->decrementMessageRefCount((sd_bus_message*)msg_); + connection_->decrementMessageRefCount(static_cast(msg_)); } Message& Message::operator<<(bool item) { - int intItem = item; + int itemAsInt = static_cast(item); // Direct sd-bus method, bypassing SdBus mutex, are called here, since Message serialization/deserialization, // as well as getter/setter methods are not thread safe by design. Additionally, they are called frequently, // so some overhead is spared. What is thread-safe in Message class is Message constructors, copy/move operations // and the destructor, so the Message instance can be passed from one thread to another safely. - auto r = sd_bus_message_append_basic((sd_bus_message*)msg_, SD_BUS_TYPE_BOOLEAN, &intItem); + auto r = sd_bus_message_append_basic(static_cast(msg_), SD_BUS_TYPE_BOOLEAN, &itemAsInt); SDBUS_THROW_ERROR_IF(r < 0, "Failed to serialize a bool value", -r); return *this; @@ -123,7 +136,7 @@ Message& Message::operator<<(bool item) Message& Message::operator<<(int16_t item) { - auto r = sd_bus_message_append_basic((sd_bus_message*)msg_, SD_BUS_TYPE_INT16, &item); + auto r = sd_bus_message_append_basic(static_cast(msg_), SD_BUS_TYPE_INT16, &item); SDBUS_THROW_ERROR_IF(r < 0, "Failed to serialize a int16_t value", -r); return *this; @@ -131,7 +144,7 @@ Message& Message::operator<<(int16_t item) Message& Message::operator<<(int32_t item) { - auto r = sd_bus_message_append_basic((sd_bus_message*)msg_, SD_BUS_TYPE_INT32, &item); + auto r = sd_bus_message_append_basic(static_cast(msg_), SD_BUS_TYPE_INT32, &item); SDBUS_THROW_ERROR_IF(r < 0, "Failed to serialize a int32_t value", -r); return *this; @@ -139,7 +152,7 @@ Message& Message::operator<<(int32_t item) Message& Message::operator<<(int64_t item) { - auto r = sd_bus_message_append_basic((sd_bus_message*)msg_, SD_BUS_TYPE_INT64, &item); + auto r = sd_bus_message_append_basic(static_cast(msg_), SD_BUS_TYPE_INT64, &item); SDBUS_THROW_ERROR_IF(r < 0, "Failed to serialize a int64_t value", -r); return *this; @@ -147,7 +160,7 @@ Message& Message::operator<<(int64_t item) Message& Message::operator<<(uint8_t item) { - auto r = sd_bus_message_append_basic((sd_bus_message*)msg_, SD_BUS_TYPE_BYTE, &item); + auto r = sd_bus_message_append_basic(static_cast(msg_), SD_BUS_TYPE_BYTE, &item); SDBUS_THROW_ERROR_IF(r < 0, "Failed to serialize a byte value", -r); return *this; @@ -155,7 +168,7 @@ Message& Message::operator<<(uint8_t item) Message& Message::operator<<(uint16_t item) { - auto r = sd_bus_message_append_basic((sd_bus_message*)msg_, SD_BUS_TYPE_UINT16, &item); + auto r = sd_bus_message_append_basic(static_cast(msg_), SD_BUS_TYPE_UINT16, &item); SDBUS_THROW_ERROR_IF(r < 0, "Failed to serialize a uint16_t value", -r); return *this; @@ -163,7 +176,7 @@ Message& Message::operator<<(uint16_t item) Message& Message::operator<<(uint32_t item) { - auto r = sd_bus_message_append_basic((sd_bus_message*)msg_, SD_BUS_TYPE_UINT32, &item); + auto r = sd_bus_message_append_basic(static_cast(msg_), SD_BUS_TYPE_UINT32, &item); SDBUS_THROW_ERROR_IF(r < 0, "Failed to serialize a uint32_t value", -r); return *this; @@ -171,7 +184,7 @@ Message& Message::operator<<(uint32_t item) Message& Message::operator<<(uint64_t item) { - auto r = sd_bus_message_append_basic((sd_bus_message*)msg_, SD_BUS_TYPE_UINT64, &item); + auto r = sd_bus_message_append_basic(static_cast(msg_), SD_BUS_TYPE_UINT64, &item); SDBUS_THROW_ERROR_IF(r < 0, "Failed to serialize a uint64_t value", -r); return *this; @@ -179,7 +192,7 @@ Message& Message::operator<<(uint64_t item) Message& Message::operator<<(double item) { - auto r = sd_bus_message_append_basic((sd_bus_message*)msg_, SD_BUS_TYPE_DOUBLE, &item); + auto r = sd_bus_message_append_basic(static_cast(msg_), SD_BUS_TYPE_DOUBLE, &item); SDBUS_THROW_ERROR_IF(r < 0, "Failed to serialize a double value", -r); return *this; @@ -187,7 +200,7 @@ Message& Message::operator<<(double item) Message& Message::operator<<(const char* item) { - auto r = sd_bus_message_append_basic((sd_bus_message*)msg_, SD_BUS_TYPE_STRING, item); + auto r = sd_bus_message_append_basic(static_cast(msg_), SD_BUS_TYPE_STRING, item); SDBUS_THROW_ERROR_IF(r < 0, "Failed to serialize a C-string value", -r); return *this; @@ -195,7 +208,7 @@ Message& Message::operator<<(const char* item) Message& Message::operator<<(const std::string& item) { - auto r = sd_bus_message_append_basic((sd_bus_message*)msg_, SD_BUS_TYPE_STRING, item.c_str()); + auto r = sd_bus_message_append_basic(static_cast(msg_), SD_BUS_TYPE_STRING, item.c_str()); SDBUS_THROW_ERROR_IF(r < 0, "Failed to serialize a string value", -r); return *this; @@ -204,7 +217,7 @@ Message& Message::operator<<(const std::string& item) Message& Message::operator<<(std::string_view item) { char* destPtr{}; - auto r = sd_bus_message_append_string_space((sd_bus_message*)msg_, item.length(), &destPtr); + auto r = sd_bus_message_append_string_space(static_cast(msg_), item.length(), &destPtr); SDBUS_THROW_ERROR_IF(r < 0, "Failed to serialize a string_view value", -r); std::memcpy(destPtr, item.data(), item.length()); @@ -221,7 +234,7 @@ Message& Message::operator<<(const Variant &item) Message& Message::operator<<(const ObjectPath &item) { - auto r = sd_bus_message_append_basic((sd_bus_message*)msg_, SD_BUS_TYPE_OBJECT_PATH, item.c_str()); + auto r = sd_bus_message_append_basic(static_cast(msg_), SD_BUS_TYPE_OBJECT_PATH, item.c_str()); SDBUS_THROW_ERROR_IF(r < 0, "Failed to serialize an ObjectPath value", -r); return *this; @@ -229,7 +242,7 @@ Message& Message::operator<<(const ObjectPath &item) Message& Message::operator<<(const Signature &item) { - auto r = sd_bus_message_append_basic((sd_bus_message*)msg_, SD_BUS_TYPE_SIGNATURE, item.c_str()); + auto r = sd_bus_message_append_basic(static_cast(msg_), SD_BUS_TYPE_SIGNATURE, item.c_str()); SDBUS_THROW_ERROR_IF(r < 0, "Failed to serialize a Signature value", -r); return *this; @@ -238,7 +251,7 @@ Message& Message::operator<<(const Signature &item) Message& Message::operator<<(const UnixFd &item) { auto fd = item.get(); - auto r = sd_bus_message_append_basic((sd_bus_message*)msg_, SD_BUS_TYPE_UNIX_FD, &fd); + auto r = sd_bus_message_append_basic(static_cast(msg_), SD_BUS_TYPE_UNIX_FD, &fd); SDBUS_THROW_ERROR_IF(r < 0, "Failed to serialize a UnixFd value", -r); return *this; @@ -246,7 +259,7 @@ Message& Message::operator<<(const UnixFd &item) Message& Message::appendArray(char type, const void *ptr, size_t size) { - auto r = sd_bus_message_append_array((sd_bus_message*)msg_, type, ptr, size); + auto r = sd_bus_message_append_array(static_cast(msg_), type, ptr, size); SDBUS_THROW_ERROR_IF(r < 0, "Failed to serialize an array", -r); return *this; @@ -254,8 +267,8 @@ Message& Message::appendArray(char type, const void *ptr, size_t size) Message& Message::operator>>(bool& item) { - int intItem; - auto r = sd_bus_message_read_basic((sd_bus_message*)msg_, SD_BUS_TYPE_BOOLEAN, &intItem); + int intItem{}; + auto r = sd_bus_message_read_basic(static_cast(msg_), SD_BUS_TYPE_BOOLEAN, &intItem); if (r == 0) ok_ = false; @@ -268,7 +281,7 @@ Message& Message::operator>>(bool& item) Message& Message::operator>>(int16_t& item) { - auto r = sd_bus_message_read_basic((sd_bus_message*)msg_, SD_BUS_TYPE_INT16, &item); + auto r = sd_bus_message_read_basic(static_cast(msg_), SD_BUS_TYPE_INT16, &item); if (r == 0) ok_ = false; @@ -279,7 +292,7 @@ Message& Message::operator>>(int16_t& item) Message& Message::operator>>(int32_t& item) { - auto r = sd_bus_message_read_basic((sd_bus_message*)msg_, SD_BUS_TYPE_INT32, &item); + auto r = sd_bus_message_read_basic(static_cast(msg_), SD_BUS_TYPE_INT32, &item); if (r == 0) ok_ = false; @@ -290,7 +303,7 @@ Message& Message::operator>>(int32_t& item) Message& Message::operator>>(int64_t& item) { - auto r = sd_bus_message_read_basic((sd_bus_message*)msg_, SD_BUS_TYPE_INT64, &item); + auto r = sd_bus_message_read_basic(static_cast(msg_), SD_BUS_TYPE_INT64, &item); if (r == 0) ok_ = false; @@ -301,7 +314,7 @@ Message& Message::operator>>(int64_t& item) Message& Message::operator>>(uint8_t& item) { - auto r = sd_bus_message_read_basic((sd_bus_message*)msg_, SD_BUS_TYPE_BYTE, &item); + auto r = sd_bus_message_read_basic(static_cast(msg_), SD_BUS_TYPE_BYTE, &item); if (r == 0) ok_ = false; @@ -312,7 +325,7 @@ Message& Message::operator>>(uint8_t& item) Message& Message::operator>>(uint16_t& item) { - auto r = sd_bus_message_read_basic((sd_bus_message*)msg_, SD_BUS_TYPE_UINT16, &item); + auto r = sd_bus_message_read_basic(static_cast(msg_), SD_BUS_TYPE_UINT16, &item); if (r == 0) ok_ = false; @@ -323,7 +336,7 @@ Message& Message::operator>>(uint16_t& item) Message& Message::operator>>(uint32_t& item) { - auto r = sd_bus_message_read_basic((sd_bus_message*)msg_, SD_BUS_TYPE_UINT32, &item); + auto r = sd_bus_message_read_basic(static_cast(msg_), SD_BUS_TYPE_UINT32, &item); if (r == 0) ok_ = false; @@ -334,7 +347,7 @@ Message& Message::operator>>(uint32_t& item) Message& Message::operator>>(uint64_t& item) { - auto r = sd_bus_message_read_basic((sd_bus_message*)msg_, SD_BUS_TYPE_UINT64, &item); + auto r = sd_bus_message_read_basic(static_cast(msg_), SD_BUS_TYPE_UINT64, &item); if (r == 0) ok_ = false; @@ -345,7 +358,7 @@ Message& Message::operator>>(uint64_t& item) Message& Message::readArray(char type, const void **ptr, size_t *size) { - auto r = sd_bus_message_read_array((sd_bus_message*)msg_, type, ptr, size); + auto r = sd_bus_message_read_array(static_cast(msg_), type, ptr, size); if (r == 0) ok_ = false; @@ -356,7 +369,7 @@ Message& Message::readArray(char type, const void **ptr, size_t *size) Message& Message::operator>>(double& item) { - auto r = sd_bus_message_read_basic((sd_bus_message*)msg_, SD_BUS_TYPE_DOUBLE, &item); + auto r = sd_bus_message_read_basic(static_cast(msg_), SD_BUS_TYPE_DOUBLE, &item); if (r == 0) ok_ = false; @@ -367,7 +380,7 @@ Message& Message::operator>>(double& item) Message& Message::operator>>(char*& item) { - auto r = sd_bus_message_read_basic((sd_bus_message*)msg_, SD_BUS_TYPE_STRING, &item); + auto r = sd_bus_message_read_basic(static_cast(msg_), SD_BUS_TYPE_STRING, reinterpret_cast(&item)); if (r == 0) ok_ = false; @@ -403,7 +416,7 @@ Message& Message::operator>>(Variant &item) Message& Message::operator>>(ObjectPath &item) { char* str{}; - auto r = sd_bus_message_read_basic((sd_bus_message*)msg_, SD_BUS_TYPE_OBJECT_PATH, &str); + auto r = sd_bus_message_read_basic(static_cast(msg_), SD_BUS_TYPE_OBJECT_PATH, reinterpret_cast(&str)); if (r == 0) ok_ = false; @@ -418,7 +431,7 @@ Message& Message::operator>>(ObjectPath &item) Message& Message::operator>>(Signature &item) { char* str{}; - auto r = sd_bus_message_read_basic((sd_bus_message*)msg_, SD_BUS_TYPE_SIGNATURE, &str); + auto r = sd_bus_message_read_basic(static_cast(msg_), SD_BUS_TYPE_SIGNATURE, reinterpret_cast(&str)); if (r == 0) ok_ = false; @@ -433,7 +446,7 @@ Message& Message::operator>>(Signature &item) Message& Message::operator>>(UnixFd &item) { int fd = -1; - auto r = sd_bus_message_read_basic((sd_bus_message*)msg_, SD_BUS_TYPE_UNIX_FD, &fd); + auto r = sd_bus_message_read_basic(static_cast(msg_), SD_BUS_TYPE_UNIX_FD, &fd); if (r == 0) ok_ = false; @@ -446,7 +459,7 @@ Message& Message::operator>>(UnixFd &item) Message& Message::openContainer(const char* signature) { - auto r = sd_bus_message_open_container((sd_bus_message*)msg_, SD_BUS_TYPE_ARRAY, signature); + auto r = sd_bus_message_open_container(static_cast(msg_), SD_BUS_TYPE_ARRAY, signature); SDBUS_THROW_ERROR_IF(r < 0, "Failed to open a container", -r); return *this; @@ -454,7 +467,7 @@ Message& Message::openContainer(const char* signature) Message& Message::closeContainer() { - auto r = sd_bus_message_close_container((sd_bus_message*)msg_); + auto r = sd_bus_message_close_container(static_cast(msg_)); SDBUS_THROW_ERROR_IF(r < 0, "Failed to close a container", -r); return *this; @@ -462,7 +475,7 @@ Message& Message::closeContainer() Message& Message::openDictEntry(const char* signature) { - auto r = sd_bus_message_open_container((sd_bus_message*)msg_, SD_BUS_TYPE_DICT_ENTRY, signature); + auto r = sd_bus_message_open_container(static_cast(msg_), SD_BUS_TYPE_DICT_ENTRY, signature); SDBUS_THROW_ERROR_IF(r < 0, "Failed to open a dictionary entry", -r); return *this; @@ -470,7 +483,7 @@ Message& Message::openDictEntry(const char* signature) Message& Message::closeDictEntry() { - auto r = sd_bus_message_close_container((sd_bus_message*)msg_); + auto r = sd_bus_message_close_container(static_cast(msg_)); SDBUS_THROW_ERROR_IF(r < 0, "Failed to close a dictionary entry", -r); return *this; @@ -478,7 +491,7 @@ Message& Message::closeDictEntry() Message& Message::openVariant(const char* signature) { - auto r = sd_bus_message_open_container((sd_bus_message*)msg_, SD_BUS_TYPE_VARIANT, signature); + auto r = sd_bus_message_open_container(static_cast(msg_), SD_BUS_TYPE_VARIANT, signature); SDBUS_THROW_ERROR_IF(r < 0, "Failed to open a variant", -r); return *this; @@ -486,7 +499,7 @@ Message& Message::openVariant(const char* signature) Message& Message::closeVariant() { - auto r = sd_bus_message_close_container((sd_bus_message*)msg_); + auto r = sd_bus_message_close_container(static_cast(msg_)); SDBUS_THROW_ERROR_IF(r < 0, "Failed to close a variant", -r); return *this; @@ -494,7 +507,7 @@ Message& Message::closeVariant() Message& Message::openStruct(const char* signature) { - auto r = sd_bus_message_open_container((sd_bus_message*)msg_, SD_BUS_TYPE_STRUCT, signature); + auto r = sd_bus_message_open_container(static_cast(msg_), SD_BUS_TYPE_STRUCT, signature); SDBUS_THROW_ERROR_IF(r < 0, "Failed to open a struct", -r); return *this; @@ -502,7 +515,7 @@ Message& Message::openStruct(const char* signature) Message& Message::closeStruct() { - auto r = sd_bus_message_close_container((sd_bus_message*)msg_); + auto r = sd_bus_message_close_container(static_cast(msg_)); SDBUS_THROW_ERROR_IF(r < 0, "Failed to close a struct", -r); return *this; @@ -510,7 +523,7 @@ Message& Message::closeStruct() Message& Message::enterContainer(const char* signature) { - auto r = sd_bus_message_enter_container((sd_bus_message*)msg_, SD_BUS_TYPE_ARRAY, signature); + auto r = sd_bus_message_enter_container(static_cast(msg_), SD_BUS_TYPE_ARRAY, signature); if (r == 0) ok_ = false; @@ -521,7 +534,7 @@ Message& Message::enterContainer(const char* signature) Message& Message::exitContainer() { - auto r = sd_bus_message_exit_container((sd_bus_message*)msg_); + auto r = sd_bus_message_exit_container(static_cast(msg_)); SDBUS_THROW_ERROR_IF(r < 0, "Failed to exit a container", -r); return *this; @@ -529,7 +542,7 @@ Message& Message::exitContainer() Message& Message::enterDictEntry(const char* signature) { - auto r = sd_bus_message_enter_container((sd_bus_message*)msg_, SD_BUS_TYPE_DICT_ENTRY, signature); + auto r = sd_bus_message_enter_container(static_cast(msg_), SD_BUS_TYPE_DICT_ENTRY, signature); if (r == 0) ok_ = false; @@ -540,7 +553,7 @@ Message& Message::enterDictEntry(const char* signature) Message& Message::exitDictEntry() { - auto r = sd_bus_message_exit_container((sd_bus_message*)msg_); + auto r = sd_bus_message_exit_container(static_cast(msg_)); SDBUS_THROW_ERROR_IF(r < 0, "Failed to exit a dictionary entry", -r); return *this; @@ -548,7 +561,7 @@ Message& Message::exitDictEntry() Message& Message::enterVariant(const char* signature) { - auto r = sd_bus_message_enter_container((sd_bus_message*)msg_, SD_BUS_TYPE_VARIANT, signature); + auto r = sd_bus_message_enter_container(static_cast(msg_), SD_BUS_TYPE_VARIANT, signature); if (r == 0) ok_ = false; @@ -559,7 +572,7 @@ Message& Message::enterVariant(const char* signature) Message& Message::exitVariant() { - auto r = sd_bus_message_exit_container((sd_bus_message*)msg_); + auto r = sd_bus_message_exit_container(static_cast(msg_)); SDBUS_THROW_ERROR_IF(r < 0, "Failed to exit a variant", -r); return *this; @@ -567,7 +580,7 @@ Message& Message::exitVariant() Message& Message::enterStruct(const char* signature) { - auto r = sd_bus_message_enter_container((sd_bus_message*)msg_, SD_BUS_TYPE_STRUCT, signature); + auto r = sd_bus_message_enter_container(static_cast(msg_), SD_BUS_TYPE_STRUCT, signature); if (r == 0) ok_ = false; @@ -578,7 +591,7 @@ Message& Message::enterStruct(const char* signature) Message& Message::exitStruct() { - auto r = sd_bus_message_exit_container((sd_bus_message*)msg_); + auto r = sd_bus_message_exit_container(static_cast(msg_)); SDBUS_THROW_ERROR_IF(r < 0, "Failed to exit a struct", -r); return *this; @@ -597,7 +610,7 @@ void Message::clearFlags() void Message::copyTo(Message& destination, bool complete) const { - auto r = sd_bus_message_copy((sd_bus_message*)destination.msg_, (sd_bus_message*)msg_, complete); + auto r = sd_bus_message_copy(static_cast(destination.msg_), static_cast(msg_), complete); // NOLINT(readability-implicit-bool-conversion) SDBUS_THROW_ERROR_IF(r < 0, "Failed to copy the message", -r); } @@ -605,45 +618,45 @@ void Message::seal() { const auto messageCookie = 1; const auto sealTimeout = 0; - auto r = sd_bus_message_seal((sd_bus_message*)msg_, messageCookie, sealTimeout); + auto r = sd_bus_message_seal(static_cast(msg_), messageCookie, sealTimeout); SDBUS_THROW_ERROR_IF(r < 0, "Failed to seal the message", -r); } void Message::rewind(bool complete) { - auto r = sd_bus_message_rewind((sd_bus_message*)msg_, complete); + auto r = sd_bus_message_rewind(static_cast(msg_), complete); // NOLINT(readability-implicit-bool-conversion) SDBUS_THROW_ERROR_IF(r < 0, "Failed to rewind the message", -r); } const char* Message::getInterfaceName() const { - return sd_bus_message_get_interface((sd_bus_message*)msg_); + return sd_bus_message_get_interface(static_cast(msg_)); } const char* Message::getMemberName() const { - return sd_bus_message_get_member((sd_bus_message*)msg_); + return sd_bus_message_get_member(static_cast(msg_)); } const char* Message::getSender() const { - return sd_bus_message_get_sender((sd_bus_message*)msg_); + return sd_bus_message_get_sender(static_cast(msg_)); } const char* Message::getPath() const { - return sd_bus_message_get_path((sd_bus_message*)msg_); + return sd_bus_message_get_path(static_cast(msg_)); } const char* Message::getDestination() const { - return sd_bus_message_get_destination((sd_bus_message*)msg_); + return sd_bus_message_get_destination(static_cast(msg_)); } uint64_t Message::getCookie() const { - uint64_t cookie; - auto r = sd_bus_message_get_cookie((sd_bus_message*)msg_, &cookie); + uint64_t cookie{}; + auto r = sd_bus_message_get_cookie(static_cast(msg_), &cookie); SDBUS_THROW_ERROR_IF(r < 0, "Failed to get cookie", -r); return cookie; } @@ -652,7 +665,7 @@ std::pair Message::peekType() const { char typeSignature{}; const char* contentsSignature{}; - auto r = sd_bus_message_peek_type((sd_bus_message*)msg_, &typeSignature, &contentsSignature); + auto r = sd_bus_message_peek_type(static_cast(msg_), &typeSignature, &contentsSignature); SDBUS_THROW_ERROR_IF(r < 0, "Failed to peek message type", -r); return {typeSignature, contentsSignature}; } @@ -664,12 +677,12 @@ bool Message::isValid() const bool Message::isEmpty() const { - return sd_bus_message_is_empty((sd_bus_message*)msg_) != 0; + return sd_bus_message_is_empty(static_cast(msg_)) != 0; } bool Message::isAtEnd(bool complete) const { - return sd_bus_message_at_end((sd_bus_message*)msg_, complete) > 0; + return sd_bus_message_at_end(static_cast(msg_), complete) > 0; // NOLINT(readability-implicit-bool-conversion) } // TODO: Create a RAII ownership class for creds with copy&move semantics, doing ref()/unref() under the hood. @@ -677,11 +690,11 @@ bool Message::isAtEnd(bool complete) const // The class will expose methods like getPid(), getUid(), etc. that will directly call sd_bus_creds_* functions, no need for mutex here. pid_t Message::getCredsPid() const { - uint64_t mask = SD_BUS_CREDS_PID | SD_BUS_CREDS_AUGMENT; + const uint64_t mask = SD_BUS_CREDS_PID | SD_BUS_CREDS_AUGMENT; sd_bus_creds *creds = nullptr; SCOPE_EXIT{ connection_->decrementCredsRefCount(creds); }; - int r = connection_->querySenderCredentials((sd_bus_message*)msg_, mask, &creds); + int r = connection_->querySenderCredentials(static_cast(msg_), mask, &creds); SDBUS_THROW_ERROR_IF(r < 0, "Failed to get bus creds", -r); pid_t pid = 0; @@ -692,13 +705,13 @@ pid_t Message::getCredsPid() const uid_t Message::getCredsUid() const { - uint64_t mask = SD_BUS_CREDS_UID | SD_BUS_CREDS_AUGMENT; + const uint64_t mask = SD_BUS_CREDS_UID | SD_BUS_CREDS_AUGMENT; sd_bus_creds *creds = nullptr; SCOPE_EXIT{ connection_->decrementCredsRefCount(creds); }; - int r = connection_->querySenderCredentials((sd_bus_message*)msg_, mask, &creds); + int r = connection_->querySenderCredentials(static_cast(msg_), mask, &creds); SDBUS_THROW_ERROR_IF(r < 0, "Failed to get bus creds", -r); - uid_t uid = (uid_t)-1; + auto uid = static_cast(-1); r = sd_bus_creds_get_uid(creds, &uid); SDBUS_THROW_ERROR_IF(r < 0, "Failed to get bus cred uid", -r); return uid; @@ -706,13 +719,13 @@ uid_t Message::getCredsUid() const uid_t Message::getCredsEuid() const { - uint64_t mask = SD_BUS_CREDS_EUID | SD_BUS_CREDS_AUGMENT; + const uint64_t mask = SD_BUS_CREDS_EUID | SD_BUS_CREDS_AUGMENT; sd_bus_creds *creds = nullptr; SCOPE_EXIT{ connection_->decrementCredsRefCount(creds); }; - int r = connection_->querySenderCredentials((sd_bus_message*)msg_, mask, &creds); + int r = connection_->querySenderCredentials(static_cast(msg_), mask, &creds); SDBUS_THROW_ERROR_IF(r < 0, "Failed to get bus creds", -r); - uid_t euid = (uid_t)-1; + auto euid = static_cast(-1); r = sd_bus_creds_get_euid(creds, &euid); SDBUS_THROW_ERROR_IF(r < 0, "Failed to get bus cred euid", -r); return euid; @@ -720,13 +733,13 @@ uid_t Message::getCredsEuid() const gid_t Message::getCredsGid() const { - uint64_t mask = SD_BUS_CREDS_GID | SD_BUS_CREDS_AUGMENT; + const uint64_t mask = SD_BUS_CREDS_GID | SD_BUS_CREDS_AUGMENT; sd_bus_creds *creds = nullptr; SCOPE_EXIT{ connection_->decrementCredsRefCount(creds); }; - int r = connection_->querySenderCredentials((sd_bus_message*)msg_, mask, &creds); + int r = connection_->querySenderCredentials(static_cast(msg_), mask, &creds); SDBUS_THROW_ERROR_IF(r < 0, "Failed to get bus creds", -r); - gid_t gid = (gid_t)-1; + auto gid = static_cast(-1); r = sd_bus_creds_get_gid(creds, &gid); SDBUS_THROW_ERROR_IF(r < 0, "Failed to get bus cred gid", -r); return gid; @@ -734,13 +747,13 @@ gid_t Message::getCredsGid() const gid_t Message::getCredsEgid() const { - uint64_t mask = SD_BUS_CREDS_EGID | SD_BUS_CREDS_AUGMENT; + const uint64_t mask = SD_BUS_CREDS_EGID | SD_BUS_CREDS_AUGMENT; sd_bus_creds *creds = nullptr; SCOPE_EXIT{ connection_->decrementCredsRefCount(creds); }; - int r = connection_->querySenderCredentials((sd_bus_message*)msg_, mask, &creds); + int r = connection_->querySenderCredentials(static_cast(msg_), mask, &creds); SDBUS_THROW_ERROR_IF(r < 0, "Failed to get bus creds", -r); - gid_t egid = (gid_t)-1; + auto egid = static_cast(-1); r = sd_bus_creds_get_egid(creds, &egid); SDBUS_THROW_ERROR_IF(r < 0, "Failed to get bus cred egid", -r); return egid; @@ -748,10 +761,10 @@ gid_t Message::getCredsEgid() const std::vector Message::getCredsSupplementaryGids() const { - uint64_t mask = SD_BUS_CREDS_SUPPLEMENTARY_GIDS | SD_BUS_CREDS_AUGMENT; + const uint64_t mask = SD_BUS_CREDS_SUPPLEMENTARY_GIDS | SD_BUS_CREDS_AUGMENT; sd_bus_creds *creds = nullptr; SCOPE_EXIT{ connection_->decrementCredsRefCount(creds); }; - int r = connection_->querySenderCredentials((sd_bus_message*)msg_, mask, &creds); + int r = connection_->querySenderCredentials(static_cast(msg_), mask, &creds); SDBUS_THROW_ERROR_IF(r < 0, "Failed to get bus creds", -r); const gid_t *cGids = nullptr; @@ -762,7 +775,7 @@ std::vector Message::getCredsSupplementaryGids() const if (cGids != nullptr) { for (int i = 0; i < r; i++) - gids.push_back(cGids[i]); + gids.push_back(cGids[i]); // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) } return gids; @@ -770,10 +783,10 @@ std::vector Message::getCredsSupplementaryGids() const std::string Message::getSELinuxContext() const { - uint64_t mask = SD_BUS_CREDS_AUGMENT | SD_BUS_CREDS_SELINUX_CONTEXT; + const uint64_t mask = SD_BUS_CREDS_AUGMENT | SD_BUS_CREDS_SELINUX_CONTEXT; sd_bus_creds *creds = nullptr; SCOPE_EXIT{ connection_->decrementCredsRefCount(creds); }; - int r = connection_->querySenderCredentials((sd_bus_message*)msg_, mask, &creds); + int r = connection_->querySenderCredentials(static_cast(msg_), mask, &creds); SDBUS_THROW_ERROR_IF(r < 0, "Failed to get bus creds", -r); const char *cLabel = nullptr; @@ -792,13 +805,13 @@ MethodCall::MethodCall( void *msg void MethodCall::dontExpectReply() { - auto r = sd_bus_message_set_expect_reply((sd_bus_message*)msg_, 0); + auto r = sd_bus_message_set_expect_reply(static_cast(msg_), 0); SDBUS_THROW_ERROR_IF(r < 0, "Failed to set the dont-expect-reply flag", -r); } bool MethodCall::doesntExpectReply() const { - auto r = sd_bus_message_get_expect_reply((sd_bus_message*)msg_); + auto r = sd_bus_message_get_expect_reply(static_cast(msg_)); SDBUS_THROW_ERROR_IF(r < 0, "Failed to get the dont-expect-reply flag", -r); return r == 0; } @@ -807,69 +820,69 @@ MethodReply MethodCall::send(uint64_t timeout) const { if (!doesntExpectReply()) return sendWithReply(timeout); - else - return sendWithNoReply(); + + return sendWithNoReply(); } MethodReply MethodCall::sendWithReply(uint64_t timeout) const { - auto* sdbusReply = connection_->callMethod((sd_bus_message*)msg_, timeout); + auto* sdbusReply = connection_->callMethod(static_cast(msg_), timeout); return Factory::create(sdbusReply, connection_, adopt_message); } MethodReply MethodCall::sendWithNoReply() const { - connection_->sendMessage((sd_bus_message*)msg_); + connection_->sendMessage(static_cast(msg_)); return Factory::create(); // No reply } -Slot MethodCall::send(void* callback, void* userData, uint64_t timeout, return_slot_t) const +Slot MethodCall::send(void* callback, void* userData, uint64_t timeout, return_slot_t) const // NOLINT(bugprone-easily-swappable-parameters) { - return connection_->callMethodAsync((sd_bus_message*)msg_, (sd_bus_message_handler_t)callback, userData, timeout, return_slot); + return connection_->callMethodAsync(static_cast(msg_), reinterpret_cast(callback), userData, timeout, return_slot); } MethodReply MethodCall::createReply() const { - auto* sdbusReply = connection_->createMethodReply((sd_bus_message*)msg_); + auto* sdbusReply = connection_->createMethodReply(static_cast(msg_)); return Factory::create(sdbusReply, connection_, adopt_message); } MethodReply MethodCall::createErrorReply(const Error& error) const { - sd_bus_message* sdbusErrorReply = connection_->createErrorReplyMessage((sd_bus_message*)msg_, error); + sd_bus_message* sdbusErrorReply = connection_->createErrorReplyMessage(static_cast(msg_), error); return Factory::create(sdbusErrorReply, connection_, adopt_message); } void MethodReply::send() const { - connection_->sendMessage((sd_bus_message*)msg_); + connection_->sendMessage(static_cast(msg_)); } uint64_t MethodReply::getReplyCookie() const { - uint64_t cookie; - auto r = sd_bus_message_get_reply_cookie((sd_bus_message*)msg_, &cookie); + uint64_t cookie{}; + auto r = sd_bus_message_get_reply_cookie(static_cast(msg_), &cookie); SDBUS_THROW_ERROR_IF(r < 0, "Failed to get cookie", -r); return cookie; } void Signal::send() const { - connection_->sendMessage((sd_bus_message*)msg_); + connection_->sendMessage(static_cast(msg_)); } void Signal::setDestination(const std::string& destination) { - return setDestination(destination.c_str()); + setDestination(destination.c_str()); } void Signal::setDestination(const char* destination) { - auto r = sd_bus_message_set_destination((sd_bus_message*)msg_, destination); + auto r = sd_bus_message_set_destination(static_cast(msg_), destination); SDBUS_THROW_ERROR_IF(r < 0, "Failed to set signal destination", -r); } @@ -886,16 +899,16 @@ namespace { // Another common solution is global sdbus-c++ startup/shutdown functions, but that would be an intrusive change. #ifdef __cpp_constinit -constinit static bool pseudoConnectionDestroyed{}; +constinit bool pseudoConnectionDestroyed{}; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables) #else -static bool pseudoConnectionDestroyed{}; +bool pseudoConnectionDestroyed{}; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables) #endif std::unique_ptr createPseudoConnection() { auto deleter = [](sdbus::internal::IConnection* con) { - delete con; + delete con; // NOLINT(cppcoreguidelines-owning-memory) pseudoConnectionDestroyed = true; }; @@ -909,7 +922,7 @@ sdbus::internal::IConnection& getPseudoConnectionInstance() if (pseudoConnectionDestroyed) { connection = createPseudoConnection(); // Phoenix rising from the ashes - atexit([](){ connection.~unique_ptr(); }); // We have to manually take care of deleting the phoenix + std::ignore = atexit([](){ connection.~unique_ptr(); }); // We have to manually take care of deleting the phoenix pseudoConnectionDestroyed = false; } @@ -918,7 +931,7 @@ sdbus::internal::IConnection& getPseudoConnectionInstance() return *connection; } -} +} // namespace PlainMessage createPlainMessage() { @@ -930,4 +943,4 @@ PlainMessage createPlainMessage() return connection.createPlainMessage(); } -} +} // namespace sdbus diff --git a/src/Object.cpp b/src/Object.cpp index f0fce0f5..fdeeccf5 100644 --- a/src/Object.cpp +++ b/src/Object.cpp @@ -29,17 +29,25 @@ #include "sdbus-c++/Error.h" #include "sdbus-c++/Flags.h" #include "sdbus-c++/IConnection.h" +#include "sdbus-c++/IObject.h" #include "sdbus-c++/Message.h" +#include "sdbus-c++/TypeTraits.h" +#include "sdbus-c++/VTableItems.h" #include "IConnection.h" #include "MessageUtils.h" -#include "ScopeGuard.h" #include "Utils.h" #include "VTableUtils.h" +#include #include +#include +#include #include SDBUS_HEADER +#include #include +#include +#include namespace sdbus::internal { @@ -69,12 +77,12 @@ Slot Object::addVTable(InterfaceName interfaceName, std::vector vtab // 3rd step -- register the vtable with sd-bus internalVTable->slot = connection_.addObjectVTable( objectPath_ , internalVTable->interfaceName - , &internalVTable->sdbusVTable[0] + , internalVTable->sdbusVTable.data() , internalVTable.get() , return_slot ); // Return vtable wrapped in a Slot object - return {internalVTable.release(), [](void *ptr){ delete static_cast(ptr); }}; + return {internalVTable.release(), [](void *ptr){ delete static_cast(ptr); }}; // NOLINT(cppcoreguidelines-owning-memory) } void Object::unregister() @@ -181,9 +189,9 @@ Object::VTable Object::createInternalVTable(InterfaceName interfaceName, std::ve } // Sort arrays so we can do fast searching for an item in sd-bus callback handlers - std::sort(internalVTable.methods.begin(), internalVTable.methods.end(), [](const auto& a, const auto& b){ return a.name < b.name; }); - std::sort(internalVTable.signals.begin(), internalVTable.signals.end(), [](const auto& a, const auto& b){ return a.name < b.name; }); - std::sort(internalVTable.properties.begin(), internalVTable.properties.end(), [](const auto& a, const auto& b){ return a.name < b.name; }); + std::sort(internalVTable.methods.begin(), internalVTable.methods.end(), [](const auto& lhs, const auto& rhs){ return lhs.name < rhs.name; }); + std::sort(internalVTable.signals.begin(), internalVTable.signals.end(), [](const auto& lhs, const auto& rhs){ return lhs.name < rhs.name; }); + std::sort(internalVTable.properties.begin(), internalVTable.properties.end(), [](const auto& lhs, const auto& rhs){ return lhs.name < rhs.name; }); internalVTable.object = this; @@ -389,7 +397,7 @@ int Object::sdbus_property_set_callback( sd_bus */*bus*/ return ok ? 1 : -1; } -} +} // namespace sdbus::internal namespace sdbus { @@ -401,4 +409,4 @@ std::unique_ptr createObject(sdbus::IConnection& connection, Obj return std::make_unique(*sdbusConnection, std::move(objectPath)); } -} +} // namespace sdbus diff --git a/src/Object.h b/src/Object.h index 2bf5eb76..d6432578 100644 --- a/src/Object.h +++ b/src/Object.h @@ -126,12 +126,12 @@ namespace sdbus::internal { }; VTable createInternalVTable(InterfaceName interfaceName, std::vector vtable); - void writeInterfaceFlagsToVTable(InterfaceFlagsVTableItem flags, VTable& vtable); - void writeMethodRecordToVTable(MethodVTableItem method, VTable& vtable); - void writeSignalRecordToVTable(SignalVTableItem signal, VTable& vtable); - void writePropertyRecordToVTable(PropertyVTableItem property, VTable& vtable); + static void writeInterfaceFlagsToVTable(InterfaceFlagsVTableItem flags, VTable& vtable); + static void writeMethodRecordToVTable(MethodVTableItem method, VTable& vtable); + static void writeSignalRecordToVTable(SignalVTableItem signal, VTable& vtable); + static void writePropertyRecordToVTable(PropertyVTableItem property, VTable& vtable); - std::vector createInternalSdBusVTable(const VTable& vtable); + static std::vector createInternalSdBusVTable(const VTable& vtable); static void startSdBusVTable(const Flags& interfaceFlags, std::vector& vtable); static void writeMethodRecordToSdBusVTable(const VTable::MethodItem& method, std::vector& vtable); static void writeSignalRecordToSdBusVTable(const VTable::SignalItem& signal, std::vector& vtable); diff --git a/src/Proxy.cpp b/src/Proxy.cpp index 14029c9b..37b3c946 100644 --- a/src/Proxy.cpp +++ b/src/Proxy.cpp @@ -28,15 +28,25 @@ #include "sdbus-c++/Error.h" #include "sdbus-c++/IConnection.h" +#include "sdbus-c++/IProxy.h" #include "sdbus-c++/Message.h" +#include "sdbus-c++/TypeTraits.h" #include "IConnection.h" #include "MessageUtils.h" #include "ScopeGuard.h" #include "Utils.h" +#include #include +#include +#include #include +#include +#include +#include +#include +#include #include SDBUS_HEADER #include @@ -124,7 +134,7 @@ PendingAsyncCall Proxy::callMethodAsync(const MethodCall& message, async_reply_h , .proxy = *this , .floating = false }); - asyncCallInfo->slot = message.send((void*)&Proxy::sdbus_async_reply_handler, asyncCallInfo.get(), timeout, return_slot); + asyncCallInfo->slot = message.send(reinterpret_cast(&Proxy::sdbus_async_reply_handler), asyncCallInfo.get(), timeout, return_slot); auto asyncCallInfoWeakPtr = std::weak_ptr{asyncCallInfo}; @@ -141,9 +151,9 @@ Slot Proxy::callMethodAsync(const MethodCall& message, async_reply_handler async , .proxy = *this , .floating = true }); - asyncCallInfo->slot = message.send((void*)&Proxy::sdbus_async_reply_handler, asyncCallInfo.get(), timeout, return_slot); + asyncCallInfo->slot = message.send(reinterpret_cast(&Proxy::sdbus_async_reply_handler), asyncCallInfo.get(), timeout, return_slot); - return {asyncCallInfo.release(), [](void *ptr){ delete static_cast(ptr); }}; + return {asyncCallInfo.release(), [](void *ptr){ delete static_cast(ptr); }}; // NOLINT(cppcoreguidelines-owning-memory) } std::future Proxy::callMethodAsync(const MethodCall& message, with_future_t) @@ -212,7 +222,7 @@ Slot Proxy::registerSignalHandler( const char* interfaceName , signalInfo.get() , return_slot ); - return {signalInfo.release(), [](void *ptr){ delete static_cast(ptr); }}; + return {signalInfo.release(), [](void *ptr){ delete static_cast(ptr); }}; // NOLINT(cppcoreguidelines-owning-memory) } void Proxy::unregister() @@ -290,7 +300,7 @@ Proxy::FloatingAsyncCallSlots::~FloatingAsyncCallSlots() void Proxy::FloatingAsyncCallSlots::push_back(std::shared_ptr asyncCallInfo) { - std::lock_guard lock(mutex_); + const std::lock_guard lock(mutex_); if (!asyncCallInfo->finished) // The call may have finished in the meantime slots_.emplace_back(std::move(asyncCallInfo)); } @@ -326,7 +336,7 @@ void Proxy::FloatingAsyncCallSlots::clear() // mutex) is in progress in a different thread, we get double-mutex deadlock. } -} +} // namespace sdbus::internal namespace sdbus { @@ -354,7 +364,7 @@ bool PendingAsyncCall::isPending() const return !callInfo_.expired(); } -} +} // namespace sdbus namespace sdbus { @@ -370,30 +380,28 @@ std::unique_ptr createProxy( IConnection& connection , std::move(objectPath) ); } +// NOLINTNEXTLINE(cppcoreguidelines-rvalue-reference-param-not-moved): connection is moved but cast to an internal type std::unique_ptr createProxy( std::unique_ptr&& connection , ServiceName destination , ObjectPath objectPath ) { - auto* sdbusConnection = dynamic_cast(connection.get()); + auto* sdbusConnection = dynamic_cast(connection.release()); SDBUS_THROW_ERROR_IF(!sdbusConnection, "Connection is not a real sdbus-c++ connection", EINVAL); - connection.release(); - return std::make_unique( std::unique_ptr(sdbusConnection) , std::move(destination) , std::move(objectPath) ); } +// NOLINTNEXTLINE(cppcoreguidelines-rvalue-reference-param-not-moved): connection is moved cast to an internal type std::unique_ptr createProxy( std::unique_ptr&& connection , ServiceName destination , ObjectPath objectPath , dont_run_event_loop_thread_t ) { - auto* sdbusConnection = dynamic_cast(connection.get()); + auto* sdbusConnection = dynamic_cast(connection.release()); SDBUS_THROW_ERROR_IF(!sdbusConnection, "Connection is not a real sdbus-c++ connection", EINVAL); - connection.release(); - return std::make_unique( std::unique_ptr(sdbusConnection) , std::move(destination) , std::move(objectPath) @@ -440,4 +448,4 @@ std::unique_ptr createLightWeightProxy(ServiceName destination, O return createProxy(std::move(destination), std::move(objectPath), dont_run_event_loop_thread); } -} +} // namespace sdbus diff --git a/src/SdBus.cpp b/src/SdBus.cpp index 7774212d..ef558d2c 100644 --- a/src/SdBus.cpp +++ b/src/SdBus.cpp @@ -26,93 +26,97 @@ */ #include "SdBus.h" -#include +#include "sdbus-c++/Error.h" // NOLINT(misc-include-cleaner) +#include SDBUS_HEADER #include +#include +#include +#include namespace sdbus::internal { -sd_bus_message* SdBus::sd_bus_message_ref(sd_bus_message *m) +sd_bus_message* SdBus::sd_bus_message_ref(sd_bus_message *msg) { - std::lock_guard lock(sdbusMutex_); + const std::lock_guard lock(sdbusMutex_); - return ::sd_bus_message_ref(m); + return ::sd_bus_message_ref(msg); } -sd_bus_message* SdBus::sd_bus_message_unref(sd_bus_message *m) +sd_bus_message* SdBus::sd_bus_message_unref(sd_bus_message *msg) { - std::lock_guard lock(sdbusMutex_); + const std::lock_guard lock(sdbusMutex_); - return ::sd_bus_message_unref(m); + return ::sd_bus_message_unref(msg); } -int SdBus::sd_bus_send(sd_bus *bus, sd_bus_message *m, uint64_t *cookie) +int SdBus::sd_bus_send(sd_bus *bus, sd_bus_message *msg, uint64_t *cookie) { - std::lock_guard lock(sdbusMutex_); + const std::lock_guard lock(sdbusMutex_); - auto r = ::sd_bus_send(bus, m, cookie); + auto r = ::sd_bus_send(bus, msg, cookie); if (r < 0) return r; return r; } -int SdBus::sd_bus_call(sd_bus *bus, sd_bus_message *m, uint64_t usec, sd_bus_error *ret_error, sd_bus_message **reply) +int SdBus::sd_bus_call(sd_bus *bus, sd_bus_message *msg, uint64_t usec, sd_bus_error *ret_error, sd_bus_message **reply) { - std::lock_guard lock(sdbusMutex_); + const std::lock_guard lock(sdbusMutex_); - return ::sd_bus_call(bus, m, usec, ret_error, reply); + return ::sd_bus_call(bus, msg, usec, ret_error, reply); } -int SdBus::sd_bus_call_async(sd_bus *bus, sd_bus_slot **slot, sd_bus_message *m, sd_bus_message_handler_t callback, void *userdata, uint64_t usec) +int SdBus::sd_bus_call_async(sd_bus *bus, sd_bus_slot **slot, sd_bus_message *msg, sd_bus_message_handler_t callback, void *userdata, uint64_t usec) { - std::lock_guard lock(sdbusMutex_); + const std::lock_guard lock(sdbusMutex_); - auto r = ::sd_bus_call_async(bus, slot, m, callback, userdata, usec); + auto r = ::sd_bus_call_async(bus, slot, msg, callback, userdata, usec); if (r < 0) return r; return r; } -int SdBus::sd_bus_message_new(sd_bus *bus, sd_bus_message **m, uint8_t type) +int SdBus::sd_bus_message_new(sd_bus *bus, sd_bus_message **msg, uint8_t type) { - std::lock_guard lock(sdbusMutex_); + const std::lock_guard lock(sdbusMutex_); - return ::sd_bus_message_new(bus, m, type); + return ::sd_bus_message_new(bus, msg, type); } -int SdBus::sd_bus_message_new_method_call(sd_bus *bus, sd_bus_message **m, const char *destination, const char *path, const char *interface, const char *member) +int SdBus::sd_bus_message_new_method_call(sd_bus *bus, sd_bus_message **msg, const char *destination, const char *path, const char *interface, const char *member) { - std::lock_guard lock(sdbusMutex_); + const std::lock_guard lock(sdbusMutex_); - return ::sd_bus_message_new_method_call(bus, m, destination, path, interface, member); + return ::sd_bus_message_new_method_call(bus, msg, destination, path, interface, member); } -int SdBus::sd_bus_message_new_signal(sd_bus *bus, sd_bus_message **m, const char *path, const char *interface, const char *member) +int SdBus::sd_bus_message_new_signal(sd_bus *bus, sd_bus_message **msg, const char *path, const char *interface, const char *member) { - std::lock_guard lock(sdbusMutex_); + const std::lock_guard lock(sdbusMutex_); - return ::sd_bus_message_new_signal(bus, m, path, interface, member); + return ::sd_bus_message_new_signal(bus, msg, path, interface, member); } -int SdBus::sd_bus_message_new_method_return(sd_bus_message *call, sd_bus_message **m) +int SdBus::sd_bus_message_new_method_return(sd_bus_message *call, sd_bus_message **msg) { - std::lock_guard lock(sdbusMutex_); + const std::lock_guard lock(sdbusMutex_); - return ::sd_bus_message_new_method_return(call, m); + return ::sd_bus_message_new_method_return(call, msg); } -int SdBus::sd_bus_message_new_method_error(sd_bus_message *call, sd_bus_message **m, const sd_bus_error *e) +int SdBus::sd_bus_message_new_method_error(sd_bus_message *call, sd_bus_message **msg, const sd_bus_error *err) { - std::lock_guard lock(sdbusMutex_); + const std::lock_guard lock(sdbusMutex_); - return ::sd_bus_message_new_method_error(call, m, e); + return ::sd_bus_message_new_method_error(call, msg, err); } int SdBus::sd_bus_set_method_call_timeout(sd_bus *bus, uint64_t usec) { #if LIBSYSTEMD_VERSION>=240 - std::lock_guard lock(sdbusMutex_); + const std::lock_guard lock(sdbusMutex_); return ::sd_bus_set_method_call_timeout(bus, usec); #else @@ -125,7 +129,7 @@ int SdBus::sd_bus_set_method_call_timeout(sd_bus *bus, uint64_t usec) int SdBus::sd_bus_get_method_call_timeout(sd_bus *bus, uint64_t *ret) { #if LIBSYSTEMD_VERSION>=240 - std::lock_guard lock(sdbusMutex_); + const std::lock_guard lock(sdbusMutex_); return ::sd_bus_get_method_call_timeout(bus, ret); #else @@ -137,35 +141,35 @@ int SdBus::sd_bus_get_method_call_timeout(sd_bus *bus, uint64_t *ret) int SdBus::sd_bus_emit_properties_changed_strv(sd_bus *bus, const char *path, const char *interface, char **names) { - std::lock_guard lock(sdbusMutex_); + const std::lock_guard lock(sdbusMutex_); return ::sd_bus_emit_properties_changed_strv(bus, path, interface, names); } int SdBus::sd_bus_emit_object_added(sd_bus *bus, const char *path) { - std::lock_guard lock(sdbusMutex_); + const std::lock_guard lock(sdbusMutex_); return ::sd_bus_emit_object_added(bus, path); } int SdBus::sd_bus_emit_object_removed(sd_bus *bus, const char *path) { - std::lock_guard lock(sdbusMutex_); + const std::lock_guard lock(sdbusMutex_); return ::sd_bus_emit_object_removed(bus, path); } int SdBus::sd_bus_emit_interfaces_added_strv(sd_bus *bus, const char *path, char **interfaces) { - std::lock_guard lock(sdbusMutex_); + const std::lock_guard lock(sdbusMutex_); return ::sd_bus_emit_interfaces_added_strv(bus, path, interfaces); } int SdBus::sd_bus_emit_interfaces_removed_strv(sd_bus *bus, const char *path, char **interfaces) { - std::lock_guard lock(sdbusMutex_); + const std::lock_guard lock(sdbusMutex_); return ::sd_bus_emit_interfaces_removed_strv(bus, path, interfaces); } @@ -197,14 +201,14 @@ int SdBus::sd_bus_open_user_with_address(sd_bus **ret, const char* address) if (r < 0) return r; - r = ::sd_bus_set_bus_client(bus, true); + r = ::sd_bus_set_bus_client(bus, true); // NOLINT(readability-implicit-bool-conversion) if (r < 0) return r; // Copying behavior from // https://github.com/systemd/systemd/blob/fee6441601c979165ebcbb35472036439f8dad5f/src/libsystemd/sd-bus/sd-bus.c#L1381 // Here, we make the bus as trusted - r = ::sd_bus_set_trusted(bus, true); + r = ::sd_bus_set_trusted(bus, true); // NOLINT(readability-implicit-bool-conversion) if (r < 0) return r; @@ -276,7 +280,7 @@ int SdBus::sd_bus_open_server(sd_bus **ret, int fd) if (r < 0) return r; - r = ::sd_bus_set_server(bus, true, id); + r = ::sd_bus_set_server(bus, true, id); // NOLINT(readability-implicit-bool-conversion) if (r < 0) return r; @@ -303,62 +307,63 @@ int SdBus::sd_bus_open_system_remote(sd_bus **ret, const char *host) int SdBus::sd_bus_request_name(sd_bus *bus, const char *name, uint64_t flags) { - std::lock_guard lock(sdbusMutex_); + const std::lock_guard lock(sdbusMutex_); return ::sd_bus_request_name(bus, name, flags); } int SdBus::sd_bus_release_name(sd_bus *bus, const char *name) { - std::lock_guard lock(sdbusMutex_); + const std::lock_guard lock(sdbusMutex_); return ::sd_bus_release_name(bus, name); } int SdBus::sd_bus_get_unique_name(sd_bus *bus, const char **name) { - std::lock_guard lock(sdbusMutex_); + const std::lock_guard lock(sdbusMutex_); + return ::sd_bus_get_unique_name(bus, name); } int SdBus::sd_bus_add_object_vtable(sd_bus *bus, sd_bus_slot **slot, const char *path, const char *interface, const sd_bus_vtable *vtable, void *userdata) { - std::lock_guard lock(sdbusMutex_); + const std::lock_guard lock(sdbusMutex_); return ::sd_bus_add_object_vtable(bus, slot, path, interface, vtable, userdata); } int SdBus::sd_bus_add_object_manager(sd_bus *bus, sd_bus_slot **slot, const char *path) { - std::lock_guard lock(sdbusMutex_); + const std::lock_guard lock(sdbusMutex_); return ::sd_bus_add_object_manager(bus, slot, path); } int SdBus::sd_bus_add_match(sd_bus *bus, sd_bus_slot **slot, const char *match, sd_bus_message_handler_t callback, void *userdata) { - std::lock_guard lock(sdbusMutex_); + const std::lock_guard lock(sdbusMutex_); return ::sd_bus_add_match(bus, slot, match, callback, userdata); } int SdBus::sd_bus_add_match_async(sd_bus *bus, sd_bus_slot **slot, const char *match, sd_bus_message_handler_t callback, sd_bus_message_handler_t install_callback, void *userdata) { - std::lock_guard lock(sdbusMutex_); + const std::lock_guard lock(sdbusMutex_); return ::sd_bus_add_match_async(bus, slot, match, callback, install_callback, userdata); } int SdBus::sd_bus_match_signal(sd_bus *bus, sd_bus_slot **ret, const char *sender, const char *path, const char *interface, const char *member, sd_bus_message_handler_t callback, void *userdata) { - std::lock_guard lock(sdbusMutex_); + const std::lock_guard lock(sdbusMutex_); return ::sd_bus_match_signal(bus, ret, sender, path, interface, member, callback, userdata); } sd_bus_slot* SdBus::sd_bus_slot_unref(sd_bus_slot *slot) { - std::lock_guard lock(sdbusMutex_); + const std::lock_guard lock(sdbusMutex_); return ::sd_bus_slot_unref(slot); } @@ -373,11 +378,11 @@ int SdBus::sd_bus_start(sd_bus *bus) return ::sd_bus_start(bus); } -int SdBus::sd_bus_process(sd_bus *bus, sd_bus_message **r) +int SdBus::sd_bus_process(sd_bus *bus, sd_bus_message **msg) { - std::lock_guard lock(sdbusMutex_); + const std::lock_guard lock(sdbusMutex_); - return ::sd_bus_process(bus, r); + return ::sd_bus_process(bus, msg); } sd_bus_message* SdBus::sd_bus_get_current_message(sd_bus *bus) @@ -387,7 +392,7 @@ sd_bus_message* SdBus::sd_bus_get_current_message(sd_bus *bus) int SdBus::sd_bus_get_poll_data(sd_bus *bus, PollData* data) { - std::lock_guard lock(sdbusMutex_); + const std::lock_guard lock(sdbusMutex_); auto r = ::sd_bus_get_fd(bus); if (r < 0) @@ -404,9 +409,9 @@ int SdBus::sd_bus_get_poll_data(sd_bus *bus, PollData* data) return r; } -int SdBus::sd_bus_get_n_queued(sd_bus *bus, uint64_t *read, uint64_t* write) +int SdBus::sd_bus_get_n_queued(sd_bus *bus, uint64_t *read, uint64_t* write) // NOLINT(bugprone-easily-swappable-parameters) { - std::lock_guard lock(sdbusMutex_); + const std::lock_guard lock(sdbusMutex_); auto r1 = ::sd_bus_get_n_queued_read(bus, read); auto r2 = ::sd_bus_get_n_queued_write(bus, write); @@ -434,81 +439,81 @@ sd_bus* SdBus::sd_bus_close_unref(sd_bus *bus) #endif } -int SdBus::sd_bus_message_set_destination(sd_bus_message *m, const char *destination) +int SdBus::sd_bus_message_set_destination(sd_bus_message *msg, const char *destination) { - std::lock_guard lock(sdbusMutex_); + const std::lock_guard lock(sdbusMutex_); - return ::sd_bus_message_set_destination(m, destination); + return ::sd_bus_message_set_destination(msg, destination); } -int SdBus::sd_bus_query_sender_creds(sd_bus_message *m, uint64_t mask, sd_bus_creds **c) +int SdBus::sd_bus_query_sender_creds(sd_bus_message *msg, uint64_t mask, sd_bus_creds **creds) { - std::lock_guard lock(sdbusMutex_); + const std::lock_guard lock(sdbusMutex_); - return ::sd_bus_query_sender_creds(m, mask, c); + return ::sd_bus_query_sender_creds(msg, mask, creds); } -sd_bus_creds* SdBus::sd_bus_creds_ref(sd_bus_creds *c) +sd_bus_creds* SdBus::sd_bus_creds_ref(sd_bus_creds *creds) { - std::lock_guard lock(sdbusMutex_); + const std::lock_guard lock(sdbusMutex_); - return ::sd_bus_creds_ref(c); + return ::sd_bus_creds_ref(creds); } -sd_bus_creds* SdBus::sd_bus_creds_unref(sd_bus_creds *c) +sd_bus_creds* SdBus::sd_bus_creds_unref(sd_bus_creds *creds) { - std::lock_guard lock(sdbusMutex_); + const std::lock_guard lock(sdbusMutex_); - return ::sd_bus_creds_unref(c); + return ::sd_bus_creds_unref(creds); } -int SdBus::sd_bus_creds_get_pid(sd_bus_creds *c, pid_t *pid) +int SdBus::sd_bus_creds_get_pid(sd_bus_creds *creds, pid_t *pid) { - std::lock_guard lock(sdbusMutex_); + const std::lock_guard lock(sdbusMutex_); - return ::sd_bus_creds_get_pid(c, pid); + return ::sd_bus_creds_get_pid(creds, pid); } -int SdBus::sd_bus_creds_get_uid(sd_bus_creds *c, uid_t *uid) +int SdBus::sd_bus_creds_get_uid(sd_bus_creds *creds, uid_t *uid) { - std::lock_guard lock(sdbusMutex_); + const std::lock_guard lock(sdbusMutex_); - return ::sd_bus_creds_get_uid(c, uid); + return ::sd_bus_creds_get_uid(creds, uid); } -int SdBus::sd_bus_creds_get_euid(sd_bus_creds *c, uid_t *euid) +int SdBus::sd_bus_creds_get_euid(sd_bus_creds *creds, uid_t *euid) { - std::lock_guard lock(sdbusMutex_); + const std::lock_guard lock(sdbusMutex_); - return ::sd_bus_creds_get_euid(c, euid); + return ::sd_bus_creds_get_euid(creds, euid); } -int SdBus::sd_bus_creds_get_gid(sd_bus_creds *c, gid_t *gid) +int SdBus::sd_bus_creds_get_gid(sd_bus_creds *creds, gid_t *gid) { - std::lock_guard lock(sdbusMutex_); + const std::lock_guard lock(sdbusMutex_); - return ::sd_bus_creds_get_gid(c, gid); + return ::sd_bus_creds_get_gid(creds, gid); } -int SdBus::sd_bus_creds_get_egid(sd_bus_creds *c, uid_t *egid) +int SdBus::sd_bus_creds_get_egid(sd_bus_creds *creds, uid_t *egid) { - std::lock_guard lock(sdbusMutex_); + const std::lock_guard lock(sdbusMutex_); - return ::sd_bus_creds_get_egid(c, egid); + return ::sd_bus_creds_get_egid(creds, egid); } -int SdBus::sd_bus_creds_get_supplementary_gids(sd_bus_creds *c, const gid_t **gids) +int SdBus::sd_bus_creds_get_supplementary_gids(sd_bus_creds *creds, const gid_t **gids) { - std::lock_guard lock(sdbusMutex_); + const std::lock_guard lock(sdbusMutex_); - return ::sd_bus_creds_get_supplementary_gids(c, gids); + return ::sd_bus_creds_get_supplementary_gids(creds, gids); } -int SdBus::sd_bus_creds_get_selinux_context(sd_bus_creds *c, const char **label) +int SdBus::sd_bus_creds_get_selinux_context(sd_bus_creds *creds, const char **label) { - std::lock_guard lock(sdbusMutex_); + const std::lock_guard lock(sdbusMutex_); - return ::sd_bus_creds_get_selinux_context(c, label); + return ::sd_bus_creds_get_selinux_context(creds, label); } -} +} // namespace sdbus::internal diff --git a/src/SdBus.h b/src/SdBus.h index 7b8127d9..7167de50 100644 --- a/src/SdBus.h +++ b/src/SdBus.h @@ -62,7 +62,7 @@ class SdBus final : public ISdBus virtual int sd_bus_open_system(sd_bus **ret) override; virtual int sd_bus_open_user(sd_bus **ret) override; virtual int sd_bus_open_user_with_address(sd_bus **ret, const char* address) override; - virtual int sd_bus_open_system_remote(sd_bus **ret, const char* hsot) override; + virtual int sd_bus_open_system_remote(sd_bus **ret, const char* host) override; virtual int sd_bus_open_direct(sd_bus **ret, const char* address) override; virtual int sd_bus_open_direct(sd_bus **ret, int fd) override; virtual int sd_bus_open_server(sd_bus **ret, int fd) override; @@ -79,7 +79,7 @@ class SdBus final : public ISdBus virtual int sd_bus_new(sd_bus **ret) override; virtual int sd_bus_start(sd_bus *bus) override; - virtual int sd_bus_process(sd_bus *bus, sd_bus_message **r) override; + virtual int sd_bus_process(sd_bus *bus, sd_bus_message **msg) override; virtual sd_bus_message* sd_bus_get_current_message(sd_bus *bus) override; virtual int sd_bus_get_poll_data(sd_bus *bus, PollData* data) override; virtual int sd_bus_get_n_queued(sd_bus *bus, uint64_t *read, uint64_t* write) override; diff --git a/src/Types.cpp b/src/Types.cpp index 4f91e939..f07ef475 100644 --- a/src/Types.cpp +++ b/src/Types.cpp @@ -24,11 +24,9 @@ * along with sdbus-c++. If not, see . */ -#include "sdbus-c++/Types.h" - #include "sdbus-c++/Error.h" - -#include "MessageUtils.h" +#include "sdbus-c++/Message.h" +#include "sdbus-c++/Types.h" #include #include @@ -82,7 +80,7 @@ int UnixFd::checkedDup(int fd) return fd; } - int ret = ::dup(fd); // NOLINT(android-cloexec-dup) // TODO: verify + const int ret = ::dup(fd); // NOLINT(android-cloexec-dup) // TODO: verify if (ret < 0) { throw std::system_error(errno, std::generic_category(), "dup failed"); From 6d959385197a1c60e57ce86d9435db2b53db7931 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stanislav=20Angelovi=C4=8D?= Date: Mon, 5 May 2025 21:52:05 +0200 Subject: [PATCH 02/13] fix: address clang-tidy warnings in stress tests --- .clang-tidy | 3 + CMakeLists.txt | 8 +- tests/stresstests/sdbus-c++-stress-tests.cpp | 91 ++++++++++++++------ 3 files changed, 73 insertions(+), 29 deletions(-) diff --git a/.clang-tidy b/.clang-tidy index e95c3235..e17fe36c 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -4,7 +4,10 @@ Checks: "*,\ -llvmlibc-*,\ -altera-*,\ -fuchsia-*, + -cert-err58-cpp,\ -modernize-use-trailing-return-type,\ + -cppcoreguidelines-avoid-magic-numbers,\ + -readability-magic-numbers,\ -readability-braces-around-statements,\ -google-readability-braces-around-statements,\ -hicpp-braces-around-statements,\ diff --git a/CMakeLists.txt b/CMakeLists.txt index a5b83f6e..c580ac9e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -271,15 +271,17 @@ endif() if(SDBUSCPP_CLANG_TIDY) message(STATUS "Building with static analysis") + #set(CLANG_TIDY "/home/one/CLion2/clion-2024.3.5/bin/clang/linux/x64/bin/clang-tidy") find_program(CLANG_TIDY NAMES clang-tidy) if(NOT CLANG_TIDY) - message(STATUS "clang-tidy not found") + message(WARNING "clang-tidy not found") else() message(STATUS "clang-tidy found: ${CLANG_TIDY}") set_target_properties(sdbus-c++-objlib PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY}") set_target_properties(sdbus-c++ PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY}") - set_target_properties(sdbus-c++-unit-tests PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY}") - set_target_properties(sdbus-c++-integration-tests PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY}") + #set_target_properties(sdbus-c++-unit-tests PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY}") + #set_target_properties(sdbus-c++-integration-tests PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY}") + set_target_properties(sdbus-c++-stress-tests PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY}") endif() endif() diff --git a/tests/stresstests/sdbus-c++-stress-tests.cpp b/tests/stresstests/sdbus-c++-stress-tests.cpp index 66f82463..57f06a0c 100644 --- a/tests/stresstests/sdbus-c++-stress-tests.cpp +++ b/tests/stresstests/sdbus-c++-stress-tests.cpp @@ -34,16 +34,22 @@ #include #include #include -#include #include #include #include #include +#include +#include #include #include #include #include #include +#include +#include +#include +#include +#include using namespace std::chrono_literals; @@ -62,13 +68,18 @@ class CelsiusThermometerAdaptor final : public sdbus::AdaptorInterfaces lock{childrenMutex_}; + const std::lock_guard lock{childrenMutex_}; children_.erase(request.delegateObjectPath); } } @@ -152,6 +168,11 @@ class FahrenheitThermometerAdaptor final : public sdbus::AdaptorInterfaces< org: registerAdaptor(); } + FahrenheitThermometerAdaptor(const FahrenheitThermometerAdaptor&) = delete; + FahrenheitThermometerAdaptor& operator=(const FahrenheitThermometerAdaptor&) = delete; + FahrenheitThermometerAdaptor(FahrenheitThermometerAdaptor&&) = delete; + FahrenheitThermometerAdaptor& operator=(FahrenheitThermometerAdaptor&&) = delete; + ~FahrenheitThermometerAdaptor() { exit_ = true; @@ -163,13 +184,13 @@ class FahrenheitThermometerAdaptor final : public sdbus::AdaptorInterfaces< org: } protected: - virtual uint32_t getCurrentTemperature() override + uint32_t getCurrentTemperature() override { // In this D-Bus call, make yet another D-Bus call to another service over the same connection return static_cast(celsiusProxy_.getCurrentTemperature() * 1.8 + 32.); } - virtual void createDelegateObject(sdbus::Result&& result) override + void createDelegateObject(sdbus::Result&& result) override { static size_t objectCounter{}; objectCounter++; @@ -180,7 +201,7 @@ class FahrenheitThermometerAdaptor final : public sdbus::AdaptorInterfaces< org: cond_.notify_one(); } - virtual void destroyDelegateObject(sdbus::Result<>&& /*result*/, sdbus::ObjectPath delegate) override + void destroyDelegateObject(sdbus::Result<>&& /*result*/, sdbus::ObjectPath delegate) override { std::unique_lock lock(mutex_); requests_.push(WorkItem{0, std::move(delegate), {}}); @@ -203,7 +224,7 @@ class FahrenheitThermometerAdaptor final : public sdbus::AdaptorInterfaces< org: std::condition_variable cond_; std::queue requests_; std::vector workers_; - std::atomic exit_{}; + std::atomic exit_; }; class FahrenheitThermometerProxy : public sdbus::ProxyInterfaces< org::sdbuscpp::stresstests::fahrenheit::thermometer_proxy @@ -216,6 +237,11 @@ class FahrenheitThermometerProxy : public sdbus::ProxyInterfaces< org::sdbuscpp: registerProxy(); } + FahrenheitThermometerProxy(const FahrenheitThermometerProxy&) = delete; + FahrenheitThermometerProxy& operator=(const FahrenheitThermometerProxy&) = delete; + FahrenheitThermometerProxy(FahrenheitThermometerProxy&&) = delete; + FahrenheitThermometerProxy& operator=(FahrenheitThermometerProxy&&) = delete; + ~FahrenheitThermometerProxy() { unregisterProxy(); @@ -262,6 +288,11 @@ class ConcatenatorAdaptor final : public sdbus::AdaptorInterfaces&& result, std::map params) override + void concatenate(sdbus::Result&& result, std::map params) override { std::unique_lock lock(mutex_); requests_.push(WorkItem{std::move(params), std::move(result)}); @@ -291,7 +322,7 @@ class ConcatenatorAdaptor final : public sdbus::AdaptorInterfaces requests_; std::vector workers_; - std::atomic exit_{}; + std::atomic exit_; }; class ConcatenatorProxy final : public sdbus::ProxyInterfaces @@ -303,13 +334,18 @@ class ConcatenatorProxy final : public sdbus::ProxyInterfaces error) override + void onConcatenateReply(const std::string& result, [[maybe_unused]] std::optional error) override { assert(error == std::nullopt); @@ -318,21 +354,21 @@ class ConcatenatorProxy final : public sdbus::ProxyInterfaces> aString; assert(aString == "sdbus-c++-stress-tests"); - uint32_t aNumber; + uint32_t aNumber{}; str >> aNumber; assert(aNumber > 0); ++repliesReceived_; } - virtual void onConcatenatedSignal(const std::string& concatenatedString) override + void onConcatenatedSignal(const std::string& concatenatedString) override { std::stringstream str(concatenatedString); std::string aString; str >> aString; assert(aString == "sdbus-c++-stress-tests"); - uint32_t aNumber; + uint32_t aNumber{}; str >> aNumber; assert(aNumber > 0); @@ -340,15 +376,15 @@ class ConcatenatorProxy final : public sdbus::ProxyInterfaces repliesReceived_{}; - std::atomic signalsReceived_{}; + std::atomic repliesReceived_; + std::atomic signalsReceived_; }; //----------------------------------------- -int main(int argc, char *argv[]) +int main(int argc, char *argv[]) // NOLINT(bugprone-exception-escape, readability-function-cognitive-complexity) { - long loops; - long loopDuration; + long loops{}; + long loopDuration{}; if (argc == 1) { @@ -357,13 +393,13 @@ int main(int argc, char *argv[]) } else if (argc == 3) { - loops = std::atol(argv[1]); - loopDuration = std::atol(argv[2]); + loops = std::atol(argv[1]); // NOLINT(cert-err34-c, cppcoreguidelines-pro-bounds-pointer-arithmetic) + loopDuration = std::atol(argv[2]); // NOLINT(cert-err34-c, cppcoreguidelines-pro-bounds-pointer-arithmetic) } else throw std::runtime_error("Wrong program options"); - std::cout << "Going on with " << loops << " loops and " << loopDuration << "ms loop duration" << std::endl; + std::cout << "Going on with " << loops << " loops and " << loopDuration << "ms loop duration\n"; std::atomic concatenationCallsMade{0}; std::atomic concatenationRepliesReceived{0}; @@ -377,19 +413,20 @@ int main(int argc, char *argv[]) { std::this_thread::sleep_for(1s); - std::cout << "Made " << concatenationCallsMade << " concatenation calls, received " << concatenationRepliesReceived << " replies and " << concatenationSignalsReceived << " signals so far." << std::endl; - std::cout << "Made " << thermometerCallsMade << " thermometer calls so far." << std::endl << std::endl; + std::cout << "Made " << concatenationCallsMade << " concatenation calls, received " << concatenationRepliesReceived << " replies and " << concatenationSignalsReceived << " signals so far.\n"; + std::cout << "Made " << thermometerCallsMade << " thermometer calls so far.\n\n"; } }); for (long loop = 0; loop < loops; ++loop) { - std::cout << "Entering loop " << loop+1 << std::endl; + std::cout << "Entering loop " << loop+1 << '\n'; auto service2Connection = sdbus::createSystemBusConnection(SERVICE_2_BUS_NAME); std::atomic service2ThreadReady{}; std::thread service2Thread([&con = *service2Connection, &service2ThreadReady]() { + // NOLINTNEXTLINE(misc-const-correctness) CelsiusThermometerAdaptor thermometer(con, CELSIUS_THERMOMETER_OBJECT_PATH); service2ThreadReady = true; con.enterEventLoop(); @@ -399,7 +436,9 @@ int main(int argc, char *argv[]) std::atomic service1ThreadReady{}; std::thread service1Thread([&con = *service1Connection, &service1ThreadReady]() { + // NOLINTNEXTLINE(misc-const-correctness) ConcatenatorAdaptor concatenator(con, CONCATENATOR_OBJECT_PATH); + // NOLINTNEXTLINE(misc-const-correctness) FahrenheitThermometerAdaptor thermometer(con, FAHRENHEIT_THERMOMETER_OBJECT_PATH, false); service1ThreadReady = true; con.enterEventLoop(); @@ -442,8 +481,8 @@ int main(int argc, char *argv[]) // Update statistics concatenationCallsMade = localCounter; - concatenationRepliesReceived = (uint32_t)concatenator.repliesReceived_; - concatenationSignalsReceived = (uint32_t)concatenator.signalsReceived_; + concatenationRepliesReceived = static_cast(concatenator.repliesReceived_); + concatenationSignalsReceived = static_cast(concatenator.signalsReceived_); } } }); From f1ae9a73842234c58bfd9961448c364ee10018a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stanislav=20Angelovi=C4=8D?= Date: Tue, 6 May 2025 10:34:51 +0200 Subject: [PATCH 03/13] chore(ci): add new clang-tidy job --- .github/workflows/ci.yml | 45 ++++++++++++++++++++++++++-------------- 1 file changed, 29 insertions(+), 16 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8463dfd7..9fe2d778 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -46,34 +46,26 @@ jobs: - name: configure-debug-gcc11 # For gcc 11, turn off the annoying deprecated-copy warning if: matrix.build == 'shared-libsystemd' && matrix.compiler == 'g++' && matrix.os == 'ubuntu-22.04' run: | - mkdir build - cd build - cmake -DCMAKE_BUILD_TYPE=Debug -DCMAKE_INSTALL_PREFIX:PATH=/usr -DCMAKE_CXX_FLAGS="-O0 -g -W -Wextra -Wall -Wnon-virtual-dtor -Wno-deprecated-copy -Werror $SDBUSCPP_EXTRA_CXX_FLAGS" -DCMAKE_VERBOSE_MAKEFILE=ON -DSDBUSCPP_INSTALL=ON -DSDBUSCPP_BUILD_TESTS=ON -DSDBUSCPP_BUILD_PERF_TESTS=ON -DSDBUSCPP_BUILD_STRESS_TESTS=ON -DSDBUSCPP_BUILD_CODEGEN=ON -DSDBUSCPP_GOOGLETEST_VERSION=1.14.0 .. + cmake -B _build -DCMAKE_BUILD_TYPE=Debug -DCMAKE_INSTALL_PREFIX:PATH=/usr -DCMAKE_CXX_FLAGS="-O0 -g -W -Wextra -Wall -Wnon-virtual-dtor -Wno-deprecated-copy -Werror $SDBUSCPP_EXTRA_CXX_FLAGS" -DCMAKE_VERBOSE_MAKEFILE=ON -DSDBUSCPP_INSTALL=ON -DSDBUSCPP_BUILD_TESTS=ON -DSDBUSCPP_BUILD_PERF_TESTS=ON -DSDBUSCPP_BUILD_STRESS_TESTS=ON -DSDBUSCPP_BUILD_CODEGEN=ON -DSDBUSCPP_GOOGLETEST_VERSION=1.14.0 - name: configure-debug if: matrix.build == 'shared-libsystemd' && (matrix.compiler != 'g++' || matrix.os != 'ubuntu-22.04') run: | - mkdir build - cd build - cmake -DCMAKE_BUILD_TYPE=Debug -DCMAKE_INSTALL_PREFIX:PATH=/usr -DCMAKE_CXX_FLAGS="-O0 -g -W -Wextra -Wall -Wnon-virtual-dtor -Werror $SDBUSCPP_EXTRA_CXX_FLAGS" -DCMAKE_VERBOSE_MAKEFILE=ON -DSDBUSCPP_INSTALL=ON -DSDBUSCPP_BUILD_TESTS=ON -DSDBUSCPP_BUILD_PERF_TESTS=ON -DSDBUSCPP_BUILD_STRESS_TESTS=ON -DSDBUSCPP_BUILD_CODEGEN=ON -DSDBUSCPP_GOOGLETEST_VERSION=1.14.0 .. + cmake -B _build -DCMAKE_BUILD_TYPE=Debug -DCMAKE_INSTALL_PREFIX:PATH=/usr -DCMAKE_CXX_FLAGS="-O0 -g -W -Wextra -Wall -Wnon-virtual-dtor -Werror $SDBUSCPP_EXTRA_CXX_FLAGS" -DCMAKE_VERBOSE_MAKEFILE=ON -DSDBUSCPP_INSTALL=ON -DSDBUSCPP_BUILD_TESTS=ON -DSDBUSCPP_BUILD_PERF_TESTS=ON -DSDBUSCPP_BUILD_STRESS_TESTS=ON -DSDBUSCPP_BUILD_CODEGEN=ON -DSDBUSCPP_GOOGLETEST_VERSION=1.14.0 - name: configure-release-with-embedded-libsystemd if: matrix.build == 'embedded-static-libsystemd' run: | - mkdir build - cd build - cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX:PATH=/usr -DCMAKE_CXX_FLAGS="$SDBUSCPP_EXTRA_CXX_FLAGS" -DCMAKE_VERBOSE_MAKEFILE=ON -DSDBUSCPP_INSTALL=ON -DSDBUSCPP_BUILD_TESTS=ON -DSDBUSCPP_BUILD_PERF_TESTS=ON -DSDBUSCPP_BUILD_STRESS_TESTS=ON -DSDBUSCPP_BUILD_CODEGEN=ON -DSDBUSCPP_BUILD_LIBSYSTEMD=ON -DSDBUSCPP_LIBSYSTEMD_VERSION=252 -DSDBUSCPP_GOOGLETEST_VERSION=1.14.0 .. + cmake -B _build -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX:PATH=/usr -DCMAKE_CXX_FLAGS="$SDBUSCPP_EXTRA_CXX_FLAGS" -DCMAKE_VERBOSE_MAKEFILE=ON -DSDBUSCPP_INSTALL=ON -DSDBUSCPP_BUILD_TESTS=ON -DSDBUSCPP_BUILD_PERF_TESTS=ON -DSDBUSCPP_BUILD_STRESS_TESTS=ON -DSDBUSCPP_BUILD_CODEGEN=ON -DSDBUSCPP_BUILD_LIBSYSTEMD=ON -DSDBUSCPP_LIBSYSTEMD_VERSION=252 -DSDBUSCPP_GOOGLETEST_VERSION=1.14.0 - name: make run: | - cd build - cmake --build . -j4 + cmake --build _build -j4 - name: verify run: | - cd build - sudo cmake --build . --target install + sudo cmake --build _build --target install ctest --output-on-failure - name: pack if: matrix.build == 'shared-libsystemd' run: | - cd build + cd _build cpack -G DEB - name: 'Upload Artifact' if: matrix.build == 'shared-libsystemd' && matrix.compiler == 'g++' @@ -81,9 +73,30 @@ jobs: with: name: "debian-packages-${{ matrix.os }}-${{ matrix.compiler }}" path: | - build/sdbus-c++*.deb - build/sdbus-c++*.ddeb + _build/sdbus-c++*.deb + _build/sdbus-c++*.ddeb retention-days: 10 + static-analysis: + name: static-analysis (ubuntu-24.04, clang-tidy, shared-libsystemd) + runs-on: ubuntu-24.04 + strategy: + fail-fast: false + steps: + - uses: actions/checkout@v4 + - name: install-deps + run: | + sudo apt-get update -y + sudo apt-get install -y libsystemd-dev libgmock-dev clang + sudo update-alternatives --remove-all cc + sudo update-alternatives --install /usr/bin/cc cc /usr/bin/clang 10 + sudo update-alternatives --remove-all c++ + sudo update-alternatives --install /usr/bin/c++ c++ /usr/bin/clang++ 10 + - name: configure + run: | + cmake -B _build -DCMAKE_BUILD_TYPE=Debug -DCMAKE_CXX_FLAGS="-O0 -g" -DCMAKE_VERBOSE_MAKEFILE=ON -DSDBUSCPP_CLANG_TIDY=ON -DSDBUSCPP_BUILD_TESTS=ON -DSDBUSCPP_BUILD_PERF_TESTS=ON -DSDBUSCPP_BUILD_STRESS_TESTS=ON + - name: make + run: | + cmake --build _build -j4 freebsd-build: name: build (freebsd, clang/libc++, basu) runs-on: ubuntu-22.04 # until https://github.com/actions/runner/issues/385 From 698e3368082ceb34f9f9b4359ef00492c34742ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stanislav=20Angelovi=C4=8D?= Date: Thu, 8 Jan 2026 19:07:22 +0100 Subject: [PATCH 04/13] fix: address clang-tidy warnings in unit tests --- CMakeLists.txt | 4 +- tests/unittests/Connection_test.cpp | 32 ++++--- tests/unittests/Message_test.cpp | 110 +++++++++++++----------- tests/unittests/PollData_test.cpp | 48 +++++------ tests/unittests/TypeTraits_test.cpp | 114 +++++++++++++----------- tests/unittests/Types_test.cpp | 129 +++++++++++++++------------- 6 files changed, 238 insertions(+), 199 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index c580ac9e..76188c96 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -271,15 +271,15 @@ endif() if(SDBUSCPP_CLANG_TIDY) message(STATUS "Building with static analysis") - #set(CLANG_TIDY "/home/one/CLion2/clion-2024.3.5/bin/clang/linux/x64/bin/clang-tidy") find_program(CLANG_TIDY NAMES clang-tidy) if(NOT CLANG_TIDY) message(WARNING "clang-tidy not found") else() message(STATUS "clang-tidy found: ${CLANG_TIDY}") + # TODO: Check what happens if the targets don't exist set_target_properties(sdbus-c++-objlib PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY}") set_target_properties(sdbus-c++ PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY}") - #set_target_properties(sdbus-c++-unit-tests PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY}") + set_target_properties(sdbus-c++-unit-tests PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY}") #set_target_properties(sdbus-c++-integration-tests PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY}") set_target_properties(sdbus-c++-stress-tests PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY}") endif() diff --git a/tests/unittests/Connection_test.cpp b/tests/unittests/Connection_test.cpp index 88a2662c..5f116daf 100644 --- a/tests/unittests/Connection_test.cpp +++ b/tests/unittests/Connection_test.cpp @@ -26,10 +26,17 @@ */ #include "Connection.h" +#include "sdbus-c++/Error.h" #include "sdbus-c++/Types.h" #include "unittests/mocks/SdBusMock.h" -#include +#include // IWYU pragma: export +#include +#include +#include + +// NOLINTBEGIN(cppcoreguidelines-non-private-member-variables-in-classes,misc-non-private-member-variables-in-classes) +// NOLINTBEGIN(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp) using ::testing::_; using ::testing::DoAll; @@ -194,30 +201,33 @@ template<> std::unique_ptr AConnectionNameRequest(std::unique_ptr>(sdBusIntfMock_), Connection::remote_system_bus, "some host"); } -typedef ::testing::Types< Connection::default_bus_t - , Connection::system_bus_t - , Connection::session_bus_t - , Connection::custom_session_bus_t - , Connection::remote_system_bus_t - , Connection::pseudo_bus_t - > BusTypeTags; +using BusTypeTags = ::testing::Types< Connection::default_bus_t + , Connection::system_bus_t + , Connection::session_bus_t + , Connection::custom_session_bus_t + , Connection::remote_system_bus_t + , Connection::pseudo_bus_t + >; TYPED_TEST_SUITE(AConnectionNameRequest, BusTypeTags); -} +} // namespace TYPED_TEST(AConnectionNameRequest, DoesNotThrowOnSuccess) { EXPECT_CALL(*this->sdBusIntfMock_, sd_bus_request_name(_, _, _)).WillOnce(Return(1)); - sdbus::ConnectionName name{"org.sdbuscpp.somename"}; + const sdbus::ConnectionName name{"org.sdbuscpp.somename"}; this->con_->requestName(name); } TYPED_TEST(AConnectionNameRequest, ThrowsOnFail) { - sdbus::ConnectionName name{"org.sdbuscpp.somename"}; + const sdbus::ConnectionName name{"org.sdbuscpp.somename"}; EXPECT_CALL(*this->sdBusIntfMock_, sd_bus_request_name(_, _, _)).WillOnce(Return(-1)); ASSERT_THROW(this->con_->requestName(name), sdbus::Error); } + +// NOLINTEND(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp) +// NOLINTEND(cppcoreguidelines-non-private-member-variables-in-classes,misc-non-private-member-variables-in-classes) diff --git a/tests/unittests/Message_test.cpp b/tests/unittests/Message_test.cpp index d8ec5913..a6ce0c45 100644 --- a/tests/unittests/Message_test.cpp +++ b/tests/unittests/Message_test.cpp @@ -24,17 +24,25 @@ * along with sdbus-c++. If not, see . */ +#include +#include #include -#include "MessageUtils.h" +#include #include #include +#include #include #include +#include +#include +#include +#include +#include +#include using ::testing::Eq; using ::testing::StrEq; using ::testing::Gt; -using ::testing::DoubleEq; using ::testing::IsNull; using ::testing::SizeIs; using ::testing::ElementsAre; @@ -48,15 +56,15 @@ namespace msg >> str; return str; } -} +} // namespace namespace sdbus { - template - sdbus::Message& operator<<(sdbus::Message& msg, const std::list<_ElementType>& items) + template + sdbus::Message& operator<<(sdbus::Message& msg, const std::list& items) { // TODO: This can also be simplified on the basis of a callback (see dictionary...) - msg.openContainer<_ElementType>(); + msg.openContainer(); for (const auto& item : items) msg << item; @@ -66,15 +74,15 @@ namespace sdbus { return msg; } - template - sdbus::Message& operator>>(sdbus::Message& msg, std::list<_ElementType>& items) + template + sdbus::Message& operator>>(sdbus::Message& msg, std::list& items) { - if(!msg.enterContainer<_ElementType>()) + if(!msg.enterContainer()) return msg; while (true) { - _ElementType elem; + ElementType elem; if (msg >> elem) items.emplace_back(std::move(elem)); else @@ -88,15 +96,15 @@ namespace sdbus { return msg; } -} +} // namespace sdbus -template -struct sdbus::signature_of> - : sdbus::signature_of> +template +struct sdbus::signature_of> + : sdbus::signature_of> {}; namespace my { - enum class Enum + enum class Enum : std::uint8_t { Value1, Value2, @@ -105,42 +113,42 @@ namespace my { struct Struct { - int i; + int i{}; std::string s; std::list l; - Enum e; + Enum e{}; friend bool operator==(const Struct& lhs, const Struct& rhs) = default; }; struct RelaxedStruct { - int i; + int i{}; std::string s; std::list l; - Enum e; + Enum e{}; friend bool operator==(const RelaxedStruct& lhs, const RelaxedStruct& rhs) = default; }; struct NestedStruct { - int i; + int i{}; std::string s; - Enum e; + Enum e{}; Struct x; friend bool operator==(const NestedStruct& lhs, const NestedStruct& rhs) = default; }; -} +} // namespace my -SDBUSCPP_REGISTER_STRUCT(my::Struct, i, s, l, e); +SDBUSCPP_REGISTER_STRUCT(my::Struct, i, s, l, e); // NOLINT(readability-identifier-length) SDBUSCPP_ENABLE_RELAXED_DICT2STRUCT_DESERIALIZATION(my::RelaxedStruct); -SDBUSCPP_REGISTER_STRUCT(my::RelaxedStruct, i, s, l, e); +SDBUSCPP_REGISTER_STRUCT(my::RelaxedStruct, i, s, l, e); // NOLINT(readability-identifier-length) SDBUSCPP_ENABLE_NESTED_STRUCT2DICT_SERIALIZATION(my::NestedStruct); -SDBUSCPP_REGISTER_STRUCT(my::NestedStruct, i, s, e, x); +SDBUSCPP_REGISTER_STRUCT(my::NestedStruct, i, s, e, x); // NOLINT(readability-identifier-length) /*-------------------------------------*/ /* -- TEST CASES -- */ @@ -153,7 +161,7 @@ TEST(AMessage, CanBeDefaultConstructed) TEST(AMessage, IsInvalidAfterDefaultConstructed) { - sdbus::PlainMessage msg; + const sdbus::PlainMessage msg; ASSERT_FALSE(msg.isValid()); } @@ -218,7 +226,7 @@ TEST(AMessage, CanCarryASimpleInteger) msg << dataWritten; msg.seal(); - int dataRead; + int dataRead{}; msg >> dataRead; ASSERT_THAT(dataRead, Eq(dataWritten)); @@ -258,7 +266,7 @@ TEST(AMessage, CanCarryAVariant) { auto msg = sdbus::createPlainMessage(); - const auto dataWritten = sdbus::Variant((double)3.14); + const auto dataWritten = sdbus::Variant(3.14); msg << dataWritten; msg.seal(); @@ -273,7 +281,7 @@ TEST(AMessage, CanCarryACollectionOfEmbeddedVariants) { auto msg = sdbus::createPlainMessage(); - std::vector value{sdbus::Variant{"hello"s}, sdbus::Variant{(double)3.14}}; + std::vector value{sdbus::Variant{"hello"s}, sdbus::Variant{3.14}}; const auto dataWritten = sdbus::Variant{value}; msg << dataWritten; @@ -320,12 +328,12 @@ TEST(AMessage, CanCarryDBusArrayOfTrivialTypesGivenAsStdArray) { auto msg = sdbus::createPlainMessage(); - const std::array dataWritten{3545342, 43643532, 324325}; + const std::array dataWritten{3545342, 43643532, 324325}; msg << dataWritten; msg.seal(); - std::array dataRead; + std::array dataRead{}; msg >> dataRead; ASSERT_THAT(dataRead, Eq(dataWritten)); @@ -351,13 +359,13 @@ TEST(AMessage, CanCarryDBusArrayOfTrivialTypesGivenAsStdSpan) { auto msg = sdbus::createPlainMessage(); - const std::array sourceArray{3545342, 43643532, 324325}; + const std::array sourceArray{3545342, 43643532, 324325}; const std::span dataWritten{sourceArray}; msg << dataWritten; msg.seal(); - std::array destinationArray; + std::array destinationArray{}; std::span dataRead{destinationArray}; msg >> dataRead; @@ -386,8 +394,8 @@ TEST(AMessage, CanCarryAnEnumValue) { auto msg = sdbus::createPlainMessage(); - enum class EnumA : int16_t {X = 5} aWritten{EnumA::X}; - enum EnumB {Y = 11} bWritten{EnumB::Y}; + const enum class EnumA : int16_t {X = 5} aWritten{EnumA::X}; // NOLINT(performance-enum-size) + const enum EnumB {Y = 11} bWritten{EnumB::Y}; // NOLINT(performance-enum-size) msg << aWritten << bWritten; msg.seal(); @@ -409,7 +417,7 @@ TEST(AMessage, ThrowsWhenDestinationStdArrayIsTooSmallDuringDeserialization) msg << dataWritten; msg.seal(); - std::array dataRead; + std::array dataRead{}; ASSERT_THROW(msg >> dataRead, sdbus::Error); } @@ -423,7 +431,7 @@ TEST(AMessage, ThrowsWhenDestinationStdSpanIsTooSmallDuringDeserialization) msg << dataWritten; msg.seal(); - std::array destinationArray; + std::array destinationArray{}; std::span dataRead{destinationArray}; ASSERT_THROW(msg >> dataRead, sdbus::Error); } @@ -433,7 +441,7 @@ TEST(AMessage, CanCarryADictionary) { auto msg = sdbus::createPlainMessage(); - std::map dataWritten{{1, "one"}, {2, "two"}}; + const std::map dataWritten{{1, "one"}, {2, "two"}}; msg << dataWritten; msg.seal(); @@ -468,7 +476,7 @@ TEST(AMessage, CanCarryAComplexType) > >; - ComplexType dataWritten = { {1, {{{5, {{sdbus::ObjectPath{"/some/object"}, true, 45, {{6, "hello"}, {7, "world"}}}}}}, sdbus::Signature{"av"}, 3.14}}}; + const ComplexType dataWritten = { {1, {{{5, {{sdbus::ObjectPath{"/some/object"}, true, 45, {{6, "hello"}, {7, "world"}}}}}}, sdbus::Signature{"av"}, 3.14}}}; msg << dataWritten; msg.seal(); @@ -596,10 +604,10 @@ TEST(AMessage, CanDeserializeDictionaryOfStringsToVariantsIntoUserDefinedStruct) { auto msg = sdbus::createPlainMessage(); - std::map dataWritten{ {"i", sdbus::Variant{3545342}} - , {"s", sdbus::Variant{"hello"s}} - , {"l", sdbus::Variant{std::list{3.14, 2.4568546}}} - , {"e", sdbus::Variant{my::Enum::Value2}} }; + const std::map dataWritten{ {"i", sdbus::Variant{3545342}} + , {"s", sdbus::Variant{"hello"s}} + , {"l", sdbus::Variant{std::list{3.14, 2.4568546}}} + , {"e", sdbus::Variant{my::Enum::Value2}} }; msg << dataWritten; msg.seal(); @@ -614,10 +622,10 @@ TEST(AMessage, FailsDeserializingDictionaryIntoUserDefinedStructIfStructMemberIs { auto msg = sdbus::createPlainMessage(); - std::map dataWritten{ {"i", sdbus::Variant{3545342}} - , {"nonexistent", sdbus::Variant{"hello"s}} - , {"l", sdbus::Variant{std::list{3.14, 2.4568546}}} - , {"e", sdbus::Variant{my::Enum::Value2}} }; + const std::map dataWritten{ {"i", sdbus::Variant{3545342}} + , {"nonexistent", sdbus::Variant{"hello"s}} + , {"l", sdbus::Variant{std::list{3.14, 2.4568546}}} + , {"e", sdbus::Variant{my::Enum::Value2}} }; msg << dataWritten; msg.seal(); @@ -631,10 +639,10 @@ TEST(AMessage, DeserializesDictionaryIntoStructWithMissingMembersSuccessfullyIfR { auto msg = sdbus::createPlainMessage(); - std::map dataWritten{ {"some_nonexistent_struct_member", sdbus::Variant{3545342}} - , {"another_nonexistent_struct_member", sdbus::Variant{"hello"s}} - , {"l", sdbus::Variant{std::list{3.14, 2.4568546}}} - , {"e", sdbus::Variant{my::Enum::Value2}} }; + const std::map dataWritten{ {"some_nonexistent_struct_member", sdbus::Variant{3545342}} + , {"another_nonexistent_struct_member", sdbus::Variant{"hello"s}} + , {"l", sdbus::Variant{std::list{3.14, 2.4568546}}} + , {"e", sdbus::Variant{my::Enum::Value2}} }; msg << dataWritten; msg.seal(); diff --git a/tests/unittests/PollData_test.cpp b/tests/unittests/PollData_test.cpp index 7aabf51e..09e9d788 100644 --- a/tests/unittests/PollData_test.cpp +++ b/tests/unittests/PollData_test.cpp @@ -42,84 +42,84 @@ using namespace std::chrono_literals; TEST(PollData, ReturnsZeroRelativeTimeoutForZeroAbsoluteTimeout) { - sdbus::IConnection::PollData pd; - pd.timeout = std::chrono::microseconds::zero(); + sdbus::IConnection::PollData pollData{}; + pollData.timeout = std::chrono::microseconds::zero(); - auto relativeTimeout = pd.getRelativeTimeout(); + auto relativeTimeout = pollData.getRelativeTimeout(); EXPECT_THAT(relativeTimeout, Eq(std::chrono::microseconds::zero())); } TEST(PollData, ReturnsZeroPollTimeoutForZeroAbsoluteTimeout) { - sdbus::IConnection::PollData pd; - pd.timeout = std::chrono::microseconds::zero(); + sdbus::IConnection::PollData pollData{}; + pollData.timeout = std::chrono::microseconds::zero(); - auto pollTimeout = pd.getPollTimeout(); + auto pollTimeout = pollData.getPollTimeout(); EXPECT_THAT(pollTimeout, Eq(0)); } TEST(PollData, ReturnsInfiniteRelativeTimeoutForInfiniteAbsoluteTimeout) { - sdbus::IConnection::PollData pd; - pd.timeout = std::chrono::microseconds::max(); + sdbus::IConnection::PollData pollData{}; + pollData.timeout = std::chrono::microseconds::max(); - auto relativeTimeout = pd.getRelativeTimeout(); + auto relativeTimeout = pollData.getRelativeTimeout(); EXPECT_THAT(relativeTimeout, Eq(std::chrono::microseconds::max())); } TEST(PollData, ReturnsNegativePollTimeoutForInfiniteAbsoluteTimeout) { - sdbus::IConnection::PollData pd; - pd.timeout = std::chrono::microseconds::max(); + sdbus::IConnection::PollData pollData{}; + pollData.timeout = std::chrono::microseconds::max(); - auto pollTimeout = pd.getPollTimeout(); + auto pollTimeout = pollData.getPollTimeout(); EXPECT_THAT(pollTimeout, Eq(-1)); } TEST(PollData, ReturnsZeroRelativeTimeoutForPastAbsoluteTimeout) { - sdbus::IConnection::PollData pd; + sdbus::IConnection::PollData pollData{}; auto past = std::chrono::steady_clock::now() - 10s; - pd.timeout = std::chrono::duration_cast(past.time_since_epoch()); + pollData.timeout = std::chrono::duration_cast(past.time_since_epoch()); - auto relativeTimeout = pd.getRelativeTimeout(); + auto relativeTimeout = pollData.getRelativeTimeout(); EXPECT_THAT(relativeTimeout, Eq(0us)); } TEST(PollData, ReturnsZeroPollTimeoutForPastAbsoluteTimeout) { - sdbus::IConnection::PollData pd; + sdbus::IConnection::PollData pollData{}; auto past = std::chrono::steady_clock::now() - 10s; - pd.timeout = std::chrono::duration_cast(past.time_since_epoch()); + pollData.timeout = std::chrono::duration_cast(past.time_since_epoch()); - auto pollTimeout = pd.getPollTimeout(); + auto pollTimeout = pollData.getPollTimeout(); EXPECT_THAT(pollTimeout, Eq(0)); } TEST(PollData, ReturnsCorrectRelativeTimeoutForFutureAbsoluteTimeout) { - sdbus::IConnection::PollData pd; + sdbus::IConnection::PollData pollData{}; auto future = std::chrono::steady_clock::now() + 1s; - pd.timeout = std::chrono::duration_cast(future.time_since_epoch()); + pollData.timeout = std::chrono::duration_cast(future.time_since_epoch()); - auto relativeTimeout = pd.getRelativeTimeout(); + auto relativeTimeout = pollData.getRelativeTimeout(); EXPECT_THAT(relativeTimeout, AllOf(Ge(900ms), Le(1100ms))); } TEST(PollData, ReturnsCorrectPollTimeoutForFutureAbsoluteTimeout) { - sdbus::IConnection::PollData pd; + sdbus::IConnection::PollData pollData{}; auto future = std::chrono::steady_clock::now() + 1s; - pd.timeout = std::chrono::duration_cast(future.time_since_epoch()); + pollData.timeout = std::chrono::duration_cast(future.time_since_epoch()); - auto pollTimeout = pd.getPollTimeout(); + auto pollTimeout = pollData.getPollTimeout(); EXPECT_THAT(pollTimeout, AllOf(Ge(900), Le(1100))); } diff --git a/tests/unittests/TypeTraits_test.cpp b/tests/unittests/TypeTraits_test.cpp index d0b8cdd9..35504af6 100644 --- a/tests/unittests/TypeTraits_test.cpp +++ b/tests/unittests/TypeTraits_test.cpp @@ -30,6 +30,15 @@ #include #include #include +#include +#include +#include +#include +#include +#include +#include +#include +#include using ::testing::Eq; @@ -39,12 +48,12 @@ namespace // FIXTURE DEFINITION FOR TYPED TESTS // ---- - template + template class Type2DBusTypeSignatureConversion : public ::testing::Test { protected: - const std::string dbusTypeSignature_{getDBusTypeSignature()}; + std::string dbusTypeSignature_{getDBusTypeSignature()}; private: static std::string getDBusTypeSignature(); }; @@ -54,20 +63,22 @@ namespace A, B, C }; - enum struct SomeEnumStruct : int64_t + enum struct SomeEnumStruct : int64_t // NOLINT(performance-enum-size) { A, B, C }; - enum SomeClassicEnum + enum SomeClassicEnum // NOLINT(performance-enum-size) { A, B, C }; + // NOLINTNEXTLINE(cppcoreguidelines-macro-usage) #define TYPE(...) \ template <> \ std::string Type2DBusTypeSignatureConversion<__VA_ARGS__>::getDBusTypeSignature() \ /**/ + // NOLINTNEXTLINE(cppcoreguidelines-macro-usage) #define HAS_DBUS_TYPE_SIGNATURE(_SIG) \ { \ return (_SIG); \ @@ -132,46 +143,45 @@ namespace >; TYPE(ComplexType)HAS_DBUS_TYPE_SIGNATURE("a{t(a{ya(oanbva{is})}ghss)}") - typedef ::testing::Types< bool - , uint8_t - , int16_t - , uint16_t - , int32_t - , uint32_t - , int64_t - , uint64_t - , double - , const char* - , std::string - , std::string_view - , sdbus::BusName - , sdbus::InterfaceName - , sdbus::MemberName - , sdbus::ObjectPath - , sdbus::Signature - , sdbus::Variant - , std::variant - , sdbus::UnixFd - , sdbus::Struct - , sdbus::Struct - , std::vector - , std::array + using DBusSupportedTypes = ::testing::Types< bool + , uint8_t + , int16_t + , uint16_t + , int32_t + , uint32_t + , int64_t + , uint64_t + , double + , const char* + , std::string + , std::string_view + , sdbus::BusName + , sdbus::InterfaceName + , sdbus::MemberName + , sdbus::ObjectPath + , sdbus::Signature + , sdbus::Variant + , std::variant + , sdbus::UnixFd + , sdbus::Struct + , sdbus::Struct + , std::vector + , std::array #ifdef __cpp_lib_span - , std::span + , std::span #endif - , SomeEnumClass - , const SomeEnumClass - , volatile SomeEnumClass - , const volatile SomeEnumClass - , SomeEnumStruct - , SomeClassicEnum - , std::map - , std::unordered_map - , ComplexType - > DBusSupportedTypes; + , SomeEnumClass + , const SomeEnumClass + , volatile SomeEnumClass + , const volatile SomeEnumClass + , SomeEnumStruct + , SomeClassicEnum + , std::map + , std::unordered_map + , ComplexType >; TYPED_TEST_SUITE(Type2DBusTypeSignatureConversion, DBusSupportedTypes); -} +} // namespace /*-------------------------------------*/ /* -- TEST CASES -- */ @@ -189,11 +199,11 @@ TEST(FreeFunctionTypeTraits, DetectsTraitsOfTrivialSignatureFunction) using Fnc = decltype(f); static_assert(!sdbus::is_async_method_v, "Free function incorrectly detected as async method"); - static_assert(std::is_same, std::tuple<>>::value, "Incorrectly detected free function parameters"); - static_assert(std::is_same, std::tuple<>>::value, "Incorrectly detected tuple of free function parameters"); - static_assert(std::is_same, void>::value, "Incorrectly detected tuple of free function return types"); + static_assert(std::is_same_v, std::tuple<>>, "Incorrectly detected free function parameters"); + static_assert(std::is_same_v, std::tuple<>>, "Incorrectly detected tuple of free function parameters"); + static_assert(std::is_same_v, void>, "Incorrectly detected tuple of free function return types"); static_assert(sdbus::function_argument_count_v == 0, "Incorrectly detected free function parameter count"); - static_assert(std::is_void>::value, "Incorrectly detected free function return type"); + static_assert(std::is_void_v>, "Incorrectly detected free function return type"); } TEST(FreeFunctionTypeTraits, DetectsTraitsOfNontrivialSignatureFunction) @@ -202,11 +212,11 @@ TEST(FreeFunctionTypeTraits, DetectsTraitsOfNontrivialSignatureFunction) using Fnc = decltype(f); static_assert(!sdbus::is_async_method_v, "Free function incorrectly detected as async method"); - static_assert(std::is_same, std::tuple>::value, "Incorrectly detected free function parameters"); - static_assert(std::is_same, std::tuple>::value, "Incorrectly detected tuple of free function parameters"); - static_assert(std::is_same, std::tuple>::value, "Incorrectly detected tuple of free function return types"); + static_assert(std::is_same_v, std::tuple>, "Incorrectly detected free function parameters"); + static_assert(std::is_same_v, std::tuple>, "Incorrectly detected tuple of free function parameters"); + static_assert(std::is_same_v, std::tuple>, "Incorrectly detected tuple of free function return types"); static_assert(sdbus::function_argument_count_v == 3, "Incorrectly detected free function parameter count"); - static_assert(std::is_same, std::tuple>::value, "Incorrectly detected free function return type"); + static_assert(std::is_same_v, std::tuple>, "Incorrectly detected free function return type"); } TEST(FreeFunctionTypeTraits, DetectsTraitsOfAsyncFunction) @@ -215,9 +225,9 @@ TEST(FreeFunctionTypeTraits, DetectsTraitsOfAsyncFunction) using Fnc = decltype(f); static_assert(sdbus::is_async_method_v, "Free async function incorrectly detected as sync method"); - static_assert(std::is_same, std::tuple>::value, "Incorrectly detected free function parameters"); - static_assert(std::is_same, std::tuple>::value, "Incorrectly detected tuple of free function parameters"); - static_assert(std::is_same, std::tuple>::value, "Incorrectly detected tuple of free function return types"); + static_assert(std::is_same_v, std::tuple>, "Incorrectly detected free function parameters"); + static_assert(std::is_same_v, std::tuple>, "Incorrectly detected tuple of free function parameters"); + static_assert(std::is_same_v, std::tuple>, "Incorrectly detected tuple of free function return types"); static_assert(sdbus::function_argument_count_v == 3, "Incorrectly detected free function parameter count"); - static_assert(std::is_same, std::tuple>::value, "Incorrectly detected free function return type"); + static_assert(std::is_same_v, std::tuple>, "Incorrectly detected free function return type"); } diff --git a/tests/unittests/Types_test.cpp b/tests/unittests/Types_test.cpp index bd3bc97f..0a5baf06 100644 --- a/tests/unittests/Types_test.cpp +++ b/tests/unittests/Types_test.cpp @@ -24,12 +24,24 @@ * along with sdbus-c++. If not, see . */ +#include +#include #include -#include "MessageUtils.h" +#include + #include #include #include +#include +#include +#include +#include +#include #include +#include +#include +#include +#include using ::testing::Eq; using ::testing::Gt; @@ -39,7 +51,7 @@ namespace { constexpr const uint64_t ANY_UINT64 = 84578348354; constexpr const double ANY_DOUBLE = 3.14; -} +} // namespace /*-------------------------------------*/ /* -- TEST CASES -- */ @@ -52,14 +64,14 @@ TEST(AVariant, CanBeDefaultConstructed) TEST(AVariant, ContainsNoValueAfterDefaultConstructed) { - sdbus::Variant v; + const sdbus::Variant var; - ASSERT_TRUE(v.isEmpty()); + ASSERT_TRUE(var.isEmpty()); } TEST(AVariant, CanBeConstructedFromASimpleValue) { - int value = 5; + const int value = 5; ASSERT_NO_THROW(sdbus::Variant{value}); } @@ -67,7 +79,7 @@ TEST(AVariant, CanBeConstructedFromASimpleValue) TEST(AVariant, CanBeConstructedFromAComplexValue) { using ComplexType = std::map>>; - ComplexType value{ {ANY_UINT64, ComplexType::mapped_type{{"hello"s, ANY_DOUBLE}, {"world"s, ANY_DOUBLE}}} }; + const ComplexType value{ {ANY_UINT64, ComplexType::mapped_type{{"hello"s, ANY_DOUBLE}, {"world"s, ANY_DOUBLE}}} }; ASSERT_NO_THROW(sdbus::Variant{value}); } @@ -77,9 +89,9 @@ TEST(AVariant, CanBeConstructedFromAnStdVariant) using ComplexType = std::vector>; using StdVariantType = std::variant; ComplexType value{{"hello"s, ANY_DOUBLE}, {"world"s, ANY_DOUBLE}}; - StdVariantType stdVariant{value}; + const StdVariantType stdVariant{value}; - sdbus::Variant sdbusVariant{stdVariant}; + const sdbus::Variant sdbusVariant{stdVariant}; ASSERT_TRUE(sdbusVariant.containsValueOfType()); ASSERT_THAT(sdbusVariant.get(), Eq(value)); @@ -88,10 +100,10 @@ TEST(AVariant, CanBeConstructedFromAnStdVariant) TEST(AVariant, CanBeCopied) { auto value = "hello"s; - sdbus::Variant variant(value); + const sdbus::Variant variant(value); - auto variantCopy1{variant}; - auto variantCopy2 = variantCopy1; + const auto variantCopy1{variant}; // NOLINT(performance-unnecessary-copy-initialization) + const auto variantCopy2 = variantCopy1; // NOLINT(performance-unnecessary-copy-initialization) ASSERT_THAT(variantCopy1.get(), Eq(value)); ASSERT_THAT(variantCopy2.get(), Eq(value)); @@ -105,33 +117,33 @@ TEST(AVariant, CanBeMoved) auto movedVariant{std::move(variant)}; ASSERT_THAT(movedVariant.get(), Eq(value)); - ASSERT_TRUE(variant.isEmpty()); + ASSERT_TRUE(variant.isEmpty()); // NOLINT(bugprone-use-after-move,hicpp-invalid-access-moved) } TEST(AVariant, CanBeMovedIntoAMap) { - auto value = "hello"s; - sdbus::Variant variant(value); + const auto value = "hello"s; + sdbus::Variant variant(value); // NOLINT(misc-const-correctness) std::map mymap; mymap.try_emplace("payload", std::move(variant)); ASSERT_THAT(mymap["payload"].get(), Eq(value)); - ASSERT_TRUE(variant.isEmpty()); + ASSERT_TRUE(variant.isEmpty()); // NOLINT(bugprone-use-after-move,hicpp-invalid-access-moved) } TEST(AVariant, IsNotEmptyWhenContainsAValue) { - sdbus::Variant v("hello"); + const sdbus::Variant var("hello"); - ASSERT_FALSE(v.isEmpty()); + ASSERT_FALSE(var.isEmpty()); } TEST(ASimpleVariant, ReturnsTheSimpleValueWhenAsked) { - int value = 5; + const int value = 5; - sdbus::Variant variant(value); + const sdbus::Variant variant(value); ASSERT_THAT(variant.get(), Eq(value)); } @@ -139,17 +151,17 @@ TEST(ASimpleVariant, ReturnsTheSimpleValueWhenAsked) TEST(AComplexVariant, ReturnsTheComplexValueWhenAsked) { using ComplexType = std::map>>; - ComplexType value{ {ANY_UINT64, ComplexType::mapped_type{{"hello"s, ANY_DOUBLE}, {"world"s, ANY_DOUBLE}}} }; + const ComplexType value{ {ANY_UINT64, ComplexType::mapped_type{{"hello"s, ANY_DOUBLE}, {"world"s, ANY_DOUBLE}}} }; - sdbus::Variant variant(value); + const sdbus::Variant variant(value); - ASSERT_THAT(variant.get(), Eq(value)); + ASSERT_THAT(variant.get(), Eq(value)); } TEST(AVariant, HasConceptuallyNonmutableGetMethodWhichCanBeCalledXTimes) { - std::string value{"I am a string"}; - sdbus::Variant variant(value); + const std::string value{"I am a string"}; + const sdbus::Variant variant(value); ASSERT_THAT(variant.get(), Eq(value)); ASSERT_THAT(variant.get(), Eq(value)); @@ -159,9 +171,9 @@ TEST(AVariant, HasConceptuallyNonmutableGetMethodWhichCanBeCalledXTimes) TEST(AVariant, ReturnsTrueWhenAskedIfItContainsTheTypeItReallyContains) { using ComplexType = std::map>>; - ComplexType value{ {ANY_UINT64, ComplexType::mapped_type{{"hello"s, ANY_DOUBLE}, {"world"s, ANY_DOUBLE}}} }; + const ComplexType value{ {ANY_UINT64, ComplexType::mapped_type{{"hello"s, ANY_DOUBLE}, {"world"s, ANY_DOUBLE}}} }; - sdbus::Variant variant(value); + const sdbus::Variant variant(value); ASSERT_TRUE(variant.containsValueOfType()); } @@ -170,8 +182,8 @@ TEST(AVariant, CanBeConvertedIntoAnStdVariant) { using ComplexType = std::vector>; using StdVariantType = std::variant; - ComplexType value{{"hello"s, ANY_DOUBLE}, {"world"s, ANY_DOUBLE}}; - sdbus::Variant sdbusVariant{value}; + const ComplexType value{{"hello"s, ANY_DOUBLE}, {"world"s, ANY_DOUBLE}}; + const sdbus::Variant sdbusVariant{value}; StdVariantType stdVariant{sdbusVariant}; ASSERT_TRUE(std::holds_alternative(stdVariant)); @@ -183,18 +195,18 @@ TEST(AVariant, IsImplicitlyInterchangeableWithStdVariant) using ComplexType = std::vector>; using StdVariantType = std::variant; ComplexType value{{"hello"s, ANY_DOUBLE}, {"world"s, ANY_DOUBLE}}; - StdVariantType stdVariant{value}; + const StdVariantType stdVariant{value}; - auto stdVariantCopy = [](const sdbus::Variant &v) -> StdVariantType { return v; }(stdVariant); + auto stdVariantCopy = [](const sdbus::Variant &var) -> StdVariantType { return var; }(stdVariant); ASSERT_THAT(stdVariantCopy, Eq(stdVariant)); } TEST(ASimpleVariant, ReturnsFalseWhenAskedIfItContainsTypeItDoesntReallyContain) { - int value = 5; + const int value = 5; - sdbus::Variant variant(value); + const sdbus::Variant variant(value); ASSERT_FALSE(variant.containsValueOfType()); } @@ -203,17 +215,17 @@ TEST(AVariant, CanContainOtherEmbeddedVariants) { using TypeWithVariants = std::vector>; TypeWithVariants value; - value.push_back({sdbus::Variant("a string"), ANY_DOUBLE}); - value.push_back({sdbus::Variant(ANY_UINT64), ANY_DOUBLE}); + value.emplace_back(sdbus::Variant("a string"), ANY_DOUBLE); + value.emplace_back(sdbus::Variant(ANY_UINT64), ANY_DOUBLE); - sdbus::Variant variant(value); + const sdbus::Variant variant(value); ASSERT_TRUE(variant.containsValueOfType()); } TEST(ANonEmptyVariant, SerializesSuccessfullyToAMessage) { - sdbus::Variant variant("a string"); + const sdbus::Variant variant("a string"); auto msg = sdbus::createPlainMessage(); @@ -222,7 +234,7 @@ TEST(ANonEmptyVariant, SerializesSuccessfullyToAMessage) TEST(AnEmptyVariant, ThrowsWhenBeingSerializedToAMessage) { - sdbus::Variant variant; + const sdbus::Variant variant; auto msg = sdbus::createPlainMessage(); @@ -232,8 +244,8 @@ TEST(AnEmptyVariant, ThrowsWhenBeingSerializedToAMessage) TEST(ANonEmptyVariant, SerializesToAndDeserializesFromAMessageSuccessfully) { using ComplexType = std::map>>; - ComplexType value{ {ANY_UINT64, ComplexType::mapped_type{{"hello"s, ANY_DOUBLE}, {"world"s, ANY_DOUBLE}}} }; - sdbus::Variant variant(value); + const ComplexType value{ {ANY_UINT64, ComplexType::mapped_type{{"hello"s, ANY_DOUBLE}, {"world"s, ANY_DOUBLE}}} }; + const sdbus::Variant variant(value); auto msg = sdbus::createPlainMessage(); variant.serializeTo(msg); @@ -241,30 +253,30 @@ TEST(ANonEmptyVariant, SerializesToAndDeserializesFromAMessageSuccessfully) sdbus::Variant variant2; variant2.deserializeFrom(msg); - ASSERT_THAT(variant2.get(), Eq(value)); + ASSERT_THAT(variant2.get(), Eq(value)); } TEST(CopiesOfVariant, SerializeToAndDeserializeFromMessageSuccessfully) { using ComplexType = std::map>>; - ComplexType value{ {ANY_UINT64, ComplexType::mapped_type{{"hello"s, ANY_DOUBLE}, {"world"s, ANY_DOUBLE}}} }; - sdbus::Variant variant(value); - auto variantCopy1{variant}; - auto variantCopy2 = variant; + const ComplexType value{ {ANY_UINT64, ComplexType::mapped_type{{"hello"s, ANY_DOUBLE}, {"world"s, ANY_DOUBLE}}} }; + const sdbus::Variant variant(value); + auto variantCopy1{variant}; // NOLINT(performance-unnecessary-copy-initialization) + auto variantCopy2 = variant; // NOLINT(performance-unnecessary-copy-initialization) auto msg = sdbus::createPlainMessage(); variant.serializeTo(msg); variantCopy1.serializeTo(msg); variantCopy2.serializeTo(msg); msg.seal(); - sdbus::Variant receivedVariant1, receivedVariant2, receivedVariant3; + sdbus::Variant receivedVariant1, receivedVariant2, receivedVariant3; // NOLINT(readability-isolate-declaration) receivedVariant1.deserializeFrom(msg); receivedVariant2.deserializeFrom(msg); receivedVariant3.deserializeFrom(msg); - ASSERT_THAT(receivedVariant1.get(), Eq(value)); - ASSERT_THAT(receivedVariant2.get(), Eq(value)); - ASSERT_THAT(receivedVariant3.get(), Eq(value)); + ASSERT_THAT(receivedVariant1.get(), Eq(value)); + ASSERT_THAT(receivedVariant2.get(), Eq(value)); + ASSERT_THAT(receivedVariant3.get(), Eq(value)); } TEST(AStruct, CanBeCreatedFromStdTuple) @@ -295,7 +307,7 @@ TEST(AStruct, CanBeUsedLikeStdTupleType) TEST(AStruct, CanBeUsedInStructuredBinding) { - sdbus::Struct valueStruct(1234, "abcd", true); + const sdbus::Struct valueStruct(1234, "abcd", true); auto [first, second, third] = valueStruct; @@ -311,7 +323,7 @@ TEST(AnObjectPath, CanBeConstructedFromCString) TEST(AnObjectPath, CanBeConstructedFromStdString) { - std::string aPath{"/some/path"}; + const std::string aPath{"/some/path"}; ASSERT_THAT(sdbus::ObjectPath{aPath}, Eq(aPath)); } @@ -322,7 +334,6 @@ TEST(AnObjectPath, CanBeMovedLikeAStdString) sdbus::ObjectPath oPath{aPath}; ASSERT_THAT(sdbus::ObjectPath{std::move(oPath)}, Eq(sdbus::ObjectPath(std::move(aPath)))); - ASSERT_THAT(std::string(oPath), Eq(aPath)); } TEST(ASignature, CanBeConstructedFromCString) @@ -334,7 +345,7 @@ TEST(ASignature, CanBeConstructedFromCString) TEST(ASignature, CanBeConstructedFromStdString) { - std::string aSignature{"us"}; + const std::string aSignature{"us"}; ASSERT_THAT(sdbus::Signature{aSignature}, Eq(aSignature)); } @@ -365,9 +376,9 @@ TEST(AUnixFd, AdoptsAndOwnsFdAsIsUponAdoptionConstruction) TEST(AUnixFd, DuplicatesFdUponCopyConstruction) { - sdbus::UnixFd unixFd(::eventfd(0, EFD_SEMAPHORE | EFD_NONBLOCK)); + const sdbus::UnixFd unixFd(::eventfd(0, EFD_SEMAPHORE | EFD_NONBLOCK)); - sdbus::UnixFd unixFdCopy{unixFd}; + const sdbus::UnixFd unixFdCopy{unixFd}; // NOLINT(performance-unnecessary-copy-initialization) EXPECT_THAT(unixFdCopy.get(), Gt(unixFd.get())); } @@ -377,20 +388,20 @@ TEST(AUnixFd, TakesOverFdUponMoveConstruction) auto fd = ::eventfd(0, EFD_SEMAPHORE | EFD_NONBLOCK); sdbus::UnixFd unixFd(fd, sdbus::adopt_fd); - sdbus::UnixFd unixFdNew{std::move(unixFd)}; + const sdbus::UnixFd unixFdNew{std::move(unixFd)}; - EXPECT_FALSE(unixFd.isValid()); + EXPECT_FALSE(unixFd.isValid()); // NOLINT(bugprone-use-after-move,hicpp-invalid-access-moved,clang-analyzer-cplusplus.Move) EXPECT_THAT(unixFdNew.get(), Eq(fd)); } TEST(AUnixFd, ClosesFdProperlyUponDestruction) { - int fd, fdCopy; + int fd{}, fdCopy{}; // NOLINT(readability-isolate-declaration) { fd = ::eventfd(0, EFD_SEMAPHORE | EFD_NONBLOCK); sdbus::UnixFd unixFd(fd, sdbus::adopt_fd); auto unixFdNew = std::move(unixFd); - auto unixFdCopy = unixFdNew; + auto unixFdCopy = unixFdNew; // NOLINT(performance-unnecessary-copy-initialization) fdCopy = unixFdCopy.get(); } @@ -401,7 +412,7 @@ TEST(AUnixFd, ClosesFdProperlyUponDestruction) TEST(AUnixFd, DoesNotCloseReleasedFd) { auto fd = ::eventfd(0, EFD_SEMAPHORE | EFD_NONBLOCK); - int fdReleased; + int fdReleased{}; { sdbus::UnixFd unixFd(fd, sdbus::adopt_fd); fdReleased = unixFd.release(); From 238aa0a4e62b1bda495994d2aa56b65f031e9470 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stanislav=20Angelovi=C4=8D?= Date: Fri, 9 Jan 2026 17:04:06 +0100 Subject: [PATCH 05/13] fix: address clang-tidy warnings in perf tests --- .clang-tidy | 4 +-- tests/perftests/client.cpp | 60 +++++++++++++++++++++++--------------- tests/perftests/server.cpp | 29 +++++++++++++----- 3 files changed, 59 insertions(+), 34 deletions(-) diff --git a/.clang-tidy b/.clang-tidy index e17fe36c..5559081a 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -42,7 +42,7 @@ CheckOptions: - key: hicpp-special-member-functions.AllowSoleDefaultDtor value: '1' - key: readability-identifier-length.IgnoredVariableNames - value: 'r|fd|id|ok|it' + value: 'r|fd|id|ok|it|ts' - key: readability-identifier-length.IgnoredParameterNames value: 'fd|id|b' - key: performance-move-const-arg.CheckTriviallyCopyableMove @@ -50,7 +50,7 @@ CheckOptions: - key: hicpp-move-const-arg.CheckTriviallyCopyableMove value: '0' - key: misc-include-cleaner.IgnoreHeaders - value: 'systemd/.*|gtest/.*|gmock/.*|bits/chrono.h|bits/basic_string.h|time.h|poll.h' + value: 'systemd/.*|gtest/.*|gmock/.*|bits/chrono.h|bits/basic_string.h|time.h|poll.h|stdlib.h' - key: readability-simplify-boolean-expr.IgnoreMacros value: '1' - key: cppcoreguidelines-rvalue-reference-param-not-moved.IgnoreUnnamedParams diff --git a/tests/perftests/client.cpp b/tests/perftests/client.cpp index fcc83d17..52dcd30a 100644 --- a/tests/perftests/client.cpp +++ b/tests/perftests/client.cpp @@ -25,20 +25,22 @@ */ #include "perftests-proxy.h" +#include +#include +#include +#include #include -#include +#include #include #include -#include #include #include #include #include -#include using namespace std::chrono_literals; -uint64_t totalDuration = 0; +uint64_t totalDuration = 0; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables) class PerftestProxy final : public sdbus::ProxyInterfaces { @@ -49,13 +51,18 @@ class PerftestProxy final : public sdbus::ProxyInterfaces startTime; @@ -71,7 +78,7 @@ class PerftestProxy final : public sdbus::ProxyInterfaces(stopTime - startTime).count(); totalDuration += duration; - std::cout << "Received " << m_msgCount << " signals in: " << duration << " ms" << std::endl; + std::cout << "Received " << m_msgCount << " signals in: " << duration << " ms" << '\n'; counter = 0; } } @@ -90,8 +97,13 @@ std::string createRandomString(size_t length) "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"; const size_t max_index = (sizeof(charset) - 1); - return charset[ rand() % max_index ]; + return charset[ random() % max_index ]; }; + + struct timespec ts{}; + (void)timespec_get(&ts, TIME_UTC); + srandom(ts.tv_nsec ^ ts.tv_sec); /* Seed the PRNG */ + std::string str(length, 0); std::generate_n(str.begin(), length, randchar); return str; @@ -106,44 +118,44 @@ int main(int /*argc*/, char */*argv*/[]) PerftestProxy client(std::move(destination), std::move(objectPath)); const unsigned int repetitions{20}; - unsigned int msgCount = 1000; + unsigned int const msgCount = 1000; unsigned int msgSize{}; msgSize = 20; - std::cout << "** Measuring signals of size " << msgSize << " bytes (" << repetitions << " repetitions)..." << std::endl << std::endl; + std::cout << "** Measuring signals of size " << msgSize << " bytes (" << repetitions << " repetitions)..." << '\n' << '\n'; client.m_msgCount = msgCount; client.m_msgSize = msgSize; - for (unsigned int r = 0; r < repetitions; ++r) + for (unsigned int i = 0; i < repetitions; ++i) { client.sendDataSignals(msgCount, msgSize); std::this_thread::sleep_for(1000ms); } - std::cout << "AVERAGE: " << (totalDuration/repetitions) << " ms" << std::endl; + std::cout << "AVERAGE: " << (totalDuration/repetitions) << " ms" << '\n'; totalDuration = 0; msgSize = 1000; - std::cout << std::endl << "** Measuring signals of size " << msgSize << " bytes (" << repetitions << " repetitions)..." << std::endl << std::endl; + std::cout << '\n' << "** Measuring signals of size " << msgSize << " bytes (" << repetitions << " repetitions)..." << '\n' << '\n'; client.m_msgCount = msgCount; client.m_msgSize = msgSize; - for (unsigned int r = 0; r < repetitions; ++r) + for (unsigned int i = 0; i < repetitions; ++i) { client.sendDataSignals(msgCount, msgSize); std::this_thread::sleep_for(1000ms); } - std::cout << "AVERAGE: " << (totalDuration/repetitions) << " ms" << std::endl; + std::cout << "AVERAGE: " << (totalDuration/repetitions) << " ms" << '\n'; totalDuration = 0; msgSize = 20; - std::cout << std::endl << "** Measuring method calls of size " << msgSize << " bytes (" << repetitions << " repetitions)..." << std::endl << std::endl; - for (unsigned int r = 0; r < repetitions; ++r) + std::cout << '\n' << "** Measuring method calls of size " << msgSize << " bytes (" << repetitions << " repetitions)..." << '\n' << '\n'; + for (unsigned int i = 0; i < repetitions; ++i) { auto str1 = createRandomString(msgSize/2); auto str2 = createRandomString(msgSize/2); auto startTime = std::chrono::steady_clock::now(); - for (unsigned int i = 0; i < msgCount; i++) + for (unsigned int j = 0; j < msgCount; j++) { auto result = client.concatenateTwoStrings(str1, str2); @@ -153,23 +165,23 @@ int main(int /*argc*/, char */*argv*/[]) auto stopTime = std::chrono::steady_clock::now(); auto duration = std::chrono::duration_cast(stopTime - startTime).count(); totalDuration += duration; - std::cout << "Called " << msgCount << " methods in: " << duration << " ms" << std::endl; + std::cout << "Called " << msgCount << " methods in: " << duration << " ms" << '\n'; std::this_thread::sleep_for(1000ms); } - std::cout << "AVERAGE: " << (totalDuration/repetitions) << " ms" << std::endl; + std::cout << "AVERAGE: " << (totalDuration/repetitions) << " ms" << '\n'; totalDuration = 0; msgSize = 1000; - std::cout << std::endl << "** Measuring method calls of size " << msgSize << " bytes (" << repetitions << " repetitions)..." << std::endl << std::endl; - for (unsigned int r = 0; r < repetitions; ++r) + std::cout << '\n' << "** Measuring method calls of size " << msgSize << " bytes (" << repetitions << " repetitions)..." << '\n' << '\n'; + for (unsigned int i = 0; i < repetitions; ++i) { auto str1 = createRandomString(msgSize/2); auto str2 = createRandomString(msgSize/2); auto startTime = std::chrono::steady_clock::now(); - for (unsigned int i = 0; i < msgCount; i++) + for (unsigned int j = 0; j < msgCount; j++) { auto result = client.concatenateTwoStrings(str1, str2); @@ -179,12 +191,12 @@ int main(int /*argc*/, char */*argv*/[]) auto stopTime = std::chrono::steady_clock::now(); auto duration = std::chrono::duration_cast(stopTime - startTime).count(); totalDuration += duration; - std::cout << "Called " << msgCount << " methods in: " << duration << " ms" << std::endl; + std::cout << "Called " << msgCount << " methods in: " << duration << " ms" << '\n'; std::this_thread::sleep_for(1000ms); } - std::cout << "AVERAGE: " << (totalDuration/repetitions) << " ms" << std::endl; + std::cout << "AVERAGE: " << (totalDuration/repetitions) << " ms" << '\n'; totalDuration = 0; return 0; diff --git a/tests/perftests/server.cpp b/tests/perftests/server.cpp index f88d2b20..82bca57d 100644 --- a/tests/perftests/server.cpp +++ b/tests/perftests/server.cpp @@ -25,10 +25,13 @@ */ #include "perftests-adaptor.h" +#include +#include +#include +#include #include -#include +#include #include -#include #include #include #include @@ -46,13 +49,18 @@ class PerftestAdaptor final : public sdbus::AdaptorInterfaces(stop_time - start_time).count() << " ms" << std::endl; + std::cout << "Server sent " << numberOfSignals << " signals in: " << std::chrono::duration_cast(stop_time - start_time).count() << " ms" << '\n'; } - virtual std::string concatenateTwoStrings(const std::string& string1, const std::string& string2) override + std::string concatenateTwoStrings(const std::string& string1, const std::string& string2) override { return string1 + string2; } @@ -81,8 +89,13 @@ std::string createRandomString(size_t length) "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"; const size_t max_index = (sizeof(charset) - 1); - return charset[ rand() % max_index ]; + return charset[ random() % max_index ]; }; + + struct timespec ts{}; + (void)timespec_get(&ts, TIME_UTC); + srandom(ts.tv_nsec ^ ts.tv_sec); /* Seed the PRNG */ + std::string str(length, 0); std::generate_n(str.begin(), length, randchar); return str; @@ -92,11 +105,11 @@ std::string createRandomString(size_t length) //----------------------------------------- int main(int /*argc*/, char */*argv*/[]) { - sdbus::ServiceName serviceName{"org.sdbuscpp.perftests"}; + sdbus::ServiceName const serviceName{"org.sdbuscpp.perftests"}; auto connection = sdbus::createSystemBusConnection(serviceName); sdbus::ObjectPath objectPath{"/org/sdbuscpp/perftests"}; - PerftestAdaptor server(*connection, std::move(objectPath)); + PerftestAdaptor server(*connection, std::move(objectPath)); // NOLINT(misc-const-correctness) connection->enterEventLoop(); } From 5ad5835014233f36d84e27b69ffdc5713ae3e358 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stanislav=20Angelovi=C4=8D?= Date: Fri, 9 Jan 2026 17:44:35 +0100 Subject: [PATCH 06/13] chore: don't check tools code by clang-tidy --- tools/CMakeLists.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/tools/CMakeLists.txt b/tools/CMakeLists.txt index 23aeb258..d220550e 100644 --- a/tools/CMakeLists.txt +++ b/tools/CMakeLists.txt @@ -36,6 +36,7 @@ set(SDBUSCPP_XML2CPP_SRCS #------------------------------- set(CMAKE_CXX_STANDARD 14) +unset(CMAKE_CXX_CLANG_TIDY) # Do not propagate clang-tidy to tools #---------------------------------- # EXECUTABLE BUILD INFORMATION From 27d3084295ea95f58a6575db94732b73c1d94e96 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stanislav=20Angelovi=C4=8D?= Date: Fri, 9 Jan 2026 17:44:57 +0100 Subject: [PATCH 07/13] fix: address clang-tidy warnings in integration tests --- .clang-tidy | 5 +- include/sdbus-c++/TypeTraits.h | 12 ++++ .../DBusAsyncMethodsTests.cpp | 40 ++++++----- .../integrationtests/DBusConnectionTests.cpp | 7 +- tests/integrationtests/DBusGeneralTests.cpp | 32 ++++----- tests/integrationtests/DBusMethodsTests.cpp | 57 ++++++++------- .../integrationtests/DBusPropertiesTests.cpp | 21 ++---- tests/integrationtests/DBusSignalsTests.cpp | 18 +++-- .../DBusStandardInterfacesTests.cpp | 46 +++++++------ tests/integrationtests/TestAdaptor.cpp | 69 ++++++++++++------- tests/integrationtests/TestAdaptor.h | 20 +++--- tests/integrationtests/TestFixture.cpp | 7 +- tests/integrationtests/TestProxy.cpp | 36 ++++++---- tests/integrationtests/TestProxy.h | 4 +- 14 files changed, 200 insertions(+), 174 deletions(-) diff --git a/.clang-tidy b/.clang-tidy index 5559081a..ba9ae4e9 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -18,6 +18,7 @@ Checks: "*,\ -readability-named-parameter,\ -bugprone-macro-parentheses,\ -google-readability-todo,\ + -google-build-using-namespace,\ -cppcoreguidelines-pro-type-reinterpret-cast,\ -cppcoreguidelines-pro-bounds-array-to-pointer-decay,\ -hicpp-no-array-decay,\ @@ -42,7 +43,7 @@ CheckOptions: - key: hicpp-special-member-functions.AllowSoleDefaultDtor value: '1' - key: readability-identifier-length.IgnoredVariableNames - value: 'r|fd|id|ok|it|ts' + value: 'r|t|fd|id|ok|it|ts' - key: readability-identifier-length.IgnoredParameterNames value: 'fd|id|b' - key: performance-move-const-arg.CheckTriviallyCopyableMove @@ -50,7 +51,7 @@ CheckOptions: - key: hicpp-move-const-arg.CheckTriviallyCopyableMove value: '0' - key: misc-include-cleaner.IgnoreHeaders - value: 'systemd/.*|gtest/.*|gmock/.*|bits/chrono.h|bits/basic_string.h|time.h|poll.h|stdlib.h' + value: 'systemd/.*|sdbus-c\+\+/.*|gtest/.*|gmock/.*|bits/chrono.h|bits/basic_string.h|time.h|poll.h|stdlib.h' - key: readability-simplify-boolean-expr.IgnoreMacros value: '1' - key: cppcoreguidelines-rvalue-reference-param-not-moved.IgnoreUnnamedParams diff --git a/include/sdbus-c++/TypeTraits.h b/include/sdbus-c++/TypeTraits.h index e9143fa6..ccec69c7 100644 --- a/include/sdbus-c++/TypeTraits.h +++ b/include/sdbus-c++/TypeTraits.h @@ -447,6 +447,18 @@ namespace sdbus { static constexpr bool has_error_param = true; }; + template + struct function_traits&&, _Args...)> : function_traits_base + { + static constexpr bool has_error_param = true; + }; + + template + struct function_traits&, _Args...)> : function_traits_base + { + static constexpr bool has_error_param = true; + }; + template struct function_traits, _Args...)> : function_traits_base, _Args...> { diff --git a/tests/integrationtests/DBusAsyncMethodsTests.cpp b/tests/integrationtests/DBusAsyncMethodsTests.cpp index abbc1b55..eb986e23 100644 --- a/tests/integrationtests/DBusAsyncMethodsTests.cpp +++ b/tests/integrationtests/DBusAsyncMethodsTests.cpp @@ -25,27 +25,30 @@ */ #include "TestFixture.h" -#include "TestAdaptor.h" #include "TestProxy.h" -#include "sdbus-c++/sdbus-c++.h" +#include "Defs.h" +#include +#include +#include +#include +#include #include #include +#include +#include +#include #include #include -#include #include -#include #include -#include +#include +#include using ::testing::Eq; -using ::testing::DoubleEq; -using ::testing::Gt; using ::testing::Le; using ::testing::AnyOf; using ::testing::ElementsAre; -using ::testing::SizeIs; using namespace std::chrono_literals; using namespace sdbus::test; @@ -100,14 +103,14 @@ TYPED_TEST(AsyncSdbusTestObject, RunsServerSideAsynchronousMethodAsynchronously) ++startedCount; while (!invoke) ; auto result = proxy.doOperationAsync(param); - std::lock_guard guard(mtx); + std::lock_guard const guard(mtx); results.push_back(result); }; std::thread invocations[]{std::thread{call, 1500}, std::thread{call, 1000}, std::thread{call, 500}}; while (startedCount != 3) ; invoke = true; - std::for_each(std::begin(invocations), std::end(invocations), [](auto& t){ t.join(); }); + std::for_each(std::begin(invocations), std::end(invocations), [](auto& thread){ thread.join(); }); ASSERT_THAT(results, ElementsAre(500, 1000, 1500)); } @@ -137,7 +140,7 @@ TYPED_TEST(AsyncSdbusTestObject, HandlesCorrectlyABulkOfParallelServerSideAsyncM std::thread invocations[]{std::thread{call}, std::thread{call}, std::thread{call}}; while (startedCount != 3) ; invoke = true; - std::for_each(std::begin(invocations), std::end(invocations), [](auto& t){ t.join(); }); + std::for_each(std::begin(invocations), std::end(invocations), [](auto& thread){ thread.join(); }); ASSERT_THAT(resultCount, Eq(1500)); } @@ -203,7 +206,7 @@ TYPED_TEST(AsyncSdbusTestObject, InvokesMethodWithLargeDataAsynchronouslyOnClien TYPED_TEST(AsyncSdbusTestObject, AnswersThatAsyncCallIsPendingIfItIsInProgress) { - this->m_proxy->installDoOperationClientSideAsyncReplyHandler([&](uint32_t /*res*/, std::optional /*err*/){}); + this->m_proxy->installDoOperationClientSideAsyncReplyHandler([&](uint32_t /*res*/, const std::optional& /*err*/){}); auto call = this->m_proxy->doOperationClientSideAsync(100); @@ -214,7 +217,7 @@ TYPED_TEST(AsyncSdbusTestObject, CancelsPendingAsyncCallOnClientSide) { std::promise promise; auto future = promise.get_future(); - this->m_proxy->installDoOperationClientSideAsyncReplyHandler([&](uint32_t /*res*/, std::optional /*err*/){ promise.set_value(1); }); + this->m_proxy->installDoOperationClientSideAsyncReplyHandler([&](uint32_t /*res*/, const std::optional& /*err*/){ promise.set_value(1); }); auto call = this->m_proxy->doOperationClientSideAsync(100); call.cancel(); @@ -226,7 +229,7 @@ TYPED_TEST(AsyncSdbusTestObject, CancelsPendingAsyncCallOnClientSideByDestroying { std::promise promise; auto future = promise.get_future(); - this->m_proxy->installDoOperationClientSideAsyncReplyHandler([&](uint32_t /*res*/, std::optional /*err*/){ promise.set_value(1); }); + this->m_proxy->installDoOperationClientSideAsyncReplyHandler([&](uint32_t /*res*/, const std::optional& /*err*/){ promise.set_value(1); }); { auto slot = this->m_proxy->doOperationClientSideAsync(100, sdbus::return_slot); @@ -239,8 +242,7 @@ TYPED_TEST(AsyncSdbusTestObject, CancelsPendingAsyncCallOnClientSideByDestroying TYPED_TEST(AsyncSdbusTestObject, AnswersThatAsyncCallIsNotPendingAfterItHasBeenCancelled) { std::promise promise; - auto future = promise.get_future(); - this->m_proxy->installDoOperationClientSideAsyncReplyHandler([&](uint32_t /*res*/, std::optional /*err*/){ promise.set_value(1); }); + this->m_proxy->installDoOperationClientSideAsyncReplyHandler([&](uint32_t /*res*/, const std::optional& /*err*/){ promise.set_value(1); }); auto call = this->m_proxy->doOperationClientSideAsync(100); call.cancel(); @@ -252,7 +254,7 @@ TYPED_TEST(AsyncSdbusTestObject, AnswersThatAsyncCallIsNotPendingAfterItHasBeenC { std::promise promise; auto future = promise.get_future(); - this->m_proxy->installDoOperationClientSideAsyncReplyHandler([&](uint32_t /*res*/, std::optional /*err*/){ promise.set_value(1); }); + this->m_proxy->installDoOperationClientSideAsyncReplyHandler([&](uint32_t /*res*/, const std::optional& /*err*/){ promise.set_value(1); }); auto call = this->m_proxy->doOperationClientSideAsync(0); (void) future.get(); // Wait for the call to finish @@ -262,7 +264,7 @@ TYPED_TEST(AsyncSdbusTestObject, AnswersThatAsyncCallIsNotPendingAfterItHasBeenC TYPED_TEST(AsyncSdbusTestObject, AnswersThatDefaultConstructedAsyncCallIsNotPending) { - sdbus::PendingAsyncCall call; + sdbus::PendingAsyncCall const call; ASSERT_FALSE(call.isPending()); } @@ -276,7 +278,7 @@ TYPED_TEST(AsyncSdbusTestObject, SupportsAsyncCallCopyAssignment) ASSERT_TRUE(call.isPending()); } -TYPED_TEST(AsyncSdbusTestObject, ReturnsNonnullErrorWhenAsynchronousMethodCallFails) +TYPED_TEST(AsyncSdbusTestObject, ReturnsNonnullErrorWhenAsynchronousMethodCallFails) // NOLINT(readability-function-cognitive-complexity) { std::promise promise; auto future = promise.get_future(); diff --git a/tests/integrationtests/DBusConnectionTests.cpp b/tests/integrationtests/DBusConnectionTests.cpp index 0093e708..b24b5e37 100644 --- a/tests/integrationtests/DBusConnectionTests.cpp +++ b/tests/integrationtests/DBusConnectionTests.cpp @@ -33,13 +33,10 @@ // gmock #include -#include // STL #include -#include -using ::testing::Eq; using namespace sdbus::test; /*-------------------------------------*/ @@ -63,7 +60,7 @@ TEST(Connection, CanRequestName) TEST(SystemBusConnection, CannotRequestNonregisteredDbusName) { auto connection = sdbus::createSystemBusConnection(); - sdbus::ServiceName notSupportedBusName{"some.random.not.supported.dbus.name"}; + sdbus::ServiceName const notSupportedBusName{"some.random.not.supported.dbus.name"}; ASSERT_THROW(connection->requestName(notSupportedBusName), sdbus::Error); } @@ -79,7 +76,7 @@ TEST(Connection, CanReleaseRequestedName) TEST(Connection, CannotReleaseNonrequestedName) { auto connection = sdbus::createBusConnection(); - sdbus::ServiceName notAcquiredBusName{"some.random.unacquired.name"}; + sdbus::ServiceName const notAcquiredBusName{"some.random.unacquired.name"}; ASSERT_THROW(connection->releaseName(notAcquiredBusName), sdbus::Error); } diff --git a/tests/integrationtests/DBusGeneralTests.cpp b/tests/integrationtests/DBusGeneralTests.cpp index 52df2ef5..839a31b9 100644 --- a/tests/integrationtests/DBusGeneralTests.cpp +++ b/tests/integrationtests/DBusGeneralTests.cpp @@ -27,20 +27,18 @@ #include "TestAdaptor.h" #include "TestProxy.h" #include "TestFixture.h" -#include "sdbus-c++/sdbus-c++.h" +#include "Defs.h" +#include +#include +#include +#include #include #include -#include -#include -#include +#include #include -#include -#include -#include -#include +#include -using ::testing::ElementsAre; using ::testing::Eq; using namespace std::chrono_literals; using namespace sdbus::test; @@ -57,8 +55,8 @@ TEST(AdaptorAndProxy, CanBeConstructedSuccessfully) auto connection = sdbus::createBusConnection(); connection->requestName(SERVICE_NAME); - ASSERT_NO_THROW(TestAdaptor adaptor(*connection, OBJECT_PATH)); - ASSERT_NO_THROW(TestProxy proxy(SERVICE_NAME, OBJECT_PATH)); + ASSERT_NO_THROW(const TestAdaptor adaptor(*connection, OBJECT_PATH)); + ASSERT_NO_THROW(const TestProxy proxy(SERVICE_NAME, OBJECT_PATH)); connection->releaseName(SERVICE_NAME); } @@ -79,7 +77,7 @@ TYPED_TEST(AConnection, WillCallCallbackHandlerForIncomingMessageMatchingMatchRu { auto matchRule = "sender='" + SERVICE_NAME + "',path='" + OBJECT_PATH + "'"; std::atomic matchingMessageReceived{false}; - auto slot = this->s_proxyConnection->addMatch(matchRule, [&](sdbus::Message msg) + auto slot = this->s_proxyConnection->addMatch(matchRule, [&](const sdbus::Message& msg) { if(msg.getPath() == OBJECT_PATH) matchingMessageReceived = true; @@ -96,12 +94,12 @@ TYPED_TEST(AConnection, CanInstallMatchRuleAsynchronously) std::atomic matchingMessageReceived{false}; std::atomic matchRuleInstalled{false}; auto slot = this->s_proxyConnection->addMatchAsync( matchRule - , [&](sdbus::Message msg) + , [&](const sdbus::Message& msg) { if(msg.getPath() == OBJECT_PATH) matchingMessageReceived = true; } - , [&](sdbus::Message /*msg*/) + , [&](const sdbus::Message& /*msg*/) { matchRuleInstalled = true; } @@ -118,7 +116,7 @@ TYPED_TEST(AConnection, WillUnsubscribeMatchRuleWhenClientDestroysTheAssociatedS { auto matchRule = "sender='" + SERVICE_NAME + "',path='" + OBJECT_PATH + "'"; std::atomic matchingMessageReceived{false}; - auto slot = this->s_proxyConnection->addMatch(matchRule, [&](sdbus::Message msg) + auto slot = this->s_proxyConnection->addMatch(matchRule, [&](const sdbus::Message& msg) { if(msg.getPath() == OBJECT_PATH) matchingMessageReceived = true; @@ -136,7 +134,7 @@ TYPED_TEST(AConnection, CanAddFloatingMatchRule) std::atomic matchingMessageReceived{false}; auto con = sdbus::createBusConnection(); con->enterEventLoopAsync(); - auto callback = [&](sdbus::Message msg) + auto callback = [&](const sdbus::Message& msg) { if(msg.getPath() == OBJECT_PATH) matchingMessageReceived = true; @@ -157,7 +155,7 @@ TYPED_TEST(AConnection, WillNotPassToMatchCallbackMessagesThatDoNotMatchTheRule) { auto matchRule = "type='signal',interface='" + INTERFACE_NAME + "',member='simpleSignal'"; std::atomic numberOfMatchingMessages{}; - auto slot = this->s_proxyConnection->addMatch(matchRule, [&](sdbus::Message msg) + auto slot = this->s_proxyConnection->addMatch(matchRule, [&](const sdbus::Message& msg) { if(msg.getMemberName() == "simpleSignal"sv) numberOfMatchingMessages++; diff --git a/tests/integrationtests/DBusMethodsTests.cpp b/tests/integrationtests/DBusMethodsTests.cpp index 382b30c3..39ee5448 100644 --- a/tests/integrationtests/DBusMethodsTests.cpp +++ b/tests/integrationtests/DBusMethodsTests.cpp @@ -25,27 +25,24 @@ */ #include "TestFixture.h" -#include "TestAdaptor.h" #include "TestProxy.h" -#include "sdbus-c++/sdbus-c++.h" +#include "Defs.h" +#include +#include #include #include +#include +#include #include -#include -#include #include -#include -#include -#include +#include +#include using ::testing::Eq; -using ::testing::DoubleEq; using ::testing::Gt; using ::testing::Le; using ::testing::AnyOf; -using ::testing::ElementsAre; -using ::testing::SizeIs; using ::testing::NotNull; using namespace std::chrono_literals; using namespace std::string_literals; @@ -54,15 +51,15 @@ using namespace sdbus::test; namespace my { struct Struct { - int i; + int i{}; std::string s; std::vector l; friend bool operator==(const Struct &lhs, const Struct &rhs) = default; }; -} +} // namespace my -SDBUSCPP_REGISTER_STRUCT(my::Struct, i, s, l); +SDBUSCPP_REGISTER_STRUCT(my::Struct, i, s, l); // NOLINT(readability-identifier-length) /*-------------------------------------*/ /* -- TEST CASES -- */ @@ -91,36 +88,36 @@ TYPED_TEST(SdbusTestObject, CallsMethodsWithTuplesSuccessfully) TYPED_TEST(SdbusTestObject, CallsMethodsWithStructSuccessfully) { - sdbus::Struct> a{}; - auto vectorRes = this->m_proxy->getInts16FromStruct(a); + sdbus::Struct> const strctA{}; + auto vectorRes = this->m_proxy->getInts16FromStruct(strctA); ASSERT_THAT(vectorRes, Eq(std::vector{0})); // because second item is by default initialized to 0 - sdbus::Struct> b{ + sdbus::Struct> const strctB{ UINT8_VALUE, INT16_VALUE, DOUBLE_VALUE, STRING_VALUE, {INT16_VALUE, -INT16_VALUE} }; - vectorRes = this->m_proxy->getInts16FromStruct(b); + vectorRes = this->m_proxy->getInts16FromStruct(strctB); ASSERT_THAT(vectorRes, Eq(std::vector{INT16_VALUE, INT16_VALUE, -INT16_VALUE})); } TYPED_TEST(SdbusTestObject, CallsMethodWithVariantSuccessfully) { - sdbus::Variant v{DOUBLE_VALUE}; - sdbus::Variant variantRes = this->m_proxy->processVariant(v); + sdbus::Variant const var{DOUBLE_VALUE}; + sdbus::Variant const variantRes = this->m_proxy->processVariant(var); ASSERT_THAT(variantRes.get(), Eq(static_cast(DOUBLE_VALUE))); } TYPED_TEST(SdbusTestObject, CallsMethodWithStdVariantSuccessfully) { - std::variant v{DOUBLE_VALUE}; - auto variantRes = this->m_proxy->processVariant(v); + std::variant const var{DOUBLE_VALUE}; + auto variantRes = this->m_proxy->processVariant(var); ASSERT_THAT(std::get(variantRes), Eq(static_cast(DOUBLE_VALUE))); } TYPED_TEST(SdbusTestObject, CallsMethodWithStructVariantsAndGetMapSuccessfully) { - std::vector x{-2, 0, 2}; - sdbus::Struct y{false, true}; - std::map mapOfVariants = this->m_proxy->getMapOfVariants(x, y); + std::vector const vec{-2, 0, 2}; + sdbus::Struct const strct{false, true}; + std::map mapOfVariants = this->m_proxy->getMapOfVariants(vec, strct); decltype(mapOfVariants) res{ {-2, sdbus::Variant{false}} , {0, sdbus::Variant{false}} , {2, sdbus::Variant{true}}}; @@ -352,10 +349,10 @@ TYPED_TEST(SdbusTestObject, CanCallMethodSynchronouslyWithoutAnEventLoopThread) TYPED_TEST(SdbusTestObject, CanRegisterAdditionalVTableDynamicallyAtAnyTime) { auto& object = this->m_adaptor->getObject(); - sdbus::InterfaceName interfaceName{"org.sdbuscpp.integrationtests2"}; + sdbus::InterfaceName const interfaceName{"org.sdbuscpp.integrationtests2"}; auto vtableSlot = object.addVTable( interfaceName - , { sdbus::registerMethod("add").implementedAs([](const int64_t& a, const double& b){ return a + b; }) - , sdbus::registerMethod("subtract").implementedAs([](const int& a, const int& b){ return a - b; }) } + , { sdbus::registerMethod("add").implementedAs([](const double& lhs, const double& rhs){ return lhs + rhs; }) + , sdbus::registerMethod("subtract").implementedAs([](const int& lhs, const int& rhs){ return lhs - rhs; }) } , sdbus::return_slot ); // The new remote vtable is registered as long as we keep vtableSlot, so remote method calls now should pass @@ -369,11 +366,11 @@ TYPED_TEST(SdbusTestObject, CanRegisterAdditionalVTableDynamicallyAtAnyTime) TYPED_TEST(SdbusTestObject, CanUnregisterAdditionallyRegisteredVTableAtAnyTime) { auto& object = this->m_adaptor->getObject(); - sdbus::InterfaceName interfaceName{"org.sdbuscpp.integrationtests2"}; + sdbus::InterfaceName const interfaceName{"org.sdbuscpp.integrationtests2"}; auto vtableSlot = object.addVTable( interfaceName - , { sdbus::registerMethod("add").implementedAs([](const int64_t& a, const double& b){ return a + b; }) - , sdbus::registerMethod("subtract").implementedAs([](const int& a, const int& b){ return a - b; }) } + , { sdbus::registerMethod("add").implementedAs([](const double& lhs, const double& rhs){ return lhs + rhs; }) + , sdbus::registerMethod("subtract").implementedAs([](const int& lhs, const int& rhs){ return lhs - rhs; }) } , sdbus::return_slot ); vtableSlot.reset(); // Letting the slot go means letting go the associated vtable registration diff --git a/tests/integrationtests/DBusPropertiesTests.cpp b/tests/integrationtests/DBusPropertiesTests.cpp index 59c1b3f3..962162d0 100644 --- a/tests/integrationtests/DBusPropertiesTests.cpp +++ b/tests/integrationtests/DBusPropertiesTests.cpp @@ -25,26 +25,15 @@ */ #include "TestFixture.h" -#include "TestAdaptor.h" -#include "TestProxy.h" -#include "sdbus-c++/sdbus-c++.h" +#include "Defs.h" +#include +#include #include #include #include -#include -#include -#include -#include -#include -#include using ::testing::Eq; -using ::testing::DoubleEq; -using ::testing::Gt; -using ::testing::AnyOf; -using ::testing::ElementsAre; -using ::testing::SizeIs; using ::testing::NotNull; using ::testing::Not; using ::testing::IsEmpty; @@ -67,7 +56,7 @@ TYPED_TEST(SdbusTestObject, FailsWritingToReadOnlyProperty) TYPED_TEST(SdbusTestObject, WritesAndReadsReadWritePropertySuccessfully) { - uint32_t newActionValue = 5678; + uint32_t const newActionValue = 5678; this->m_proxy->action(newActionValue); @@ -84,7 +73,7 @@ TYPED_TEST(SdbusTestObject, CanAccessAssociatedPropertySetMessageInPropertySetHa TYPED_TEST(SdbusTestObject, WritesAndReadsReadWriteVariantPropertySuccessfully) { - sdbus::Variant newActionValue{5678}; + sdbus::Variant const newActionValue{5678}; this->m_proxy->actionVariant(newActionValue); diff --git a/tests/integrationtests/DBusSignalsTests.cpp b/tests/integrationtests/DBusSignalsTests.cpp index 4f8fcd02..b99fc1e7 100644 --- a/tests/integrationtests/DBusSignalsTests.cpp +++ b/tests/integrationtests/DBusSignalsTests.cpp @@ -27,19 +27,17 @@ #include "TestFixture.h" #include "TestAdaptor.h" #include "TestProxy.h" -#include "sdbus-c++/sdbus-c++.h" +#include "Defs.h" +#include +#include #include #include +#include #include -#include using ::testing::Eq; using ::testing::DoubleEq; -using ::testing::Gt; -using ::testing::AnyOf; -using ::testing::ElementsAre; -using ::testing::SizeIs; using ::testing::NotNull; using namespace std::chrono_literals; using namespace sdbus::test; @@ -69,7 +67,7 @@ TYPED_TEST(SdbusTestObject, EmitsSimpleSignalToMultipleProxiesSuccessfully) TYPED_TEST(SdbusTestObject, ProxyDoesNotReceiveSignalFromOtherBusName) { - sdbus::ServiceName otherBusName{SERVICE_NAME + "2"}; + sdbus::ServiceName const otherBusName{SERVICE_NAME + "2"}; auto connection2 = sdbus::createBusConnection(otherBusName); auto adaptor2 = std::make_unique(*connection2, OBJECT_PATH); @@ -101,11 +99,11 @@ TYPED_TEST(SdbusTestObject, EmitsSignalWithLargeMapSuccessfully) TYPED_TEST(SdbusTestObject, EmitsSignalWithVariantSuccessfully) { - double d = 3.14; - this->m_adaptor->emitSignalWithVariant(sdbus::Variant{d}); + double const val = 3.14; + this->m_adaptor->emitSignalWithVariant(sdbus::Variant{val}); ASSERT_TRUE(waitUntil(this->m_proxy->m_gotSignalWithVariant)); - ASSERT_THAT(this->m_proxy->m_variantFromSignal, DoubleEq(d)); + ASSERT_THAT(this->m_proxy->m_variantFromSignal, DoubleEq(val)); } TYPED_TEST(SdbusTestObject, EmitsSignalWithoutRegistrationSuccessfully) diff --git a/tests/integrationtests/DBusStandardInterfacesTests.cpp b/tests/integrationtests/DBusStandardInterfacesTests.cpp index 058cfb8f..df37f57f 100644 --- a/tests/integrationtests/DBusStandardInterfacesTests.cpp +++ b/tests/integrationtests/DBusStandardInterfacesTests.cpp @@ -26,24 +26,25 @@ #include "TestFixture.h" #include "TestAdaptor.h" -#include "TestProxy.h" -#include "sdbus-c++/sdbus-c++.h" - +#include "Defs.h" +#include "integrationtests-adaptor.h" +#include + +#include +#include +#include +#include #include #include +#include +#include #include -#include -#include -#include -#include #include #include +#include +#include using ::testing::Eq; -using ::testing::DoubleEq; -using ::testing::Gt; -using ::testing::AnyOf; -using ::testing::ElementsAre; using ::testing::SizeIs; using namespace std::chrono_literals; using namespace sdbus::test; @@ -82,7 +83,7 @@ TYPED_TEST(SdbusTestObject, GetsPropertyAsynchronouslyViaPropertiesInterface) std::promise promise; auto future = promise.get_future(); - this->m_proxy->GetAsync(INTERFACE_NAME, "state", [&](std::optional err, sdbus::Variant value) + this->m_proxy->GetAsync(INTERFACE_NAME, "state", [&](std::optional err, const sdbus::Variant& value) { if (!err) promise.set_value(value.get()); @@ -102,7 +103,7 @@ TYPED_TEST(SdbusTestObject, GetsPropertyAsynchronouslyViaPropertiesInterfaceWith TYPED_TEST(SdbusTestObject, SetsPropertyViaPropertiesInterface) { - uint32_t newActionValue = 2345; + uint32_t const newActionValue = 2345; this->m_proxy->Set(INTERFACE_NAME, "action", sdbus::Variant{newActionValue}); @@ -111,7 +112,7 @@ TYPED_TEST(SdbusTestObject, SetsPropertyViaPropertiesInterface) TYPED_TEST(SdbusTestObject, SetsPropertyAsynchronouslyViaPropertiesInterface) { - uint32_t newActionValue = 2346; + uint32_t const newActionValue = 2346; std::promise promise; auto future = promise.get_future(); @@ -129,7 +130,7 @@ TYPED_TEST(SdbusTestObject, SetsPropertyAsynchronouslyViaPropertiesInterface) TYPED_TEST(SdbusTestObject, CancelsAsynchronousPropertySettingViaPropertiesInterface) { - uint32_t newActionValue = 2346; + uint32_t const newActionValue = 2346; std::promise promise; auto future = promise.get_future(); @@ -149,7 +150,7 @@ TYPED_TEST(SdbusTestObject, CancelsAsynchronousPropertySettingViaPropertiesInter TYPED_TEST(SdbusTestObject, SetsPropertyAsynchronouslyViaPropertiesInterfaceWithFuture) { - uint32_t newActionValue = 2347; + uint32_t const newActionValue = 2347; auto future = this->m_proxy->SetAsync(INTERFACE_NAME, "action", sdbus::Variant{newActionValue}, sdbus::with_future); @@ -222,7 +223,7 @@ TYPED_TEST(SdbusTestObject, EmitsPropertyChangedSignalForSelectedProperties) ASSERT_TRUE(waitUntil(signalReceived)); } -TYPED_TEST(SdbusTestObject, EmitsPropertyChangedSignalForAllProperties) +TYPED_TEST(SdbusTestObject, EmitsPropertyChangedSignalForAllProperties) // NOLINT(readability-function-cognitive-complexity) { std::atomic signalReceived{false}; this->m_proxy->m_onPropertiesChangedHandler = [&signalReceived]( const sdbus::InterfaceName& interfaceName @@ -270,7 +271,7 @@ TYPED_TEST(SdbusTestObject, GetsManagedObjectsAsynchronously) auto future = promise.get_future(); auto adaptor2 = std::make_unique(*this->s_adaptorConnection, OBJECT_PATH_2); - this->m_objectManagerProxy->GetManagedObjectsAsync([&](std::optional /*err*/, const std::map>>& objectsInterfacesAndProperties) + this->m_objectManagerProxy->GetManagedObjectsAsync([&](const std::optional& /*err*/, const std::map>>& objectsInterfacesAndProperties) { promise.set_value(objectsInterfacesAndProperties.size()); }); @@ -284,7 +285,7 @@ TYPED_TEST(SdbusTestObject, GetsManagedObjectsAsynchronouslyViaSlotReturningOver auto future = promise.get_future(); auto adaptor2 = std::make_unique(*this->s_adaptorConnection, OBJECT_PATH_2); - auto slot = this->m_objectManagerProxy->GetManagedObjectsAsync([&](std::optional /*err*/, const std::map>>& objectsInterfacesAndProperties) + auto slot = this->m_objectManagerProxy->GetManagedObjectsAsync([&](const std::optional& /*err*/, const std::map>>& objectsInterfacesAndProperties) { promise.set_value(objectsInterfacesAndProperties.size()); }, sdbus::return_slot); @@ -301,9 +302,10 @@ TYPED_TEST(SdbusTestObject, GetsManagedObjectsAsynchronouslyViaFutureOverload) ASSERT_THAT(future.get().size(), Eq(2)); } -TYPED_TEST(SdbusTestObject, EmitsInterfacesAddedSignalForSelectedObjectInterfaces) +TYPED_TEST(SdbusTestObject, EmitsInterfacesAddedSignalForSelectedObjectInterfaces) // NOLINT(readability-function-cognitive-complexity) { - std::atomic signalReceived{false}; + std::atomic signalReceived{false}; + // NOLINTNEXTLINE(readability-function-cognitive-complexity) this->m_objectManagerProxy->m_onInterfacesAddedHandler = [&signalReceived]( const sdbus::ObjectPath& objectPath , const std::map>& interfacesAndProperties ) { @@ -334,7 +336,7 @@ TYPED_TEST(SdbusTestObject, EmitsInterfacesAddedSignalForSelectedObjectInterface ASSERT_TRUE(waitUntil(signalReceived)); } -TYPED_TEST(SdbusTestObject, EmitsInterfacesAddedSignalForAllObjectInterfaces) +TYPED_TEST(SdbusTestObject, EmitsInterfacesAddedSignalForAllObjectInterfaces) // NOLINT(readability-function-cognitive-complexity) { std::atomic signalReceived{false}; this->m_objectManagerProxy->m_onInterfacesAddedHandler = [&signalReceived]( const sdbus::ObjectPath& objectPath diff --git a/tests/integrationtests/TestAdaptor.cpp b/tests/integrationtests/TestAdaptor.cpp index 21f5330c..4637ace5 100644 --- a/tests/integrationtests/TestAdaptor.cpp +++ b/tests/integrationtests/TestAdaptor.cpp @@ -25,11 +25,28 @@ */ #include "TestAdaptor.h" +#include "sdbus-c++/IConnection.h" +#include "sdbus-c++/Types.h" +#include "sdbus-c++/AdaptorInterfaces.h" +#include +#include "integrationtests/Defs.h" +#include +#include +#include +#include +#include "sdbus-c++/Message.h" +#include "sdbus-c++/MethodResult.h" +#include "sdbus-c++/Error.h" #include #include #include +#include +#include +#include +#include +#include -namespace sdbus { namespace test { +namespace sdbus::test { TestAdaptor::TestAdaptor(sdbus::IConnection& connection, sdbus::ObjectPath path) : AdaptorInterfaces(connection, std::move(path)) @@ -56,37 +73,37 @@ std::tuple TestAdaptor::getTuple() return std::make_tuple(UINT32_VALUE, STRING_VALUE); } -double TestAdaptor::multiply(const int64_t& a, const double& b) +double TestAdaptor::multiply(const int64_t& lhs, const double& rhs) { - return a * b; + return lhs * rhs; // NOLINT(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) } -void TestAdaptor::multiplyWithNoReply(const int64_t& a, const double& b) +void TestAdaptor::multiplyWithNoReply(const int64_t& lhs, const double& rhs) { - m_multiplyResult = a * b; + m_multiplyResult = lhs * rhs; // NOLINT(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) m_wasMultiplyCalled = true; } -std::vector TestAdaptor::getInts16FromStruct(const sdbus::Struct>& x) +std::vector TestAdaptor::getInts16FromStruct(const sdbus::Struct>& strct) { - std::vector res{x.get<1>()}; - auto y = std::get>(x); - res.insert(res.end(), y.begin(), y.end()); + std::vector res{strct.get<1>()}; + auto vec = std::get>(strct); + res.insert(res.end(), vec.begin(), vec.end()); return res; } -sdbus::Variant TestAdaptor::processVariant(const std::variant& v) +sdbus::Variant TestAdaptor::processVariant(const std::variant& var) { - sdbus::Variant res{static_cast(std::get(v))}; + sdbus::Variant res{static_cast(std::get(var))}; return res; } -std::map TestAdaptor::getMapOfVariants(const std::vector& x, const sdbus::Struct& y) +std::map TestAdaptor::getMapOfVariants(const std::vector& vec, const sdbus::Struct& strct) { std::map res; - for (auto item : x) + for (auto item : vec) { - res[item] = (item <= 0) ? std::get<0>(y) : std::get<1>(y); + res[item] = (item <= 0) ? std::get<0>(strct) : std::get<1>(strct); } return res; } @@ -96,24 +113,24 @@ sdbus::Struct>> TestAdapto return sdbus::Struct{STRING_VALUE, sdbus::Struct{std::map{{INT32_VALUE, INT32_VALUE}}}}; } -int32_t TestAdaptor::sumStructItems(const sdbus::Struct& a, const sdbus::Struct& b) +int32_t TestAdaptor::sumStructItems(const sdbus::Struct& strctA, const sdbus::Struct& strctB) { int32_t res{0}; - res += std::get<0>(a) + std::get<1>(a); - res += std::get<0>(b) + std::get<1>(b); + res += std::get<0>(strctA) + std::get<1>(strctA); + res += std::get<0>(strctB) + std::get<1>(strctB); // NOLINT(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) return res; } -uint32_t TestAdaptor::sumArrayItems(const std::vector& a, const std::array& b) +uint32_t TestAdaptor::sumArrayItems(const std::vector& vec, const std::array& arr) { uint32_t res{0}; - for (auto x : a) + for (auto elem : vec) { - res += x; + res += elem; } - for (auto x : b) + for (auto elem : arr) { - res += x; + res += elem; } return res; } @@ -289,12 +306,12 @@ void TestAdaptor::blocking(const bool& value) m_blocking = value; } -void TestAdaptor::emitSignalWithoutRegistration(const sdbus::Struct>& s) +void TestAdaptor::emitSignalWithoutRegistration(const sdbus::Struct>& strct) { - getObject().emitSignal("signalWithoutRegistration").onInterface(sdbus::test::INTERFACE_NAME).withArguments(s); + getObject().emitSignal("signalWithoutRegistration").onInterface(sdbus::test::INTERFACE_NAME).withArguments(strct); } -std::string TestAdaptor::getExpectedXmlApiDescription() const +std::string TestAdaptor::getExpectedXmlApiDescription() { return R"delimiter( getTuple() override; - double multiply(const int64_t& a, const double& b) override; - void multiplyWithNoReply(const int64_t& a, const double& b) override; - std::vector getInts16FromStruct(const sdbus::Struct>& arg0) override; + double multiply(const int64_t& lhs, const double& rhs) override; + void multiplyWithNoReply(const int64_t& lhs, const double& rhs) override; + std::vector getInts16FromStruct(const sdbus::Struct>& strct) override; sdbus::Variant processVariant(const std::variant& variant) override; - std::map getMapOfVariants(const std::vector& x, const sdbus::Struct& y) override; + std::map getMapOfVariants(const std::vector& vec, const sdbus::Struct& strct) override; sdbus::Struct>> getStructInStruct() override; - int32_t sumStructItems(const sdbus::Struct& arg0, const sdbus::Struct& arg1) override; - uint32_t sumArrayItems(const std::vector& arg0, const std::array& arg1) override; - uint32_t doOperation(const uint32_t& arg0) override; + int32_t sumStructItems(const sdbus::Struct& strctA, const sdbus::Struct& strctB) override; + uint32_t sumArrayItems(const std::vector& vec, const std::array& arr) override; + uint32_t doOperation(const uint32_t& param) override; std::map doOperationWithLargeData(const std::map& largeParam) override; - void doOperationAsync(sdbus::Result&& result, uint32_t arg0) override; - void doOperationAsyncWithLargeData(sdbus::Result>&& result, uint32_t arg0, const std::map& largeParam) override; + void doOperationAsync(sdbus::Result&& result, uint32_t param) override; + void doOperationAsyncWithLargeData(sdbus::Result>&& result, uint32_t param, const std::map& largeMap) override; sdbus::Signature getSignature() override; sdbus::ObjectPath getObjPath() override; sdbus::UnixFd getUnixFd() override; @@ -97,7 +97,7 @@ class TestAdaptor final : public sdbus::AdaptorInterfaces< org::sdbuscpp::integr public: void emitSignalWithoutRegistration(const sdbus::Struct>& s); - std::string getExpectedXmlApiDescription() const; + static std::string getExpectedXmlApiDescription() ; private: const std::string m_state{DEFAULT_STATE_VALUE}; diff --git a/tests/integrationtests/TestFixture.cpp b/tests/integrationtests/TestFixture.cpp index 0ddd2207..afc8d65b 100644 --- a/tests/integrationtests/TestFixture.cpp +++ b/tests/integrationtests/TestFixture.cpp @@ -25,8 +25,11 @@ */ #include "TestFixture.h" +#include +#include "sdbus-c++/IConnection.h" +#include -namespace sdbus { namespace test { +namespace sdbus::test { std::unique_ptr BaseTestFixture::s_adaptorConnection = sdbus::createBusConnection(); std::unique_ptr BaseTestFixture::s_proxyConnection = sdbus::createBusConnection(); @@ -41,4 +44,4 @@ int TestFixture::s_eventExitFd{-1}; #endif // SDBUS_basu -}} +} // namespace sdbus::test diff --git a/tests/integrationtests/TestProxy.cpp b/tests/integrationtests/TestProxy.cpp index b829754a..e9d93d3e 100644 --- a/tests/integrationtests/TestProxy.cpp +++ b/tests/integrationtests/TestProxy.cpp @@ -25,16 +25,26 @@ */ #include "TestProxy.h" -#include +#include +#include "Defs.h" +#include +#include +#include +#include +#include +#include +#include #include #include +#include +#include -namespace sdbus { namespace test { +namespace sdbus::test { TestProxy::TestProxy(ServiceName destination, ObjectPath objectPath) : ProxyInterfaces(std::move(destination), std::move(objectPath)) { - getProxy().uponSignal("signalWithoutRegistration").onInterface(sdbus::test::INTERFACE_NAME).call([this](const sdbus::Struct>& s){ this->onSignalWithoutRegistration(s); }); + getProxy().uponSignal("signalWithoutRegistration").onInterface(sdbus::test::INTERFACE_NAME).call([this](const sdbus::Struct>& strct){ this->onSignalWithoutRegistration(strct); }); registerProxy(); } @@ -49,7 +59,7 @@ TestProxy::TestProxy(ServiceName destination, ObjectPath objectPath, dont_run_ev TestProxy::TestProxy(sdbus::IConnection& connection, ServiceName destination, ObjectPath objectPath) : ProxyInterfaces(connection, std::move(destination), std::move(objectPath)) { - getProxy().uponSignal("signalWithoutRegistration").onInterface(sdbus::test::INTERFACE_NAME).call([this](const sdbus::Struct>& s){ this->onSignalWithoutRegistration(s); }); + getProxy().uponSignal("signalWithoutRegistration").onInterface(sdbus::test::INTERFACE_NAME).call([this](const sdbus::Struct>& strct){ this->onSignalWithoutRegistration(strct); }); registerProxy(); } @@ -79,17 +89,17 @@ void TestProxy::onSignalWithVariant(const sdbus::Variant& aVariant) m_gotSignalWithVariant = true; } -void TestProxy::onSignalWithoutRegistration(const sdbus::Struct>& s) +void TestProxy::onSignalWithoutRegistration(const sdbus::Struct>& strct) { // Static cast to std::string is a workaround for gcc 11.4 false positive warning (which later gcc versions nor Clang emit) - m_signatureFromSignal[std::get<0>(s)] = static_cast(std::get<0>(std::get<1>(s))); + m_signatureFromSignal[std::get<0>(strct)] = static_cast(std::get<0>(std::get<1>(strct))); m_gotSignalWithSignature = true; } -void TestProxy::onDoOperationReply(uint32_t returnValue, std::optional error) +void TestProxy::onDoOperationReply(uint32_t returnValue, std::optional error) const { if (m_DoOperationClientSideAsyncReplyHandler) - m_DoOperationClientSideAsyncReplyHandler(returnValue, error); + m_DoOperationClientSideAsyncReplyHandler(returnValue, std::move(error)); } void TestProxy::onPropertiesChanged( const sdbus::InterfaceName& interfaceName @@ -108,7 +118,7 @@ void TestProxy::installDoOperationClientSideAsyncReplyHandler(std::function>& s); - void onDoOperationReply(uint32_t returnValue, std::optional error); + void onDoOperationReply(uint32_t returnValue, std::optional error) const; // Signals of standard D-Bus interfaces void onPropertiesChanged( const sdbus::InterfaceName& interfaceName @@ -115,7 +115,7 @@ class TestProxy final : public sdbus::ProxyInterfaces< org::sdbuscpp::integratio std::atomic m_gotSignalWithMap{false}; std::map m_mapFromSignal; std::atomic m_gotSignalWithVariant{false}; - double m_variantFromSignal; + double m_variantFromSignal{}; std::atomic m_gotSignalWithSignature{false}; std::map m_signatureFromSignal; From 3741d65f3a949270032dae4877c76570d54fb7ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stanislav=20Angelovi=C4=8D?= Date: Fri, 9 Jan 2026 23:22:02 +0100 Subject: [PATCH 08/13] chore(cmake): refactor handling of clang-tidy --- CMakeLists.txt | 22 ++-------------------- cmake/clang-tidy.cmake | 16 ++++++++++++++++ 2 files changed, 18 insertions(+), 20 deletions(-) create mode 100644 cmake/clang-tidy.cmake diff --git a/CMakeLists.txt b/CMakeLists.txt index 76188c96..cf200fdb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -130,6 +130,8 @@ endif() find_package(Threads REQUIRED) +include(cmake/clang-tidy.cmake) # Static analysis with clang-tidy + #------------------------------- # SOURCE FILES CONFIGURATION #------------------------------- @@ -265,26 +267,6 @@ if(SDBUSCPP_BUILD_DOCS) add_subdirectory("${CMAKE_CURRENT_SOURCE_DIR}/docs") endif() -#---------------------------------- -# STATIC ANALYSIS -#---------------------------------- - -if(SDBUSCPP_CLANG_TIDY) - message(STATUS "Building with static analysis") - find_program(CLANG_TIDY NAMES clang-tidy) - if(NOT CLANG_TIDY) - message(WARNING "clang-tidy not found") - else() - message(STATUS "clang-tidy found: ${CLANG_TIDY}") - # TODO: Check what happens if the targets don't exist - set_target_properties(sdbus-c++-objlib PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY}") - set_target_properties(sdbus-c++ PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY}") - set_target_properties(sdbus-c++-unit-tests PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY}") - #set_target_properties(sdbus-c++-integration-tests PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY}") - set_target_properties(sdbus-c++-stress-tests PROPERTIES CXX_CLANG_TIDY "${CLANG_TIDY}") - endif() -endif() - #---------------------------------- # CMAKE CONFIG & PACKAGE CONFIG #---------------------------------- diff --git a/cmake/clang-tidy.cmake b/cmake/clang-tidy.cmake new file mode 100644 index 00000000..8a5eaf2c --- /dev/null +++ b/cmake/clang-tidy.cmake @@ -0,0 +1,16 @@ +#---------------------------------- +# STATIC ANALYSIS +#---------------------------------- + +if(SDBUSCPP_CLANG_TIDY) + message(STATUS "Building with static analysis") + find_program(CLANG_TIDY NAMES clang-tidy) + if(NOT CLANG_TIDY) + message(WARNING "clang-tidy not found") + else() + message(STATUS "clang-tidy found: ${CLANG_TIDY}") + set(DO_CLANG_TIDY "${CLANG_TIDY}") + #set(DO_CLANG_TIDY "${CLANG_TIDY}" "-fix") + set(CMAKE_CXX_CLANG_TIDY "${DO_CLANG_TIDY}") + endif() +endif() From 65ea39bcbad721803c4a612c135fca8386c84e7c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stanislav=20Angelovi=C4=8D?= Date: Fri, 9 Jan 2026 23:34:30 +0100 Subject: [PATCH 09/13] fix: address clang-tidy warnings in examples --- .github/workflows/ci.yml | 2 +- .../obj-manager-client.cpp | 28 ++++++++++++++----- .../obj-manager-server.cpp | 18 ++++++++++-- 3 files changed, 38 insertions(+), 10 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9fe2d778..ac656f41 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -93,7 +93,7 @@ jobs: sudo update-alternatives --install /usr/bin/c++ c++ /usr/bin/clang++ 10 - name: configure run: | - cmake -B _build -DCMAKE_BUILD_TYPE=Debug -DCMAKE_CXX_FLAGS="-O0 -g" -DCMAKE_VERBOSE_MAKEFILE=ON -DSDBUSCPP_CLANG_TIDY=ON -DSDBUSCPP_BUILD_TESTS=ON -DSDBUSCPP_BUILD_PERF_TESTS=ON -DSDBUSCPP_BUILD_STRESS_TESTS=ON + cmake -B _build -DCMAKE_BUILD_TYPE=Debug -DCMAKE_CXX_FLAGS="-O0 -g" -DCMAKE_VERBOSE_MAKEFILE=ON -DSDBUSCPP_CLANG_TIDY=ON -DSDBUSCPP_BUILD_TESTS=ON -DSDBUSCPP_BUILD_PERF_TESTS=ON -DSDBUSCPP_BUILD_STRESS_TESTS=ON -DSDBUSCPP_BUILD_EXAMPLES=ON - name: make run: | cmake --build _build -j4 diff --git a/examples/org.freedesktop.DBus.ObjectManager/obj-manager-client.cpp b/examples/org.freedesktop.DBus.ObjectManager/obj-manager-client.cpp index fb2d8a30..ae1d8f68 100644 --- a/examples/org.freedesktop.DBus.ObjectManager/obj-manager-client.cpp +++ b/examples/org.freedesktop.DBus.ObjectManager/obj-manager-client.cpp @@ -12,17 +12,26 @@ #include "examplemanager-planet1-client-glue.h" #include #include -#include +#include +#include +#include +#include +#include class PlanetProxy final : public sdbus::ProxyInterfaces< org::sdbuscpp::ExampleManager::Planet1_proxy > { public: PlanetProxy(sdbus::IConnection& connection, sdbus::ServiceName destination, sdbus::ObjectPath path) - : ProxyInterfaces(connection, std::move(destination), std::move(path)) + : ProxyInterfaces(connection, std::move(destination), std::move(path)) { registerProxy(); } + PlanetProxy(const PlanetProxy&) = delete; + PlanetProxy& operator=(const PlanetProxy&) = delete; + PlanetProxy(PlanetProxy&&) = delete; + PlanetProxy& operator=(PlanetProxy&&) = delete; + ~PlanetProxy() { unregisterProxy(); @@ -35,11 +44,16 @@ class ManagerProxy final : public sdbus::ProxyInterfaces(); // or create a proxy instance to the newly added object. PlanetProxy planet(m_connection, m_destination, objectPath); - std::cout << name << " has a population of " << planet.GetPopulation() << ".\n" << std::endl; + std::cout << name << " has a population of " << planet.GetPopulation() << ".\n" << '\n'; } void onInterfacesRemoved( const sdbus::ObjectPath& objectPath @@ -83,7 +97,7 @@ class ManagerProxy final : public sdbus::ProxyInterfaces #include #include +#include +#include +#include using sdbus::ObjectPath; @@ -30,6 +33,11 @@ class ManagerAdaptor : public sdbus::AdaptorInterfacesrequestName(serviceName); connection->enterEventLoopAsync(); + // NOLINTNEXTLINE(clang-analyzer-deadcode.DeadStores) auto manager = std::make_unique(*connection, ObjectPath{"/org/sdbuscpp/examplemanager"}); while (true) { From e5aa8d15a5fe63cf64ead14b9b4e2e0ea11d9bcc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stanislav=20Angelovi=C4=8D?= Date: Mon, 12 Jan 2026 08:55:10 +0100 Subject: [PATCH 10/13] chore: update year to 2026 --- include/sdbus-c++/AdaptorInterfaces.h | 2 +- include/sdbus-c++/ConvenienceApiClasses.h | 2 +- include/sdbus-c++/ConvenienceApiClasses.inl | 2 +- include/sdbus-c++/Error.h | 7 ++--- include/sdbus-c++/Flags.h | 2 +- include/sdbus-c++/IConnection.h | 26 +++++++++---------- include/sdbus-c++/IObject.h | 2 +- include/sdbus-c++/IProxy.h | 2 +- include/sdbus-c++/Message.h | 2 +- include/sdbus-c++/MethodResult.h | 2 +- include/sdbus-c++/ProxyInterfaces.h | 2 +- include/sdbus-c++/StandardInterfaces.h | 2 +- include/sdbus-c++/TypeTraits.h | 2 +- include/sdbus-c++/Types.h | 2 +- include/sdbus-c++/VTableItems.h | 2 +- include/sdbus-c++/VTableItems.inl | 2 +- include/sdbus-c++/sdbus-c++.h | 2 +- src/Connection.cpp | 2 +- src/Connection.h | 2 +- src/Error.cpp | 2 +- src/Flags.cpp | 2 +- src/IConnection.h | 2 +- src/ISdBus.h | 2 +- src/Message.cpp | 2 +- src/MessageUtils.h | 2 +- src/Object.cpp | 2 +- src/Object.h | 2 +- src/Proxy.cpp | 2 +- src/Proxy.h | 2 +- src/ScopeGuard.h | 2 +- src/SdBus.cpp | 2 +- src/SdBus.h | 2 +- src/Types.cpp | 2 +- src/Utils.h | 2 +- src/VTableUtils.c | 2 +- src/VTableUtils.h | 2 +- .../DBusAsyncMethodsTests.cpp | 2 +- .../integrationtests/DBusConnectionTests.cpp | 2 +- tests/integrationtests/DBusGeneralTests.cpp | 2 +- tests/integrationtests/DBusMethodsTests.cpp | 2 +- .../integrationtests/DBusPropertiesTests.cpp | 2 +- tests/integrationtests/DBusSignalsTests.cpp | 2 +- .../DBusStandardInterfacesTests.cpp | 2 +- tests/integrationtests/Defs.h | 2 +- tests/integrationtests/TestAdaptor.cpp | 2 +- tests/integrationtests/TestAdaptor.h | 2 +- tests/integrationtests/TestFixture.cpp | 2 +- tests/integrationtests/TestFixture.h | 2 +- tests/integrationtests/TestProxy.cpp | 2 +- tests/integrationtests/TestProxy.h | 2 +- .../sdbus-c++-integration-tests.cpp | 2 +- tests/perftests/client.cpp | 2 +- tests/perftests/server.cpp | 2 +- tests/stresstests/sdbus-c++-stress-tests.cpp | 2 +- tests/unittests/Connection_test.cpp | 2 +- tests/unittests/Message_test.cpp | 2 +- tests/unittests/PollData_test.cpp | 2 +- tests/unittests/TypeTraits_test.cpp | 2 +- tests/unittests/Types_test.cpp | 2 +- tests/unittests/mocks/SdBusMock.h | 2 +- tests/unittests/sdbus-c++-unit-tests.cpp | 2 +- tools/xml2cpp-codegen/AdaptorGenerator.cpp | 2 +- tools/xml2cpp-codegen/AdaptorGenerator.h | 2 +- tools/xml2cpp-codegen/BaseGenerator.cpp | 2 +- tools/xml2cpp-codegen/BaseGenerator.h | 2 +- tools/xml2cpp-codegen/ProxyGenerator.cpp | 2 +- tools/xml2cpp-codegen/ProxyGenerator.h | 2 +- tools/xml2cpp-codegen/xml2cpp.cpp | 2 +- 68 files changed, 83 insertions(+), 82 deletions(-) diff --git a/include/sdbus-c++/AdaptorInterfaces.h b/include/sdbus-c++/AdaptorInterfaces.h index 550a0959..299ad1f3 100644 --- a/include/sdbus-c++/AdaptorInterfaces.h +++ b/include/sdbus-c++/AdaptorInterfaces.h @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file AdaptorInterfaces.h * diff --git a/include/sdbus-c++/ConvenienceApiClasses.h b/include/sdbus-c++/ConvenienceApiClasses.h index d644ab8e..e738b849 100644 --- a/include/sdbus-c++/ConvenienceApiClasses.h +++ b/include/sdbus-c++/ConvenienceApiClasses.h @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file ConvenienceApiClasses.h * diff --git a/include/sdbus-c++/ConvenienceApiClasses.inl b/include/sdbus-c++/ConvenienceApiClasses.inl index 4be40a9f..685e5544 100644 --- a/include/sdbus-c++/ConvenienceApiClasses.inl +++ b/include/sdbus-c++/ConvenienceApiClasses.inl @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file ConvenienceApiClasses.inl * diff --git a/include/sdbus-c++/Error.h b/include/sdbus-c++/Error.h index 4f6e2e9d..ad813d8a 100644 --- a/include/sdbus-c++/Error.h +++ b/include/sdbus-c++/Error.h @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file Error.h * @@ -27,7 +27,7 @@ #ifndef SDBUS_CXX_ERROR_H_ #define SDBUS_CXX_ERROR_H_ -#include +#include #include #include @@ -93,8 +93,9 @@ namespace sdbus { Error createError(int errNo, std::string customMsg = {}); inline const Error::Name SDBUSCPP_ERROR_NAME{"org.sdbuscpp.Error"}; -} +} // namespace sdbus +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) #define SDBUS_THROW_ERROR(_MSG, _ERRNO) \ throw sdbus::createError((_ERRNO), (_MSG)) \ /**/ diff --git a/include/sdbus-c++/Flags.h b/include/sdbus-c++/Flags.h index d85a4aa5..e2d6a627 100644 --- a/include/sdbus-c++/Flags.h +++ b/include/sdbus-c++/Flags.h @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file Flags.h * diff --git a/include/sdbus-c++/IConnection.h b/include/sdbus-c++/IConnection.h index 42caa76b..1160ddcf 100644 --- a/include/sdbus-c++/IConnection.h +++ b/include/sdbus-c++/IConnection.h @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file IConnection.h * @@ -440,7 +440,7 @@ namespace sdbus { * * @throws sdbus::Error in case of failure */ - [[nodiscard]] std::unique_ptr createBusConnection(); + [[nodiscard]] std::unique_ptr createBusConnection(); /*! * @brief Creates/opens D-Bus session bus connection with a name when in a user context, and a system bus connection with a name, otherwise. @@ -450,7 +450,7 @@ namespace sdbus { * * @throws sdbus::Error in case of failure */ - [[nodiscard]] std::unique_ptr createBusConnection(const ServiceName& name); + [[nodiscard]] std::unique_ptr createBusConnection(const ServiceName& name); /*! * @brief Creates/opens D-Bus system bus connection @@ -459,7 +459,7 @@ namespace sdbus { * * @throws sdbus::Error in case of failure */ - [[nodiscard]] std::unique_ptr createSystemBusConnection(); + [[nodiscard]] std::unique_ptr createSystemBusConnection(); /*! * @brief Creates/opens D-Bus system bus connection with a name @@ -469,7 +469,7 @@ namespace sdbus { * * @throws sdbus::Error in case of failure */ - [[nodiscard]] std::unique_ptr createSystemBusConnection(const ServiceName& name); + [[nodiscard]] std::unique_ptr createSystemBusConnection(const ServiceName& name); /*! * @brief Creates/opens D-Bus session bus connection @@ -478,7 +478,7 @@ namespace sdbus { * * @throws sdbus::Error in case of failure */ - [[nodiscard]] std::unique_ptr createSessionBusConnection(); + [[nodiscard]] std::unique_ptr createSessionBusConnection(); /*! * @brief Creates/opens D-Bus session bus connection with a name @@ -488,7 +488,7 @@ namespace sdbus { * * @throws sdbus::Error in case of failure */ - [[nodiscard]] std::unique_ptr createSessionBusConnection(const ServiceName& name); + [[nodiscard]] std::unique_ptr createSessionBusConnection(const ServiceName& name); /*! * @brief Creates/opens D-Bus session bus connection at a custom address @@ -500,7 +500,7 @@ namespace sdbus { * * Consult manual pages for `sd_bus_set_address` of the underlying sd-bus library for more information. */ - [[nodiscard]] std::unique_ptr createSessionBusConnectionWithAddress(const std::string& address); + [[nodiscard]] std::unique_ptr createSessionBusConnectionWithAddress(const std::string& address); /*! * @brief Creates/opens D-Bus system connection on a remote host using ssh @@ -510,7 +510,7 @@ namespace sdbus { * * @throws sdbus::Error in case of failure */ - [[nodiscard]] std::unique_ptr createRemoteSystemBusConnection(const std::string& host); + [[nodiscard]] std::unique_ptr createRemoteSystemBusConnection(const std::string& host); /*! * @brief Opens direct D-Bus connection at a custom address @@ -520,7 +520,7 @@ namespace sdbus { * * @throws sdbus::Error in case of failure */ - [[nodiscard]] std::unique_ptr createDirectBusConnection(const std::string& address); + [[nodiscard]] std::unique_ptr createDirectBusConnection(const std::string& address); /*! * @brief Opens direct D-Bus connection at the given file descriptor @@ -533,7 +533,7 @@ namespace sdbus { * * @throws sdbus::Error in case of failure */ - [[nodiscard]] std::unique_ptr createDirectBusConnection(int fd); + [[nodiscard]] std::unique_ptr createDirectBusConnection(int fd); /*! * @brief Opens direct D-Bus connection at fd as a server @@ -549,7 +549,7 @@ namespace sdbus { * * @throws sdbus::Error in case of failure */ - [[nodiscard]] std::unique_ptr createServerBus(int fd); + [[nodiscard]] std::unique_ptr createServerBus(int fd); /*! * @brief Creates sdbus-c++ bus connection representation out of underlying sd_bus instance @@ -578,7 +578,7 @@ namespace sdbus { * auto con = sdbus::createBusConnection(bus); // IConnection consumes sd_bus object * @endcode */ - [[nodiscard]] std::unique_ptr createBusConnection(sd_bus *bus); + [[nodiscard]] std::unique_ptr createBusConnection(sd_bus *bus); } #endif /* SDBUS_CXX_ICONNECTION_H_ */ diff --git a/include/sdbus-c++/IObject.h b/include/sdbus-c++/IObject.h index 21953bcc..f828411c 100644 --- a/include/sdbus-c++/IObject.h +++ b/include/sdbus-c++/IObject.h @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file IObject.h * diff --git a/include/sdbus-c++/IProxy.h b/include/sdbus-c++/IProxy.h index 5c21191a..6777767d 100644 --- a/include/sdbus-c++/IProxy.h +++ b/include/sdbus-c++/IProxy.h @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file IProxy.h * diff --git a/include/sdbus-c++/Message.h b/include/sdbus-c++/Message.h index fcd3ebcd..dfc6732e 100644 --- a/include/sdbus-c++/Message.h +++ b/include/sdbus-c++/Message.h @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file Message.h * diff --git a/include/sdbus-c++/MethodResult.h b/include/sdbus-c++/MethodResult.h index d6f8540f..dac04bf9 100644 --- a/include/sdbus-c++/MethodResult.h +++ b/include/sdbus-c++/MethodResult.h @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file MethodResult.h * diff --git a/include/sdbus-c++/ProxyInterfaces.h b/include/sdbus-c++/ProxyInterfaces.h index 72f25c6b..56110bba 100644 --- a/include/sdbus-c++/ProxyInterfaces.h +++ b/include/sdbus-c++/ProxyInterfaces.h @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file ProxyInterfaces.h * diff --git a/include/sdbus-c++/StandardInterfaces.h b/include/sdbus-c++/StandardInterfaces.h index 83007b0e..c30b9e17 100644 --- a/include/sdbus-c++/StandardInterfaces.h +++ b/include/sdbus-c++/StandardInterfaces.h @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file StandardInterfaces.h * diff --git a/include/sdbus-c++/TypeTraits.h b/include/sdbus-c++/TypeTraits.h index ccec69c7..37d1f078 100644 --- a/include/sdbus-c++/TypeTraits.h +++ b/include/sdbus-c++/TypeTraits.h @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file TypeTraits.h * diff --git a/include/sdbus-c++/Types.h b/include/sdbus-c++/Types.h index 7b04746f..601fd015 100644 --- a/include/sdbus-c++/Types.h +++ b/include/sdbus-c++/Types.h @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file Types.h * diff --git a/include/sdbus-c++/VTableItems.h b/include/sdbus-c++/VTableItems.h index 019a57b8..23bda879 100644 --- a/include/sdbus-c++/VTableItems.h +++ b/include/sdbus-c++/VTableItems.h @@ -1,5 +1,5 @@ /** - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file VTableItems.h * diff --git a/include/sdbus-c++/VTableItems.inl b/include/sdbus-c++/VTableItems.inl index 127006df..86356cf1 100644 --- a/include/sdbus-c++/VTableItems.inl +++ b/include/sdbus-c++/VTableItems.inl @@ -1,5 +1,5 @@ /** - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file VTableItems.inl * diff --git a/include/sdbus-c++/sdbus-c++.h b/include/sdbus-c++/sdbus-c++.h index 787d8054..3f94ba71 100644 --- a/include/sdbus-c++/sdbus-c++.h +++ b/include/sdbus-c++/sdbus-c++.h @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file sdbus-c++.h * diff --git a/src/Connection.cpp b/src/Connection.cpp index cc05ac08..6177a0f4 100644 --- a/src/Connection.cpp +++ b/src/Connection.cpp @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file Connection.cpp * diff --git a/src/Connection.h b/src/Connection.h index cbd05393..35f8d527 100644 --- a/src/Connection.h +++ b/src/Connection.h @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file Connection.h * diff --git a/src/Error.cpp b/src/Error.cpp index 66b48031..7c2539c5 100644 --- a/src/Error.cpp +++ b/src/Error.cpp @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file Error.cpp * diff --git a/src/Flags.cpp b/src/Flags.cpp index b97ac7fd..0404c709 100644 --- a/src/Flags.cpp +++ b/src/Flags.cpp @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file Flags.cpp * diff --git a/src/IConnection.h b/src/IConnection.h index 7e104a8c..3fb8a4ce 100644 --- a/src/IConnection.h +++ b/src/IConnection.h @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file IConnection.h * diff --git a/src/ISdBus.h b/src/ISdBus.h index c48b0f95..423dc199 100644 --- a/src/ISdBus.h +++ b/src/ISdBus.h @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file ISdBus.h * @author Ardazishvili Roman (ardazishvili.roman@yandex.ru) diff --git a/src/Message.cpp b/src/Message.cpp index 99d03996..aac21398 100644 --- a/src/Message.cpp +++ b/src/Message.cpp @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file Message.cpp * diff --git a/src/MessageUtils.h b/src/MessageUtils.h index e6db9923..3c45f1af 100644 --- a/src/MessageUtils.h +++ b/src/MessageUtils.h @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file MessageUtils.h * diff --git a/src/Object.cpp b/src/Object.cpp index fdeeccf5..9f8746e9 100644 --- a/src/Object.cpp +++ b/src/Object.cpp @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file Object.cpp * diff --git a/src/Object.h b/src/Object.h index d6432578..81447981 100644 --- a/src/Object.h +++ b/src/Object.h @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file Object.h * diff --git a/src/Proxy.cpp b/src/Proxy.cpp index 37b3c946..35540cce 100644 --- a/src/Proxy.cpp +++ b/src/Proxy.cpp @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file Proxy.cpp * diff --git a/src/Proxy.h b/src/Proxy.h index bd42dcf9..50ec3c26 100644 --- a/src/Proxy.h +++ b/src/Proxy.h @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file Proxy.h * diff --git a/src/ScopeGuard.h b/src/ScopeGuard.h index d64a5edd..209d17f3 100644 --- a/src/ScopeGuard.h +++ b/src/ScopeGuard.h @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file ScopeGuard.h * diff --git a/src/SdBus.cpp b/src/SdBus.cpp index ef558d2c..bd070808 100644 --- a/src/SdBus.cpp +++ b/src/SdBus.cpp @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file SdBus.cpp * @author Ardazishvili Roman (ardazishvili.roman@yandex.ru) diff --git a/src/SdBus.h b/src/SdBus.h index 7167de50..1d7e6750 100644 --- a/src/SdBus.h +++ b/src/SdBus.h @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file SdBus.h * @author Ardazishvili Roman (ardazishvili.roman@yandex.ru) diff --git a/src/Types.cpp b/src/Types.cpp index f07ef475..2d3472f5 100644 --- a/src/Types.cpp +++ b/src/Types.cpp @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file Types.cpp * diff --git a/src/Utils.h b/src/Utils.h index edf1c5d8..e4f25c7c 100644 --- a/src/Utils.h +++ b/src/Utils.h @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file Utils.h * diff --git a/src/VTableUtils.c b/src/VTableUtils.c index 906d0699..3cd5a312 100644 --- a/src/VTableUtils.c +++ b/src/VTableUtils.c @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file VTableUtils.c * diff --git a/src/VTableUtils.h b/src/VTableUtils.h index fd9356cd..de0e5937 100644 --- a/src/VTableUtils.h +++ b/src/VTableUtils.h @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file VTableUtils.h * diff --git a/tests/integrationtests/DBusAsyncMethodsTests.cpp b/tests/integrationtests/DBusAsyncMethodsTests.cpp index eb986e23..4c17a995 100644 --- a/tests/integrationtests/DBusAsyncMethodsTests.cpp +++ b/tests/integrationtests/DBusAsyncMethodsTests.cpp @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file DBusAsyncMethodsTests.cpp * diff --git a/tests/integrationtests/DBusConnectionTests.cpp b/tests/integrationtests/DBusConnectionTests.cpp index b24b5e37..bee33405 100644 --- a/tests/integrationtests/DBusConnectionTests.cpp +++ b/tests/integrationtests/DBusConnectionTests.cpp @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file DBusConnectionTests.cpp * diff --git a/tests/integrationtests/DBusGeneralTests.cpp b/tests/integrationtests/DBusGeneralTests.cpp index 839a31b9..a3269803 100644 --- a/tests/integrationtests/DBusGeneralTests.cpp +++ b/tests/integrationtests/DBusGeneralTests.cpp @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file DBusGeneralTests.cpp * diff --git a/tests/integrationtests/DBusMethodsTests.cpp b/tests/integrationtests/DBusMethodsTests.cpp index 39ee5448..92ca927f 100644 --- a/tests/integrationtests/DBusMethodsTests.cpp +++ b/tests/integrationtests/DBusMethodsTests.cpp @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file DBusMethodsTests.cpp * diff --git a/tests/integrationtests/DBusPropertiesTests.cpp b/tests/integrationtests/DBusPropertiesTests.cpp index 962162d0..25b2329e 100644 --- a/tests/integrationtests/DBusPropertiesTests.cpp +++ b/tests/integrationtests/DBusPropertiesTests.cpp @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file DBusPropertiesTests.cpp * diff --git a/tests/integrationtests/DBusSignalsTests.cpp b/tests/integrationtests/DBusSignalsTests.cpp index b99fc1e7..a3a016f1 100644 --- a/tests/integrationtests/DBusSignalsTests.cpp +++ b/tests/integrationtests/DBusSignalsTests.cpp @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file AdaptorAndProxy_test.cpp * diff --git a/tests/integrationtests/DBusStandardInterfacesTests.cpp b/tests/integrationtests/DBusStandardInterfacesTests.cpp index df37f57f..83a7c335 100644 --- a/tests/integrationtests/DBusStandardInterfacesTests.cpp +++ b/tests/integrationtests/DBusStandardInterfacesTests.cpp @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file DBusStandardInterfacesTests.cpp * diff --git a/tests/integrationtests/Defs.h b/tests/integrationtests/Defs.h index 97cfcdd6..229f4897 100644 --- a/tests/integrationtests/Defs.h +++ b/tests/integrationtests/Defs.h @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file Defs.h * diff --git a/tests/integrationtests/TestAdaptor.cpp b/tests/integrationtests/TestAdaptor.cpp index 4637ace5..bc8c89ec 100644 --- a/tests/integrationtests/TestAdaptor.cpp +++ b/tests/integrationtests/TestAdaptor.cpp @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file TestAdaptor.cpp * diff --git a/tests/integrationtests/TestAdaptor.h b/tests/integrationtests/TestAdaptor.h index 847e2a59..c793a2a3 100644 --- a/tests/integrationtests/TestAdaptor.h +++ b/tests/integrationtests/TestAdaptor.h @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file TestAdaptor.h * diff --git a/tests/integrationtests/TestFixture.cpp b/tests/integrationtests/TestFixture.cpp index afc8d65b..d0845d47 100644 --- a/tests/integrationtests/TestFixture.cpp +++ b/tests/integrationtests/TestFixture.cpp @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file TestFixture.cpp * diff --git a/tests/integrationtests/TestFixture.h b/tests/integrationtests/TestFixture.h index afab1940..0bd46db2 100644 --- a/tests/integrationtests/TestFixture.h +++ b/tests/integrationtests/TestFixture.h @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file TestFixture.h * diff --git a/tests/integrationtests/TestProxy.cpp b/tests/integrationtests/TestProxy.cpp index e9d93d3e..9aeca83f 100644 --- a/tests/integrationtests/TestProxy.cpp +++ b/tests/integrationtests/TestProxy.cpp @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file TestProxy.cpp * diff --git a/tests/integrationtests/TestProxy.h b/tests/integrationtests/TestProxy.h index 683b56c7..c3a91b9e 100644 --- a/tests/integrationtests/TestProxy.h +++ b/tests/integrationtests/TestProxy.h @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file TestProxy.h * diff --git a/tests/integrationtests/sdbus-c++-integration-tests.cpp b/tests/integrationtests/sdbus-c++-integration-tests.cpp index 84816394..859920db 100644 --- a/tests/integrationtests/sdbus-c++-integration-tests.cpp +++ b/tests/integrationtests/sdbus-c++-integration-tests.cpp @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file sdbus-c++-integration-tests.cpp * diff --git a/tests/perftests/client.cpp b/tests/perftests/client.cpp index 52dcd30a..38ddc27b 100644 --- a/tests/perftests/client.cpp +++ b/tests/perftests/client.cpp @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file client.cpp * diff --git a/tests/perftests/server.cpp b/tests/perftests/server.cpp index 82bca57d..b3faa0d4 100644 --- a/tests/perftests/server.cpp +++ b/tests/perftests/server.cpp @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file server.cpp * diff --git a/tests/stresstests/sdbus-c++-stress-tests.cpp b/tests/stresstests/sdbus-c++-stress-tests.cpp index 57f06a0c..497db3bc 100644 --- a/tests/stresstests/sdbus-c++-stress-tests.cpp +++ b/tests/stresstests/sdbus-c++-stress-tests.cpp @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file sdbus-c++-stress-tests.cpp * diff --git a/tests/unittests/Connection_test.cpp b/tests/unittests/Connection_test.cpp index 5f116daf..8fd78794 100644 --- a/tests/unittests/Connection_test.cpp +++ b/tests/unittests/Connection_test.cpp @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file Connection_test.cpp * @author Ardazishvili Roman (ardazishvili.roman@yandex.ru) diff --git a/tests/unittests/Message_test.cpp b/tests/unittests/Message_test.cpp index a6ce0c45..dd0287a6 100644 --- a/tests/unittests/Message_test.cpp +++ b/tests/unittests/Message_test.cpp @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file Message_test.cpp * diff --git a/tests/unittests/PollData_test.cpp b/tests/unittests/PollData_test.cpp index 09e9d788..247feed1 100644 --- a/tests/unittests/PollData_test.cpp +++ b/tests/unittests/PollData_test.cpp @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file PollData_test.cpp * diff --git a/tests/unittests/TypeTraits_test.cpp b/tests/unittests/TypeTraits_test.cpp index 35504af6..d115c01a 100644 --- a/tests/unittests/TypeTraits_test.cpp +++ b/tests/unittests/TypeTraits_test.cpp @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file TypeTraits_test.cpp * diff --git a/tests/unittests/Types_test.cpp b/tests/unittests/Types_test.cpp index 0a5baf06..f9f1487e 100644 --- a/tests/unittests/Types_test.cpp +++ b/tests/unittests/Types_test.cpp @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file Types_test.cpp * diff --git a/tests/unittests/mocks/SdBusMock.h b/tests/unittests/mocks/SdBusMock.h index 9d0fd2be..c8b1e1c0 100644 --- a/tests/unittests/mocks/SdBusMock.h +++ b/tests/unittests/mocks/SdBusMock.h @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file SdBusMock.h * @author Ardazishvili Roman (ardazishvili.roman@yandex.ru) diff --git a/tests/unittests/sdbus-c++-unit-tests.cpp b/tests/unittests/sdbus-c++-unit-tests.cpp index 56e6602a..a15c90ec 100644 --- a/tests/unittests/sdbus-c++-unit-tests.cpp +++ b/tests/unittests/sdbus-c++-unit-tests.cpp @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file sdbus-c++-unit-tests.cpp * diff --git a/tools/xml2cpp-codegen/AdaptorGenerator.cpp b/tools/xml2cpp-codegen/AdaptorGenerator.cpp index dc480b98..82a6a5e7 100644 --- a/tools/xml2cpp-codegen/AdaptorGenerator.cpp +++ b/tools/xml2cpp-codegen/AdaptorGenerator.cpp @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file AdaptorGenerator.cpp * diff --git a/tools/xml2cpp-codegen/AdaptorGenerator.h b/tools/xml2cpp-codegen/AdaptorGenerator.h index 36c90d0c..17bedad3 100644 --- a/tools/xml2cpp-codegen/AdaptorGenerator.h +++ b/tools/xml2cpp-codegen/AdaptorGenerator.h @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file AdaptorGenerator.h * diff --git a/tools/xml2cpp-codegen/BaseGenerator.cpp b/tools/xml2cpp-codegen/BaseGenerator.cpp index d9dde3fd..75250b90 100644 --- a/tools/xml2cpp-codegen/BaseGenerator.cpp +++ b/tools/xml2cpp-codegen/BaseGenerator.cpp @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file BaseGenerator.cpp * diff --git a/tools/xml2cpp-codegen/BaseGenerator.h b/tools/xml2cpp-codegen/BaseGenerator.h index 3b7c8e44..7a91c558 100644 --- a/tools/xml2cpp-codegen/BaseGenerator.h +++ b/tools/xml2cpp-codegen/BaseGenerator.h @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file BaseGenerator.h * diff --git a/tools/xml2cpp-codegen/ProxyGenerator.cpp b/tools/xml2cpp-codegen/ProxyGenerator.cpp index cbd17aaf..b80bac58 100644 --- a/tools/xml2cpp-codegen/ProxyGenerator.cpp +++ b/tools/xml2cpp-codegen/ProxyGenerator.cpp @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file ProxyGenerator.cpp * diff --git a/tools/xml2cpp-codegen/ProxyGenerator.h b/tools/xml2cpp-codegen/ProxyGenerator.h index 7ae2f4ae..cd896f0d 100644 --- a/tools/xml2cpp-codegen/ProxyGenerator.h +++ b/tools/xml2cpp-codegen/ProxyGenerator.h @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file ProxyGenerator.h * diff --git a/tools/xml2cpp-codegen/xml2cpp.cpp b/tools/xml2cpp-codegen/xml2cpp.cpp index ba9e45f5..5d75a45d 100644 --- a/tools/xml2cpp-codegen/xml2cpp.cpp +++ b/tools/xml2cpp-codegen/xml2cpp.cpp @@ -1,6 +1,6 @@ /** * (C) 2016 - 2021 KISTLER INSTRUMENTE AG, Winterthur, Switzerland - * (C) 2016 - 2024 Stanislav Angelovic + * (C) 2016 - 2026 Stanislav Angelovic * * @file xml2cpp.cpp * From dc91924dee8bd55fb95ec89e8d5e4a3f6133bea2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stanislav=20Angelovi=C4=8D?= Date: Mon, 12 Jan 2026 11:10:25 +0100 Subject: [PATCH 11/13] fix: address clang-tidy warnings in headers --- .clang-tidy | 6 +- examples/CMakeLists.txt | 16 +- .../examplemanager-planet1-client-glue.h | 0 .../examplemanager-planet1-server-glue.h | 0 .../org.sdbuscpp.ExampleManager.Planet1.xml | 0 .../obj-manager-server.cpp | 14 +- include/sdbus-c++/AdaptorInterfaces.h | 27 +- include/sdbus-c++/ConvenienceApiClasses.h | 93 ++--- include/sdbus-c++/ConvenienceApiClasses.inl | 148 +++---- include/sdbus-c++/Error.h | 2 +- include/sdbus-c++/Flags.h | 2 +- include/sdbus-c++/IConnection.h | 12 +- include/sdbus-c++/IObject.h | 18 +- include/sdbus-c++/IProxy.h | 79 ++-- include/sdbus-c++/Message.h | 385 ++++++++--------- include/sdbus-c++/MethodResult.h | 24 +- include/sdbus-c++/ProxyInterfaces.h | 37 +- include/sdbus-c++/StandardInterfaces.h | 171 ++++---- include/sdbus-c++/TypeTraits.h | 393 +++++++++--------- include/sdbus-c++/Types.h | 111 ++--- include/sdbus-c++/VTableItems.h | 16 +- include/sdbus-c++/VTableItems.inl | 72 ++-- src/Connection.cpp | 4 +- src/Connection.h | 41 +- src/IConnection.h | 6 +- src/ISdBus.h | 46 +- src/MessageUtils.h | 26 +- src/Object.h | 7 +- src/Proxy.cpp | 2 +- src/Proxy.h | 19 +- src/ScopeGuard.h | 35 +- src/SdBus.h | 130 +++--- src/Utils.h | 10 +- tests/CMakeLists.txt | 43 +- tests/integrationtests/Defs.h | 15 +- tests/integrationtests/TestAdaptor.cpp | 2 +- tests/integrationtests/TestAdaptor.h | 15 +- tests/integrationtests/TestFixture.h | 70 ++-- tests/integrationtests/TestProxy.h | 22 +- .../gen-cpp}/integrationtests-adaptor.h | 0 .../gen-cpp}/integrationtests-proxy.h | 0 .../org.sdbuscpp.integrationtests.xml | 0 .../gen-cpp}/perftests-adaptor.h | 0 .../{ => dbus-api/gen-cpp}/perftests-proxy.h | 0 .../{ => dbus-api}/org.sdbuscpp.perftests.xml | 0 .../gen-cpp}/celsius-thermometer-adaptor.h | 0 .../gen-cpp}/celsius-thermometer-proxy.h | 0 .../gen-cpp}/concatenator-adaptor.h | 0 .../gen-cpp}/concatenator-proxy.h | 0 .../gen-cpp}/fahrenheit-thermometer-adaptor.h | 0 .../gen-cpp}/fahrenheit-thermometer-proxy.h | 0 ...dbuscpp.stresstest.celsius.thermometer.xml | 0 .../org.sdbuscpp.stresstest.concatenator.xml | 0 ...scpp.stresstest.fahrenheit.thermometer.xml | 0 tests/unittests/Connection_test.cpp | 10 +- tests/unittests/mocks/SdBusMock.h | 24 +- 56 files changed, 1107 insertions(+), 1046 deletions(-) rename examples/org.freedesktop.DBus.ObjectManager/{ => dbus-api/gen-cpp}/examplemanager-planet1-client-glue.h (100%) rename examples/org.freedesktop.DBus.ObjectManager/{ => dbus-api/gen-cpp}/examplemanager-planet1-server-glue.h (100%) rename examples/org.freedesktop.DBus.ObjectManager/{ => dbus-api}/org.sdbuscpp.ExampleManager.Planet1.xml (100%) rename tests/integrationtests/{ => dbus-api/gen-cpp}/integrationtests-adaptor.h (100%) rename tests/integrationtests/{ => dbus-api/gen-cpp}/integrationtests-proxy.h (100%) rename tests/integrationtests/{ => dbus-api}/org.sdbuscpp.integrationtests.xml (100%) rename tests/perftests/{ => dbus-api/gen-cpp}/perftests-adaptor.h (100%) rename tests/perftests/{ => dbus-api/gen-cpp}/perftests-proxy.h (100%) rename tests/perftests/{ => dbus-api}/org.sdbuscpp.perftests.xml (100%) rename tests/stresstests/{ => dbus-api/gen-cpp}/celsius-thermometer-adaptor.h (100%) rename tests/stresstests/{ => dbus-api/gen-cpp}/celsius-thermometer-proxy.h (100%) rename tests/stresstests/{ => dbus-api/gen-cpp}/concatenator-adaptor.h (100%) rename tests/stresstests/{ => dbus-api/gen-cpp}/concatenator-proxy.h (100%) rename tests/stresstests/{ => dbus-api/gen-cpp}/fahrenheit-thermometer-adaptor.h (100%) rename tests/stresstests/{ => dbus-api/gen-cpp}/fahrenheit-thermometer-proxy.h (100%) rename tests/stresstests/{ => dbus-api}/org.sdbuscpp.stresstest.celsius.thermometer.xml (100%) rename tests/stresstests/{ => dbus-api}/org.sdbuscpp.stresstest.concatenator.xml (100%) rename tests/stresstests/{ => dbus-api}/org.sdbuscpp.stresstest.fahrenheit.thermometer.xml (100%) diff --git a/.clang-tidy b/.clang-tidy index ba9ae4e9..5bcbaebb 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -13,7 +13,9 @@ Checks: "*,\ -hicpp-braces-around-statements,\ -hicpp-signed-bitwise,\ -llvm-include-order,\ + -llvm-header-guard,\ -google-runtime-int,\ + -google-default-arguments,\ -hicpp-named-parameter,\ -readability-named-parameter,\ -bugprone-macro-parentheses,\ @@ -24,9 +26,11 @@ Checks: "*,\ -hicpp-no-array-decay,\ -cppcoreguidelines-avoid-c-arrays,\ -hicpp-avoid-c-arrays,\ + -cppcoreguidelines-non-private-member-variables-in-classes,\ + -misc-non-private-member-variables-in-classes,\ -modernize-avoid-c-arrays" -HeaderFilterRegex: 'src|sdbus-c++' +HeaderFilterRegex: '.*' FormatStyle: file WarningsAsErrors: "*" CheckOptions: diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index 423259a8..57e4c768 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -1,9 +1,21 @@ # Building examples -add_executable(obj-manager-server org.freedesktop.DBus.ObjectManager/obj-manager-server.cpp) +set(OBJECTMANAGER_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/org.freedesktop.DBus.ObjectManager) +set(OBJECTMANAGER_GENERATED_DIR ${OBJECTMANAGER_SOURCE_DIR}/dbus-api/gen-cpp) +set(OBJECTMANAGER_SERVER_SRCS + ${OBJECTMANAGER_SOURCE_DIR}/obj-manager-server.cpp + ${OBJECTMANAGER_GENERATED_DIR}/examplemanager-planet1-server-glue.h) + +add_executable(obj-manager-server ${OBJECTMANAGER_SERVER_SRCS}) +target_include_directories(obj-manager-server SYSTEM PRIVATE ${OBJECTMANAGER_GENERATED_DIR}) target_link_libraries(obj-manager-server sdbus-c++) -add_executable(obj-manager-client org.freedesktop.DBus.ObjectManager/obj-manager-client.cpp) +set(OBJECTMANAGER_CLIENT_SRCS + ${OBJECTMANAGER_SOURCE_DIR}/obj-manager-client.cpp + ${OBJECTMANAGER_GENERATED_DIR}/examplemanager-planet1-client-glue.h) + +add_executable(obj-manager-client ${OBJECTMANAGER_CLIENT_SRCS}) +target_include_directories(obj-manager-client SYSTEM PRIVATE ${OBJECTMANAGER_GENERATED_DIR}) target_link_libraries(obj-manager-client sdbus-c++) if(SDBUSCPP_INSTALL) diff --git a/examples/org.freedesktop.DBus.ObjectManager/examplemanager-planet1-client-glue.h b/examples/org.freedesktop.DBus.ObjectManager/dbus-api/gen-cpp/examplemanager-planet1-client-glue.h similarity index 100% rename from examples/org.freedesktop.DBus.ObjectManager/examplemanager-planet1-client-glue.h rename to examples/org.freedesktop.DBus.ObjectManager/dbus-api/gen-cpp/examplemanager-planet1-client-glue.h diff --git a/examples/org.freedesktop.DBus.ObjectManager/examplemanager-planet1-server-glue.h b/examples/org.freedesktop.DBus.ObjectManager/dbus-api/gen-cpp/examplemanager-planet1-server-glue.h similarity index 100% rename from examples/org.freedesktop.DBus.ObjectManager/examplemanager-planet1-server-glue.h rename to examples/org.freedesktop.DBus.ObjectManager/dbus-api/gen-cpp/examplemanager-planet1-server-glue.h diff --git a/examples/org.freedesktop.DBus.ObjectManager/org.sdbuscpp.ExampleManager.Planet1.xml b/examples/org.freedesktop.DBus.ObjectManager/dbus-api/org.sdbuscpp.ExampleManager.Planet1.xml similarity index 100% rename from examples/org.freedesktop.DBus.ObjectManager/org.sdbuscpp.ExampleManager.Planet1.xml rename to examples/org.freedesktop.DBus.ObjectManager/dbus-api/org.sdbuscpp.ExampleManager.Planet1.xml diff --git a/examples/org.freedesktop.DBus.ObjectManager/obj-manager-server.cpp b/examples/org.freedesktop.DBus.ObjectManager/obj-manager-server.cpp index c83079a3..fbf75575 100644 --- a/examples/org.freedesktop.DBus.ObjectManager/obj-manager-server.cpp +++ b/examples/org.freedesktop.DBus.ObjectManager/obj-manager-server.cpp @@ -22,8 +22,6 @@ #include #include -using sdbus::ObjectPath; - class ManagerAdaptor : public sdbus::AdaptorInterfaces { public: @@ -55,7 +53,7 @@ class PlanetAdaptor final : public sdbus::AdaptorInterfaces< org::sdbuscpp::Exam , m_population(population) { registerAdaptor(); - emitInterfacesAddedSignal({sdbus::InterfaceName{org::sdbuscpp::ExampleManager::Planet1_adaptor::INTERFACE_NAME}}); + emitInterfacesAddedSignal({sdbus::InterfaceName{Planet1_adaptor::INTERFACE_NAME}}); } PlanetAdaptor(const PlanetAdaptor&) = delete; @@ -65,7 +63,7 @@ class PlanetAdaptor final : public sdbus::AdaptorInterfaces< org::sdbuscpp::Exam ~PlanetAdaptor() { - emitInterfacesRemovedSignal({sdbus::InterfaceName{org::sdbuscpp::ExampleManager::Planet1_adaptor::INTERFACE_NAME}}); + emitInterfacesRemovedSignal({sdbus::InterfaceName{Planet1_adaptor::INTERFACE_NAME}}); unregisterAdaptor(); } @@ -102,15 +100,15 @@ int main() connection->enterEventLoopAsync(); // NOLINTNEXTLINE(clang-analyzer-deadcode.DeadStores) - auto manager = std::make_unique(*connection, ObjectPath{"/org/sdbuscpp/examplemanager"}); + auto manager = std::make_unique(*connection, sdbus::ObjectPath{"/org/sdbuscpp/examplemanager"}); while (true) { printCountDown("Creating PlanetAdaptor in ", 5); - auto earth = std::make_unique(*connection, ObjectPath{"/org/sdbuscpp/examplemanager/Planet1/Earth"}, "Earth", 7'874'965'825); + auto earth = std::make_unique(*connection, sdbus::ObjectPath{"/org/sdbuscpp/examplemanager/Planet1/Earth"}, "Earth", 7'874'965'825); printCountDown("Creating PlanetAdaptor in ", 5); - auto trantor = std::make_unique(*connection, ObjectPath{"/org/sdbuscpp/examplemanager/Planet1/Trantor"}, "Trantor", 40'000'000'000); + auto trantor = std::make_unique(*connection, sdbus::ObjectPath{"/org/sdbuscpp/examplemanager/Planet1/Trantor"}, "Trantor", 40'000'000'000); printCountDown("Creating PlanetAdaptor in ", 5); - auto laconia = std::make_unique(*connection, ObjectPath{"/org/sdbuscpp/examplemanager/Planet1/Laconia"}, "Laconia", 231'721); + auto laconia = std::make_unique(*connection, sdbus::ObjectPath{"/org/sdbuscpp/examplemanager/Planet1/Laconia"}, "Laconia", 231'721); printCountDown("Removing PlanetAdaptor in ", 5); earth.reset(); printCountDown("Removing PlanetAdaptor in ", 5); diff --git a/include/sdbus-c++/AdaptorInterfaces.h b/include/sdbus-c++/AdaptorInterfaces.h index 299ad1f3..a11a539e 100644 --- a/include/sdbus-c++/AdaptorInterfaces.h +++ b/include/sdbus-c++/AdaptorInterfaces.h @@ -35,7 +35,7 @@ // Forward declarations namespace sdbus { class IConnection; -} +} // namespace sdbus namespace sdbus { @@ -50,18 +50,18 @@ namespace sdbus { class ObjectHolder { protected: - ObjectHolder(std::unique_ptr&& object) + explicit ObjectHolder(std::unique_ptr&& object) : object_(std::move(object)) { } - const IObject& getObject() const + [[nodiscard]] const IObject& getObject() const { assert(object_ != nullptr); return *object_; } - IObject& getObject() + [[nodiscard]] IObject& getObject() { assert(object_ != nullptr); return *object_; @@ -88,12 +88,17 @@ namespace sdbus { * so that the object API vtable is registered and unregistered at the proper time. * ***********************************************/ - template + template class AdaptorInterfaces : protected ObjectHolder - , public _Interfaces... + , public Interfaces... { public: + AdaptorInterfaces(const AdaptorInterfaces&) = delete; + AdaptorInterfaces& operator=(const AdaptorInterfaces&) = delete; + AdaptorInterfaces(AdaptorInterfaces&&) = delete; + AdaptorInterfaces& operator=(AdaptorInterfaces&&) = delete; + /*! * @brief Creates object instance * @@ -104,7 +109,7 @@ namespace sdbus { */ AdaptorInterfaces(IConnection& connection, ObjectPath objectPath) : ObjectHolder(createObject(connection, std::move(objectPath))) - , _Interfaces(getObject())... + , Interfaces(getObject())... { } @@ -117,7 +122,7 @@ namespace sdbus { */ void registerAdaptor() { - (_Interfaces::registerAdaptor(), ...); + (Interfaces::registerAdaptor(), ...); } /*! @@ -140,13 +145,9 @@ namespace sdbus { protected: using base_type = AdaptorInterfaces; - AdaptorInterfaces(const AdaptorInterfaces&) = delete; - AdaptorInterfaces& operator=(const AdaptorInterfaces&) = delete; - AdaptorInterfaces(AdaptorInterfaces&&) = delete; - AdaptorInterfaces& operator=(AdaptorInterfaces&&) = delete; ~AdaptorInterfaces() = default; }; -} +} // namespace sdbus #endif /* SDBUS_CXX_ADAPTORINTERFACES_H_ */ diff --git a/include/sdbus-c++/ConvenienceApiClasses.h b/include/sdbus-c++/ConvenienceApiClasses.h index e738b849..ac4f0f64 100644 --- a/include/sdbus-c++/ConvenienceApiClasses.h +++ b/include/sdbus-c++/ConvenienceApiClasses.h @@ -46,7 +46,7 @@ namespace sdbus { class IProxy; class Error; class PendingAsyncCall; -} +} // namespace sdbus namespace sdbus { @@ -62,8 +62,7 @@ namespace sdbus { friend IObject; VTableAdder(IObject& object, std::vector vtable); - private: - IObject& object_; + IObject& object_; // NOLINT(cppcoreguidelines-avoid-const-or-ref-data-members) std::vector vtable_; }; @@ -73,9 +72,12 @@ namespace sdbus { SignalEmitter& onInterface(const InterfaceName& interfaceName); SignalEmitter& onInterface(const std::string& interfaceName); SignalEmitter& onInterface(const char* interfaceName); - template void withArguments(_Args&&... args); + template void withArguments(Args&&... args); + SignalEmitter(const SignalEmitter&) = delete; + SignalEmitter& operator=(const SignalEmitter&) = delete; SignalEmitter(SignalEmitter&& other) = default; + SignalEmitter& operator=(SignalEmitter&&) = delete; ~SignalEmitter() noexcept(false); private: @@ -83,8 +85,7 @@ namespace sdbus { SignalEmitter(IObject& object, const SignalName& signalName); SignalEmitter(IObject& object, const char* signalName); - private: - IObject& object_; + IObject& object_; // NOLINT(cppcoreguidelines-avoid-const-or-ref-data-members) const char* signalName_; Signal signal_; int exceptions_{}; // Number of active exceptions when SignalEmitter is constructed @@ -97,13 +98,16 @@ namespace sdbus { MethodInvoker& onInterface(const std::string& interfaceName); MethodInvoker& onInterface(const char* interfaceName); MethodInvoker& withTimeout(uint64_t usec); - template - MethodInvoker& withTimeout(const std::chrono::duration<_Rep, _Period>& timeout); - template MethodInvoker& withArguments(_Args&&... args); - template void storeResultsTo(_Args&... args); + template + MethodInvoker& withTimeout(const std::chrono::duration& timeout); + template MethodInvoker& withArguments(Args&&... args); + template void storeResultsTo(Args&... args); void dontExpectReply(); + MethodInvoker(const MethodInvoker&) = delete; + MethodInvoker& operator=(const MethodInvoker&) = delete; MethodInvoker(MethodInvoker&& other) = default; + MethodInvoker& operator=(MethodInvoker&&) = delete; ~MethodInvoker() noexcept(false); private: @@ -111,8 +115,7 @@ namespace sdbus { MethodInvoker(IProxy& proxy, const MethodName& methodName); MethodInvoker(IProxy& proxy, const char* methodName); - private: - IProxy& proxy_; + IProxy& proxy_; // NOLINT(cppcoreguidelines-avoid-const-or-ref-data-members) const char* methodName_; uint64_t timeout_{}; MethodCall method_; @@ -127,24 +130,23 @@ namespace sdbus { AsyncMethodInvoker& onInterface(const std::string& interfaceName); AsyncMethodInvoker& onInterface(const char* interfaceName); AsyncMethodInvoker& withTimeout(uint64_t usec); - template - AsyncMethodInvoker& withTimeout(const std::chrono::duration<_Rep, _Period>& timeout); - template AsyncMethodInvoker& withArguments(_Args&&... args); - template PendingAsyncCall uponReplyInvoke(_Function&& callback); - template [[nodiscard]] Slot uponReplyInvoke(_Function&& callback, return_slot_t); + template + AsyncMethodInvoker& withTimeout(const std::chrono::duration& timeout); + template AsyncMethodInvoker& withArguments(Args&&... args); + template PendingAsyncCall uponReplyInvoke(Function&& callback); + template [[nodiscard]] Slot uponReplyInvoke(Function&& callback, return_slot_t); // Returned future will be std::future for no (void) D-Bus method return value // or std::future for single D-Bus method return value // or std::future> for multiple method return values - template std::future> getResultAsFuture(); + template std::future> getResultAsFuture(); private: friend IProxy; AsyncMethodInvoker(IProxy& proxy, const MethodName& methodName); AsyncMethodInvoker(IProxy& proxy, const char* methodName); - template async_reply_handler makeAsyncReplyHandler(_Function&& callback); + template async_reply_handler makeAsyncReplyHandler(Function&& callback); - private: - IProxy& proxy_; + IProxy& proxy_; // NOLINT(cppcoreguidelines-avoid-const-or-ref-data-members) const char* methodName_; uint64_t timeout_{}; MethodCall method_; @@ -156,17 +158,16 @@ namespace sdbus { SignalSubscriber& onInterface(const InterfaceName& interfaceName); SignalSubscriber& onInterface(const std::string& interfaceName); SignalSubscriber& onInterface(const char* interfaceName); - template void call(_Function&& callback); - template [[nodiscard]] Slot call(_Function&& callback, return_slot_t); + template void call(Function&& callback); + template [[nodiscard]] Slot call(Function&& callback, return_slot_t); private: friend IProxy; SignalSubscriber(IProxy& proxy, const SignalName& signalName); SignalSubscriber(IProxy& proxy, const char* signalName); - template signal_handler makeSignalHandler(_Function&& callback); + template signal_handler makeSignalHandler(Function&& callback); - private: - IProxy& proxy_; + IProxy& proxy_; // NOLINT(cppcoreguidelines-avoid-const-or-ref-data-members) const char* signalName_; const char* interfaceName_{}; }; @@ -182,8 +183,7 @@ namespace sdbus { static constexpr const char* DBUS_PROPERTIES_INTERFACE_NAME = "org.freedesktop.DBus.Properties"; - private: - IProxy& proxy_; + IProxy& proxy_; // NOLINT(cppcoreguidelines-avoid-const-or-ref-data-members) std::string_view propertyName_; }; @@ -191,8 +191,8 @@ namespace sdbus { { public: AsyncPropertyGetter& onInterface(std::string_view interfaceName); - template PendingAsyncCall uponReplyInvoke(_Function&& callback); - template [[nodiscard]] Slot uponReplyInvoke(_Function&& callback, return_slot_t); + template PendingAsyncCall uponReplyInvoke(Function&& callback); + template [[nodiscard]] Slot uponReplyInvoke(Function&& callback, return_slot_t); std::future getResultAsFuture(); private: @@ -201,8 +201,7 @@ namespace sdbus { static constexpr const char* DBUS_PROPERTIES_INTERFACE_NAME = "org.freedesktop.DBus.Properties"; - private: - IProxy& proxy_; + IProxy& proxy_; // NOLINT(cppcoreguidelines-avoid-const-or-ref-data-members) std::string_view propertyName_; std::string_view interfaceName_; }; @@ -211,8 +210,8 @@ namespace sdbus { { public: PropertySetter& onInterface(std::string_view interfaceName); - template void toValue(const _Value& value); - template void toValue(const _Value& value, dont_expect_reply_t); + template void toValue(const Value& value); + template void toValue(const Value& value, dont_expect_reply_t); void toValue(const Variant& value); void toValue(const Variant& value, dont_expect_reply_t); @@ -222,8 +221,7 @@ namespace sdbus { static constexpr const char* DBUS_PROPERTIES_INTERFACE_NAME = "org.freedesktop.DBus.Properties"; - private: - IProxy& proxy_; + IProxy& proxy_; // NOLINT(cppcoreguidelines-avoid-const-or-ref-data-members) std::string_view propertyName_; std::string_view interfaceName_; }; @@ -232,10 +230,10 @@ namespace sdbus { { public: AsyncPropertySetter& onInterface(std::string_view interfaceName); - template AsyncPropertySetter& toValue(_Value&& value); + template AsyncPropertySetter& toValue(Value&& value); AsyncPropertySetter& toValue(Variant value); - template PendingAsyncCall uponReplyInvoke(_Function&& callback); - template [[nodiscard]] Slot uponReplyInvoke(_Function&& callback, return_slot_t); + template PendingAsyncCall uponReplyInvoke(Function&& callback); + template [[nodiscard]] Slot uponReplyInvoke(Function&& callback, return_slot_t); std::future getResultAsFuture(); private: @@ -244,8 +242,7 @@ namespace sdbus { static constexpr const char* DBUS_PROPERTIES_INTERFACE_NAME = "org.freedesktop.DBus.Properties"; - private: - IProxy& proxy_; + IProxy& proxy_; // NOLINT(cppcoreguidelines-avoid-const-or-ref-data-members) std::string_view propertyName_; std::string_view interfaceName_; Variant value_; @@ -258,30 +255,28 @@ namespace sdbus { private: friend IProxy; - AllPropertiesGetter(IProxy& proxy); + explicit AllPropertiesGetter(IProxy& proxy); static constexpr const char* DBUS_PROPERTIES_INTERFACE_NAME = "org.freedesktop.DBus.Properties"; - private: - IProxy& proxy_; + IProxy& proxy_; // NOLINT(cppcoreguidelines-avoid-const-or-ref-data-members) }; class AsyncAllPropertiesGetter { public: AsyncAllPropertiesGetter& onInterface(std::string_view interfaceName); - template PendingAsyncCall uponReplyInvoke(_Function&& callback); - template [[nodiscard]] Slot uponReplyInvoke(_Function&& callback, return_slot_t); + template PendingAsyncCall uponReplyInvoke(Function&& callback); + template [[nodiscard]] Slot uponReplyInvoke(Function&& callback, return_slot_t); std::future> getResultAsFuture(); private: friend IProxy; - AsyncAllPropertiesGetter(IProxy& proxy); + explicit AsyncAllPropertiesGetter(IProxy& proxy); static constexpr const char* DBUS_PROPERTIES_INTERFACE_NAME = "org.freedesktop.DBus.Properties"; - private: - IProxy& proxy_; + IProxy& proxy_; // NOLINT(cppcoreguidelines-avoid-const-or-ref-data-members) std::string_view interfaceName_; }; diff --git a/include/sdbus-c++/ConvenienceApiClasses.inl b/include/sdbus-c++/ConvenienceApiClasses.inl index 685e5544..8944815f 100644 --- a/include/sdbus-c++/ConvenienceApiClasses.inl +++ b/include/sdbus-c++/ConvenienceApiClasses.inl @@ -28,8 +28,8 @@ #define SDBUS_CPP_CONVENIENCEAPICLASSES_INL_ #include -#include -#include +#include // NOLINT(misc-header-include-cycle) +#include // NOLINT(misc-header-include-cycle) #include #include #include @@ -124,12 +124,12 @@ namespace sdbus { return *this; } - template - inline void SignalEmitter::withArguments(_Args&&... args) + template + inline void SignalEmitter::withArguments(Args&&... args) { assert(signal_.isValid()); // onInterface() must be placed/called prior to withArguments() - detail::serialize_pack(signal_, std::forward<_Args>(args)...); + detail::serialize_pack(signal_, std::forward(args)...); } /*** ------------- ***/ @@ -191,25 +191,25 @@ namespace sdbus { return *this; } - template - inline MethodInvoker& MethodInvoker::withTimeout(const std::chrono::duration<_Rep, _Period>& timeout) + template + inline MethodInvoker& MethodInvoker::withTimeout(const std::chrono::duration& timeout) { auto microsecs = std::chrono::duration_cast(timeout); return withTimeout(microsecs.count()); } - template - inline MethodInvoker& MethodInvoker::withArguments(_Args&&... args) + template + inline MethodInvoker& MethodInvoker::withArguments(Args&&... args) { assert(method_.isValid()); // onInterface() must be placed/called prior to this function - detail::serialize_pack(method_, std::forward<_Args>(args)...); + detail::serialize_pack(method_, std::forward(args)...); return *this; } - template - inline void MethodInvoker::storeResultsTo(_Args&... args) + template + inline void MethodInvoker::storeResultsTo(Args&... args) { assert(method_.isValid()); // onInterface() must be placed/called prior to this function @@ -265,50 +265,50 @@ namespace sdbus { return *this; } - template - inline AsyncMethodInvoker& AsyncMethodInvoker::withTimeout(const std::chrono::duration<_Rep, _Period>& timeout) + template + inline AsyncMethodInvoker& AsyncMethodInvoker::withTimeout(const std::chrono::duration& timeout) { auto microsecs = std::chrono::duration_cast(timeout); return withTimeout(microsecs.count()); } - template - inline AsyncMethodInvoker& AsyncMethodInvoker::withArguments(_Args&&... args) + template + inline AsyncMethodInvoker& AsyncMethodInvoker::withArguments(Args&&... args) { assert(method_.isValid()); // onInterface() must be placed/called prior to this function - detail::serialize_pack(method_, std::forward<_Args>(args)...); + detail::serialize_pack(method_, std::forward(args)...); return *this; } - template - PendingAsyncCall AsyncMethodInvoker::uponReplyInvoke(_Function&& callback) + template + PendingAsyncCall AsyncMethodInvoker::uponReplyInvoke(Function&& callback) { assert(method_.isValid()); // onInterface() must be placed/called prior to this function - return proxy_.callMethodAsync(method_, makeAsyncReplyHandler(std::forward<_Function>(callback)), timeout_); + return proxy_.callMethodAsync(method_, makeAsyncReplyHandler(std::forward(callback)), timeout_); } - template - [[nodiscard]] Slot AsyncMethodInvoker::uponReplyInvoke(_Function&& callback, return_slot_t) + template + [[nodiscard]] Slot AsyncMethodInvoker::uponReplyInvoke(Function&& callback, return_slot_t) { assert(method_.isValid()); // onInterface() must be placed/called prior to this function return proxy_.callMethodAsync( method_ - , makeAsyncReplyHandler(std::forward<_Function>(callback)) + , makeAsyncReplyHandler(std::forward(callback)) , timeout_ , return_slot ); } - template - inline async_reply_handler AsyncMethodInvoker::makeAsyncReplyHandler(_Function&& callback) + template + inline async_reply_handler AsyncMethodInvoker::makeAsyncReplyHandler(Function&& callback) { - return [callback = std::forward<_Function>(callback)](MethodReply reply, std::optional error) + return [callback = std::forward(callback)](MethodReply reply, std::optional error) { // Create a tuple of callback input arguments' types, which will be used // as a storage for the argument values deserialized from the message. - tuple_of_function_input_arg_types_t<_Function> args; + tuple_of_function_input_arg_types_t args; // Deserialize input arguments from the message into the tuple (if no error occurred). if (!error) @@ -331,16 +331,16 @@ namespace sdbus { }; } - template - std::future> AsyncMethodInvoker::getResultAsFuture() + template + std::future> AsyncMethodInvoker::getResultAsFuture() { - auto promise = std::make_shared>>(); + auto promise = std::make_shared>>(); auto future = promise->get_future(); - uponReplyInvoke([promise = std::move(promise)](std::optional error, _Args... args) + uponReplyInvoke([promise = std::move(promise)](std::optional error, Args... args) { if (!error) - if constexpr (!std::is_void_v>) + if constexpr (!std::is_void_v>) promise->set_value({std::move(args)...}); else promise->set_value(); @@ -386,41 +386,41 @@ namespace sdbus { return *this; } - template - inline void SignalSubscriber::call(_Function&& callback) + template + inline void SignalSubscriber::call(Function&& callback) { assert(interfaceName_ != nullptr); // onInterface() must be placed/called prior to this function proxy_.registerSignalHandler( interfaceName_ , signalName_ - , makeSignalHandler(std::forward<_Function>(callback)) ); + , makeSignalHandler(std::forward(callback)) ); } - template - [[nodiscard]] inline Slot SignalSubscriber::call(_Function&& callback, return_slot_t) + template + [[nodiscard]] inline Slot SignalSubscriber::call(Function&& callback, return_slot_t) { assert(interfaceName_ != nullptr); // onInterface() must be placed/called prior to this function return proxy_.registerSignalHandler( interfaceName_ , signalName_ - , makeSignalHandler(std::forward<_Function>(callback)) + , makeSignalHandler(std::forward(callback)) , return_slot ); } - template - inline signal_handler SignalSubscriber::makeSignalHandler(_Function&& callback) + template + inline signal_handler SignalSubscriber::makeSignalHandler(Function&& callback) { - return [callback = std::forward<_Function>(callback)](Signal signal) + return [callback = std::forward(callback)](Signal signal) { // Create a tuple of callback input arguments' types, which will be used // as a storage for the argument values deserialized from the signal message. - tuple_of_function_input_arg_types_t<_Function> signalArgs; + tuple_of_function_input_arg_types_t signalArgs; // The signal handler can take pure signal parameters only, or an additional `std::optional` as its first // parameter. In the former case, if the deserialization fails (e.g. due to signature mismatch), // the failure is ignored (and signal simply dropped). In the latter case, the deserialization failure // will be communicated to the client's signal handler as a valid Error object inside the std::optional parameter. - if constexpr (has_error_param_v<_Function>) + if constexpr (has_error_param_v) { // Deserialize input arguments from the signal message into the tuple try @@ -486,10 +486,10 @@ namespace sdbus { return *this; } - template - PendingAsyncCall AsyncPropertyGetter::uponReplyInvoke(_Function&& callback) + template + PendingAsyncCall AsyncPropertyGetter::uponReplyInvoke(Function&& callback) { - static_assert( std::is_invocable_r_v, Variant> + static_assert( std::is_invocable_r_v, Variant> , "Property get callback function must accept std::optional and property value as Variant" ); assert(!interfaceName_.empty()); // onInterface() must be placed/called prior to this function @@ -497,13 +497,13 @@ namespace sdbus { return proxy_.callMethodAsync("Get") .onInterface(DBUS_PROPERTIES_INTERFACE_NAME) .withArguments(interfaceName_, propertyName_) - .uponReplyInvoke(std::forward<_Function>(callback)); + .uponReplyInvoke(std::forward(callback)); } - template - [[nodiscard]] Slot AsyncPropertyGetter::uponReplyInvoke(_Function&& callback, return_slot_t) + template + [[nodiscard]] Slot AsyncPropertyGetter::uponReplyInvoke(Function&& callback, return_slot_t) { - static_assert( std::is_invocable_r_v, Variant> + static_assert( std::is_invocable_r_v, Variant> , "Property get callback function must accept std::optional and property value as Variant" ); assert(!interfaceName_.empty()); // onInterface() must be placed/called prior to this function @@ -511,7 +511,7 @@ namespace sdbus { return proxy_.callMethodAsync("Get") .onInterface(DBUS_PROPERTIES_INTERFACE_NAME) .withArguments(interfaceName_, propertyName_) - .uponReplyInvoke(std::forward<_Function>(callback), return_slot); + .uponReplyInvoke(std::forward(callback), return_slot); } inline std::future AsyncPropertyGetter::getResultAsFuture() @@ -541,14 +541,14 @@ namespace sdbus { return *this; } - template - inline void PropertySetter::toValue(const _Value& value) + template + inline void PropertySetter::toValue(const Value& value) { PropertySetter::toValue(Variant{value}); } - template - inline void PropertySetter::toValue(const _Value& value, dont_expect_reply_t) + template + inline void PropertySetter::toValue(const Value& value, dont_expect_reply_t) { PropertySetter::toValue(Variant{value}, dont_expect_reply); } @@ -589,10 +589,10 @@ namespace sdbus { return *this; } - template - inline AsyncPropertySetter& AsyncPropertySetter::toValue(_Value&& value) + template + inline AsyncPropertySetter& AsyncPropertySetter::toValue(Value&& value) { - return AsyncPropertySetter::toValue(Variant{std::forward<_Value>(value)}); + return AsyncPropertySetter::toValue(Variant{std::forward(value)}); } inline AsyncPropertySetter& AsyncPropertySetter::toValue(Variant value) @@ -602,10 +602,10 @@ namespace sdbus { return *this; } - template - PendingAsyncCall AsyncPropertySetter::uponReplyInvoke(_Function&& callback) + template + PendingAsyncCall AsyncPropertySetter::uponReplyInvoke(Function&& callback) { - static_assert( std::is_invocable_r_v> + static_assert( std::is_invocable_r_v> , "Property set callback function must accept std::optional only" ); assert(!interfaceName_.empty()); // onInterface() must be placed/called prior to this function @@ -613,13 +613,13 @@ namespace sdbus { return proxy_.callMethodAsync("Set") .onInterface(DBUS_PROPERTIES_INTERFACE_NAME) .withArguments(interfaceName_, propertyName_, std::move(value_)) - .uponReplyInvoke(std::forward<_Function>(callback)); + .uponReplyInvoke(std::forward(callback)); } - template - [[nodiscard]] Slot AsyncPropertySetter::uponReplyInvoke(_Function&& callback, return_slot_t) + template + [[nodiscard]] Slot AsyncPropertySetter::uponReplyInvoke(Function&& callback, return_slot_t) { - static_assert( std::is_invocable_r_v> + static_assert( std::is_invocable_r_v> , "Property set callback function must accept std::optional only" ); assert(!interfaceName_.empty()); // onInterface() must be placed/called prior to this function @@ -627,7 +627,7 @@ namespace sdbus { return proxy_.callMethodAsync("Set") .onInterface(DBUS_PROPERTIES_INTERFACE_NAME) .withArguments(interfaceName_, propertyName_, std::move(value_)) - .uponReplyInvoke(std::forward<_Function>(callback), return_slot); + .uponReplyInvoke(std::forward(callback), return_slot); } inline std::future AsyncPropertySetter::getResultAsFuture() @@ -675,10 +675,10 @@ namespace sdbus { return *this; } - template - PendingAsyncCall AsyncAllPropertiesGetter::uponReplyInvoke(_Function&& callback) + template + PendingAsyncCall AsyncAllPropertiesGetter::uponReplyInvoke(Function&& callback) { - static_assert( std::is_invocable_r_v, std::map> + static_assert( std::is_invocable_r_v, std::map> , "All properties get callback function must accept std::optional and a map of property names to their values" ); assert(!interfaceName_.empty()); // onInterface() must be placed/called prior to this function @@ -686,13 +686,13 @@ namespace sdbus { return proxy_.callMethodAsync("GetAll") .onInterface(DBUS_PROPERTIES_INTERFACE_NAME) .withArguments(interfaceName_) - .uponReplyInvoke(std::forward<_Function>(callback)); + .uponReplyInvoke(std::forward(callback)); } - template - [[nodiscard]] Slot AsyncAllPropertiesGetter::uponReplyInvoke(_Function&& callback, return_slot_t) + template + [[nodiscard]] Slot AsyncAllPropertiesGetter::uponReplyInvoke(Function&& callback, return_slot_t) { - static_assert( std::is_invocable_r_v, std::map> + static_assert( std::is_invocable_r_v, std::map> , "All properties get callback function must accept std::optional and a map of property names to their values" ); assert(!interfaceName_.empty()); // onInterface() must be placed/called prior to this function @@ -700,7 +700,7 @@ namespace sdbus { return proxy_.callMethodAsync("GetAll") .onInterface(DBUS_PROPERTIES_INTERFACE_NAME) .withArguments(interfaceName_) - .uponReplyInvoke(std::forward<_Function>(callback), return_slot); + .uponReplyInvoke(std::forward(callback), return_slot); } inline std::future> AsyncAllPropertiesGetter::getResultAsFuture() diff --git a/include/sdbus-c++/Error.h b/include/sdbus-c++/Error.h index ad813d8a..4cdc1aee 100644 --- a/include/sdbus-c++/Error.h +++ b/include/sdbus-c++/Error.h @@ -99,7 +99,7 @@ namespace sdbus { #define SDBUS_THROW_ERROR(_MSG, _ERRNO) \ throw sdbus::createError((_ERRNO), (_MSG)) \ /**/ - +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) #define SDBUS_THROW_ERROR_IF(_COND, _MSG, _ERRNO) \ if (!(_COND)) ; else SDBUS_THROW_ERROR((_MSG), (_ERRNO)) \ /**/ diff --git a/include/sdbus-c++/Flags.h b/include/sdbus-c++/Flags.h index e2d6a627..364b235b 100644 --- a/include/sdbus-c++/Flags.h +++ b/include/sdbus-c++/Flags.h @@ -94,6 +94,6 @@ namespace sdbus { std::bitset flags_; }; -} +} // namespace sdbus #endif /* SDBUS_CXX_FLAGS_H_ */ diff --git a/include/sdbus-c++/IConnection.h b/include/sdbus-c++/IConnection.h index 1160ddcf..636874b7 100644 --- a/include/sdbus-c++/IConnection.h +++ b/include/sdbus-c++/IConnection.h @@ -43,7 +43,7 @@ namespace sdbus { class ObjectPath; class BusName; using ServiceName = BusName; -} +} // namespace sdbus namespace sdbus { @@ -207,8 +207,8 @@ namespace sdbus { /*! * @copydoc IConnection::setMethodCallTimeout(uint64_t) */ - template - void setMethodCallTimeout(const std::chrono::duration<_Rep, _Period>& timeout); + template + void setMethodCallTimeout(const std::chrono::duration& timeout); /*! * @brief Gets general method call timeout @@ -426,8 +426,8 @@ namespace sdbus { }; }; - template - inline void IConnection::setMethodCallTimeout(const std::chrono::duration<_Rep, _Period>& timeout) + template + inline void IConnection::setMethodCallTimeout(const std::chrono::duration& timeout) { auto microsecs = std::chrono::duration_cast(timeout); return setMethodCallTimeout(microsecs.count()); @@ -579,6 +579,6 @@ namespace sdbus { * @endcode */ [[nodiscard]] std::unique_ptr createBusConnection(sd_bus *bus); -} +} // namespace sdbus #endif /* SDBUS_CXX_ICONNECTION_H_ */ diff --git a/include/sdbus-c++/IObject.h b/include/sdbus-c++/IObject.h index f828411c..bdce2097 100644 --- a/include/sdbus-c++/IObject.h +++ b/include/sdbus-c++/IObject.h @@ -42,7 +42,7 @@ namespace sdbus { class Signal; class IConnection; class ObjectPath; -} +} // namespace sdbus namespace sdbus { @@ -129,7 +129,7 @@ namespace sdbus { * @throws sdbus::Error in case of failure */ template < typename... VTableItems - , typename = std::enable_if_t<(is_one_of_variants_types> && ...)> > + , typename = std::enable_if_t<(is_one_of_variants_types> && ...)> > // NOLINT(modernize-use-constraints): We are C++17 compatible at the moment [[nodiscard]] VTableAdder addVTable(VTableItems&&... items); /*! @@ -309,7 +309,7 @@ namespace sdbus { */ virtual void unregister() = 0; - public: // Lower-level, message-based API + // Lower-level, message-based API /*! * @brief Adds a declaration of methods, properties and signals of the object at a given interface * @@ -426,17 +426,17 @@ namespace sdbus { inline SignalEmitter IObject::emitSignal(const SignalName& signalName) { - return SignalEmitter(*this, signalName); + return {*this, signalName}; } inline SignalEmitter IObject::emitSignal(const std::string& signalName) { - return SignalEmitter(*this, signalName.c_str()); + return {*this, signalName.c_str()}; } inline SignalEmitter IObject::emitSignal(const char* signalName) { - return SignalEmitter(*this, signalName); + return {*this, signalName}; } template @@ -453,7 +453,7 @@ namespace sdbus { inline VTableAdder IObject::addVTable(std::vector vtable) { - return VTableAdder(*this, std::move(vtable)); + return {*this, std::move(vtable)}; } /*! @@ -476,9 +476,9 @@ namespace sdbus { */ [[nodiscard]] std::unique_ptr createObject(sdbus::IConnection& connection, ObjectPath objectPath); -} +} // namespace sdbus -#include +#include // NOLINT(misc-header-include-cycle) #include #endif /* SDBUS_CXX_IOBJECT_H_ */ diff --git a/include/sdbus-c++/IProxy.h b/include/sdbus-c++/IProxy.h index 6777767d..ae93b31f 100644 --- a/include/sdbus-c++/IProxy.h +++ b/include/sdbus-c++/IProxy.h @@ -46,8 +46,8 @@ namespace sdbus { class PendingAsyncCall; namespace internal { class Proxy; - } -} + } // namespace internal +} // namespace sdbus namespace sdbus { @@ -350,7 +350,7 @@ namespace sdbus { */ virtual void unregister() = 0; - public: // Lower-level, message-based API + // Lower-level, message-based API /*! * @brief Creates a method call message * @@ -430,8 +430,8 @@ namespace sdbus { /*! * @copydoc IProxy::callMethod(const MethodCall&,uint64_t) */ - template - MethodReply callMethod(const MethodCall& message, const std::chrono::duration<_Rep, _Period>& timeout); + template + MethodReply callMethod(const MethodCall& message, const std::chrono::duration& timeout); /*! * @brief Calls method on the D-Bus object asynchronously @@ -539,18 +539,18 @@ namespace sdbus { /*! * @copydoc IProxy::callMethod(const MethodCall&,async_reply_handler,uint64_t) */ - template + template PendingAsyncCall callMethodAsync( const MethodCall& message , async_reply_handler asyncReplyCallback - , const std::chrono::duration<_Rep, _Period>& timeout ); + , const std::chrono::duration& timeout ); /*! * @copydoc IProxy::callMethod(const MethodCall&,async_reply_handler,uint64_t,return_slot_t) */ - template + template [[nodiscard]] Slot callMethodAsync( const MethodCall& message , async_reply_handler asyncReplyCallback - , const std::chrono::duration<_Rep, _Period>& timeout + , const std::chrono::duration& timeout , return_slot_t ); /*! @@ -601,9 +601,9 @@ namespace sdbus { /*! * @copydoc IProxy::callMethod(const MethodCall&,uint64_t,with_future_t) */ - template + template std::future callMethodAsync( const MethodCall& message - , const std::chrono::duration<_Rep, _Period>& timeout + , const std::chrono::duration& timeout , with_future_t ); /*! @@ -698,43 +698,42 @@ namespace sdbus { private: friend internal::Proxy; - PendingAsyncCall(std::weak_ptr callInfo); + explicit PendingAsyncCall(std::weak_ptr callInfo); - private: std::weak_ptr callInfo_; }; // Out-of-line member definitions - template - inline MethodReply IProxy::callMethod(const MethodCall& message, const std::chrono::duration<_Rep, _Period>& timeout) + template + inline MethodReply IProxy::callMethod(const MethodCall& message, const std::chrono::duration& timeout) { auto microsecs = std::chrono::duration_cast(timeout); return callMethod(message, microsecs.count()); } - template + template inline PendingAsyncCall IProxy::callMethodAsync( const MethodCall& message , async_reply_handler asyncReplyCallback - , const std::chrono::duration<_Rep, _Period>& timeout ) + , const std::chrono::duration& timeout ) { auto microsecs = std::chrono::duration_cast(timeout); return callMethodAsync(message, std::move(asyncReplyCallback), microsecs.count()); } - template + template inline Slot IProxy::callMethodAsync( const MethodCall& message , async_reply_handler asyncReplyCallback - , const std::chrono::duration<_Rep, _Period>& timeout + , const std::chrono::duration& timeout , return_slot_t ) { auto microsecs = std::chrono::duration_cast(timeout); return callMethodAsync(message, std::move(asyncReplyCallback), microsecs.count(), return_slot); } - template + template inline std::future IProxy::callMethodAsync( const MethodCall& message - , const std::chrono::duration<_Rep, _Period>& timeout + , const std::chrono::duration& timeout , with_future_t ) { auto microsecs = std::chrono::duration_cast(timeout); @@ -743,87 +742,87 @@ namespace sdbus { inline MethodInvoker IProxy::callMethod(const MethodName& methodName) { - return MethodInvoker(*this, methodName); + return {*this, methodName}; } inline MethodInvoker IProxy::callMethod(const std::string& methodName) { - return MethodInvoker(*this, methodName.c_str()); + return {*this, methodName.c_str()}; } inline MethodInvoker IProxy::callMethod(const char* methodName) { - return MethodInvoker(*this, methodName); + return {*this, methodName}; } inline AsyncMethodInvoker IProxy::callMethodAsync(const MethodName& methodName) { - return AsyncMethodInvoker(*this, methodName); + return {*this, methodName}; } inline AsyncMethodInvoker IProxy::callMethodAsync(const std::string& methodName) { - return AsyncMethodInvoker(*this, methodName.c_str()); + return {*this, methodName.c_str()}; } inline AsyncMethodInvoker IProxy::callMethodAsync(const char* methodName) { - return AsyncMethodInvoker(*this, methodName); + return {*this, methodName}; } inline SignalSubscriber IProxy::uponSignal(const SignalName& signalName) { - return SignalSubscriber(*this, signalName); + return {*this, signalName}; } inline SignalSubscriber IProxy::uponSignal(const std::string& signalName) { - return SignalSubscriber(*this, signalName.c_str()); + return {*this, signalName.c_str()}; } inline SignalSubscriber IProxy::uponSignal(const char* signalName) { - return SignalSubscriber(*this, signalName); + return {*this, signalName}; } inline PropertyGetter IProxy::getProperty(const PropertyName& propertyName) { - return PropertyGetter(*this, propertyName); + return {*this, propertyName}; } inline PropertyGetter IProxy::getProperty(std::string_view propertyName) { - return PropertyGetter(*this, std::move(propertyName)); + return {*this, std::move(propertyName)}; } inline AsyncPropertyGetter IProxy::getPropertyAsync(const PropertyName& propertyName) { - return AsyncPropertyGetter(*this, propertyName); + return {*this, propertyName}; } inline AsyncPropertyGetter IProxy::getPropertyAsync(std::string_view propertyName) { - return AsyncPropertyGetter(*this, std::move(propertyName)); + return {*this, std::move(propertyName)}; } inline PropertySetter IProxy::setProperty(const PropertyName& propertyName) { - return PropertySetter(*this, propertyName); + return {*this, propertyName}; } inline PropertySetter IProxy::setProperty(std::string_view propertyName) { - return PropertySetter(*this, std::move(propertyName)); + return {*this, std::move(propertyName)}; } inline AsyncPropertySetter IProxy::setPropertyAsync(const PropertyName& propertyName) { - return AsyncPropertySetter(*this, propertyName); + return {*this, propertyName}; } inline AsyncPropertySetter IProxy::setPropertyAsync(std::string_view propertyName) { - return AsyncPropertySetter(*this, std::move(propertyName)); + return {*this, std::move(propertyName)}; } inline AllPropertiesGetter IProxy::getAllProperties() @@ -974,8 +973,8 @@ namespace sdbus { */ [[nodiscard]] std::unique_ptr createLightWeightProxy(ServiceName destination, ObjectPath objectPath); -} +} // namespace sdbus -#include +#include // NOLINT(misc-header-include-cycle) #endif /* SDBUS_CXX_IPROXY_H_ */ diff --git a/include/sdbus-c++/Message.h b/include/sdbus-c++/Message.h index dfc6732e..75555920 100644 --- a/include/sdbus-c++/Message.h +++ b/include/sdbus-c++/Message.h @@ -54,13 +54,13 @@ namespace sdbus { class Variant; class ObjectPath; class Signature; - template class Struct; + template class Struct; class UnixFd; class MethodReply; namespace internal { class IConnection; - } -} + } // namespace internal +} // namespace sdbus namespace sdbus { @@ -104,26 +104,27 @@ namespace sdbus { Message& operator<<(const ObjectPath &item); Message& operator<<(const Signature &item); Message& operator<<(const UnixFd &item); - template - Message& operator<<(const std::vector<_Element, _Allocator>& items); - template - Message& operator<<(const std::array<_Element, _Size>& items); + template + Message& operator<<(const std::vector& items); + template + Message& operator<<(const std::array& items); #ifdef __cpp_lib_span - template - Message& operator<<(const std::span<_Element, _Extent>& items); + template + Message& operator<<(const std::span& items); #endif - template >> - Message& operator<<(const _Enum& item); - template - Message& operator<<(const DictEntry<_Key, _Value>& value); - template - Message& operator<<(const std::map<_Key, _Value, _Compare, _Allocator>& items); - template - Message& operator<<(const std::unordered_map<_Key, _Value, _Hash, _KeyEqual, _Allocator>& items); - template - Message& operator<<(const Struct<_ValueTypes...>& item); - template - Message& operator<<(const std::tuple<_ValueTypes...>& item); + // NOLINTNEXTLINE(modernize-use-constraints): Public API is C++17-compatible + template >> + Message& operator<<(const Enum& item); + template + Message& operator<<(const DictEntry& value); + template + Message& operator<<(const std::map& items); + template + Message& operator<<(const std::unordered_map& items); + template + Message& operator<<(const Struct& item); + template + Message& operator<<(const std::tuple& item); Message& operator>>(bool& item); Message& operator>>(int16_t& item); @@ -142,57 +143,58 @@ namespace sdbus { Message& operator>>(ObjectPath &item); Message& operator>>(Signature &item); Message& operator>>(UnixFd &item); - template - Message& operator>>(std::vector<_Element, _Allocator>& items); - template - Message& operator>>(std::array<_Element, _Size>& items); + template + Message& operator>>(std::vector& items); + template + Message& operator>>(std::array& items); #ifdef __cpp_lib_span - template - Message& operator>>(std::span<_Element, _Extent>& items); + template + Message& operator>>(std::span& items); #endif - template >> - Message& operator>>(_Enum& item); - template - Message& operator>>(DictEntry<_Key, _Value>& value); - template - Message& operator>>(std::map<_Key, _Value, _Compare, _Allocator>& items); - template - Message& operator>>(std::unordered_map<_Key, _Value, _Hash, _KeyEqual, _Allocator>& items); - template - Message& operator>>(Struct<_ValueTypes...>& item); - template - Message& operator>>(std::tuple<_ValueTypes...>& item); - - template + // NOLINTNEXTLINE(modernize-use-constraints): Public API is C++17-compatible + template >> + Message& operator>>(Enum& item); + template + Message& operator>>(DictEntry& value); + template + Message& operator>>(std::map& items); + template + Message& operator>>(std::unordered_map& items); + template + Message& operator>>(Struct& item); + template + Message& operator>>(std::tuple& item); + + template Message& openContainer(); Message& openContainer(const char* signature); Message& closeContainer(); - template + template Message& openDictEntry(); Message& openDictEntry(const char* signature); Message& closeDictEntry(); - template + template Message& openVariant(); Message& openVariant(const char* signature); Message& closeVariant(); - template + template Message& openStruct(); Message& openStruct(const char* signature); Message& closeStruct(); - template + template Message& enterContainer(); Message& enterContainer(const char* signature); Message& exitContainer(); - template + template Message& enterDictEntry(); Message& enterDictEntry(const char* signature); Message& exitDictEntry(); - template + template Message& enterVariant(); Message& enterVariant(const char* signature); Message& exitVariant(); - template + template Message& enterStruct(); Message& enterStruct(const char* signature); Message& exitStruct(); @@ -200,12 +202,12 @@ namespace sdbus { Message& appendArray(char type, const void *ptr, size_t size); Message& readArray(char type, const void **ptr, size_t *size); - template - Message& serializeDictionary(const _Callback& callback); - template - Message& serializeDictionary(const std::initializer_list>& dictEntries); - template - Message& deserializeDictionary(const _Callback& callback); + template + Message& serializeDictionary(const Callback& callback); + template + Message& serializeDictionary(const std::initializer_list>& dictEntries); + template + Message& deserializeDictionary(const Callback& callback); explicit operator bool() const; void clearFlags(); @@ -237,18 +239,18 @@ namespace sdbus { class Factory; private: - template - void serializeArray(const _Array& items); - template - void deserializeArray(_Array& items); - template - void deserializeArrayFast(_Array& items); - template - void deserializeArrayFast(std::vector<_Element, _Allocator>& items); - template - void deserializeArraySlow(_Array& items); - template - void deserializeArraySlow(std::vector<_Element, _Allocator>& items); + template + void serializeArray(const Array& items); + template + void deserializeArray(Array& items); + template + void deserializeArrayFast(Array& items); + template + void deserializeArrayFast(std::vector& items); + template + void deserializeArraySlow(Array& items); + template + void deserializeArraySlow(std::vector& items); protected: Message() = default; @@ -258,7 +260,7 @@ namespace sdbus { friend Factory; - protected: + void* msg_{}; internal::IConnection* connection_{}; mutable bool ok_{true}; @@ -355,16 +357,16 @@ namespace sdbus { return *this; } - template - inline Message& Message::operator<<(const std::vector<_Element, _Allocator>& items) + template + inline Message& Message::operator<<(const std::vector& items) { serializeArray(items); return *this; } - template - inline Message& Message::operator<<(const std::array<_Element, _Size>& items) + template + inline Message& Message::operator<<(const std::array& items) { serializeArray(items); @@ -372,8 +374,8 @@ namespace sdbus { } #ifdef __cpp_lib_span - template - inline Message& Message::operator<<(const std::span<_Element, _Extent>& items) + template + inline Message& Message::operator<<(const std::span& items) { serializeArray(items); @@ -381,16 +383,16 @@ namespace sdbus { } #endif - template - inline Message& Message::operator<<(const _Enum &item) + template + inline Message& Message::operator<<(const Enum &item) { - return operator<<(static_cast>(item)); + return operator<<(static_cast>(item)); } - template - inline void Message::serializeArray(const _Array& items) + template + inline void Message::serializeArray(const Array& items) { - using ElementType = typename _Array::value_type; + using ElementType = typename Array::value_type; // Use faster, one-step serialization of contiguous array of elements of trivial D-Bus types except bool, // otherwise use step-by-step serialization of individual elements. @@ -410,10 +412,10 @@ namespace sdbus { } } - template - inline Message& Message::operator<<(const DictEntry<_Key, _Value>& value) + template + inline Message& Message::operator<<(const DictEntry& value) { - openDictEntry<_Key, _Value>(); + openDictEntry(); *this << value.first; *this << value.second; closeDictEntry(); @@ -421,34 +423,34 @@ namespace sdbus { return *this; } - template - inline Message& Message::operator<<(const std::map<_Key, _Value, _Compare, _Allocator>& items) + template + inline Message& Message::operator<<(const std::map& items) { - serializeDictionary<_Key, _Value>([&items](Message& msg){ for (const auto& item : items) msg << item; }); + serializeDictionary([&items](Message& msg){ for (const auto& item : items) msg << item; }); return *this; } - template - inline Message& Message::operator<<(const std::unordered_map<_Key, _Value, _Hash, _KeyEqual, _Allocator>& items) + template + inline Message& Message::operator<<(const std::unordered_map& items) { - serializeDictionary<_Key, _Value>([&items](Message& msg){ for (const auto& item : items) msg << item; }); + serializeDictionary([&items](Message& msg){ for (const auto& item : items) msg << item; }); return *this; } - template - inline Message& Message::serializeDictionary(const std::initializer_list>& items) + template + inline Message& Message::serializeDictionary(const std::initializer_list>& dictEntries) { - serializeDictionary<_Key, _Value>([&](Message& msg){ for (const auto& item : items) msg << item; }); + serializeDictionary([&](Message& msg){ for (const auto& entry : dictEntries) msg << entry; }); return *this; } - template - inline Message& Message::serializeDictionary(const _Callback& callback) + template + inline Message& Message::serializeDictionary(const Callback& callback) { - openContainer>(); + openContainer>(); callback(*this); closeContainer(); @@ -457,75 +459,75 @@ namespace sdbus { namespace detail { - template - void serialize_pack(Message& msg, _Args&&... args) + template + void serialize_pack(Message& msg, Args&&... args) { - (void)(msg << ... << args); + (void)(msg << ... << std::forward(args)); } - template + template void serialize_tuple( Message& msg - , const _Tuple& t - , std::index_sequence<_Is...>) + , const Tuple& tuple + , std::index_sequence) { - serialize_pack(msg, std::get<_Is>(t)...); + serialize_pack(msg, std::get(tuple)...); } - } + } // namespace detail - template - inline Message& Message::operator<<(const Struct<_ValueTypes...>& item) + template + inline Message& Message::operator<<(const Struct& item) { - openStruct<_ValueTypes...>(); - detail::serialize_tuple(*this, item, std::index_sequence_for<_ValueTypes...>{}); + openStruct(); + detail::serialize_tuple(*this, item, std::index_sequence_for{}); closeStruct(); return *this; } - template - inline Message& Message::operator<<(const std::tuple<_ValueTypes...>& item) + template + inline Message& Message::operator<<(const std::tuple& item) { - detail::serialize_tuple(*this, item, std::index_sequence_for<_ValueTypes...>{}); + detail::serialize_tuple(*this, item, std::index_sequence_for{}); return *this; } namespace detail { - template - bool deserialize_variant(Message& msg, std::variant<_Elements...>& value, const char* signature) + template + bool deserialize_variant(Message& msg, std::variant& value, const char* signature) { - constexpr auto elemSignature = as_null_terminated(sdbus::signature_of_v<_Element>); + constexpr auto elemSignature = as_null_terminated(sdbus::signature_of_v); if (std::strcmp(signature, elemSignature.data()) != 0) return false; - _Element temp; + Element temp; msg.enterVariant(signature); msg >> temp; msg.exitVariant(); value = std::move(temp); return true; } - } + } // namespace detail template inline Message& Message::operator>>(std::variant& value) { auto [type, contents] = peekType(); - bool result = (detail::deserialize_variant(*this, value, contents) || ...); + const bool result = (detail::deserialize_variant(*this, value, contents) || ...); SDBUS_THROW_ERROR_IF(!result, "Failed to deserialize variant: signature did not match any of the variant types", EINVAL); return *this; } - template - inline Message& Message::operator>>(std::vector<_Element, _Allocator>& items) + template + inline Message& Message::operator>>(std::vector& items) { deserializeArray(items); return *this; } - template - inline Message& Message::operator>>(std::array<_Element, _Size>& items) + template + inline Message& Message::operator>>(std::array& items) { deserializeArray(items); @@ -533,8 +535,8 @@ namespace sdbus { } #ifdef __cpp_lib_span - template - inline Message& Message::operator>>(std::span<_Element, _Extent>& items) + template + inline Message& Message::operator>>(std::span& items) { deserializeArray(items); @@ -542,19 +544,19 @@ namespace sdbus { } #endif - template - inline Message& Message::operator>>(_Enum& item) + template + inline Message& Message::operator>>(Enum& item) { - std::underlying_type_t<_Enum> val; + std::underlying_type_t val; *this >> val; - item = static_cast<_Enum>(val); + item = static_cast(val); return *this; } - template - inline void Message::deserializeArray(_Array& items) + template + inline void Message::deserializeArray(Array& items) { - using ElementType = typename _Array::value_type; + using ElementType = typename Array::value_type; // Use faster, one-step deserialization of contiguous array of elements of trivial D-Bus types except bool, // otherwise use step-by-step deserialization of individual elements. @@ -568,40 +570,41 @@ namespace sdbus { } } - template - inline void Message::deserializeArrayFast(_Array& items) + template + inline void Message::deserializeArrayFast(Array& items) { - using ElementType = typename _Array::value_type; + using ElementType = typename Array::value_type; size_t arraySize{}; const ElementType* arrayPtr{}; constexpr auto signature = as_null_terminated(sdbus::signature_of_v); - readArray(*signature.data(), (const void**)&arrayPtr, &arraySize); + readArray(*signature.data(), reinterpret_cast(&arrayPtr), &arraySize); - size_t elementsInMsg = arraySize / sizeof(ElementType); - bool notEnoughSpace = items.size() < elementsInMsg; + const size_t elementsInMsg = arraySize / sizeof(ElementType); + const bool notEnoughSpace = items.size() < elementsInMsg; SDBUS_THROW_ERROR_IF(notEnoughSpace, "Failed to deserialize array: not enough space in destination sequence", EINVAL); std::copy_n(arrayPtr, elementsInMsg, items.begin()); } - template - void Message::deserializeArrayFast(std::vector<_Element, _Allocator>& items) + template + void Message::deserializeArrayFast(std::vector& items) { size_t arraySize{}; - const _Element* arrayPtr{}; + const Element* arrayPtr{}; - constexpr auto signature = as_null_terminated(sdbus::signature_of_v<_Element>); - readArray(*signature.data(), (const void**)&arrayPtr, &arraySize); + constexpr auto signature = as_null_terminated(sdbus::signature_of_v); + readArray(*signature.data(), reinterpret_cast(&arrayPtr), &arraySize); - items.insert(items.end(), arrayPtr, arrayPtr + (arraySize / sizeof(_Element))); + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) + items.insert(items.end(), arrayPtr, arrayPtr + (arraySize / sizeof(Element))); } - template - inline void Message::deserializeArraySlow(_Array& items) + template + inline void Message::deserializeArraySlow(Array& items) { - using ElementType = typename _Array::value_type; + using ElementType = typename Array::value_type; if(!enterContainer()) return; @@ -617,15 +620,15 @@ namespace sdbus { exitContainer(); } - template - void Message::deserializeArraySlow(std::vector<_Element, _Allocator>& items) + template + void Message::deserializeArraySlow(std::vector& items) { - if(!enterContainer<_Element>()) + if(!enterContainer()) return; while (true) { - _Element elem; + Element elem; if (*this >> elem) items.emplace_back(std::move(elem)); else @@ -637,10 +640,10 @@ namespace sdbus { exitContainer(); } - template - inline Message& Message::operator>>(DictEntry<_Key, _Value>& value) + template + inline Message& Message::operator>>(DictEntry& value) { - if (!enterDictEntry<_Key, _Value>()) + if (!enterDictEntry()) return *this; *this >> value.first >> value.second; exitDictEntry(); @@ -648,31 +651,31 @@ namespace sdbus { return *this; } - template - inline Message& Message::operator>>(std::map<_Key, _Value, _Compare, _Allocator>& items) + template + inline Message& Message::operator>>(std::map& items) { - deserializeDictionary<_Key, _Value>([&items](auto dictEntry){ items.insert(std::move(dictEntry)); }); + deserializeDictionary([&items](auto dictEntry){ items.insert(std::move(dictEntry)); }); return *this; } - template - inline Message& Message::operator>>(std::unordered_map<_Key, _Value, _Hash, _KeyEqual, _Allocator>& items) + template + inline Message& Message::operator>>(std::unordered_map& items) { - deserializeDictionary<_Key, _Value>([&items](auto dictEntry){ items.insert(std::move(dictEntry)); }); + deserializeDictionary([&items](auto dictEntry){ items.insert(std::move(dictEntry)); }); return *this; } - template - inline Message& Message::deserializeDictionary(const _Callback& callback) + template + inline Message& Message::deserializeDictionary(const Callback& callback) { - if (!enterContainer>()) + if (!enterContainer>()) return *this; while (true) { - DictEntry<_Key, _Value> dictEntry; + DictEntry dictEntry; *this >> dictEntry; if (!*this) break; @@ -687,97 +690,97 @@ namespace sdbus { namespace detail { - template - void deserialize_pack(Message& msg, _Args&... args) + template + void deserialize_pack(Message& msg, Args&... args) { (void)(msg >> ... >> args); } - template + template void deserialize_tuple( Message& msg - , _Tuple& t - , std::index_sequence<_Is...> ) + , Tuple& tuple + , std::index_sequence ) { - deserialize_pack(msg, std::get<_Is>(t)...); + deserialize_pack(msg, std::get(tuple)...); } - } + } // namespace detail - template - inline Message& Message::operator>>(Struct<_ValueTypes...>& item) + template + inline Message& Message::operator>>(Struct& item) { - if (!enterStruct<_ValueTypes...>()) + if (!enterStruct()) return *this; - detail::deserialize_tuple(*this, item, std::index_sequence_for<_ValueTypes...>{}); + detail::deserialize_tuple(*this, item, std::index_sequence_for{}); exitStruct(); return *this; } - template - inline Message& Message::operator>>(std::tuple<_ValueTypes...>& item) + template + inline Message& Message::operator>>(std::tuple& item) { - detail::deserialize_tuple(*this, item, std::index_sequence_for<_ValueTypes...>{}); + detail::deserialize_tuple(*this, item, std::index_sequence_for{}); return *this; } - template + template inline Message& Message::openContainer() { - constexpr auto signature = as_null_terminated(signature_of_v<_ElementType>); + constexpr auto signature = as_null_terminated(signature_of_v); return openContainer(signature.data()); } - template + template inline Message& Message::openDictEntry() { - constexpr auto signature = as_null_terminated(signature_of_v>); + constexpr auto signature = as_null_terminated(signature_of_v>); return openDictEntry(signature.data()); } - template + template inline Message& Message::openVariant() { - constexpr auto signature = as_null_terminated(signature_of_v<_ValueType>); + constexpr auto signature = as_null_terminated(signature_of_v); return openVariant(signature.data()); } - template + template inline Message& Message::openStruct() { - constexpr auto signature = as_null_terminated(signature_of_v>); + constexpr auto signature = as_null_terminated(signature_of_v>); return openStruct(signature.data()); } - template + template inline Message& Message::enterContainer() { - constexpr auto signature = as_null_terminated(signature_of_v<_ElementType>); + constexpr auto signature = as_null_terminated(signature_of_v); return enterContainer(signature.data()); } - template + template inline Message& Message::enterDictEntry() { - constexpr auto signature = as_null_terminated(signature_of_v>); + constexpr auto signature = as_null_terminated(signature_of_v>); return enterDictEntry(signature.data()); } - template + template inline Message& Message::enterVariant() { - constexpr auto signature = as_null_terminated(signature_of_v<_ValueType>); + constexpr auto signature = as_null_terminated(signature_of_v); return enterVariant(signature.data()); } - template + template inline Message& Message::enterStruct() { - constexpr auto signature = as_null_terminated(signature_of_v>); + constexpr auto signature = as_null_terminated(signature_of_v>); return enterStruct(signature.data()); } -} +} // namespace sdbus #endif /* SDBUS_CXX_MESSAGE_H_ */ diff --git a/include/sdbus-c++/MethodResult.h b/include/sdbus-c++/MethodResult.h index dac04bf9..3701a4d8 100644 --- a/include/sdbus-c++/MethodResult.h +++ b/include/sdbus-c++/MethodResult.h @@ -34,7 +34,7 @@ // Forward declarations namespace sdbus { class Error; -} +} // namespace sdbus namespace sdbus { @@ -46,12 +46,12 @@ namespace sdbus { * by the method to either method return value or an error. * ***********************************************/ - template + template class Result { public: Result() = default; - Result(MethodCall call); + explicit Result(MethodCall call); Result(const Result&) = delete; Result& operator=(const Result&) = delete; @@ -59,21 +59,23 @@ namespace sdbus { Result(Result&& other) = default; Result& operator=(Result&& other) = default; - void returnResults(const _Results&... results) const; + ~Result() = default; + + void returnResults(const Results&... results) const; void returnError(const Error& error) const; private: MethodCall call_; }; - template - inline Result<_Results...>::Result(MethodCall call) + template + inline Result::Result(MethodCall call) : call_(std::move(call)) { } - template - inline void Result<_Results...>::returnResults(const _Results&... results) const + template + inline void Result::returnResults(const Results&... results) const { assert(call_.isValid()); auto reply = call_.createReply(); @@ -81,13 +83,13 @@ namespace sdbus { reply.send(); } - template - inline void Result<_Results...>::returnError(const Error& error) const + template + inline void Result::returnError(const Error& error) const { auto reply = call_.createErrorReply(error); reply.send(); } -} +} // namespace sdbus #endif /* SDBUS_CXX_METHODRESULT_H_ */ diff --git a/include/sdbus-c++/ProxyInterfaces.h b/include/sdbus-c++/ProxyInterfaces.h index 56110bba..936d4da5 100644 --- a/include/sdbus-c++/ProxyInterfaces.h +++ b/include/sdbus-c++/ProxyInterfaces.h @@ -35,7 +35,7 @@ // Forward declarations namespace sdbus { class IConnection; -} +} // namespace sdbus namespace sdbus { @@ -51,19 +51,19 @@ namespace sdbus { class ProxyObjectHolder { protected: - ProxyObjectHolder(std::unique_ptr&& proxy) + explicit ProxyObjectHolder(std::unique_ptr&& proxy) : proxy_(std::move(proxy)) { assert(proxy_ != nullptr); } - const IProxy& getProxy() const + [[nodiscard]] const IProxy& getProxy() const { assert(proxy_ != nullptr); return *proxy_; } - IProxy& getProxy() + [[nodiscard]] IProxy& getProxy() { assert(proxy_ != nullptr); return *proxy_; @@ -89,12 +89,17 @@ namespace sdbus { * so that the signals are subscribed to and unsubscribed from at a proper time. * ***********************************************/ - template + template class ProxyInterfaces : protected ProxyObjectHolder - , public _Interfaces... + , public Interfaces... { public: + ProxyInterfaces(const ProxyInterfaces&) = delete; + ProxyInterfaces& operator=(const ProxyInterfaces&) = delete; + ProxyInterfaces(ProxyInterfaces&&) = delete; + ProxyInterfaces& operator=(ProxyInterfaces&&) = delete; + /*! * @brief Creates native-like proxy object instance * @@ -106,7 +111,7 @@ namespace sdbus { */ ProxyInterfaces(ServiceName destination, ObjectPath objectPath) : ProxyObjectHolder(createProxy(std::move(destination), std::move(objectPath))) - , _Interfaces(getProxy())... + , Interfaces(getProxy())... { } @@ -121,7 +126,7 @@ namespace sdbus { */ ProxyInterfaces(ServiceName destination, ObjectPath objectPath, dont_run_event_loop_thread_t) : ProxyObjectHolder(createProxy(std::move(destination), std::move(objectPath), dont_run_event_loop_thread)) - , _Interfaces(getProxy())... + , Interfaces(getProxy())... { } @@ -137,7 +142,7 @@ namespace sdbus { */ ProxyInterfaces(IConnection& connection, ServiceName destination, ObjectPath objectPath) : ProxyObjectHolder(createProxy(connection, std::move(destination), std::move(objectPath))) - , _Interfaces(getProxy())... + , Interfaces(getProxy())... { } @@ -153,7 +158,7 @@ namespace sdbus { */ ProxyInterfaces(std::unique_ptr&& connection, ServiceName destination, ObjectPath objectPath) : ProxyObjectHolder(createProxy(std::move(connection), std::move(destination), std::move(objectPath))) - , _Interfaces(getProxy())... + , Interfaces(getProxy())... { } @@ -168,8 +173,8 @@ namespace sdbus { * For more information on its behavior, consult @ref createProxy(std::unique_ptr&&,std::string,std::string,sdbus::dont_run_event_loop_thread_t) */ ProxyInterfaces(std::unique_ptr&& connection, ServiceName destination, ObjectPath objectPath, dont_run_event_loop_thread_t) - : ProxyObjectHolder(createProxy(std::move(connection), std::move(destination), std::move(objectPath), dont_run_event_loop_thread)) - , _Interfaces(getProxy())... + : ProxyObjectHolder(createProxy(std::move(connection), std::move(destination), std::move(objectPath), dont_run_event_loop_thread)) + , Interfaces(getProxy())... { } @@ -182,7 +187,7 @@ namespace sdbus { */ void registerProxy() { - (_Interfaces::registerProxy(), ...); + (Interfaces::registerProxy(), ...); } /*! @@ -205,13 +210,9 @@ namespace sdbus { protected: using base_type = ProxyInterfaces; - ProxyInterfaces(const ProxyInterfaces&) = delete; - ProxyInterfaces& operator=(const ProxyInterfaces&) = delete; - ProxyInterfaces(ProxyInterfaces&&) = delete; - ProxyInterfaces& operator=(ProxyInterfaces&&) = delete; ~ProxyInterfaces() = default; }; -} +} // namespace sdbus #endif /* SDBUS_CXX_INTERFACES_H_ */ diff --git a/include/sdbus-c++/StandardInterfaces.h b/include/sdbus-c++/StandardInterfaces.h index c30b9e17..1a0d1153 100644 --- a/include/sdbus-c++/StandardInterfaces.h +++ b/include/sdbus-c++/StandardInterfaces.h @@ -43,16 +43,11 @@ namespace sdbus { static inline const char* INTERFACE_NAME = "org.freedesktop.DBus.Peer"; protected: - Peer_proxy(sdbus::IProxy& proxy) + explicit Peer_proxy(sdbus::IProxy& proxy) : m_proxy(proxy) { } - Peer_proxy(const Peer_proxy&) = delete; - Peer_proxy& operator=(const Peer_proxy&) = delete; - Peer_proxy(Peer_proxy&&) = delete; - Peer_proxy& operator=(Peer_proxy&&) = delete; - ~Peer_proxy() = default; void registerProxy() @@ -60,6 +55,11 @@ namespace sdbus { } public: + Peer_proxy(const Peer_proxy&) = delete; + Peer_proxy& operator=(const Peer_proxy&) = delete; + Peer_proxy(Peer_proxy&&) = delete; + Peer_proxy& operator=(Peer_proxy&&) = delete; + void Ping() { m_proxy.callMethod("Ping").onInterface(INTERFACE_NAME); @@ -82,16 +82,11 @@ namespace sdbus { static inline const char* INTERFACE_NAME = "org.freedesktop.DBus.Introspectable"; protected: - Introspectable_proxy(sdbus::IProxy& proxy) + explicit Introspectable_proxy(sdbus::IProxy& proxy) : m_proxy(proxy) { } - Introspectable_proxy(const Introspectable_proxy&) = delete; - Introspectable_proxy& operator=(const Introspectable_proxy&) = delete; - Introspectable_proxy(Introspectable_proxy&&) = delete; - Introspectable_proxy& operator=(Introspectable_proxy&&) = delete; - ~Introspectable_proxy() = default; void registerProxy() @@ -99,6 +94,11 @@ namespace sdbus { } public: + Introspectable_proxy(const Introspectable_proxy&) = delete; + Introspectable_proxy& operator=(const Introspectable_proxy&) = delete; + Introspectable_proxy(Introspectable_proxy&&) = delete; + Introspectable_proxy& operator=(Introspectable_proxy&&) = delete; + std::string Introspect() { std::string xml; @@ -116,16 +116,11 @@ namespace sdbus { static inline const char* INTERFACE_NAME = "org.freedesktop.DBus.Properties"; protected: - Properties_proxy(sdbus::IProxy& proxy) + explicit Properties_proxy(sdbus::IProxy& proxy) : m_proxy(proxy) { } - Properties_proxy(const Properties_proxy&) = delete; - Properties_proxy& operator=(const Properties_proxy&) = delete; - Properties_proxy(Properties_proxy&&) = delete; - Properties_proxy& operator=(Properties_proxy&&) = delete; - ~Properties_proxy() = default; void registerProxy() @@ -146,6 +141,11 @@ namespace sdbus { , const std::vector& invalidatedProperties ) = 0; public: + Properties_proxy(const Properties_proxy&) = delete; + Properties_proxy& operator=(const Properties_proxy&) = delete; + Properties_proxy(Properties_proxy&&) = delete; + Properties_proxy& operator=(Properties_proxy&&) = delete; + sdbus::Variant Get(const InterfaceName& interfaceName, const PropertyName& propertyName) { return m_proxy.getProperty(propertyName).onInterface(interfaceName); @@ -156,16 +156,16 @@ namespace sdbus { return m_proxy.getProperty(propertyName).onInterface(interfaceName); } - template - PendingAsyncCall GetAsync(const InterfaceName& interfaceName, const PropertyName& propertyName, _Function&& callback) + template + PendingAsyncCall GetAsync(const InterfaceName& interfaceName, const PropertyName& propertyName, Function&& callback) { - return m_proxy.getPropertyAsync(propertyName).onInterface(interfaceName).uponReplyInvoke(std::forward<_Function>(callback)); + return m_proxy.getPropertyAsync(propertyName).onInterface(interfaceName).uponReplyInvoke(std::forward(callback)); } - template - [[nodiscard]] Slot GetAsync(const InterfaceName& interfaceName, const PropertyName& propertyName, _Function&& callback, return_slot_t) + template + [[nodiscard]] Slot GetAsync(const InterfaceName& interfaceName, const PropertyName& propertyName, Function&& callback, return_slot_t) { - return m_proxy.getPropertyAsync(propertyName).onInterface(interfaceName).uponReplyInvoke(std::forward<_Function>(callback), return_slot); + return m_proxy.getPropertyAsync(propertyName).onInterface(interfaceName).uponReplyInvoke(std::forward(callback), return_slot); } std::future GetAsync(const InterfaceName& interfaceName, const PropertyName& propertyName, with_future_t) @@ -173,16 +173,16 @@ namespace sdbus { return m_proxy.getPropertyAsync(propertyName).onInterface(interfaceName).getResultAsFuture(); } - template - PendingAsyncCall GetAsync(std::string_view interfaceName, std::string_view propertyName, _Function&& callback) + template + PendingAsyncCall GetAsync(std::string_view interfaceName, std::string_view propertyName, Function&& callback) { - return m_proxy.getPropertyAsync(propertyName).onInterface(interfaceName).uponReplyInvoke(std::forward<_Function>(callback)); + return m_proxy.getPropertyAsync(propertyName).onInterface(interfaceName).uponReplyInvoke(std::forward(callback)); } - template - [[nodiscard]] Slot GetAsync(std::string_view interfaceName, std::string_view propertyName, _Function&& callback, return_slot_t) + template + [[nodiscard]] Slot GetAsync(std::string_view interfaceName, std::string_view propertyName, Function&& callback, return_slot_t) { - return m_proxy.getPropertyAsync(propertyName).onInterface(interfaceName).uponReplyInvoke(std::forward<_Function>(callback), return_slot); + return m_proxy.getPropertyAsync(propertyName).onInterface(interfaceName).uponReplyInvoke(std::forward(callback), return_slot); } std::future GetAsync(std::string_view interfaceName, std::string_view propertyName, with_future_t) @@ -210,16 +210,16 @@ namespace sdbus { m_proxy.setProperty(propertyName).onInterface(interfaceName).toValue(value, dont_expect_reply); } - template - PendingAsyncCall SetAsync(const InterfaceName& interfaceName, const PropertyName& propertyName, const sdbus::Variant& value, _Function&& callback) + template + PendingAsyncCall SetAsync(const InterfaceName& interfaceName, const PropertyName& propertyName, const sdbus::Variant& value, Function&& callback) { - return m_proxy.setPropertyAsync(propertyName).onInterface(interfaceName).toValue(value).uponReplyInvoke(std::forward<_Function>(callback)); + return m_proxy.setPropertyAsync(propertyName).onInterface(interfaceName).toValue(value).uponReplyInvoke(std::forward(callback)); } - template - [[nodiscard]] Slot SetAsync(const InterfaceName& interfaceName, const PropertyName& propertyName, const sdbus::Variant& value, _Function&& callback, return_slot_t) + template + [[nodiscard]] Slot SetAsync(const InterfaceName& interfaceName, const PropertyName& propertyName, const sdbus::Variant& value, Function&& callback, return_slot_t) { - return m_proxy.setPropertyAsync(propertyName).onInterface(interfaceName).toValue(value).uponReplyInvoke(std::forward<_Function>(callback), return_slot); + return m_proxy.setPropertyAsync(propertyName).onInterface(interfaceName).toValue(value).uponReplyInvoke(std::forward(callback), return_slot); } std::future SetAsync(const InterfaceName& interfaceName, const PropertyName& propertyName, const sdbus::Variant& value, with_future_t) @@ -227,16 +227,16 @@ namespace sdbus { return m_proxy.setPropertyAsync(propertyName).onInterface(interfaceName).toValue(value).getResultAsFuture(); } - template - PendingAsyncCall SetAsync(std::string_view interfaceName, std::string_view propertyName, const sdbus::Variant& value, _Function&& callback) + template + PendingAsyncCall SetAsync(std::string_view interfaceName, std::string_view propertyName, const sdbus::Variant& value, Function&& callback) { - return m_proxy.setPropertyAsync(propertyName).onInterface(interfaceName).toValue(value).uponReplyInvoke(std::forward<_Function>(callback)); + return m_proxy.setPropertyAsync(propertyName).onInterface(interfaceName).toValue(value).uponReplyInvoke(std::forward(callback)); } - template - [[nodiscard]] Slot SetAsync(std::string_view interfaceName, std::string_view propertyName, const sdbus::Variant& value, _Function&& callback, return_slot_t) + template + [[nodiscard]] Slot SetAsync(std::string_view interfaceName, std::string_view propertyName, const sdbus::Variant& value, Function&& callback, return_slot_t) { - return m_proxy.setPropertyAsync(propertyName).onInterface(interfaceName).toValue(value).uponReplyInvoke(std::forward<_Function>(callback), return_slot); + return m_proxy.setPropertyAsync(propertyName).onInterface(interfaceName).toValue(value).uponReplyInvoke(std::forward(callback), return_slot); } std::future SetAsync(std::string_view interfaceName, std::string_view propertyName, const sdbus::Variant& value, with_future_t) @@ -254,16 +254,16 @@ namespace sdbus { return m_proxy.getAllProperties().onInterface(interfaceName); } - template - PendingAsyncCall GetAllAsync(const InterfaceName& interfaceName, _Function&& callback) + template + PendingAsyncCall GetAllAsync(const InterfaceName& interfaceName, Function&& callback) { - return m_proxy.getAllPropertiesAsync().onInterface(interfaceName).uponReplyInvoke(std::forward<_Function>(callback)); + return m_proxy.getAllPropertiesAsync().onInterface(interfaceName).uponReplyInvoke(std::forward(callback)); } - template - [[nodiscard]] Slot GetAllAsync(const InterfaceName& interfaceName, _Function&& callback, return_slot_t) + template + [[nodiscard]] Slot GetAllAsync(const InterfaceName& interfaceName, Function&& callback, return_slot_t) { - return m_proxy.getAllPropertiesAsync().onInterface(interfaceName).uponReplyInvoke(std::forward<_Function>(callback), return_slot); + return m_proxy.getAllPropertiesAsync().onInterface(interfaceName).uponReplyInvoke(std::forward(callback), return_slot); } std::future> GetAllAsync(const InterfaceName& interfaceName, with_future_t) @@ -271,16 +271,16 @@ namespace sdbus { return m_proxy.getAllPropertiesAsync().onInterface(interfaceName).getResultAsFuture(); } - template - PendingAsyncCall GetAllAsync(std::string_view interfaceName, _Function&& callback) + template + PendingAsyncCall GetAllAsync(std::string_view interfaceName, Function&& callback) { - return m_proxy.getAllPropertiesAsync().onInterface(interfaceName).uponReplyInvoke(std::forward<_Function>(callback)); + return m_proxy.getAllPropertiesAsync().onInterface(interfaceName).uponReplyInvoke(std::forward(callback)); } - template - [[nodiscard]] Slot GetAllAsync(std::string_view interfaceName, _Function&& callback, return_slot_t) + template + [[nodiscard]] Slot GetAllAsync(std::string_view interfaceName, Function&& callback, return_slot_t) { - return m_proxy.getAllPropertiesAsync().onInterface(interfaceName).uponReplyInvoke(std::forward<_Function>(callback), return_slot); + return m_proxy.getAllPropertiesAsync().onInterface(interfaceName).uponReplyInvoke(std::forward(callback), return_slot); } std::future> GetAllAsync(std::string_view interfaceName, with_future_t) @@ -298,16 +298,11 @@ namespace sdbus { static inline const char* INTERFACE_NAME = "org.freedesktop.DBus.ObjectManager"; protected: - ObjectManager_proxy(sdbus::IProxy& proxy) + explicit ObjectManager_proxy(sdbus::IProxy& proxy) : m_proxy(proxy) { } - ObjectManager_proxy(const ObjectManager_proxy&) = delete; - ObjectManager_proxy& operator=(const ObjectManager_proxy&) = delete; - ObjectManager_proxy(ObjectManager_proxy&&) = delete; - ObjectManager_proxy& operator=(ObjectManager_proxy&&) = delete; - ~ObjectManager_proxy() = default; void registerProxy() @@ -337,6 +332,11 @@ namespace sdbus { , const std::vector& interfaces) = 0; public: + ObjectManager_proxy(const ObjectManager_proxy&) = delete; + ObjectManager_proxy& operator=(const ObjectManager_proxy&) = delete; + ObjectManager_proxy(ObjectManager_proxy&&) = delete; + ObjectManager_proxy& operator=(ObjectManager_proxy&&) = delete; + std::map>> GetManagedObjects() { std::map>> objectsInterfacesAndProperties; @@ -344,16 +344,16 @@ namespace sdbus { return objectsInterfacesAndProperties; } - template - PendingAsyncCall GetManagedObjectsAsync(_Function&& callback) + template + PendingAsyncCall GetManagedObjectsAsync(Function&& callback) { - return m_proxy.callMethodAsync("GetManagedObjects").onInterface(INTERFACE_NAME).uponReplyInvoke(std::forward<_Function>(callback)); + return m_proxy.callMethodAsync("GetManagedObjects").onInterface(INTERFACE_NAME).uponReplyInvoke(std::forward(callback)); } - template - [[nodiscard]] Slot GetManagedObjectsAsync(_Function&& callback, return_slot_t) + template + [[nodiscard]] Slot GetManagedObjectsAsync(Function&& callback, return_slot_t) { - return m_proxy.callMethodAsync("GetManagedObjects").onInterface(INTERFACE_NAME).uponReplyInvoke(std::forward<_Function>(callback), return_slot); + return m_proxy.callMethodAsync("GetManagedObjects").onInterface(INTERFACE_NAME).uponReplyInvoke(std::forward(callback), return_slot); } std::future>>> GetManagedObjectsAsync(with_future_t) @@ -375,15 +375,10 @@ namespace sdbus { static inline const char* INTERFACE_NAME = "org.freedesktop.DBus.Properties"; protected: - Properties_adaptor(sdbus::IObject& object) : m_object(object) + explicit Properties_adaptor(sdbus::IObject& object) : m_object(object) { } - Properties_adaptor(const Properties_adaptor&) = delete; - Properties_adaptor& operator=(const Properties_adaptor&) = delete; - Properties_adaptor(Properties_adaptor&&) = delete; - Properties_adaptor& operator=(Properties_adaptor&&) = delete; - ~Properties_adaptor() = default; void registerAdaptor() @@ -391,6 +386,11 @@ namespace sdbus { } public: + Properties_adaptor(const Properties_adaptor&) = delete; + Properties_adaptor& operator=(const Properties_adaptor&) = delete; + Properties_adaptor(Properties_adaptor&&) = delete; + Properties_adaptor& operator=(Properties_adaptor&&) = delete; + void emitPropertiesChangedSignal(const InterfaceName& interfaceName, const std::vector& properties) { m_object.emitPropertiesChangedSignal(interfaceName, properties); @@ -418,7 +418,7 @@ namespace sdbus { /*! * @brief Object Manager Convenience Adaptor * - * Adding this class as _Interfaces.. template parameter of class AdaptorInterfaces + * Adding this class as Interfaces.. template parameter of class AdaptorInterfaces * implements the *GetManagedObjects()* method of the [org.freedesktop.DBus.ObjectManager.GetManagedObjects](https://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces-objectmanager) * interface. * @@ -434,11 +434,6 @@ namespace sdbus { { } - ObjectManager_adaptor(const ObjectManager_adaptor&) = delete; - ObjectManager_adaptor& operator=(const ObjectManager_adaptor&) = delete; - ObjectManager_adaptor(ObjectManager_adaptor&&) = delete; - ObjectManager_adaptor& operator=(ObjectManager_adaptor&&) = delete; - ~ObjectManager_adaptor() = default; void registerAdaptor() @@ -446,6 +441,12 @@ namespace sdbus { m_object.addObjectManager(); } + public: + ObjectManager_adaptor(const ObjectManager_adaptor&) = delete; + ObjectManager_adaptor& operator=(const ObjectManager_adaptor&) = delete; + ObjectManager_adaptor(ObjectManager_adaptor&&) = delete; + ObjectManager_adaptor& operator=(ObjectManager_adaptor&&) = delete; + private: sdbus::IObject& m_object; }; @@ -453,7 +454,7 @@ namespace sdbus { /*! * @brief Managed Object Convenience Adaptor * - * Adding this class as _Interfaces.. template parameter of class AdaptorInterfaces + * Adding this class as Interfaces.. template parameter of class AdaptorInterfaces * will extend the resulting object adaptor with emitInterfacesAddedSignal()/emitInterfacesRemovedSignal() * according to org.freedesktop.DBus.ObjectManager.InterfacesAdded/.InterfacesRemoved. * @@ -469,11 +470,6 @@ namespace sdbus { { } - ManagedObject_adaptor(const ManagedObject_adaptor&) = delete; - ManagedObject_adaptor& operator=(const ManagedObject_adaptor&) = delete; - ManagedObject_adaptor(ManagedObject_adaptor&&) = delete; - ManagedObject_adaptor& operator=(ManagedObject_adaptor&&) = delete; - ~ManagedObject_adaptor() = default; void registerAdaptor() @@ -481,6 +477,11 @@ namespace sdbus { } public: + ManagedObject_adaptor(const ManagedObject_adaptor&) = delete; + ManagedObject_adaptor& operator=(const ManagedObject_adaptor&) = delete; + ManagedObject_adaptor(ManagedObject_adaptor&&) = delete; + ManagedObject_adaptor& operator=(ManagedObject_adaptor&&) = delete; + /*! * @brief Emits InterfacesAdded signal for this object path * @@ -525,6 +526,6 @@ namespace sdbus { sdbus::IObject& m_object; }; -} +} // namespace sdbus #endif /* SDBUS_CXX_STANDARDINTERFACES_H_ */ diff --git a/include/sdbus-c++/TypeTraits.h b/include/sdbus-c++/TypeTraits.h index 37d1f078..6751abdf 100644 --- a/include/sdbus-c++/TypeTraits.h +++ b/include/sdbus-c++/TypeTraits.h @@ -52,11 +52,11 @@ // Forward declarations namespace sdbus { class Variant; - template class Struct; + template class Struct; class ObjectPath; class Signature; class UnixFd; - template using DictEntry = std::pair<_T1, _T2>; + template using DictEntry = std::pair; class BusName; class InterfaceName; class MemberName; @@ -66,10 +66,10 @@ namespace sdbus { class Message; class PropertySetCall; class PropertyGetReply; - template class Result; + template class Result; class Error; - template struct signature_of; -} + template struct signature_of; +} // namespace sdbus namespace sdbus { @@ -111,17 +111,17 @@ namespace sdbus { inline constexpr embed_variant_t embed_variant{}; // Helper for static assert - template constexpr bool always_false = false; + template constexpr bool always_false = false; // Helper operator+ for concatenation of `std::array`s - template - constexpr std::array<_T, _N1 + _N2> operator+(std::array<_T, _N1> lhs, std::array<_T, _N2> rhs); + template + constexpr std::array operator+(std::array lhs, std::array rhs); // Template specializations for getting D-Bus signatures from C++ types - template - constexpr auto signature_of_v = signature_of<_T>::value; + template + constexpr auto signature_of_v = signature_of::value; - template + template struct signature_of { static constexpr bool is_valid = false; @@ -131,28 +131,28 @@ namespace sdbus { { // See using-sdbus-c++.md, section "Extending sdbus-c++ type system", // on how to teach sdbus-c++ about your custom types - static_assert(always_false<_T>, "Unsupported D-Bus type (specialize `signature_of` for your custom types)"); + static_assert(always_false, "Unsupported D-Bus type (specialize `signature_of` for your custom types)"); }; }; - template - struct signature_of : signature_of<_T> + template + struct signature_of : signature_of {}; - template - struct signature_of : signature_of<_T> + template + struct signature_of : signature_of {}; - template - struct signature_of : signature_of<_T> + template + struct signature_of : signature_of {}; - template - struct signature_of<_T&> : signature_of<_T> + template + struct signature_of : signature_of {}; - template - struct signature_of<_T&&> : signature_of<_T> + template + struct signature_of : signature_of {}; template <> @@ -255,12 +255,12 @@ namespace sdbus { struct signature_of : signature_of {}; - template - struct signature_of : signature_of + template + struct signature_of : signature_of {}; - template - struct signature_of : signature_of + template + struct signature_of : signature_of {}; template <> @@ -275,10 +275,10 @@ namespace sdbus { struct signature_of : signature_of {}; - template - struct signature_of> + template + struct signature_of> { - static constexpr std::array contents = (signature_of_v<_ValueTypes> + ...); + static constexpr std::array contents = (signature_of_v + ...); static constexpr std::array value = std::array{'('} + contents + std::array{')'}; static constexpr char type_value{'r'}; /* Not actually used in signatures on D-Bus, see specs */ static constexpr bool is_valid = true; @@ -321,93 +321,93 @@ namespace sdbus { static constexpr bool is_trivial_dbus_type = false; }; - template - struct signature_of> + template + struct signature_of> { - static constexpr std::array value = std::array{'{'} + signature_of_v> + std::array{'}'}; + static constexpr std::array value = std::array{'{'} + signature_of_v> + std::array{'}'}; static constexpr char type_value{'e'}; /* Not actually used in signatures on D-Bus, see specs */ static constexpr bool is_valid = true; static constexpr bool is_trivial_dbus_type = false; }; - template - struct signature_of> + template + struct signature_of> { - static constexpr std::array value = std::array{'a'} + signature_of_v<_Element>; + static constexpr std::array value = std::array{'a'} + signature_of_v; static constexpr bool is_valid = true; static constexpr bool is_trivial_dbus_type = false; }; - template - struct signature_of> : signature_of> + template + struct signature_of> : signature_of> { }; #ifdef __cpp_lib_span - template - struct signature_of> : signature_of> + template + struct signature_of> : signature_of> { }; #endif - template // is_const_v and is_volatile_v to avoid ambiguity conflicts with const and volatile specializations of signature_of - struct signature_of<_Enum, typename std::enable_if_t && !std::is_const_v<_Enum> && !std::is_volatile_v<_Enum>>> - : signature_of> + template // is_const_v and is_volatile_v to avoid ambiguity conflicts with const and volatile specializations of signature_of + struct signature_of && !std::is_const_v && !std::is_volatile_v>> + : signature_of> {}; - template - struct signature_of> + template + struct signature_of> { - static constexpr std::array value = std::array{'a'} + signature_of_v>; + static constexpr std::array value = std::array{'a'} + signature_of_v>; static constexpr bool is_valid = true; static constexpr bool is_trivial_dbus_type = false; }; - template - struct signature_of> - : signature_of> + template + struct signature_of> + : signature_of> { }; - template - struct signature_of> // A simple concatenation of signatures of _Types + template + struct signature_of> // A simple concatenation of signatures of _Types { - static constexpr std::array value = (std::array{} + ... + signature_of_v<_Types>); + static constexpr std::array value = (std::array{} + ... + signature_of_v); static constexpr bool is_valid = false; static constexpr bool is_trivial_dbus_type = false; }; // To simplify conversions of arrays to C strings - template - constexpr auto as_null_terminated(std::array<_T, _N> arr) + template + constexpr auto as_null_terminated(std::array arr) { - return arr + std::array<_T, 1>{0}; + return arr + std::array{0}; } // Function traits implementation inspired by (c) kennytm, // https://github.com/kennytm/utils/blob/master/traits.hpp - template - struct function_traits : function_traits + template + struct function_traits : function_traits {}; - template - struct function_traits : function_traits<_Type> + template + struct function_traits : function_traits {}; - template - struct function_traits<_Type&> : function_traits<_Type> + template + struct function_traits : function_traits {}; - template + template struct function_traits_base { - typedef _ReturnType result_type; - typedef std::tuple<_Args...> arguments_type; - typedef std::tuple...> decayed_arguments_type; + using result_type = ReturnType; + using arguments_type = std::tuple; + using decayed_arguments_type = std::tuple...>; - typedef _ReturnType function_type(_Args...); + using function_type = ReturnType (Args...); - static constexpr std::size_t arity = sizeof...(_Args); + static constexpr std::size_t arity = sizeof...(Args); // template // struct arg; @@ -424,187 +424,187 @@ namespace sdbus { // typedef void type; // }; - template + template struct arg { - typedef std::tuple_element_t<_Idx, std::tuple<_Args...>> type; + using type = std::tuple_element_t>; }; - template - using arg_t = typename arg<_Idx>::type; + template + using arg_t = typename arg::type; }; - template - struct function_traits<_ReturnType(_Args...)> : function_traits_base<_ReturnType, _Args...> + template + struct function_traits : function_traits_base { static constexpr bool is_async = false; static constexpr bool has_error_param = false; }; - template - struct function_traits, _Args...)> : function_traits_base + template + struct function_traits, Args...)> : function_traits_base { static constexpr bool has_error_param = true; }; - template - struct function_traits&&, _Args...)> : function_traits_base + template + struct function_traits&&, Args...)> : function_traits_base { static constexpr bool has_error_param = true; }; - template - struct function_traits&, _Args...)> : function_traits_base + template + struct function_traits&, Args...)> : function_traits_base { static constexpr bool has_error_param = true; }; - template - struct function_traits, _Args...)> : function_traits_base, _Args...> + template + struct function_traits, Args...)> : function_traits_base, Args...> { static constexpr bool is_async = true; - using async_result_t = Result<_Results...>; + using async_result_t = Result; }; - template - struct function_traits&&, _Args...)> : function_traits_base, _Args...> + template + struct function_traits&&, Args...)> : function_traits_base, Args...> { static constexpr bool is_async = true; - using async_result_t = Result<_Results...>; + using async_result_t = Result; }; - template - struct function_traits<_ReturnType(*)(_Args...)> : function_traits<_ReturnType(_Args...)> + template + struct function_traits : function_traits {}; - template - struct function_traits<_ReturnType(_ClassType::*)(_Args...)> : function_traits<_ReturnType(_Args...)> + template + struct function_traits : function_traits { - typedef _ClassType& owner_type; + using owner_type = ClassType &; }; - template - struct function_traits<_ReturnType(_ClassType::*)(_Args...) const> : function_traits<_ReturnType(_Args...)> + template + struct function_traits : function_traits { - typedef const _ClassType& owner_type; + using owner_type = const ClassType &; }; - template - struct function_traits<_ReturnType(_ClassType::*)(_Args...) volatile> : function_traits<_ReturnType(_Args...)> + template + struct function_traits : function_traits { - typedef volatile _ClassType& owner_type; + using owner_type = volatile ClassType &; }; - template - struct function_traits<_ReturnType(_ClassType::*)(_Args...) const volatile> : function_traits<_ReturnType(_Args...)> + template + struct function_traits : function_traits { - typedef const volatile _ClassType& owner_type; + using owner_type = const volatile ClassType &; }; template struct function_traits> : function_traits {}; - template - constexpr auto is_async_method_v = function_traits<_Function>::is_async; + template + constexpr auto is_async_method_v = function_traits::is_async; - template - constexpr auto has_error_param_v = function_traits<_Function>::has_error_param; + template + constexpr auto has_error_param_v = function_traits::has_error_param; - template - using function_arguments_t = typename function_traits<_FunctionType>::arguments_type; + template + using function_arguments_t = typename function_traits::arguments_type; - template - using function_argument_t = typename function_traits<_FunctionType>::template arg_t<_Idx>; + template + using function_argument_t = typename function_traits::template arg_t; - template - constexpr auto function_argument_count_v = function_traits<_FunctionType>::arity; + template + constexpr auto function_argument_count_v = function_traits::arity; - template - using function_result_t = typename function_traits<_FunctionType>::result_type; + template + using function_result_t = typename function_traits::result_type; - template + template struct tuple_of_function_input_arg_types { - typedef typename function_traits<_Function>::decayed_arguments_type type; + using type = typename function_traits::decayed_arguments_type; }; - template - using tuple_of_function_input_arg_types_t = typename tuple_of_function_input_arg_types<_Function>::type; + template + using tuple_of_function_input_arg_types_t = typename tuple_of_function_input_arg_types::type; - template + template struct tuple_of_function_output_arg_types { - typedef typename function_traits<_Function>::result_type type; + using type = typename function_traits::result_type; }; - template - using tuple_of_function_output_arg_types_t = typename tuple_of_function_output_arg_types<_Function>::type; + template + using tuple_of_function_output_arg_types_t = typename tuple_of_function_output_arg_types::type; - template - struct signature_of_function_input_arguments : signature_of> + template + struct signature_of_function_input_arguments : signature_of> { static std::string value_as_string() { - constexpr auto signature = as_null_terminated(signature_of_v>); + constexpr auto signature = as_null_terminated(signature_of_v>); return signature.data(); } }; - template - inline auto signature_of_function_input_arguments_v = signature_of_function_input_arguments<_Function>::value_as_string(); + template + inline const auto signature_of_function_input_arguments_v = signature_of_function_input_arguments::value_as_string(); - template - struct signature_of_function_output_arguments : signature_of> + template + struct signature_of_function_output_arguments : signature_of> { static std::string value_as_string() { - constexpr auto signature = as_null_terminated(signature_of_v>); + constexpr auto signature = as_null_terminated(signature_of_v>); return signature.data(); } }; - template - inline auto signature_of_function_output_arguments_v = signature_of_function_output_arguments<_Function>::value_as_string(); + template + inline const auto signature_of_function_output_arguments_v = signature_of_function_output_arguments::value_as_string(); // std::future stuff for return values of async calls - template struct future_return + template struct future_return { - typedef std::tuple<_Args...> type; + using type = std::tuple; }; template <> struct future_return<> { - typedef void type; + using type = void; }; - template struct future_return<_Type> + template struct future_return { - typedef _Type type; + using type = Type; }; - template - using future_return_t = typename future_return<_Args...>::type; + template + using future_return_t = typename future_return::type; // Credit: Piotr Skotnicki (https://stackoverflow.com/a/57639506) template constexpr bool is_one_of_variants_types = false; - template - constexpr bool is_one_of_variants_types, _QueriedType> - = (std::is_same_v<_QueriedType, _VariantTypes> || ...); + template + constexpr bool is_one_of_variants_types, QueriedType> + = (std::is_same_v || ...); // Wrapper (tag) denoting we want to serialize user-defined struct // into a D-Bus message as a dictionary of strings to variants. - template + template struct as_dictionary { - explicit as_dictionary(const _Struct& s) : m_struct(s) {} - const _Struct& m_struct; + explicit as_dictionary(const Struct& strct) : m_struct(strct) {} + const Struct& m_struct; // NOLINT(cppcoreguidelines-avoid-const-or-ref-data-members) }; - template - const _Type& as_dictionary_if_struct(const _Type& object) + template + const Type& as_dictionary_if_struct(const Type& object) { return object; // identity in case _Type is not struct (user-defined structs shall provide an overload) } @@ -613,7 +613,7 @@ namespace sdbus { // Strict means that every key of the deserialized dictionary must have its counterpart member in the struct, otherwise an exception is thrown. // Relaxed means that a key that does not have a matching struct member is silently ignored. // The behavior can be overridden for user-defined struct by specializing this variable template. - template + template constexpr auto strict_dict_as_struct_deserialization_v = true; // By default, the struct-as-dict serialization strategy is single-level only (as opposed to nested). @@ -621,94 +621,97 @@ namespace sdbus { // Nested means that the struct *and* its members that are structs are all serialized as a dictionary. If nested strategy is also // defined for the nested struct, then the same behavior applies for that struct, recursively. // The behavior can be overridden for user-defined struct by specializing this variable template. - template + template constexpr auto nested_struct_as_dict_serialization_v = false; namespace detail { - template - constexpr decltype(auto) apply_impl( _Function&& f - , Result<_Args...>&& r - , _Tuple&& t - , std::index_sequence<_I...> ) + template + constexpr decltype(auto) apply_impl( Function&& fun + , Result&& res + , Tuple&& tuple + , std::index_sequence ) { - return std::forward<_Function>(f)(std::move(r), std::get<_I>(std::forward<_Tuple>(t))...); + return std::forward(fun)(std::move(res), std::get(std::forward(tuple))...); } - template - decltype(auto) apply_impl( _Function&& f - , std::optional e - , _Tuple&& t - , std::index_sequence<_I...> ) + template + decltype(auto) apply_impl( Function&& fun + , std::optional err + , Tuple&& tuple + , std::index_sequence ) { - return std::forward<_Function>(f)(std::move(e), std::get<_I>(std::forward<_Tuple>(t))...); + return std::forward(fun)(std::move(err), std::get(std::forward(tuple))...); } // For non-void returning functions, apply_impl simply returns function return value (a tuple of values). // For void-returning functions, apply_impl returns an empty tuple. - template - constexpr decltype(auto) apply_impl( _Function&& f - , _Tuple&& t - , std::index_sequence<_I...> ) + template + constexpr decltype(auto) apply_impl( Function&& fun + , Tuple&& tuple + , std::index_sequence ) { - if constexpr (!std::is_void_v>) - return std::forward<_Function>(f)(std::get<_I>(std::forward<_Tuple>(t))...); + if constexpr (!std::is_void_v>) + return std::forward(fun)(std::get(std::forward(tuple))...); else - return std::forward<_Function>(f)(std::get<_I>(std::forward<_Tuple>(t))...), std::tuple<>{}; + return std::forward(fun)(std::get(std::forward(tuple))...), std::tuple<>{}; } - } + } // namespace detail // Convert tuple `t' of values into a list of arguments // and invoke function `f' with those arguments. - template - constexpr decltype(auto) apply(_Function&& f, _Tuple&& t) + template + constexpr decltype(auto) apply(Function&& fun, Tuple&& tuple) { - return detail::apply_impl( std::forward<_Function>(f) - , std::forward<_Tuple>(t) - , std::make_index_sequence>::value>{} ); + return detail::apply_impl( std::forward(fun) + , std::forward(tuple) + , std::make_index_sequence>::value>{} ); } // Convert tuple `t' of values into a list of arguments // and invoke function `f' with those arguments. - template - constexpr decltype(auto) apply(_Function&& f, Result<_Args...>&& r, _Tuple&& t) + template + constexpr decltype(auto) apply(Function&& fun, Result&& res, Tuple&& tuple) { - return detail::apply_impl( std::forward<_Function>(f) - , std::move(r) - , std::forward<_Tuple>(t) - , std::make_index_sequence>::value>{} ); + return detail::apply_impl( std::forward(fun) + , std::move(res) + , std::forward(tuple) + , std::make_index_sequence>::value>{} ); } // Convert tuple `t' of values into a list of arguments // and invoke function `f' with those arguments. - template - decltype(auto) apply(_Function&& f, std::optional e, _Tuple&& t) + template + decltype(auto) apply(Function&& fun, std::optional err, Tuple&& tuple) { - return detail::apply_impl( std::forward<_Function>(f) - , std::move(e) - , std::forward<_Tuple>(t) - , std::make_index_sequence>::value>{} ); + return detail::apply_impl( std::forward(fun) + , std::move(err) + , std::forward(tuple) + , std::make_index_sequence>::value>{} ); } // Convenient concatenation of arrays - template - constexpr std::array<_T, _N1 + _N2> operator+(std::array<_T, _N1> lhs, std::array<_T, _N2> rhs) + template + constexpr std::array operator+(std::array lhs, std::array rhs) { - std::array<_T, _N1 + _N2> result{}; - std::size_t index = 0; + std::array result{}; - for (auto& el : lhs) { - result[index] = std::move(el); - ++index; - } - for (auto& el : rhs) { - result[index] = std::move(el); - ++index; - } + std::move(lhs.begin(), lhs.end(), result.begin()); + std::move(rhs.begin(), rhs.end(), result.begin() + N1); + + // std::size_t index = 0; + // for (auto& item : lhs) { + // result[index] = std::move(item); + // ++index; + // } + // for (auto& item : rhs) { + // result[index] = std::move(item); + // ++index; + // } return result; } -} +} // namespace sdbus #endif /* SDBUS_CXX_TYPETRAITS_H_ */ diff --git a/include/sdbus-c++/Types.h b/include/sdbus-c++/Types.h index 601fd015..62644da4 100644 --- a/include/sdbus-c++/Types.h +++ b/include/sdbus-c++/Types.h @@ -58,10 +58,10 @@ namespace sdbus { public: Variant(); - template - explicit Variant(const _ValueType& value) : Variant() + template + explicit Variant(const ValueType& value) : Variant() { - msg_.openVariant<_ValueType>(); + msg_.openVariant(); msg_ << value; msg_.closeVariant(); msg_.seal(); @@ -75,8 +75,8 @@ namespace sdbus { msg_.seal(); } - template - explicit Variant(const as_dictionary<_Struct>& value) : Variant() + template + explicit Variant(const as_dictionary& value) : Variant() { msg_.openVariant>(); msg_ << as_dictionary(value.m_struct); @@ -84,46 +84,47 @@ namespace sdbus { msg_.seal(); } - template - Variant(const std::variant<_Elements...>& value) + template + Variant(const std::variant& value) // NOLINT(google-explicit-constructor,hicpp-explicit-conversions): implicit conversion intentional : Variant() { msg_ << value; msg_.seal(); } - template - _ValueType get() const + template + ValueType get() const { msg_.rewind(false); - msg_.enterVariant<_ValueType>(); - _ValueType val; + msg_.enterVariant(); + ValueType val; msg_ >> val; msg_.exitVariant(); return val; } // Only allow conversion operator for true D-Bus type representations in C++ - template ::is_valid>> - explicit operator _ValueType() const + // NOLINTNEXTLINE(modernize-use-constraints): TODO for future: Use `requires signature_of<_ValueType>::is_valid` (when we stop supporting C++17 in public API) + template ::is_valid>> + explicit operator ValueType() const { - return get<_ValueType>(); + return get(); } - template - operator std::variant<_Elements...>() const + template + operator std::variant() const // NOLINT(google-explicit-constructor,hicpp-explicit-conversions): implicit conversion intentional { - std::variant<_Elements...> result; + std::variant result; msg_.rewind(false); msg_ >> result; return result; } - template + template bool containsValueOfType() const { - constexpr auto signature = as_null_terminated(signature_of_v<_Type>); + constexpr auto signature = as_null_terminated(signature_of_v); return std::strcmp(signature.data(), peekValueType()) == 0; } @@ -134,7 +135,7 @@ namespace sdbus { const char* peekValueType() const; private: - mutable PlainMessage msg_{}; + mutable PlainMessage msg_; }; /********************************************//** @@ -147,48 +148,48 @@ namespace sdbus { * std::tuple_size and in structured bindings. * ***********************************************/ - template + template class Struct - : public std::tuple<_ValueTypes...> + : public std::tuple { public: - using std::tuple<_ValueTypes...>::tuple; + using std::tuple::tuple; Struct() = default; - explicit Struct(const std::tuple<_ValueTypes...>& t) - : std::tuple<_ValueTypes...>(t) + explicit Struct(const std::tuple& tuple) + : std::tuple(tuple) { } - template - auto& get() + template + [[nodiscard]] auto& get() { - return std::get<_I>(*this); + return std::get(*this); } - template - const auto& get() const + template + [[nodiscard]] const auto& get() const { - return std::get<_I>(*this); + return std::get(*this); } }; - template - Struct(_Elements...) -> Struct<_Elements...>; + template + Struct(Elements...) -> Struct; - template - Struct(const std::tuple<_Elements...>&) -> Struct<_Elements...>; + template + Struct(const std::tuple&) -> Struct; - template - Struct(std::tuple<_Elements...>&&) -> Struct<_Elements...>; + template + Struct(std::tuple&&) -> Struct; - template - constexpr Struct...> - make_struct(_Elements&&... args) + template + constexpr Struct...> + make_struct(Elements&&... args) { - typedef Struct...> result_type; - return result_type(std::forward<_Elements>(args)...); + typedef Struct...> result_type; + return result_type(std::forward(args)...); } /********************************************//** @@ -340,12 +341,12 @@ namespace sdbus { return *this; } - UnixFd(UnixFd&& other) + UnixFd(UnixFd&& other) noexcept { *this = std::move(other); } - UnixFd& operator=(UnixFd&& other) + UnixFd& operator=(UnixFd&& other) noexcept { if (this == &other) { @@ -404,21 +405,23 @@ namespace sdbus { * value_type in STL(-like) associative containers. * ***********************************************/ - template - using DictEntry = std::pair<_T1, _T2>; + template + using DictEntry = std::pair; -} +} // namespace sdbus // Making sdbus::Struct implement the tuple-protocol, i.e. be a tuple-like type -template -struct std::tuple_element<_I, sdbus::Struct<_ValueTypes...>> - : std::tuple_element<_I, std::tuple<_ValueTypes...>> +template +struct std::tuple_element> // NOLINT(cert-dcl58-cpp): specialization in std namespace allowed in this case + : std::tuple_element> {}; -template -struct std::tuple_size> - : std::tuple_size> +template +struct std::tuple_size> // NOLINT(cert-dcl58-cpp): specialization in std namespace allowed in this case + : std::tuple_size> {}; +// NOLINTBEGIN(cppcoreguidelines-macro-usage) + /********************************************//** * @name SDBUSCPP_REGISTER_STRUCT * @@ -600,4 +603,6 @@ struct std::tuple_size> #define SDBUSCPP_PP_COMMA , #define SDBUSCPP_PP_SPACE +// NOLINTEND(cppcoreguidelines-macro-usage) + #endif /* SDBUS_CXX_TYPES_H_ */ diff --git a/include/sdbus-c++/VTableItems.h b/include/sdbus-c++/VTableItems.h index 23bda879..ae57a00a 100644 --- a/include/sdbus-c++/VTableItems.h +++ b/include/sdbus-c++/VTableItems.h @@ -38,11 +38,11 @@ namespace sdbus { struct MethodVTableItem { - template MethodVTableItem& implementedAs(_Function&& callback); + template MethodVTableItem& implementedAs(Function&& callback); MethodVTableItem& withInputParamNames(std::vector names); - template MethodVTableItem& withInputParamNames(_String... names); + template MethodVTableItem& withInputParamNames(String... names); MethodVTableItem& withOutputParamNames(std::vector names); - template MethodVTableItem& withOutputParamNames(_String... names); + template MethodVTableItem& withOutputParamNames(String... names); MethodVTableItem& markAsDeprecated(); MethodVTableItem& markAsPrivileged(); MethodVTableItem& withNoReply(); @@ -61,9 +61,9 @@ namespace sdbus { struct SignalVTableItem { - template SignalVTableItem& withParameters(); - template SignalVTableItem& withParameters(std::vector names); - template SignalVTableItem& withParameters(_String... names); + template SignalVTableItem& withParameters(); + template SignalVTableItem& withParameters(std::vector names); + template SignalVTableItem& withParameters(String... names); SignalVTableItem& markAsDeprecated(); SignalName name; @@ -77,8 +77,8 @@ namespace sdbus { struct PropertyVTableItem { - template PropertyVTableItem& withGetter(_Function&& callback); - template PropertyVTableItem& withSetter(_Function&& callback); + template PropertyVTableItem& withGetter(Function&& callback); + template PropertyVTableItem& withSetter(Function&& callback); PropertyVTableItem& markAsDeprecated(); PropertyVTableItem& markAsPrivileged(); PropertyVTableItem& withUpdateBehavior(Flags::PropertyUpdateBehaviorFlags behavior); diff --git a/include/sdbus-c++/VTableItems.inl b/include/sdbus-c++/VTableItems.inl index 86356cf1..4cc1a851 100644 --- a/include/sdbus-c++/VTableItems.inl +++ b/include/sdbus-c++/VTableItems.inl @@ -39,21 +39,21 @@ namespace sdbus { /*** Method VTable Item ***/ /*** -------------------- ***/ - template - MethodVTableItem& MethodVTableItem::implementedAs(_Function&& callback) + template + MethodVTableItem& MethodVTableItem::implementedAs(Function&& callback) { - inputSignature = signature_of_function_input_arguments_v<_Function>; - outputSignature = signature_of_function_output_arguments_v<_Function>; - callbackHandler = [callback = std::forward<_Function>(callback)](MethodCall call) + inputSignature = signature_of_function_input_arguments_v; + outputSignature = signature_of_function_output_arguments_v; + callbackHandler = [callback = std::forward(callback)](MethodCall call) { // Create a tuple of callback input arguments' types, which will be used // as a storage for the argument values deserialized from the message. - tuple_of_function_input_arg_types_t<_Function> inputArgs; + tuple_of_function_input_arg_types_t inputArgs; // Deserialize input arguments from the message into the tuple. call >> inputArgs; - if constexpr (!is_async_method_v<_Function>) + if constexpr (!is_async_method_v) { // Invoke callback with input arguments from the tuple. auto ret = sdbus::apply(callback, inputArgs); @@ -66,7 +66,7 @@ namespace sdbus { else { // Invoke callback with input arguments from the tuple and with result object to be set later - using AsyncResult = typename function_traits<_Function>::async_result_t; + using AsyncResult = typename function_traits::async_result_t; sdbus::apply(callback, AsyncResult{std::move(call)}, std::move(inputArgs)); } }; @@ -81,10 +81,10 @@ namespace sdbus { return *this; } - template - inline MethodVTableItem& MethodVTableItem::withInputParamNames(_String... names) + template + inline MethodVTableItem& MethodVTableItem::withInputParamNames(String... names) { - static_assert(std::conjunction_v...>, "Parameter names must be (convertible to) strings"); + static_assert(std::conjunction_v...>, "Parameter names must be (convertible to) strings"); return withInputParamNames({names...}); } @@ -96,10 +96,10 @@ namespace sdbus { return *this; } - template - inline MethodVTableItem& MethodVTableItem::withOutputParamNames(_String... names) + template + inline MethodVTableItem& MethodVTableItem::withOutputParamNames(String... names) { - static_assert(std::conjunction_v...>, "Parameter names must be (convertible to) strings"); + static_assert(std::conjunction_v...>, "Parameter names must be (convertible to) strings"); return withOutputParamNames({names...}); } @@ -139,29 +139,29 @@ namespace sdbus { /*** Signal VTable Item ***/ /*** -------------------- ***/ - template + template inline SignalVTableItem& SignalVTableItem::withParameters() { - signature = signature_of_function_input_arguments_v; + signature = signature_of_function_input_arguments_v; return *this; } - template + template inline SignalVTableItem& SignalVTableItem::withParameters(std::vector names) { paramNames = std::move(names); - return withParameters<_Args...>(); + return withParameters(); } - template - inline SignalVTableItem& SignalVTableItem::withParameters(_String... names) + template + inline SignalVTableItem& SignalVTableItem::withParameters(String... names) { - static_assert(std::conjunction_v...>, "Parameter names must be (convertible to) strings"); - static_assert(sizeof...(_Args) == sizeof...(_String), "Numbers of signal parameters and their names don't match"); + static_assert(std::conjunction_v...>, "Parameter names must be (convertible to) strings"); + static_assert(sizeof...(Args) == sizeof...(String), "Numbers of signal parameters and their names don't match"); - return withParameters<_Args...>({names...}); + return withParameters({names...}); } inline SignalVTableItem& SignalVTableItem::markAsDeprecated() @@ -185,16 +185,16 @@ namespace sdbus { /*** Property VTable Item ***/ /*** -------------------- ***/ - template - inline PropertyVTableItem& PropertyVTableItem::withGetter(_Function&& callback) + template + inline PropertyVTableItem& PropertyVTableItem::withGetter(Function&& callback) { - static_assert(function_argument_count_v<_Function> == 0, "Property getter function must not take any arguments"); - static_assert(!std::is_void>::value, "Property getter function must return property value"); + static_assert(function_argument_count_v == 0, "Property getter function must not take any arguments"); + static_assert(!std::is_void>::value, "Property getter function must return property value"); if (signature.empty()) - signature = signature_of_function_output_arguments_v<_Function>; + signature = signature_of_function_output_arguments_v; - getter = [callback = std::forward<_Function>(callback)](PropertyGetReply& reply) + getter = [callback = std::forward(callback)](PropertyGetReply& reply) { // Get the propety value and serialize it into the pre-constructed reply message reply << callback(); @@ -203,19 +203,19 @@ namespace sdbus { return *this; } - template - inline PropertyVTableItem& PropertyVTableItem::withSetter(_Function&& callback) + template + inline PropertyVTableItem& PropertyVTableItem::withSetter(Function&& callback) { - static_assert(function_argument_count_v<_Function> == 1, "Property setter function must take one parameter - the property value"); - static_assert(std::is_void>::value, "Property setter function must not return any value"); + static_assert(function_argument_count_v == 1, "Property setter function must take one parameter - the property value"); + static_assert(std::is_void>::value, "Property setter function must not return any value"); if (signature.empty()) - signature = signature_of_function_input_arguments_v<_Function>; + signature = signature_of_function_input_arguments_v; - setter = [callback = std::forward<_Function>(callback)](PropertySetCall call) + setter = [callback = std::forward(callback)](PropertySetCall call) { // Default-construct property value - using property_type = function_argument_t<_Function, 0>; + using property_type = function_argument_t; std::decay_t property; // Deserialize property value from the incoming call message diff --git a/src/Connection.cpp b/src/Connection.cpp index 6177a0f4..1bb01fab 100644 --- a/src/Connection.cpp +++ b/src/Connection.cpp @@ -937,14 +937,14 @@ Connection::EventFd::~EventFd() close(fd); } -void Connection::EventFd::notify() const +void Connection::EventFd::notify() // NOLINT(readability-make-member-function-const) { assert(fd >= 0); auto r = eventfd_write(fd, 1); SDBUS_THROW_ERROR_IF(r < 0, "Failed to notify event descriptor", -errno); } -bool Connection::EventFd::clear() const +bool Connection::EventFd::clear() // NOLINT(readability-make-member-function-const) { assert(fd >= 0); diff --git a/src/Connection.h b/src/Connection.h index 35f8d527..6673c70c 100644 --- a/src/Connection.h +++ b/src/Connection.h @@ -52,33 +52,33 @@ namespace sdbus { using MethodName = MemberName; using SignalName = MemberName; using PropertyName = MemberName; -} +} // namespace sdbus namespace sdbus::internal { class Connection final - : public sdbus::internal::IConnection + : public IConnection { public: // Bus type tags struct default_bus_t{}; - inline static constexpr default_bus_t default_bus{}; + static constexpr default_bus_t default_bus{}; struct system_bus_t{}; - inline static constexpr system_bus_t system_bus{}; + static constexpr system_bus_t system_bus{}; struct session_bus_t{}; - inline static constexpr session_bus_t session_bus{}; + static constexpr session_bus_t session_bus{}; struct custom_session_bus_t{}; - inline static constexpr custom_session_bus_t custom_session_bus{}; + static constexpr custom_session_bus_t custom_session_bus{}; struct remote_system_bus_t{}; - inline static constexpr remote_system_bus_t remote_system_bus{}; + static constexpr remote_system_bus_t remote_system_bus{}; struct private_bus_t{}; - inline static constexpr private_bus_t private_bus{}; + static constexpr private_bus_t private_bus{}; struct server_bus_t{}; - inline static constexpr server_bus_t server_bus{}; + static constexpr server_bus_t server_bus{}; struct sdbus_bus_t{}; // A bus connection created directly from existing sd_bus instance - inline static constexpr sdbus_bus_t sdbus_bus{}; + static constexpr sdbus_bus_t sdbus_bus{}; struct pseudo_bus_t{}; // A bus connection that is not really established with D-Bus daemon - inline static constexpr pseudo_bus_t pseudo_bus{}; + static constexpr pseudo_bus_t pseudo_bus{}; Connection(std::unique_ptr&& interface, default_bus_t); Connection(std::unique_ptr&& interface, system_bus_t); @@ -90,6 +90,10 @@ namespace sdbus::internal { Connection(std::unique_ptr&& interface, server_bus_t, int fd); Connection(std::unique_ptr&& interface, sdbus_bus_t, sd_bus *bus); Connection(std::unique_ptr&& interface, pseudo_bus_t); + Connection(const Connection&) = delete; + Connection& operator=(const Connection&) = delete; + Connection(Connection&&) = delete; + Connection& operator=(Connection&&) = delete; ~Connection() override; void requestName(const ServiceName & name) override; @@ -200,7 +204,7 @@ namespace sdbus::internal { static int sdbus_match_callback(sd_bus_message *sdbusMessage, void *userData, sd_bus_error *retError); static int sdbus_match_install_callback(sd_bus_message *sdbusMessage, void *userData, sd_bus_error *retError); - private: + #ifndef SDBUS_basu // sd_event integration is not supported if instead of libsystemd we are based on basu static Slot createSdEventSlot(sd_event *event); Slot createSdTimeEventSourceSlot(sd_event *event, int priority); @@ -217,9 +221,13 @@ namespace sdbus::internal { struct EventFd { EventFd(); + EventFd(const EventFd&) = delete; + EventFd& operator=(const EventFd&) = delete; + EventFd(EventFd&&) = delete; + EventFd& operator=(EventFd&&) = delete; ~EventFd(); - void notify() const; - bool clear() const; + void notify(); + bool clear(); int fd{-1}; }; @@ -228,7 +236,7 @@ namespace sdbus::internal { { message_handler callback; message_handler installCallback; - Connection& connection; + Connection& connection; // NOLINT(cppcoreguidelines-avoid-const-or-ref-data-members) Slot slot; }; @@ -241,7 +249,6 @@ namespace sdbus::internal { Slot sdInternalEventSource; }; - private: std::unique_ptr sdbus_; BusPtr bus_; std::thread asyncLoopThread_; @@ -251,6 +258,6 @@ namespace sdbus::internal { std::unique_ptr sdEvent_; // Integration of systemd sd-event event loop implementation }; -} +} // namespace sdbus::internal #endif /* SDBUS_CXX_INTERNAL_CONNECTION_H_ */ diff --git a/src/IConnection.h b/src/IConnection.h index 3fb8a4ce..2f76c5fc 100644 --- a/src/IConnection.h +++ b/src/IConnection.h @@ -54,8 +54,8 @@ namespace sdbus { class Error; namespace internal { class ISdBus; - } -} + } // namespace internal +} // namespace sdbus namespace sdbus::internal { @@ -130,6 +130,6 @@ namespace sdbus::internal { [[nodiscard]] std::unique_ptr createPseudoConnection(); -} +} // namespace sdbus::internal #endif /* SDBUS_CXX_INTERNAL_ICONNECTION_H_ */ diff --git a/src/ISdBus.h b/src/ISdBus.h index 423dc199..ec24a086 100644 --- a/src/ISdBus.h +++ b/src/ISdBus.h @@ -44,18 +44,18 @@ namespace sdbus::internal { virtual ~ISdBus() = default; - virtual sd_bus_message* sd_bus_message_ref(sd_bus_message *m) = 0; - virtual sd_bus_message* sd_bus_message_unref(sd_bus_message *m) = 0; + virtual sd_bus_message* sd_bus_message_ref(sd_bus_message *msg) = 0; + virtual sd_bus_message* sd_bus_message_unref(sd_bus_message *msg) = 0; - virtual int sd_bus_send(sd_bus *bus, sd_bus_message *m, uint64_t *cookie) = 0; - virtual int sd_bus_call(sd_bus *bus, sd_bus_message *m, uint64_t usec, sd_bus_error *ret_error, sd_bus_message **reply) = 0; - virtual int sd_bus_call_async(sd_bus *bus, sd_bus_slot **slot, sd_bus_message *m, sd_bus_message_handler_t callback, void *userdata, uint64_t usec) = 0; + virtual int sd_bus_send(sd_bus *bus, sd_bus_message *msg, uint64_t *cookie) = 0; + virtual int sd_bus_call(sd_bus *bus, sd_bus_message *msg, uint64_t usec, sd_bus_error *ret_error, sd_bus_message **reply) = 0; + virtual int sd_bus_call_async(sd_bus *bus, sd_bus_slot **slot, sd_bus_message *msg, sd_bus_message_handler_t callback, void *userdata, uint64_t usec) = 0; - virtual int sd_bus_message_new(sd_bus *bus, sd_bus_message **m, uint8_t type) = 0; - virtual int sd_bus_message_new_method_call(sd_bus *bus, sd_bus_message **m, const char *destination, const char *path, const char *interface, const char *member) = 0; - virtual int sd_bus_message_new_signal(sd_bus *bus, sd_bus_message **m, const char *path, const char *interface, const char *member) = 0; - virtual int sd_bus_message_new_method_return(sd_bus_message *call, sd_bus_message **m) = 0; - virtual int sd_bus_message_new_method_error(sd_bus_message *call, sd_bus_message **m, const sd_bus_error *e) = 0; + virtual int sd_bus_message_new(sd_bus *bus, sd_bus_message **msg, uint8_t type) = 0; + virtual int sd_bus_message_new_method_call(sd_bus *bus, sd_bus_message **msg, const char *destination, const char *path, const char *interface, const char *member) = 0; + virtual int sd_bus_message_new_signal(sd_bus *bus, sd_bus_message **msg, const char *path, const char *interface, const char *member) = 0; + virtual int sd_bus_message_new_method_return(sd_bus_message *call, sd_bus_message **msg) = 0; + virtual int sd_bus_message_new_method_error(sd_bus_message *call, sd_bus_message **msg, const sd_bus_error *err) = 0; virtual int sd_bus_set_method_call_timeout(sd_bus *bus, uint64_t usec) = 0; virtual int sd_bus_get_method_call_timeout(sd_bus *bus, uint64_t *ret) = 0; @@ -87,7 +87,7 @@ namespace sdbus::internal { virtual int sd_bus_new(sd_bus **ret) = 0; virtual int sd_bus_start(sd_bus *bus) = 0; - virtual int sd_bus_process(sd_bus *bus, sd_bus_message **r) = 0; + virtual int sd_bus_process(sd_bus *bus, sd_bus_message **ret) = 0; virtual sd_bus_message* sd_bus_get_current_message(sd_bus *bus) = 0; virtual int sd_bus_get_poll_data(sd_bus *bus, PollData* data) = 0; virtual int sd_bus_get_n_queued(sd_bus *bus, uint64_t *read, uint64_t* write) = 0; @@ -95,21 +95,21 @@ namespace sdbus::internal { virtual sd_bus *sd_bus_flush_close_unref(sd_bus *bus) = 0; virtual sd_bus *sd_bus_close_unref(sd_bus *bus) = 0; - virtual int sd_bus_message_set_destination(sd_bus_message *m, const char *destination) = 0; + virtual int sd_bus_message_set_destination(sd_bus_message *msg, const char *destination) = 0; - virtual int sd_bus_query_sender_creds(sd_bus_message *m, uint64_t mask, sd_bus_creds **c) = 0; - virtual sd_bus_creds* sd_bus_creds_ref(sd_bus_creds *c) = 0; - virtual sd_bus_creds* sd_bus_creds_unref(sd_bus_creds *c) = 0; + virtual int sd_bus_query_sender_creds(sd_bus_message *msg, uint64_t mask, sd_bus_creds **creds) = 0; + virtual sd_bus_creds* sd_bus_creds_ref(sd_bus_creds *creds) = 0; + virtual sd_bus_creds* sd_bus_creds_unref(sd_bus_creds *creds) = 0; - virtual int sd_bus_creds_get_pid(sd_bus_creds *c, pid_t *pid) = 0; - virtual int sd_bus_creds_get_uid(sd_bus_creds *c, uid_t *uid) = 0; - virtual int sd_bus_creds_get_euid(sd_bus_creds *c, uid_t *uid) = 0; - virtual int sd_bus_creds_get_gid(sd_bus_creds *c, gid_t *gid) = 0; - virtual int sd_bus_creds_get_egid(sd_bus_creds *c, gid_t *egid) = 0; - virtual int sd_bus_creds_get_supplementary_gids(sd_bus_creds *c, const gid_t **gids) = 0; - virtual int sd_bus_creds_get_selinux_context(sd_bus_creds *c, const char **label) = 0; + virtual int sd_bus_creds_get_pid(sd_bus_creds *creds, pid_t *pid) = 0; + virtual int sd_bus_creds_get_uid(sd_bus_creds *creds, uid_t *uid) = 0; + virtual int sd_bus_creds_get_euid(sd_bus_creds *creds, uid_t *uid) = 0; + virtual int sd_bus_creds_get_gid(sd_bus_creds *creds, gid_t *gid) = 0; + virtual int sd_bus_creds_get_egid(sd_bus_creds *creds, gid_t *egid) = 0; + virtual int sd_bus_creds_get_supplementary_gids(sd_bus_creds *creds, const gid_t **gids) = 0; + virtual int sd_bus_creds_get_selinux_context(sd_bus_creds *creds, const char **label) = 0; }; -} +} // namespace sdbus::internal #endif //SDBUS_CXX_ISDBUS_H diff --git a/src/MessageUtils.h b/src/MessageUtils.h index 3c45f1af..fb3e0325 100644 --- a/src/MessageUtils.h +++ b/src/MessageUtils.h @@ -34,30 +34,30 @@ namespace sdbus class Message::Factory { public: - template - static _Msg create() + template + static Msg create() { - return _Msg{}; + return Msg{}; } - template - static _Msg create(void *msg) + template + static Msg create(void *msg) { - return _Msg{msg}; + return Msg{msg}; } - template - static _Msg create(void *msg, internal::IConnection* connection) + template + static Msg create(void *msg, internal::IConnection* connection) { - return _Msg{msg, connection}; + return Msg{msg, connection}; } - template - static _Msg create(void *msg, internal::IConnection* connection, adopt_message_t) + template + static Msg create(void *msg, internal::IConnection* connection, adopt_message_t) { - return _Msg{msg, connection, adopt_message}; + return Msg{msg, connection, adopt_message}; } }; -} +} // namespace sdbus #endif /* SDBUS_CXX_INTERNAL_MESSAGEUTILS_H_ */ diff --git a/src/Object.h b/src/Object.h index 81447981..dd0a2b6c 100644 --- a/src/Object.h +++ b/src/Object.h @@ -53,7 +53,7 @@ namespace sdbus::internal { Slot addVTable(InterfaceName interfaceName, std::vector vtable, return_slot_t) override; void unregister() override; - Signal createSignal(const InterfaceName& interfaceName, const SignalName& signalName) const override; + [[nodiscard]] Signal createSignal(const InterfaceName& interfaceName, const SignalName& signalName) const override; Signal createSignal(const char* interfaceName, const char* signalName) const override; void emitSignal(const sdbus::Signal& message) override; void emitPropertiesChangedSignal(const InterfaceName& interfaceName, const std::vector& propNames) override; @@ -159,13 +159,12 @@ namespace sdbus::internal { , void *userData , sd_bus_error *retError ); - private: - sdbus::internal::IConnection& connection_; + IConnection& connection_; // NOLINT(cppcoreguidelines-avoid-const-or-ref-data-members) ObjectPath objectPath_; std::vector vtables_; Slot objectManagerSlot_; }; -} +} // namespace sdbus::internal #endif /* SDBUS_CXX_INTERNAL_OBJECT_H_ */ diff --git a/src/Proxy.cpp b/src/Proxy.cpp index 35540cce..7c9cf730 100644 --- a/src/Proxy.cpp +++ b/src/Proxy.cpp @@ -140,7 +140,7 @@ PendingAsyncCall Proxy::callMethodAsync(const MethodCall& message, async_reply_h floatingAsyncCallSlots_.push_back(std::move(asyncCallInfo)); - return {asyncCallInfoWeakPtr}; + return PendingAsyncCall{asyncCallInfoWeakPtr}; } Slot Proxy::callMethodAsync(const MethodCall& message, async_reply_handler asyncReplyCallback, uint64_t timeout, return_slot_t) diff --git a/src/Proxy.h b/src/Proxy.h index 50ec3c26..f11c312d 100644 --- a/src/Proxy.h +++ b/src/Proxy.h @@ -56,8 +56,8 @@ namespace sdbus::internal { , ObjectPath objectPath , dont_run_event_loop_thread_t ); - MethodCall createMethodCall(const InterfaceName& interfaceName, const MethodName& methodName) const override; - MethodCall createMethodCall(const char* interfaceName, const char* methodName) const override; + [[nodiscard]] MethodCall createMethodCall(const InterfaceName& interfaceName, const MethodName& methodName) const override; + [[nodiscard]] MethodCall createMethodCall(const char* interfaceName, const char* methodName) const override; MethodReply callMethod(const MethodCall& message) override; MethodReply callMethod(const MethodCall& message, uint64_t timeout) override; PendingAsyncCall callMethodAsync(const MethodCall& message, async_reply_handler asyncReplyCallback) override; @@ -98,7 +98,6 @@ namespace sdbus::internal { static int sdbus_signal_handler(sd_bus_message *sdbusMessage, void *userData, sd_bus_error *retError); static int sdbus_async_reply_handler(sd_bus_message *sdbusMessage, void *userData, sd_bus_error *retError); - private: friend PendingAsyncCall; std::unique_ptr< sdbus::internal::IConnection @@ -112,15 +111,15 @@ namespace sdbus::internal { struct SignalInfo { signal_handler callback; - Proxy& proxy; + Proxy& proxy; // NOLINT(cppcoreguidelines-avoid-const-or-ref-data-members) Slot slot; }; struct AsyncCallInfo { async_reply_handler callback; - Proxy& proxy; - Slot slot{}; + Proxy& proxy; // NOLINT(cppcoreguidelines-avoid-const-or-ref-data-members) + Slot slot; bool finished{false}; bool floating; }; @@ -129,7 +128,13 @@ namespace sdbus::internal { class FloatingAsyncCallSlots { public: + FloatingAsyncCallSlots() = default; + FloatingAsyncCallSlots(const FloatingAsyncCallSlots&) = delete; + FloatingAsyncCallSlots& operator=(const FloatingAsyncCallSlots&) = delete; + FloatingAsyncCallSlots(FloatingAsyncCallSlots&& other) = delete; + FloatingAsyncCallSlots& operator=(FloatingAsyncCallSlots&&) = delete; ~FloatingAsyncCallSlots(); + void push_back(std::shared_ptr asyncCallInfo); void erase(AsyncCallInfo* info); void clear(); @@ -142,6 +147,6 @@ namespace sdbus::internal { FloatingAsyncCallSlots floatingAsyncCallSlots_; }; -} +} // namespace sdbus::internal #endif /* SDBUS_CXX_INTERNAL_PROXY_H_ */ diff --git a/src/ScopeGuard.h b/src/ScopeGuard.h index 209d17f3..e159faca 100644 --- a/src/ScopeGuard.h +++ b/src/ScopeGuard.h @@ -30,6 +30,8 @@ #include #include +// NOLINTBEGIN(cppcoreguidelines-macro-usage) + // Straightforward, modern, easy-to-use RAII utility to perform work on scope exit in an exception-safe manner. // // The utility helps providing basic exception safety guarantee by ensuring that the resources are always @@ -105,21 +107,22 @@ namespace sdbus::internal { } }; - template + template class ScopeGuard { public: - ScopeGuard(_Fun f) : fnc_(std::move(f)) + explicit ScopeGuard(Fun fun) : fnc_(std::move(fun)) { } ScopeGuard() = delete; ScopeGuard(const ScopeGuard&) = delete; ScopeGuard& operator=(const ScopeGuard&) = delete; - ScopeGuard(ScopeGuard&& rhs) : fnc_(std::move(rhs.fnc_)), active_(rhs.active_), exceptions_(rhs.exceptions_) + ScopeGuard(ScopeGuard&& rhs) noexcept : fnc_(std::move(rhs.fnc_)), active_(rhs.active_), exceptions_(rhs.exceptions_) { rhs.dismiss(); } + ScopeGuard& operator=(ScopeGuard&&) = delete; void dismiss() { @@ -128,35 +131,35 @@ namespace sdbus::internal { ~ScopeGuard() { - if (active_ && _Tag::holds(exceptions_)) + if (active_ && Tag::holds(exceptions_)) fnc_(); } private: - _Fun fnc_; + Fun fnc_; int exceptions_{std::uncaught_exceptions()}; bool active_{true}; }; - template - ScopeGuard<_Fun, ScopeGuardOnExitTag> operator+(ScopeGuardOnExitTag, _Fun&& fnc) + template + ScopeGuard operator+(ScopeGuardOnExitTag, Fun&& fnc) { - return ScopeGuard<_Fun, ScopeGuardOnExitTag>(std::forward<_Fun>(fnc)); + return ScopeGuard(std::forward(fnc)); } - template - ScopeGuard<_Fun, ScopeGuardOnExitSuccessTag> operator+(ScopeGuardOnExitSuccessTag, _Fun&& fnc) + template + ScopeGuard operator+(ScopeGuardOnExitSuccessTag, Fun&& fnc) { - return ScopeGuard<_Fun, ScopeGuardOnExitSuccessTag>(std::forward<_Fun>(fnc)); + return ScopeGuard(std::forward(fnc)); } - template - ScopeGuard<_Fun, ScopeGuardOnExitFailureTag> operator+(ScopeGuardOnExitFailureTag, _Fun&& fnc) + template + ScopeGuard operator+(ScopeGuardOnExitFailureTag, Fun&& fnc) { - return ScopeGuard<_Fun, ScopeGuardOnExitFailureTag>(std::forward<_Fun>(fnc)); + return ScopeGuard(std::forward(fnc)); } -} +} // namespace sdbus::internal #define CONCATENATE_IMPL(s1, s2) s1##s2 #define CONCATENATE(s1, s2) CONCATENATE_IMPL(s1, s2) @@ -167,4 +170,6 @@ namespace sdbus::internal { #define ANONYMOUS_VARIABLE(str) CONCATENATE(str, __LINE__) #endif +// NOLINTEND(cppcoreguidelines-macro-usage) + #endif /* SDBUS_CPP_INTERNAL_SCOPEGUARD_H_ */ diff --git a/src/SdBus.h b/src/SdBus.h index 1d7e6750..aa53b2d4 100644 --- a/src/SdBus.h +++ b/src/SdBus.h @@ -36,75 +36,75 @@ namespace sdbus::internal { class SdBus final : public ISdBus { public: - virtual sd_bus_message* sd_bus_message_ref(sd_bus_message *m) override; - virtual sd_bus_message* sd_bus_message_unref(sd_bus_message *m) override; - - virtual int sd_bus_send(sd_bus *bus, sd_bus_message *m, uint64_t *cookie) override; - virtual int sd_bus_call(sd_bus *bus, sd_bus_message *m, uint64_t usec, sd_bus_error *ret_error, sd_bus_message **reply) override; - virtual int sd_bus_call_async(sd_bus *bus, sd_bus_slot **slot, sd_bus_message *m, sd_bus_message_handler_t callback, void *userdata, uint64_t usec) override; - - virtual int sd_bus_message_new(sd_bus *bus, sd_bus_message **m, uint8_t type) override; - virtual int sd_bus_message_new_method_call(sd_bus *bus, sd_bus_message **m, const char *destination, const char *path, const char *interface, const char *member) override; - virtual int sd_bus_message_new_signal(sd_bus *bus, sd_bus_message **m, const char *path, const char *interface, const char *member) override; - virtual int sd_bus_message_new_method_return(sd_bus_message *call, sd_bus_message **m) override; - virtual int sd_bus_message_new_method_error(sd_bus_message *call, sd_bus_message **m, const sd_bus_error *e) override; - - virtual int sd_bus_set_method_call_timeout(sd_bus *bus, uint64_t usec) override; - virtual int sd_bus_get_method_call_timeout(sd_bus *bus, uint64_t *ret) override; - - virtual int sd_bus_emit_properties_changed_strv(sd_bus *bus, const char *path, const char *interface, char **names) override; - virtual int sd_bus_emit_object_added(sd_bus *bus, const char *path) override; - virtual int sd_bus_emit_object_removed(sd_bus *bus, const char *path) override; - virtual int sd_bus_emit_interfaces_added_strv(sd_bus *bus, const char *path, char **interfaces) override; - virtual int sd_bus_emit_interfaces_removed_strv(sd_bus *bus, const char *path, char **interfaces) override; - - virtual int sd_bus_open(sd_bus **ret) override; - virtual int sd_bus_open_system(sd_bus **ret) override; - virtual int sd_bus_open_user(sd_bus **ret) override; - virtual int sd_bus_open_user_with_address(sd_bus **ret, const char* address) override; - virtual int sd_bus_open_system_remote(sd_bus **ret, const char* host) override; - virtual int sd_bus_open_direct(sd_bus **ret, const char* address) override; - virtual int sd_bus_open_direct(sd_bus **ret, int fd) override; - virtual int sd_bus_open_server(sd_bus **ret, int fd) override; - virtual int sd_bus_request_name(sd_bus *bus, const char *name, uint64_t flags) override; - virtual int sd_bus_release_name(sd_bus *bus, const char *name) override; - virtual int sd_bus_get_unique_name(sd_bus *bus, const char **name) override; - virtual int sd_bus_add_object_vtable(sd_bus *bus, sd_bus_slot **slot, const char *path, const char *interface, const sd_bus_vtable *vtable, void *userdata) override; - virtual int sd_bus_add_object_manager(sd_bus *bus, sd_bus_slot **slot, const char *path) override; - virtual int sd_bus_add_match(sd_bus *bus, sd_bus_slot **slot, const char *match, sd_bus_message_handler_t callback, void *userdata) override; - virtual int sd_bus_add_match_async(sd_bus *bus, sd_bus_slot **slot, const char *match, sd_bus_message_handler_t callback, sd_bus_message_handler_t install_callback, void *userdata) override; - virtual int sd_bus_match_signal(sd_bus *bus, sd_bus_slot **ret, const char *sender, const char *path, const char *interface, const char *member, sd_bus_message_handler_t callback, void *userdata) override; - virtual sd_bus_slot* sd_bus_slot_unref(sd_bus_slot *slot) override; - - virtual int sd_bus_new(sd_bus **ret) override; - virtual int sd_bus_start(sd_bus *bus) override; - - virtual int sd_bus_process(sd_bus *bus, sd_bus_message **msg) override; - virtual sd_bus_message* sd_bus_get_current_message(sd_bus *bus) override; - virtual int sd_bus_get_poll_data(sd_bus *bus, PollData* data) override; - virtual int sd_bus_get_n_queued(sd_bus *bus, uint64_t *read, uint64_t* write) override; - virtual int sd_bus_flush(sd_bus *bus) override; - virtual sd_bus *sd_bus_flush_close_unref(sd_bus *bus) override; - virtual sd_bus *sd_bus_close_unref(sd_bus *bus) override; - - virtual int sd_bus_message_set_destination(sd_bus_message *m, const char *destination) override; - - virtual int sd_bus_query_sender_creds(sd_bus_message *m, uint64_t mask, sd_bus_creds **c) override; - virtual sd_bus_creds* sd_bus_creds_ref(sd_bus_creds *c) override; - virtual sd_bus_creds* sd_bus_creds_unref(sd_bus_creds *c) override; - - virtual int sd_bus_creds_get_pid(sd_bus_creds *c, pid_t *pid) override; - virtual int sd_bus_creds_get_uid(sd_bus_creds *c, uid_t *uid) override; - virtual int sd_bus_creds_get_euid(sd_bus_creds *c, uid_t *euid) override; - virtual int sd_bus_creds_get_gid(sd_bus_creds *c, gid_t *gid) override; - virtual int sd_bus_creds_get_egid(sd_bus_creds *c, gid_t *egid) override; - virtual int sd_bus_creds_get_supplementary_gids(sd_bus_creds *c, const gid_t **gids) override; - virtual int sd_bus_creds_get_selinux_context(sd_bus_creds *c, const char **label) override; + sd_bus_message* sd_bus_message_ref(sd_bus_message *msg) override; + sd_bus_message* sd_bus_message_unref(sd_bus_message *msg) override; + + int sd_bus_send(sd_bus *bus, sd_bus_message *msg, uint64_t *cookie) override; + int sd_bus_call(sd_bus *bus, sd_bus_message *msg, uint64_t usec, sd_bus_error *ret_error, sd_bus_message **reply) override; + int sd_bus_call_async(sd_bus *bus, sd_bus_slot **slot, sd_bus_message *msg, sd_bus_message_handler_t callback, void *userdata, uint64_t usec) override; + + int sd_bus_message_new(sd_bus *bus, sd_bus_message **msg, uint8_t type) override; + int sd_bus_message_new_method_call(sd_bus *bus, sd_bus_message **msg, const char *destination, const char *path, const char *interface, const char *member) override; + int sd_bus_message_new_signal(sd_bus *bus, sd_bus_message **msg, const char *path, const char *interface, const char *member) override; + int sd_bus_message_new_method_return(sd_bus_message *call, sd_bus_message **msg) override; + int sd_bus_message_new_method_error(sd_bus_message *call, sd_bus_message **msg, const sd_bus_error *err) override; + + int sd_bus_set_method_call_timeout(sd_bus *bus, uint64_t usec) override; + int sd_bus_get_method_call_timeout(sd_bus *bus, uint64_t *ret) override; + + int sd_bus_emit_properties_changed_strv(sd_bus *bus, const char *path, const char *interface, char **names) override; + int sd_bus_emit_object_added(sd_bus *bus, const char *path) override; + int sd_bus_emit_object_removed(sd_bus *bus, const char *path) override; + int sd_bus_emit_interfaces_added_strv(sd_bus *bus, const char *path, char **interfaces) override; + int sd_bus_emit_interfaces_removed_strv(sd_bus *bus, const char *path, char **interfaces) override; + + int sd_bus_open(sd_bus **ret) override; + int sd_bus_open_system(sd_bus **ret) override; + int sd_bus_open_user(sd_bus **ret) override; + int sd_bus_open_user_with_address(sd_bus **ret, const char* address) override; + int sd_bus_open_system_remote(sd_bus **ret, const char* host) override; + int sd_bus_open_direct(sd_bus **ret, const char* address) override; + int sd_bus_open_direct(sd_bus **ret, int fd) override; + int sd_bus_open_server(sd_bus **ret, int fd) override; + int sd_bus_request_name(sd_bus *bus, const char *name, uint64_t flags) override; + int sd_bus_release_name(sd_bus *bus, const char *name) override; + int sd_bus_get_unique_name(sd_bus *bus, const char **name) override; + int sd_bus_add_object_vtable(sd_bus *bus, sd_bus_slot **slot, const char *path, const char *interface, const sd_bus_vtable *vtable, void *userdata) override; + int sd_bus_add_object_manager(sd_bus *bus, sd_bus_slot **slot, const char *path) override; + int sd_bus_add_match(sd_bus *bus, sd_bus_slot **slot, const char *match, sd_bus_message_handler_t callback, void *userdata) override; + int sd_bus_add_match_async(sd_bus *bus, sd_bus_slot **slot, const char *match, sd_bus_message_handler_t callback, sd_bus_message_handler_t install_callback, void *userdata) override; + int sd_bus_match_signal(sd_bus *bus, sd_bus_slot **ret, const char *sender, const char *path, const char *interface, const char *member, sd_bus_message_handler_t callback, void *userdata) override; + sd_bus_slot* sd_bus_slot_unref(sd_bus_slot *slot) override; + + int sd_bus_new(sd_bus **ret) override; + int sd_bus_start(sd_bus *bus) override; + + int sd_bus_process(sd_bus *bus, sd_bus_message **msg) override; + sd_bus_message* sd_bus_get_current_message(sd_bus *bus) override; + int sd_bus_get_poll_data(sd_bus *bus, PollData* data) override; + int sd_bus_get_n_queued(sd_bus *bus, uint64_t *read, uint64_t* write) override; + int sd_bus_flush(sd_bus *bus) override; + sd_bus *sd_bus_flush_close_unref(sd_bus *bus) override; + sd_bus *sd_bus_close_unref(sd_bus *bus) override; + + int sd_bus_message_set_destination(sd_bus_message *msg, const char *destination) override; + + int sd_bus_query_sender_creds(sd_bus_message *msg, uint64_t mask, sd_bus_creds **creds) override; + sd_bus_creds* sd_bus_creds_ref(sd_bus_creds *creds) override; + sd_bus_creds* sd_bus_creds_unref(sd_bus_creds *creds) override; + + int sd_bus_creds_get_pid(sd_bus_creds *creds, pid_t *pid) override; + int sd_bus_creds_get_uid(sd_bus_creds *creds, uid_t *uid) override; + int sd_bus_creds_get_euid(sd_bus_creds *creds, uid_t *euid) override; + int sd_bus_creds_get_gid(sd_bus_creds *creds, gid_t *gid) override; + int sd_bus_creds_get_egid(sd_bus_creds *creds, gid_t *egid) override; + int sd_bus_creds_get_supplementary_gids(sd_bus_creds *creds, const gid_t **gids) override; + int sd_bus_creds_get_selinux_context(sd_bus_creds *creds, const char **label) override; private: std::recursive_mutex sdbusMutex_; }; -} +} // namespace sdbus::internal #endif //SDBUS_C_SDBUS_H diff --git a/src/Utils.h b/src/Utils.h index e4f25c7c..4164d723 100644 --- a/src/Utils.h +++ b/src/Utils.h @@ -30,6 +30,8 @@ #include #include SDBUS_HEADER +// NOLINTBEGIN(cppcoreguidelines-macro-usage) + #if LIBSYSTEMD_VERSION>=246 #define SDBUS_CHECK_OBJECT_PATH(_PATH) \ SDBUS_THROW_ERROR_IF(!sd_bus_object_path_is_valid(_PATH), std::string("Invalid object path '") + _PATH + "' provided", EINVAL) \ @@ -50,10 +52,12 @@ #define SDBUS_CHECK_MEMBER_NAME(_NAME) #endif +// NOLINTEND(cppcoreguidelines-macro-usage) + namespace sdbus::internal { - template - bool invokeHandlerAndCatchErrors(_Callable callable, sd_bus_error *retError) + template + bool invokeHandlerAndCatchErrors(Callable callable, sd_bus_error *retError) { try { @@ -93,6 +97,6 @@ namespace sdbus::internal { template struct overload : Ts... { using Ts::operator()...; }; template overload(Ts...) -> overload; -} +} // namespace sdbus::internal #endif /* SDBUS_CXX_INTERNAL_UTILS_H_ */ diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 27e05e7b..acaabcd0 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -54,6 +54,7 @@ set(UNITTESTS_SRCS ${UNITTESTS_SOURCE_DIR}/mocks/SdBusMock.h) set(INTEGRATIONTESTS_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/integrationtests) +set(INTEGRATIONTESTS_GENERATED_DIR ${INTEGRATIONTESTS_SOURCE_DIR}/dbus-api/gen-cpp) set(INTEGRATIONTESTS_SRCS ${INTEGRATIONTESTS_SOURCE_DIR}/DBusConnectionTests.cpp ${INTEGRATIONTESTS_SOURCE_DIR}/DBusGeneralTests.cpp @@ -63,39 +64,35 @@ set(INTEGRATIONTESTS_SRCS ${INTEGRATIONTESTS_SOURCE_DIR}/DBusPropertiesTests.cpp ${INTEGRATIONTESTS_SOURCE_DIR}/DBusStandardInterfacesTests.cpp ${INTEGRATIONTESTS_SOURCE_DIR}/Defs.h - ${INTEGRATIONTESTS_SOURCE_DIR}/integrationtests-adaptor.h - ${INTEGRATIONTESTS_SOURCE_DIR}/integrationtests-proxy.h ${INTEGRATIONTESTS_SOURCE_DIR}/TestFixture.h ${INTEGRATIONTESTS_SOURCE_DIR}/TestFixture.cpp ${INTEGRATIONTESTS_SOURCE_DIR}/TestAdaptor.h ${INTEGRATIONTESTS_SOURCE_DIR}/TestAdaptor.cpp ${INTEGRATIONTESTS_SOURCE_DIR}/TestProxy.h ${INTEGRATIONTESTS_SOURCE_DIR}/TestProxy.cpp - ${INTEGRATIONTESTS_SOURCE_DIR}/sdbus-c++-integration-tests.cpp) + ${INTEGRATIONTESTS_SOURCE_DIR}/sdbus-c++-integration-tests.cpp + ${INTEGRATIONTESTS_GENERATED_DIR}/integrationtests-adaptor.h + ${INTEGRATIONTESTS_GENERATED_DIR}/integrationtests-proxy.h) set(PERFTESTS_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/perftests) -set(STRESSTESTS_CLIENT_SRCS +set(PERFTESTS_GENERATED_DIR ${PERFTESTS_SOURCE_DIR}/dbus-api/gen-cpp) +set(PERFTESTS_CLIENT_SRCS ${PERFTESTS_SOURCE_DIR}/client.cpp - ${PERFTESTS_SOURCE_DIR}/perftests-proxy.h) -set(STRESSTESTS_SERVER_SRCS + ${PERFTESTS_GENERATED_DIR}/perftests-proxy.h) +set(PERFTESTS_SERVER_SRCS ${PERFTESTS_SOURCE_DIR}/server.cpp - ${PERFTESTS_SOURCE_DIR}/perftests-adaptor.h) + ${PERFTESTS_GENERATED_DIR}/perftests-adaptor.h) set(STRESSTESTS_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/stresstests) +set(STRESSTESTS_GENERATED_DIR ${STRESSTESTS_SOURCE_DIR}/dbus-api/gen-cpp) set(STRESSTESTS_SRCS ${STRESSTESTS_SOURCE_DIR}/sdbus-c++-stress-tests.cpp - ${STRESSTESTS_SOURCE_DIR}/fahrenheit-thermometer-adaptor.h - ${STRESSTESTS_SOURCE_DIR}/fahrenheit-thermometer-proxy.h - ${STRESSTESTS_SOURCE_DIR}/celsius-thermometer-adaptor.h - ${STRESSTESTS_SOURCE_DIR}/celsius-thermometer-proxy.h - ${STRESSTESTS_SOURCE_DIR}/concatenator-adaptor.h - ${STRESSTESTS_SOURCE_DIR}/concatenator-proxy.h) - -#------------------------------- -# GENERAL COMPILER CONFIGURATION -#------------------------------- - -include_directories(${CMAKE_CURRENT_SOURCE_DIR}) + ${STRESSTESTS_GENERATED_DIR}/fahrenheit-thermometer-adaptor.h + ${STRESSTESTS_GENERATED_DIR}/fahrenheit-thermometer-proxy.h + ${STRESSTESTS_GENERATED_DIR}/celsius-thermometer-adaptor.h + ${STRESSTESTS_GENERATED_DIR}/celsius-thermometer-proxy.h + ${STRESSTESTS_GENERATED_DIR}/concatenator-adaptor.h + ${STRESSTESTS_GENERATED_DIR}/concatenator-proxy.h) #---------------------------------- # BUILD INFORMATION @@ -112,6 +109,7 @@ add_executable(sdbus-c++-integration-tests ${INTEGRATIONTESTS_SRCS}) target_compile_definitions(sdbus-c++-integration-tests PRIVATE LIBSYSTEMD_VERSION=${SDBUSCPP_LIBSYSTEMD_VERSION} SDBUS_${SDBUS_IMPL}) +target_include_directories(sdbus-c++-integration-tests SYSTEM PRIVATE ${INTEGRATIONTESTS_GENERATED_DIR}) if(NOT SDBUS_IMPL STREQUAL "basu") # Systemd::Libsystemd is included because integration tests use sd-event. Otherwise sdbus-c++ encapsulates and hides libsystemd. target_link_libraries(sdbus-c++-integration-tests sdbus-c++ Systemd::Libsystemd GTest::gmock) @@ -126,15 +124,18 @@ if(SDBUSCPP_BUILD_PERF_TESTS OR SDBUSCPP_BUILD_STRESS_TESTS) if(SDBUSCPP_BUILD_PERF_TESTS) message(STATUS "Building with performance tests") - add_executable(sdbus-c++-perf-tests-client ${STRESSTESTS_CLIENT_SRCS}) + add_executable(sdbus-c++-perf-tests-client ${PERFTESTS_CLIENT_SRCS}) + target_include_directories(sdbus-c++-perf-tests-client SYSTEM PRIVATE ${PERFTESTS_GENERATED_DIR}) target_link_libraries(sdbus-c++-perf-tests-client sdbus-c++ Threads::Threads) - add_executable(sdbus-c++-perf-tests-server ${STRESSTESTS_SERVER_SRCS}) + add_executable(sdbus-c++-perf-tests-server ${PERFTESTS_SERVER_SRCS}) + target_include_directories(sdbus-c++-perf-tests-server SYSTEM PRIVATE ${PERFTESTS_GENERATED_DIR}) target_link_libraries(sdbus-c++-perf-tests-server sdbus-c++ Threads::Threads) endif() if(SDBUSCPP_BUILD_STRESS_TESTS) message(STATUS "Building with stress tests") add_executable(sdbus-c++-stress-tests ${STRESSTESTS_SRCS}) + target_include_directories(sdbus-c++-stress-tests SYSTEM PRIVATE ${STRESSTESTS_GENERATED_DIR}) target_link_libraries(sdbus-c++-stress-tests sdbus-c++ Threads::Threads) endif() endif() diff --git a/tests/integrationtests/Defs.h b/tests/integrationtests/Defs.h index 229f4897..239d0106 100644 --- a/tests/integrationtests/Defs.h +++ b/tests/integrationtests/Defs.h @@ -32,7 +32,7 @@ #include #include -namespace sdbus { namespace test { +namespace sdbus::test { const InterfaceName INTERFACE_NAME{"org.sdbuscpp.integrationtests"}; const ServiceName SERVICE_NAME{"org.sdbuscpp.integrationtests"}; @@ -64,18 +64,19 @@ const bool DEFAULT_BLOCKING_VALUE{true}; constexpr const double DOUBLE_VALUE{3.24L}; -}} +} // namespace sdbus::test namespace testing::internal { // Printer for std::chrono::duration types. // This is a workaround, since it's not a good thing to add this to std namespace. -template< class Rep, class Period > -void PrintTo(const ::std::chrono::duration& d, ::std::ostream* os) { - auto seconds = std::chrono::duration_cast>(d); - *os << seconds.count() << "s"; +template +void PrintTo(const ::std::chrono::duration& duration, ::std::ostream* stream) +{ + auto seconds = std::chrono::duration_cast>(duration); + *stream << seconds.count() << "s"; } -} +} // namespace testing::internal #endif /* SDBUS_CPP_INTEGRATIONTESTS_DEFS_H_ */ diff --git a/tests/integrationtests/TestAdaptor.cpp b/tests/integrationtests/TestAdaptor.cpp index bc8c89ec..883bde9f 100644 --- a/tests/integrationtests/TestAdaptor.cpp +++ b/tests/integrationtests/TestAdaptor.cpp @@ -29,7 +29,7 @@ #include "sdbus-c++/Types.h" #include "sdbus-c++/AdaptorInterfaces.h" #include -#include "integrationtests/Defs.h" +#include "Defs.h" #include #include #include diff --git a/tests/integrationtests/TestAdaptor.h b/tests/integrationtests/TestAdaptor.h index c793a2a3..04c896c7 100644 --- a/tests/integrationtests/TestAdaptor.h +++ b/tests/integrationtests/TestAdaptor.h @@ -35,7 +35,7 @@ #include #include -namespace sdbus { namespace test { +namespace sdbus::test { class ObjectManagerTestAdaptor final : public sdbus::AdaptorInterfaces< sdbus::ObjectManager_adaptor > { @@ -46,6 +46,11 @@ class ObjectManagerTestAdaptor final : public sdbus::AdaptorInterfaces< sdbus::O registerAdaptor(); } + ObjectManagerTestAdaptor(const ObjectManagerTestAdaptor&) = delete; + ObjectManagerTestAdaptor& operator=(const ObjectManagerTestAdaptor&) = delete; + ObjectManagerTestAdaptor(ObjectManagerTestAdaptor&&) = delete; + ObjectManagerTestAdaptor& operator=(ObjectManagerTestAdaptor&&) = delete; + ~ObjectManagerTestAdaptor() { unregisterAdaptor(); @@ -58,6 +63,10 @@ class TestAdaptor final : public sdbus::AdaptorInterfaces< org::sdbuscpp::integr { public: TestAdaptor(sdbus::IConnection& connection, sdbus::ObjectPath path); + TestAdaptor(const TestAdaptor&) = delete; + TestAdaptor& operator=(const TestAdaptor&) = delete; + TestAdaptor(TestAdaptor&&) = delete; + TestAdaptor& operator=(TestAdaptor&&) = delete; ~TestAdaptor(); protected: @@ -96,7 +105,7 @@ class TestAdaptor final : public sdbus::AdaptorInterfaces< org::sdbuscpp::integr std::string state() override; public: - void emitSignalWithoutRegistration(const sdbus::Struct>& s); + void emitSignalWithoutRegistration(const sdbus::Struct>& strct); static std::string getExpectedXmlApiDescription() ; private: @@ -162,6 +171,6 @@ class DummyTestAdaptor final : public sdbus::AdaptorInterfaces< org::sdbuscpp::i std::string state() override { return {}; } }; -}} +} // namespace sdbus::test #endif /* INTEGRATIONTESTS_TESTADAPTOR_H_ */ diff --git a/tests/integrationtests/TestFixture.h b/tests/integrationtests/TestFixture.h index 0bd46db2..abc74337 100644 --- a/tests/integrationtests/TestFixture.h +++ b/tests/integrationtests/TestFixture.h @@ -41,26 +41,25 @@ #include #include #include -#include #include #include #include #include -namespace sdbus { namespace test { +namespace sdbus::test { inline const uint32_t ANY_UNSIGNED_NUMBER{123}; class BaseTestFixture : public ::testing::Test { public: - static void SetUpTestCase() + static void SetUpTestSuite() { s_adaptorConnection->requestName(SERVICE_NAME); } - static void TearDownTestCase() + static void TearDownTestSuite() { s_adaptorConnection->releaseName(SERVICE_NAME); } @@ -93,7 +92,7 @@ class BaseTestFixture : public ::testing::Test struct SdBusCppLoop{}; struct SdEventLoop{}; -template +template class TestFixture : public BaseTestFixture{}; // Fixture working upon internal sdbus-c++ event loop @@ -101,17 +100,17 @@ template <> class TestFixture : public BaseTestFixture { public: - static void SetUpTestCase() + static void SetUpTestSuite() { - BaseTestFixture::SetUpTestCase(); + BaseTestFixture::SetUpTestSuite(); s_proxyConnection->enterEventLoopAsync(); s_adaptorConnection->enterEventLoopAsync(); std::this_thread::sleep_for(std::chrono::milliseconds(50)); // Give time for the proxy connection to start listening to signals } - static void TearDownTestCase() + static void TearDownTestSuite() { - BaseTestFixture::TearDownTestCase(); + BaseTestFixture::TearDownTestSuite(); s_adaptorConnection->leaveEventLoop(); s_proxyConnection->leaveEventLoop(); } @@ -124,7 +123,7 @@ template <> class TestFixture : public BaseTestFixture { public: - static void SetUpTestCase() + static void SetUpTestSuite() { sd_event_new(&s_adaptorSdEvent); sd_event_new(&s_proxySdEvent); @@ -133,7 +132,7 @@ class TestFixture : public BaseTestFixture s_proxyConnection->attachSdEventLoop(s_proxySdEvent); s_eventExitFd = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK); - auto exitHandler = [](sd_event_source *s, auto...){ return sd_event_exit(sd_event_source_get_event(s), 0); }; + auto exitHandler = [](sd_event_source *src, auto...){ return sd_event_exit(sd_event_source_get_event(src), 0); }; sd_event_add_io(s_adaptorSdEvent, nullptr, s_eventExitFd, EPOLLIN, exitHandler, nullptr); sd_event_add_io(s_proxySdEvent, nullptr, s_eventExitFd, EPOLLIN, exitHandler, nullptr); @@ -146,11 +145,11 @@ class TestFixture : public BaseTestFixture sd_event_loop(s_proxySdEvent); }); - BaseTestFixture::SetUpTestCase(); + BaseTestFixture::SetUpTestSuite(); std::this_thread::sleep_for(std::chrono::milliseconds(50)); // Give time for the proxy connection to start listening to signals } - static void TearDownTestCase() + static void TearDownTestSuite() { (void)eventfd_write(s_eventExitFd, 1); @@ -161,7 +160,7 @@ class TestFixture : public BaseTestFixture sd_event_unref(s_proxySdEvent); close(s_eventExitFd); - BaseTestFixture::TearDownTestCase(); + BaseTestFixture::TearDownTestSuite(); } private: @@ -172,24 +171,24 @@ class TestFixture : public BaseTestFixture static int s_eventExitFd; }; -typedef ::testing::Types EventLoopTags; +using EventLoopTags = ::testing::Types; #else // SDBUS_basu -typedef ::testing::Types EventLoopTags; +using EventLoopTags = ::testing::Types; #endif // SDBUS_basu TYPED_TEST_SUITE(TestFixture, EventLoopTags); -template -using SdbusTestObject = TestFixture<_EventLoop>; +template +using SdbusTestObject = TestFixture; TYPED_TEST_SUITE(SdbusTestObject, EventLoopTags); -template -using AsyncSdbusTestObject = TestFixture<_EventLoop>; +template +using AsyncSdbusTestObject = TestFixture; TYPED_TEST_SUITE(AsyncSdbusTestObject, EventLoopTags); -template -using AConnection = TestFixture<_EventLoop>; +template +using AConnection = TestFixture; TYPED_TEST_SUITE(AConnection, EventLoopTags); class TestFixtureWithDirectConnection : public ::testing::Test @@ -197,7 +196,7 @@ class TestFixtureWithDirectConnection : public ::testing::Test private: void SetUp() override { - int sock = openUnixSocket(); + const int sock = openUnixSocket(); createClientAndServerConnections(sock); createAdaptorAndProxyObjects(); } @@ -212,18 +211,19 @@ class TestFixtureWithDirectConnection : public ::testing::Test static int openUnixSocket() { - int sock = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0); + const int sock = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0); assert(sock >= 0); - sockaddr_un sa; - memset(&sa, 0, sizeof(sa)); - sa.sun_family = AF_UNIX; - snprintf(sa.sun_path, sizeof(sa.sun_path), "%s", DIRECT_CONNECTION_SOCKET_PATH.c_str()); + sockaddr_un saddr{}; + memset(&saddr, 0, sizeof(saddr)); + saddr.sun_family = AF_UNIX; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg) + (void)snprintf(saddr.sun_path, sizeof(saddr.sun_path), "%s", DIRECT_CONNECTION_SOCKET_PATH.c_str()); unlink(DIRECT_CONNECTION_SOCKET_PATH.c_str()); umask(0000); - [[maybe_unused]] int r = bind(sock, (const sockaddr*) &sa, sizeof(sa.sun_path)); + [[maybe_unused]] int r = bind(sock, reinterpret_cast(&saddr), sizeof(saddr.sun_path)); assert(r >= 0); r = listen(sock, 5); @@ -236,7 +236,7 @@ class TestFixtureWithDirectConnection : public ::testing::Test { std::thread t([&]() { - auto fd = accept4(sock, NULL, NULL, /*SOCK_NONBLOCK|*/SOCK_CLOEXEC); + auto fd = accept4(sock, nullptr, nullptr, /*SOCK_NONBLOCK|*/SOCK_CLOEXEC); m_adaptorConnection = sdbus::createServerBus(fd); // This is necessary so that createDirectBusConnection() below does not block m_adaptorConnection->enterEventLoopAsync(); @@ -265,14 +265,14 @@ class TestFixtureWithDirectConnection : public ::testing::Test std::unique_ptr m_proxy; }; -template -inline bool waitUntil(_Fnc&& fnc, std::chrono::milliseconds timeout = std::chrono::seconds(5)) +template +inline bool waitUntil(const Fnc& fnc, std::chrono::milliseconds timeout = std::chrono::seconds(5)) { using namespace std::chrono_literals; std::chrono::milliseconds elapsed{}; - std::chrono::milliseconds step{5ms}; - do { + const std::chrono::milliseconds step{5ms}; + do { // NOLINT(cppcoreguidelines-avoid-do-while) std::this_thread::sleep_for(step); elapsed += step; if (elapsed > timeout) @@ -287,6 +287,6 @@ inline bool waitUntil(std::atomic& flag, std::chrono::milliseconds timeout return waitUntil([&flag]() -> bool { return flag; }, timeout); } -}} +} // namespace sdbus::test #endif /* SDBUS_CPP_INTEGRATIONTESTS_TESTFIXTURE_H_ */ diff --git a/tests/integrationtests/TestProxy.h b/tests/integrationtests/TestProxy.h index c3a91b9e..750936c3 100644 --- a/tests/integrationtests/TestProxy.h +++ b/tests/integrationtests/TestProxy.h @@ -35,7 +35,7 @@ #include #include -namespace sdbus { namespace test { +namespace sdbus::test { class ObjectManagerTestProxy final : public sdbus::ProxyInterfaces< sdbus::ObjectManager_proxy > { @@ -46,6 +46,11 @@ class ObjectManagerTestProxy final : public sdbus::ProxyInterfaces< sdbus::Objec registerProxy(); } + ObjectManagerTestProxy(const ObjectManagerTestProxy&) = delete; + ObjectManagerTestProxy& operator=(const ObjectManagerTestProxy&) = delete; + ObjectManagerTestProxy(ObjectManagerTestProxy&&) = delete; + ObjectManagerTestProxy& operator=(ObjectManagerTestProxy&&) = delete; + ~ObjectManagerTestProxy() { unregisterProxy(); @@ -77,6 +82,10 @@ class TestProxy final : public sdbus::ProxyInterfaces< org::sdbuscpp::integratio TestProxy(ServiceName destination, ObjectPath objectPath); TestProxy(ServiceName destination, ObjectPath objectPath, dont_run_event_loop_thread_t); TestProxy(sdbus::IConnection& connection, ServiceName destination, ObjectPath objectPath); + TestProxy(const TestProxy&) = delete; + TestProxy& operator=(const TestProxy&) = delete; + TestProxy(TestProxy&&) = delete; + TestProxy& operator=(TestProxy&&) = delete; ~TestProxy(); protected: @@ -84,7 +93,7 @@ class TestProxy final : public sdbus::ProxyInterfaces< org::sdbuscpp::integratio void onSignalWithMap(const std::map& aMap) override; void onSignalWithVariant(const sdbus::Variant& aVariant) override; - void onSignalWithoutRegistration(const sdbus::Struct>& s); + void onSignalWithoutRegistration(const sdbus::Struct>& strct); void onDoOperationReply(uint32_t returnValue, std::optional error) const; // Signals of standard D-Bus interfaces @@ -108,8 +117,7 @@ class TestProxy final : public sdbus::ProxyInterfaces< org::sdbuscpp::integratio int32_t callMethodOnNonexistentInterface(); void setStateProperty(const std::string& value); -//private: -public: // for tests +//private: (Kept public for tests) int m_SimpleSignals = 0; std::atomic m_gotSimpleSignal{false}; std::atomic m_gotSignalWithMap{false}; @@ -134,7 +142,7 @@ class DummyTestProxy final : public sdbus::ProxyInterfaces< org::sdbuscpp::integ { public: DummyTestProxy(ServiceName destination, ObjectPath objectPath) - : ProxyInterfaces(destination, objectPath) + : ProxyInterfaces(std::move(destination), std::move(objectPath)) { } @@ -144,12 +152,12 @@ class DummyTestProxy final : public sdbus::ProxyInterfaces< org::sdbuscpp::integ void onSignalWithVariant(const sdbus::Variant&) override {} void onSignalWithoutRegistration(const sdbus::Struct>&) {} - void onDoOperationReply(uint32_t, std::optional) {} + void onDoOperationReply(uint32_t, const std::optional&) {} // Signals of standard D-Bus interfaces void onPropertiesChanged(const InterfaceName&, const std::map&, const std::vector&) override {} }; -}} +} // namespace sdbus::test #endif /* SDBUS_CPP_INTEGRATIONTESTS_TESTPROXY_H_ */ diff --git a/tests/integrationtests/integrationtests-adaptor.h b/tests/integrationtests/dbus-api/gen-cpp/integrationtests-adaptor.h similarity index 100% rename from tests/integrationtests/integrationtests-adaptor.h rename to tests/integrationtests/dbus-api/gen-cpp/integrationtests-adaptor.h diff --git a/tests/integrationtests/integrationtests-proxy.h b/tests/integrationtests/dbus-api/gen-cpp/integrationtests-proxy.h similarity index 100% rename from tests/integrationtests/integrationtests-proxy.h rename to tests/integrationtests/dbus-api/gen-cpp/integrationtests-proxy.h diff --git a/tests/integrationtests/org.sdbuscpp.integrationtests.xml b/tests/integrationtests/dbus-api/org.sdbuscpp.integrationtests.xml similarity index 100% rename from tests/integrationtests/org.sdbuscpp.integrationtests.xml rename to tests/integrationtests/dbus-api/org.sdbuscpp.integrationtests.xml diff --git a/tests/perftests/perftests-adaptor.h b/tests/perftests/dbus-api/gen-cpp/perftests-adaptor.h similarity index 100% rename from tests/perftests/perftests-adaptor.h rename to tests/perftests/dbus-api/gen-cpp/perftests-adaptor.h diff --git a/tests/perftests/perftests-proxy.h b/tests/perftests/dbus-api/gen-cpp/perftests-proxy.h similarity index 100% rename from tests/perftests/perftests-proxy.h rename to tests/perftests/dbus-api/gen-cpp/perftests-proxy.h diff --git a/tests/perftests/org.sdbuscpp.perftests.xml b/tests/perftests/dbus-api/org.sdbuscpp.perftests.xml similarity index 100% rename from tests/perftests/org.sdbuscpp.perftests.xml rename to tests/perftests/dbus-api/org.sdbuscpp.perftests.xml diff --git a/tests/stresstests/celsius-thermometer-adaptor.h b/tests/stresstests/dbus-api/gen-cpp/celsius-thermometer-adaptor.h similarity index 100% rename from tests/stresstests/celsius-thermometer-adaptor.h rename to tests/stresstests/dbus-api/gen-cpp/celsius-thermometer-adaptor.h diff --git a/tests/stresstests/celsius-thermometer-proxy.h b/tests/stresstests/dbus-api/gen-cpp/celsius-thermometer-proxy.h similarity index 100% rename from tests/stresstests/celsius-thermometer-proxy.h rename to tests/stresstests/dbus-api/gen-cpp/celsius-thermometer-proxy.h diff --git a/tests/stresstests/concatenator-adaptor.h b/tests/stresstests/dbus-api/gen-cpp/concatenator-adaptor.h similarity index 100% rename from tests/stresstests/concatenator-adaptor.h rename to tests/stresstests/dbus-api/gen-cpp/concatenator-adaptor.h diff --git a/tests/stresstests/concatenator-proxy.h b/tests/stresstests/dbus-api/gen-cpp/concatenator-proxy.h similarity index 100% rename from tests/stresstests/concatenator-proxy.h rename to tests/stresstests/dbus-api/gen-cpp/concatenator-proxy.h diff --git a/tests/stresstests/fahrenheit-thermometer-adaptor.h b/tests/stresstests/dbus-api/gen-cpp/fahrenheit-thermometer-adaptor.h similarity index 100% rename from tests/stresstests/fahrenheit-thermometer-adaptor.h rename to tests/stresstests/dbus-api/gen-cpp/fahrenheit-thermometer-adaptor.h diff --git a/tests/stresstests/fahrenheit-thermometer-proxy.h b/tests/stresstests/dbus-api/gen-cpp/fahrenheit-thermometer-proxy.h similarity index 100% rename from tests/stresstests/fahrenheit-thermometer-proxy.h rename to tests/stresstests/dbus-api/gen-cpp/fahrenheit-thermometer-proxy.h diff --git a/tests/stresstests/org.sdbuscpp.stresstest.celsius.thermometer.xml b/tests/stresstests/dbus-api/org.sdbuscpp.stresstest.celsius.thermometer.xml similarity index 100% rename from tests/stresstests/org.sdbuscpp.stresstest.celsius.thermometer.xml rename to tests/stresstests/dbus-api/org.sdbuscpp.stresstest.celsius.thermometer.xml diff --git a/tests/stresstests/org.sdbuscpp.stresstest.concatenator.xml b/tests/stresstests/dbus-api/org.sdbuscpp.stresstest.concatenator.xml similarity index 100% rename from tests/stresstests/org.sdbuscpp.stresstest.concatenator.xml rename to tests/stresstests/dbus-api/org.sdbuscpp.stresstest.concatenator.xml diff --git a/tests/stresstests/org.sdbuscpp.stresstest.fahrenheit.thermometer.xml b/tests/stresstests/dbus-api/org.sdbuscpp.stresstest.fahrenheit.thermometer.xml similarity index 100% rename from tests/stresstests/org.sdbuscpp.stresstest.fahrenheit.thermometer.xml rename to tests/stresstests/dbus-api/org.sdbuscpp.stresstest.fahrenheit.thermometer.xml diff --git a/tests/unittests/Connection_test.cpp b/tests/unittests/Connection_test.cpp index 8fd78794..5c406441 100644 --- a/tests/unittests/Connection_test.cpp +++ b/tests/unittests/Connection_test.cpp @@ -28,14 +28,13 @@ #include "Connection.h" #include "sdbus-c++/Error.h" #include "sdbus-c++/Types.h" -#include "unittests/mocks/SdBusMock.h" +#include "mocks/SdBusMock.h" #include // IWYU pragma: export #include #include #include -// NOLINTBEGIN(cppcoreguidelines-non-private-member-variables-in-classes,misc-non-private-member-variables-in-classes) // NOLINTBEGIN(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp) using ::testing::_; @@ -187,10 +186,10 @@ template<> void AConnectionNameRequest::setUpBusOpenEx // `sd_bus_start` for pseudo connection shall return an error value, remember this is a fake connection... EXPECT_CALL(*sdBusIntfMock_, sd_bus_start(fakeBusPtr_)).WillOnce(Return(-EINVAL)); } -template -std::unique_ptr AConnectionNameRequest<_BusTypeTag>::makeConnection() +template +std::unique_ptr AConnectionNameRequest::makeConnection() { - return std::make_unique(std::unique_ptr>(sdBusIntfMock_), _BusTypeTag{}); + return std::make_unique(std::unique_ptr>(sdBusIntfMock_), BusTypeTag{}); } template<> std::unique_ptr AConnectionNameRequest::makeConnection() { @@ -230,4 +229,3 @@ TYPED_TEST(AConnectionNameRequest, ThrowsOnFail) } // NOLINTEND(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp) -// NOLINTEND(cppcoreguidelines-non-private-member-variables-in-classes,misc-non-private-member-variables-in-classes) diff --git a/tests/unittests/mocks/SdBusMock.h b/tests/unittests/mocks/SdBusMock.h index c8b1e1c0..9443ee1f 100644 --- a/tests/unittests/mocks/SdBusMock.h +++ b/tests/unittests/mocks/SdBusMock.h @@ -35,18 +35,18 @@ class SdBusMock : public sdbus::internal::ISdBus { public: - MOCK_METHOD1(sd_bus_message_ref, sd_bus_message*(sd_bus_message *m)); - MOCK_METHOD1(sd_bus_message_unref, sd_bus_message*(sd_bus_message *m)); + MOCK_METHOD1(sd_bus_message_ref, sd_bus_message*(sd_bus_message *msg)); + MOCK_METHOD1(sd_bus_message_unref, sd_bus_message*(sd_bus_message *msg)); - MOCK_METHOD3(sd_bus_send, int(sd_bus *bus, sd_bus_message *m, uint64_t *cookie)); - MOCK_METHOD5(sd_bus_call, int(sd_bus *bus, sd_bus_message *m, uint64_t usec, sd_bus_error *ret_error, sd_bus_message **reply)); - MOCK_METHOD6(sd_bus_call_async, int(sd_bus *bus, sd_bus_slot **slot, sd_bus_message *m, sd_bus_message_handler_t callback, void *userdata, uint64_t usec)); + MOCK_METHOD3(sd_bus_send, int(sd_bus *bus, sd_bus_message *msg, uint64_t *cookie)); + MOCK_METHOD5(sd_bus_call, int(sd_bus *bus, sd_bus_message *msg, uint64_t usec, sd_bus_error *ret_error, sd_bus_message **reply)); + MOCK_METHOD6(sd_bus_call_async, int(sd_bus *bus, sd_bus_slot **slot, sd_bus_message *msg, sd_bus_message_handler_t callback, void *userdata, uint64_t usec)); - MOCK_METHOD3(sd_bus_message_new, int(sd_bus *bus, sd_bus_message **m, uint8_t type)); - MOCK_METHOD6(sd_bus_message_new_method_call, int(sd_bus *bus, sd_bus_message **m, const char *destination, const char *path, const char *interface, const char *member)); - MOCK_METHOD5(sd_bus_message_new_signal, int(sd_bus *bus, sd_bus_message **m, const char *path, const char *interface, const char *member)); - MOCK_METHOD2(sd_bus_message_new_method_return, int(sd_bus_message *call, sd_bus_message **m)); - MOCK_METHOD3(sd_bus_message_new_method_error, int(sd_bus_message *call, sd_bus_message **m, const sd_bus_error *e)); + MOCK_METHOD3(sd_bus_message_new, int(sd_bus *bus, sd_bus_message **msg, uint8_t type)); + MOCK_METHOD6(sd_bus_message_new_method_call, int(sd_bus *bus, sd_bus_message **msg, const char *destination, const char *path, const char *interface, const char *member)); + MOCK_METHOD5(sd_bus_message_new_signal, int(sd_bus *bus, sd_bus_message **msg, const char *path, const char *interface, const char *member)); + MOCK_METHOD2(sd_bus_message_new_method_return, int(sd_bus_message *call, sd_bus_message **msg)); + MOCK_METHOD3(sd_bus_message_new_method_error, int(sd_bus_message *call, sd_bus_message **msg, const sd_bus_error *err)); MOCK_METHOD2(sd_bus_set_method_call_timeout, int(sd_bus *bus, uint64_t usec)); MOCK_METHOD2(sd_bus_get_method_call_timeout, int(sd_bus *bus, uint64_t *ret)); @@ -78,7 +78,7 @@ class SdBusMock : public sdbus::internal::ISdBus MOCK_METHOD1(sd_bus_new, int(sd_bus **ret)); MOCK_METHOD1(sd_bus_start, int(sd_bus *bus)); - MOCK_METHOD2(sd_bus_process, int(sd_bus *bus, sd_bus_message **r)); + MOCK_METHOD2(sd_bus_process, int(sd_bus *bus, sd_bus_message **ret)); MOCK_METHOD1(sd_bus_get_current_message, sd_bus_message*(sd_bus *bus)); MOCK_METHOD2(sd_bus_get_poll_data, int(sd_bus *bus, PollData* data)); MOCK_METHOD3(sd_bus_get_n_queued, int(sd_bus *bus, uint64_t *read, uint64_t* write)); @@ -86,7 +86,7 @@ class SdBusMock : public sdbus::internal::ISdBus MOCK_METHOD1(sd_bus_flush_close_unref, sd_bus *(sd_bus *bus)); MOCK_METHOD1(sd_bus_close_unref, sd_bus *(sd_bus *bus)); - MOCK_METHOD2(sd_bus_message_set_destination, int(sd_bus_message *m, const char *destination)); + MOCK_METHOD2(sd_bus_message_set_destination, int(sd_bus_message *msg, const char *destination)); MOCK_METHOD3(sd_bus_query_sender_creds, int(sd_bus_message *, uint64_t, sd_bus_creds **)); MOCK_METHOD1(sd_bus_creds_ref, sd_bus_creds*(sd_bus_creds *)); From 32e73a2b80d4eb50d0ddec3f51c465dd7a0887e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stanislav=20Angelovi=C4=8D?= Date: Wed, 14 Jan 2026 23:38:45 +0100 Subject: [PATCH 12/13] refactor: remove unnecessary sdbus:: qualification --- include/sdbus-c++/ConvenienceApiClasses.inl | 2 +- include/sdbus-c++/IObject.h | 4 +- include/sdbus-c++/IProxy.h | 38 ++++----- include/sdbus-c++/Message.h | 8 +- include/sdbus-c++/ProxyInterfaces.h | 4 +- include/sdbus-c++/StandardInterfaces.h | 94 ++++++++++----------- include/sdbus-c++/Types.h | 6 +- src/Connection.cpp | 66 +++++++-------- src/IConnection.h | 2 +- src/Message.cpp | 6 +- src/Object.cpp | 10 +-- src/Object.h | 4 +- src/Proxy.cpp | 84 +++++++++--------- src/Proxy.h | 10 +-- 14 files changed, 169 insertions(+), 169 deletions(-) diff --git a/include/sdbus-c++/ConvenienceApiClasses.inl b/include/sdbus-c++/ConvenienceApiClasses.inl index 8944815f..bf74f1f9 100644 --- a/include/sdbus-c++/ConvenienceApiClasses.inl +++ b/include/sdbus-c++/ConvenienceApiClasses.inl @@ -427,7 +427,7 @@ namespace sdbus { { signal >> signalArgs; } - catch (const sdbus::Error& e) + catch (const Error& e) { // Pass message deserialization exceptions to the client via callback error parameter, // instead of propagating them up the message loop call stack. diff --git a/include/sdbus-c++/IObject.h b/include/sdbus-c++/IObject.h index bdce2097..d2f3002c 100644 --- a/include/sdbus-c++/IObject.h +++ b/include/sdbus-c++/IObject.h @@ -414,7 +414,7 @@ namespace sdbus { * * @throws sdbus::Error in case of failure */ - virtual void emitSignal(const sdbus::Signal& message) = 0; + virtual void emitSignal(const Signal& message) = 0; protected: // Internal API for efficiency reasons used by high-level API helper classes friend SignalEmitter; @@ -474,7 +474,7 @@ namespace sdbus { * auto proxy = sdbus::createObject(connection, "/com/kistler/foo"); * @endcode */ - [[nodiscard]] std::unique_ptr createObject(sdbus::IConnection& connection, ObjectPath objectPath); + [[nodiscard]] std::unique_ptr createObject(IConnection& connection, ObjectPath objectPath); } // namespace sdbus diff --git a/include/sdbus-c++/IProxy.h b/include/sdbus-c++/IProxy.h index ae93b31f..8eb067b8 100644 --- a/include/sdbus-c++/IProxy.h +++ b/include/sdbus-c++/IProxy.h @@ -857,9 +857,9 @@ namespace sdbus { * auto proxy = sdbus::createProxy(connection, "com.kistler.foo", "/com/kistler/foo"); * @endcode */ - [[nodiscard]] std::unique_ptr createProxy( sdbus::IConnection& connection - , ServiceName destination - , ObjectPath objectPath ); + [[nodiscard]] std::unique_ptr createProxy( IConnection& connection + , ServiceName destination + , ObjectPath objectPath ); /*! * @brief Creates a proxy object for a specific remote D-Bus object @@ -883,9 +883,9 @@ namespace sdbus { * auto proxy = sdbus::createProxy(std::move(connection), "com.kistler.foo", "/com/kistler/foo"); * @endcode */ - [[nodiscard]] std::unique_ptr createProxy( std::unique_ptr&& connection - , ServiceName destination - , ObjectPath objectPath ); + [[nodiscard]] std::unique_ptr createProxy( std::unique_ptr&& connection + , ServiceName destination + , ObjectPath objectPath ); /*! * @brief Creates a light-weight proxy object for a specific remote D-Bus object @@ -910,19 +910,19 @@ namespace sdbus { * auto proxy = sdbus::createProxy(std::move(connection), "com.kistler.foo", "/com/kistler/foo", sdbus::dont_run_event_loop_thread); * @endcode */ - [[nodiscard]] std::unique_ptr createProxy( std::unique_ptr&& connection - , ServiceName destination - , ObjectPath objectPath - , dont_run_event_loop_thread_t ); + [[nodiscard]] std::unique_ptr createProxy( std::unique_ptr&& connection + , ServiceName destination + , ObjectPath objectPath + , dont_run_event_loop_thread_t ); /*! * @brief Creates a light-weight proxy object for a specific remote D-Bus object * * Does the same thing as createProxy(std::unique_ptr&&, ServiceName, ObjectPath, dont_run_event_loop_thread_t); */ - [[nodiscard]] std::unique_ptr createLightWeightProxy( std::unique_ptr&& connection - , ServiceName destination - , ObjectPath objectPath ); + [[nodiscard]] std::unique_ptr createLightWeightProxy( std::unique_ptr&& connection + , ServiceName destination + , ObjectPath objectPath ); /*! * @brief Creates a proxy object for a specific remote D-Bus object @@ -941,8 +941,8 @@ namespace sdbus { * auto proxy = sdbus::createProxy("com.kistler.foo", "/com/kistler/foo"); * @endcode */ - [[nodiscard]] std::unique_ptr createProxy( ServiceName destination - , ObjectPath objectPath ); + [[nodiscard]] std::unique_ptr createProxy( ServiceName destination + , ObjectPath objectPath ); /*! * @brief Creates a light-weight proxy object for a specific remote D-Bus object @@ -962,16 +962,16 @@ namespace sdbus { * auto proxy = sdbus::createProxy("com.kistler.foo", "/com/kistler/foo", sdbus::dont_run_event_loop_thread ); * @endcode */ - [[nodiscard]] std::unique_ptr createProxy( ServiceName destination - , ObjectPath objectPath - , dont_run_event_loop_thread_t ); + [[nodiscard]] std::unique_ptr createProxy( ServiceName destination + , ObjectPath objectPath + , dont_run_event_loop_thread_t ); /*! * @brief Creates a light-weight proxy object for a specific remote D-Bus object * * Does the same thing as createProxy(ServiceName, ObjectPath, dont_run_event_loop_thread_t); */ - [[nodiscard]] std::unique_ptr createLightWeightProxy(ServiceName destination, ObjectPath objectPath); + [[nodiscard]] std::unique_ptr createLightWeightProxy(ServiceName destination, ObjectPath objectPath); } // namespace sdbus diff --git a/include/sdbus-c++/Message.h b/include/sdbus-c++/Message.h index 75555920..d6683391 100644 --- a/include/sdbus-c++/Message.h +++ b/include/sdbus-c++/Message.h @@ -278,7 +278,7 @@ namespace sdbus { [[nodiscard]] Slot send(void* callback, void* userData, uint64_t timeout, return_slot_t) const; MethodReply createReply() const; - MethodReply createErrorReply(const sdbus::Error& error) const; + MethodReply createErrorReply(const Error& error) const; void dontExpectReply(); bool doesntExpectReply() const; @@ -496,7 +496,7 @@ namespace sdbus { template bool deserialize_variant(Message& msg, std::variant& value, const char* signature) { - constexpr auto elemSignature = as_null_terminated(sdbus::signature_of_v); + constexpr auto elemSignature = as_null_terminated(signature_of_v); if (std::strcmp(signature, elemSignature.data()) != 0) return false; @@ -578,7 +578,7 @@ namespace sdbus { size_t arraySize{}; const ElementType* arrayPtr{}; - constexpr auto signature = as_null_terminated(sdbus::signature_of_v); + constexpr auto signature = as_null_terminated(signature_of_v); readArray(*signature.data(), reinterpret_cast(&arrayPtr), &arraySize); const size_t elementsInMsg = arraySize / sizeof(ElementType); @@ -594,7 +594,7 @@ namespace sdbus { size_t arraySize{}; const Element* arrayPtr{}; - constexpr auto signature = as_null_terminated(sdbus::signature_of_v); + constexpr auto signature = as_null_terminated(signature_of_v); readArray(*signature.data(), reinterpret_cast(&arrayPtr), &arraySize); // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) diff --git a/include/sdbus-c++/ProxyInterfaces.h b/include/sdbus-c++/ProxyInterfaces.h index 936d4da5..3337c172 100644 --- a/include/sdbus-c++/ProxyInterfaces.h +++ b/include/sdbus-c++/ProxyInterfaces.h @@ -156,7 +156,7 @@ namespace sdbus { * The proxy created this way becomes an owner of the connection. * For more information on its behavior, consult @ref createProxy(std::unique_ptr&&,std::string,std::string) */ - ProxyInterfaces(std::unique_ptr&& connection, ServiceName destination, ObjectPath objectPath) + ProxyInterfaces(std::unique_ptr&& connection, ServiceName destination, ObjectPath objectPath) : ProxyObjectHolder(createProxy(std::move(connection), std::move(destination), std::move(objectPath))) , Interfaces(getProxy())... { @@ -172,7 +172,7 @@ namespace sdbus { * The proxy created this way becomes an owner of the connection. * For more information on its behavior, consult @ref createProxy(std::unique_ptr&&,std::string,std::string,sdbus::dont_run_event_loop_thread_t) */ - ProxyInterfaces(std::unique_ptr&& connection, ServiceName destination, ObjectPath objectPath, dont_run_event_loop_thread_t) + ProxyInterfaces(std::unique_ptr&& connection, ServiceName destination, ObjectPath objectPath, dont_run_event_loop_thread_t) : ProxyObjectHolder(createProxy(std::move(connection), std::move(destination), std::move(objectPath), dont_run_event_loop_thread)) , Interfaces(getProxy())... { diff --git a/include/sdbus-c++/StandardInterfaces.h b/include/sdbus-c++/StandardInterfaces.h index 1a0d1153..934245d7 100644 --- a/include/sdbus-c++/StandardInterfaces.h +++ b/include/sdbus-c++/StandardInterfaces.h @@ -43,7 +43,7 @@ namespace sdbus { static inline const char* INTERFACE_NAME = "org.freedesktop.DBus.Peer"; protected: - explicit Peer_proxy(sdbus::IProxy& proxy) + explicit Peer_proxy(IProxy& proxy) : m_proxy(proxy) { } @@ -73,7 +73,7 @@ namespace sdbus { } private: - sdbus::IProxy& m_proxy; + IProxy& m_proxy; }; // Proxy for introspection @@ -82,7 +82,7 @@ namespace sdbus { static inline const char* INTERFACE_NAME = "org.freedesktop.DBus.Introspectable"; protected: - explicit Introspectable_proxy(sdbus::IProxy& proxy) + explicit Introspectable_proxy(IProxy& proxy) : m_proxy(proxy) { } @@ -107,7 +107,7 @@ namespace sdbus { } private: - sdbus::IProxy& m_proxy; + IProxy& m_proxy; }; // Proxy for properties @@ -116,7 +116,7 @@ namespace sdbus { static inline const char* INTERFACE_NAME = "org.freedesktop.DBus.Properties"; protected: - explicit Properties_proxy(sdbus::IProxy& proxy) + explicit Properties_proxy(IProxy& proxy) : m_proxy(proxy) { } @@ -129,7 +129,7 @@ namespace sdbus { .uponSignal("PropertiesChanged") .onInterface(INTERFACE_NAME) .call([this]( const InterfaceName& interfaceName - , const std::map& changedProperties + , const std::map& changedProperties , const std::vector& invalidatedProperties ) { this->onPropertiesChanged(interfaceName, changedProperties, invalidatedProperties); @@ -137,7 +137,7 @@ namespace sdbus { } virtual void onPropertiesChanged( const InterfaceName& interfaceName - , const std::map& changedProperties + , const std::map& changedProperties , const std::vector& invalidatedProperties ) = 0; public: @@ -146,12 +146,12 @@ namespace sdbus { Properties_proxy(Properties_proxy&&) = delete; Properties_proxy& operator=(Properties_proxy&&) = delete; - sdbus::Variant Get(const InterfaceName& interfaceName, const PropertyName& propertyName) + Variant Get(const InterfaceName& interfaceName, const PropertyName& propertyName) { return m_proxy.getProperty(propertyName).onInterface(interfaceName); } - sdbus::Variant Get(std::string_view interfaceName, std::string_view propertyName) + Variant Get(std::string_view interfaceName, std::string_view propertyName) { return m_proxy.getProperty(propertyName).onInterface(interfaceName); } @@ -168,7 +168,7 @@ namespace sdbus { return m_proxy.getPropertyAsync(propertyName).onInterface(interfaceName).uponReplyInvoke(std::forward(callback), return_slot); } - std::future GetAsync(const InterfaceName& interfaceName, const PropertyName& propertyName, with_future_t) + std::future GetAsync(const InterfaceName& interfaceName, const PropertyName& propertyName, with_future_t) { return m_proxy.getPropertyAsync(propertyName).onInterface(interfaceName).getResultAsFuture(); } @@ -185,71 +185,71 @@ namespace sdbus { return m_proxy.getPropertyAsync(propertyName).onInterface(interfaceName).uponReplyInvoke(std::forward(callback), return_slot); } - std::future GetAsync(std::string_view interfaceName, std::string_view propertyName, with_future_t) + std::future GetAsync(std::string_view interfaceName, std::string_view propertyName, with_future_t) { return m_proxy.getPropertyAsync(propertyName).onInterface(interfaceName).getResultAsFuture(); } - void Set(const InterfaceName& interfaceName, const PropertyName& propertyName, const sdbus::Variant& value) + void Set(const InterfaceName& interfaceName, const PropertyName& propertyName, const Variant& value) { m_proxy.setProperty(propertyName).onInterface(interfaceName).toValue(value); } - void Set(std::string_view interfaceName, const std::string_view propertyName, const sdbus::Variant& value) + void Set(std::string_view interfaceName, const std::string_view propertyName, const Variant& value) { m_proxy.setProperty(propertyName).onInterface(interfaceName).toValue(value); } - void Set(const InterfaceName& interfaceName, const PropertyName& propertyName, const sdbus::Variant& value, dont_expect_reply_t) + void Set(const InterfaceName& interfaceName, const PropertyName& propertyName, const Variant& value, dont_expect_reply_t) { m_proxy.setProperty(propertyName).onInterface(interfaceName).toValue(value, dont_expect_reply); } - void Set(std::string_view interfaceName, const std::string_view propertyName, const sdbus::Variant& value, dont_expect_reply_t) + void Set(std::string_view interfaceName, const std::string_view propertyName, const Variant& value, dont_expect_reply_t) { m_proxy.setProperty(propertyName).onInterface(interfaceName).toValue(value, dont_expect_reply); } template - PendingAsyncCall SetAsync(const InterfaceName& interfaceName, const PropertyName& propertyName, const sdbus::Variant& value, Function&& callback) + PendingAsyncCall SetAsync(const InterfaceName& interfaceName, const PropertyName& propertyName, const Variant& value, Function&& callback) { return m_proxy.setPropertyAsync(propertyName).onInterface(interfaceName).toValue(value).uponReplyInvoke(std::forward(callback)); } template - [[nodiscard]] Slot SetAsync(const InterfaceName& interfaceName, const PropertyName& propertyName, const sdbus::Variant& value, Function&& callback, return_slot_t) + [[nodiscard]] Slot SetAsync(const InterfaceName& interfaceName, const PropertyName& propertyName, const Variant& value, Function&& callback, return_slot_t) { return m_proxy.setPropertyAsync(propertyName).onInterface(interfaceName).toValue(value).uponReplyInvoke(std::forward(callback), return_slot); } - std::future SetAsync(const InterfaceName& interfaceName, const PropertyName& propertyName, const sdbus::Variant& value, with_future_t) + std::future SetAsync(const InterfaceName& interfaceName, const PropertyName& propertyName, const Variant& value, with_future_t) { return m_proxy.setPropertyAsync(propertyName).onInterface(interfaceName).toValue(value).getResultAsFuture(); } template - PendingAsyncCall SetAsync(std::string_view interfaceName, std::string_view propertyName, const sdbus::Variant& value, Function&& callback) + PendingAsyncCall SetAsync(std::string_view interfaceName, std::string_view propertyName, const Variant& value, Function&& callback) { return m_proxy.setPropertyAsync(propertyName).onInterface(interfaceName).toValue(value).uponReplyInvoke(std::forward(callback)); } template - [[nodiscard]] Slot SetAsync(std::string_view interfaceName, std::string_view propertyName, const sdbus::Variant& value, Function&& callback, return_slot_t) + [[nodiscard]] Slot SetAsync(std::string_view interfaceName, std::string_view propertyName, const Variant& value, Function&& callback, return_slot_t) { return m_proxy.setPropertyAsync(propertyName).onInterface(interfaceName).toValue(value).uponReplyInvoke(std::forward(callback), return_slot); } - std::future SetAsync(std::string_view interfaceName, std::string_view propertyName, const sdbus::Variant& value, with_future_t) + std::future SetAsync(std::string_view interfaceName, std::string_view propertyName, const Variant& value, with_future_t) { return m_proxy.setPropertyAsync(propertyName).onInterface(interfaceName).toValue(value).getResultAsFuture(); } - std::map GetAll(const InterfaceName& interfaceName) + std::map GetAll(const InterfaceName& interfaceName) { return m_proxy.getAllProperties().onInterface(interfaceName); } - std::map GetAll(std::string_view interfaceName) + std::map GetAll(std::string_view interfaceName) { return m_proxy.getAllProperties().onInterface(interfaceName); } @@ -266,7 +266,7 @@ namespace sdbus { return m_proxy.getAllPropertiesAsync().onInterface(interfaceName).uponReplyInvoke(std::forward(callback), return_slot); } - std::future> GetAllAsync(const InterfaceName& interfaceName, with_future_t) + std::future> GetAllAsync(const InterfaceName& interfaceName, with_future_t) { return m_proxy.getAllPropertiesAsync().onInterface(interfaceName).getResultAsFuture(); } @@ -283,13 +283,13 @@ namespace sdbus { return m_proxy.getAllPropertiesAsync().onInterface(interfaceName).uponReplyInvoke(std::forward(callback), return_slot); } - std::future> GetAllAsync(std::string_view interfaceName, with_future_t) + std::future> GetAllAsync(std::string_view interfaceName, with_future_t) { return m_proxy.getAllPropertiesAsync().onInterface(interfaceName).getResultAsFuture(); } private: - sdbus::IProxy& m_proxy; + IProxy& m_proxy; }; // Proxy for object manager @@ -298,7 +298,7 @@ namespace sdbus { static inline const char* INTERFACE_NAME = "org.freedesktop.DBus.ObjectManager"; protected: - explicit ObjectManager_proxy(sdbus::IProxy& proxy) + explicit ObjectManager_proxy(IProxy& proxy) : m_proxy(proxy) { } @@ -310,8 +310,8 @@ namespace sdbus { m_proxy .uponSignal("InterfacesAdded") .onInterface(INTERFACE_NAME) - .call([this]( const sdbus::ObjectPath& objectPath - , const std::map>& interfacesAndProperties ) + .call([this]( const ObjectPath& objectPath + , const std::map>& interfacesAndProperties ) { this->onInterfacesAdded(objectPath, interfacesAndProperties); }); @@ -319,17 +319,17 @@ namespace sdbus { m_proxy .uponSignal("InterfacesRemoved") .onInterface(INTERFACE_NAME) - .call([this]( const sdbus::ObjectPath& objectPath - , const std::vector& interfaces ) + .call([this]( const ObjectPath& objectPath + , const std::vector& interfaces ) { this->onInterfacesRemoved(objectPath, interfaces); }); } - virtual void onInterfacesAdded( const sdbus::ObjectPath& objectPath - , const std::map>& interfacesAndProperties) = 0; - virtual void onInterfacesRemoved( const sdbus::ObjectPath& objectPath - , const std::vector& interfaces) = 0; + virtual void onInterfacesAdded( const ObjectPath& objectPath + , const std::map>& interfacesAndProperties) = 0; + virtual void onInterfacesRemoved( const ObjectPath& objectPath + , const std::vector& interfaces) = 0; public: ObjectManager_proxy(const ObjectManager_proxy&) = delete; @@ -337,9 +337,9 @@ namespace sdbus { ObjectManager_proxy(ObjectManager_proxy&&) = delete; ObjectManager_proxy& operator=(ObjectManager_proxy&&) = delete; - std::map>> GetManagedObjects() + std::map>> GetManagedObjects() { - std::map>> objectsInterfacesAndProperties; + std::map>> objectsInterfacesAndProperties; m_proxy.callMethod("GetManagedObjects").onInterface(INTERFACE_NAME).storeResultsTo(objectsInterfacesAndProperties); return objectsInterfacesAndProperties; } @@ -356,13 +356,13 @@ namespace sdbus { return m_proxy.callMethodAsync("GetManagedObjects").onInterface(INTERFACE_NAME).uponReplyInvoke(std::forward(callback), return_slot); } - std::future>>> GetManagedObjectsAsync(with_future_t) + std::future>>> GetManagedObjectsAsync(with_future_t) { - return m_proxy.callMethodAsync("GetManagedObjects").onInterface(INTERFACE_NAME).getResultAsFuture>>>(); + return m_proxy.callMethodAsync("GetManagedObjects").onInterface(INTERFACE_NAME).getResultAsFuture>>>(); } private: - sdbus::IProxy& m_proxy; + IProxy& m_proxy; }; // Adaptors for the above-listed standard D-Bus interfaces are not necessary because the functionality @@ -375,7 +375,7 @@ namespace sdbus { static inline const char* INTERFACE_NAME = "org.freedesktop.DBus.Properties"; protected: - explicit Properties_adaptor(sdbus::IObject& object) : m_object(object) + explicit Properties_adaptor(IObject& object) : m_object(object) { } @@ -412,7 +412,7 @@ namespace sdbus { } private: - sdbus::IObject& m_object; + IObject& m_object; }; /*! @@ -430,7 +430,7 @@ namespace sdbus { static inline const char* INTERFACE_NAME = "org.freedesktop.DBus.ObjectManager"; protected: - explicit ObjectManager_adaptor(sdbus::IObject& object) : m_object(object) + explicit ObjectManager_adaptor(IObject& object) : m_object(object) { } @@ -448,7 +448,7 @@ namespace sdbus { ObjectManager_adaptor& operator=(ObjectManager_adaptor&&) = delete; private: - sdbus::IObject& m_object; + IObject& m_object; }; /*! @@ -465,7 +465,7 @@ namespace sdbus { class ManagedObject_adaptor { protected: - explicit ManagedObject_adaptor(sdbus::IObject& object) + explicit ManagedObject_adaptor(IObject& object) : m_object(object) { } @@ -497,7 +497,7 @@ namespace sdbus { * * See IObject::emitInterfacesAddedSignal(). */ - void emitInterfacesAddedSignal(const std::vector& interfaces) + void emitInterfacesAddedSignal(const std::vector& interfaces) { m_object.emitInterfacesAddedSignal(interfaces); } @@ -523,7 +523,7 @@ namespace sdbus { } private: - sdbus::IObject& m_object; + IObject& m_object; }; } // namespace sdbus diff --git a/include/sdbus-c++/Types.h b/include/sdbus-c++/Types.h index 62644da4..b8a93bc6 100644 --- a/include/sdbus-c++/Types.h +++ b/include/sdbus-c++/Types.h @@ -466,7 +466,7 @@ struct std::tuple_size> // NOLINT(cert-dcl58-cpp): \ template <> \ struct signature_of \ - : signature_of> \ + : signature_of> \ {}; \ \ inline auto as_dictionary_if_struct(const STRUCT& object) \ @@ -474,9 +474,9 @@ struct std::tuple_size> // NOLINT(cert-dcl58-cpp): return as_dictionary(object); \ } \ \ - inline sdbus::Message& operator<<(sdbus::Message& msg, const STRUCT& items) \ + inline Message& operator<<(Message& msg, const STRUCT& items) \ { \ - return msg << sdbus::Struct{std::forward_as_tuple(SDBUSCPP_STRUCT_MEMBERS(items, __VA_ARGS__))}; \ + return msg << Struct{std::forward_as_tuple(SDBUSCPP_STRUCT_MEMBERS(items, __VA_ARGS__))}; \ } \ \ inline Message& operator<<(Message& msg, const as_dictionary& s) \ diff --git a/src/Connection.cpp b/src/Connection.cpp index 1bb01fab..13388e66 100644 --- a/src/Connection.cpp +++ b/src/Connection.cpp @@ -985,10 +985,10 @@ int IConnection::PollData::getPollTimeout() const namespace sdbus::internal { -std::unique_ptr createPseudoConnection() +std::unique_ptr createPseudoConnection() { - auto interface = std::make_unique(); - return std::make_unique(std::move(interface), Connection::pseudo_bus); + auto interface = std::make_unique(); + return std::make_unique(std::move(interface), Connection::pseudo_bus); } } // namespace sdbus::internal @@ -997,81 +997,81 @@ namespace sdbus { using internal::Connection; -std::unique_ptr createBusConnection() +std::unique_ptr createBusConnection() { - auto interface = std::make_unique(); - return std::make_unique(std::move(interface), Connection::default_bus); + auto interface = std::make_unique(); + return std::make_unique(std::move(interface), Connection::default_bus); } -std::unique_ptr createBusConnection(const ServiceName& name) +std::unique_ptr createBusConnection(const ServiceName& name) { auto conn = createBusConnection(); conn->requestName(name); return conn; } -std::unique_ptr createSystemBusConnection() +std::unique_ptr createSystemBusConnection() { - auto interface = std::make_unique(); - return std::make_unique(std::move(interface), Connection::system_bus); + auto interface = std::make_unique(); + return std::make_unique(std::move(interface), Connection::system_bus); } -std::unique_ptr createSystemBusConnection(const ServiceName& name) +std::unique_ptr createSystemBusConnection(const ServiceName& name) { auto conn = createSystemBusConnection(); conn->requestName(name); return conn; } -std::unique_ptr createSessionBusConnection() +std::unique_ptr createSessionBusConnection() { - auto interface = std::make_unique(); - return std::make_unique(std::move(interface), Connection::session_bus); + auto interface = std::make_unique(); + return std::make_unique(std::move(interface), Connection::session_bus); } -std::unique_ptr createSessionBusConnection(const ServiceName& name) +std::unique_ptr createSessionBusConnection(const ServiceName& name) { auto conn = createSessionBusConnection(); conn->requestName(name); return conn; } -std::unique_ptr createSessionBusConnectionWithAddress(const std::string &address) +std::unique_ptr createSessionBusConnectionWithAddress(const std::string &address) { - auto interface = std::make_unique(); - return std::make_unique(std::move(interface), Connection::custom_session_bus, address); + auto interface = std::make_unique(); + return std::make_unique(std::move(interface), Connection::custom_session_bus, address); } -std::unique_ptr createRemoteSystemBusConnection(const std::string& host) +std::unique_ptr createRemoteSystemBusConnection(const std::string& host) { - auto interface = std::make_unique(); - return std::make_unique(std::move(interface), Connection::remote_system_bus, host); + auto interface = std::make_unique(); + return std::make_unique(std::move(interface), Connection::remote_system_bus, host); } -std::unique_ptr createDirectBusConnection(const std::string& address) +std::unique_ptr createDirectBusConnection(const std::string& address) { - auto interface = std::make_unique(); - return std::make_unique(std::move(interface), Connection::private_bus, address); + auto interface = std::make_unique(); + return std::make_unique(std::move(interface), Connection::private_bus, address); } -std::unique_ptr createDirectBusConnection(int fd) +std::unique_ptr createDirectBusConnection(int fd) { - auto interface = std::make_unique(); - return std::make_unique(std::move(interface), Connection::private_bus, fd); + auto interface = std::make_unique(); + return std::make_unique(std::move(interface), Connection::private_bus, fd); } -std::unique_ptr createServerBus(int fd) +std::unique_ptr createServerBus(int fd) { - auto interface = std::make_unique(); - return std::make_unique(std::move(interface), Connection::server_bus, fd); + auto interface = std::make_unique(); + return std::make_unique(std::move(interface), Connection::server_bus, fd); } -std::unique_ptr createBusConnection(sd_bus *bus) +std::unique_ptr createBusConnection(sd_bus *bus) { SDBUS_THROW_ERROR_IF(bus == nullptr, "Invalid bus argument", EINVAL); - auto interface = std::make_unique(); - return std::make_unique(std::move(interface), Connection::sdbus_bus, bus); + auto interface = std::make_unique(); + return std::make_unique(std::move(interface), Connection::sdbus_bus, bus); } } // namespace sdbus diff --git a/src/IConnection.h b/src/IConnection.h index 2f76c5fc..54a3298f 100644 --- a/src/IConnection.h +++ b/src/IConnection.h @@ -128,7 +128,7 @@ namespace sdbus::internal { virtual sd_bus_message* createErrorReplyMessage(sd_bus_message* sdbusMsg, const Error& error) = 0; }; - [[nodiscard]] std::unique_ptr createPseudoConnection(); + [[nodiscard]] std::unique_ptr createPseudoConnection(); } // namespace sdbus::internal diff --git a/src/Message.cpp b/src/Message.cpp index aac21398..71ae731b 100644 --- a/src/Message.cpp +++ b/src/Message.cpp @@ -904,9 +904,9 @@ constinit bool pseudoConnectionDestroyed{}; // NOLINT(cppcoreguidelines-avoid-no bool pseudoConnectionDestroyed{}; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables) #endif -std::unique_ptr createPseudoConnection() +std::unique_ptr createPseudoConnection() { - auto deleter = [](sdbus::internal::IConnection* con) + auto deleter = [](internal::IConnection* con) { delete con; // NOLINT(cppcoreguidelines-owning-memory) pseudoConnectionDestroyed = true; @@ -915,7 +915,7 @@ std::unique_ptr createObject(sdbus::IConnection& connection, ObjectPath objectPath) +std::unique_ptr createObject(IConnection& connection, ObjectPath objectPath) { - auto* sdbusConnection = dynamic_cast(&connection); + auto* sdbusConnection = dynamic_cast(&connection); SDBUS_THROW_ERROR_IF(!sdbusConnection, "Connection is not a real sdbus-c++ connection", EINVAL); - return std::make_unique(*sdbusConnection, std::move(objectPath)); + return std::make_unique(*sdbusConnection, std::move(objectPath)); } } // namespace sdbus diff --git a/src/Object.h b/src/Object.h index dd0a2b6c..5a30b002 100644 --- a/src/Object.h +++ b/src/Object.h @@ -47,7 +47,7 @@ namespace sdbus::internal { : public IObject { public: - Object(sdbus::internal::IConnection& connection, ObjectPath objectPath); + Object(IConnection& connection, ObjectPath objectPath); void addVTable(InterfaceName interfaceName, std::vector vtable) override; Slot addVTable(InterfaceName interfaceName, std::vector vtable, return_slot_t) override; @@ -55,7 +55,7 @@ namespace sdbus::internal { [[nodiscard]] Signal createSignal(const InterfaceName& interfaceName, const SignalName& signalName) const override; Signal createSignal(const char* interfaceName, const char* signalName) const override; - void emitSignal(const sdbus::Signal& message) override; + void emitSignal(const Signal& message) override; void emitPropertiesChangedSignal(const InterfaceName& interfaceName, const std::vector& propNames) override; void emitPropertiesChangedSignal(const char* interfaceName, const std::vector& propNames) override; void emitPropertiesChangedSignal(const InterfaceName& interfaceName) override; diff --git a/src/Proxy.cpp b/src/Proxy.cpp index 7c9cf730..1d567194 100644 --- a/src/Proxy.cpp +++ b/src/Proxy.cpp @@ -52,8 +52,8 @@ namespace sdbus::internal { -Proxy::Proxy(sdbus::internal::IConnection& connection, ServiceName destination, ObjectPath objectPath) - : connection_(&connection, [](sdbus::internal::IConnection *){ /* Intentionally left empty */ }) +Proxy::Proxy(IConnection& connection, ServiceName destination, ObjectPath objectPath) + : connection_(&connection, [](IConnection *){ /* Intentionally left empty */ }) , destination_(std::move(destination)) , objectPath_(std::move(objectPath)) { @@ -64,7 +64,7 @@ Proxy::Proxy(sdbus::internal::IConnection& connection, ServiceName destination, // it here, so we expect the client to manage the event loop upon this connection themselves. } -Proxy::Proxy( std::unique_ptr&& connection +Proxy::Proxy( std::unique_ptr&& connection , ServiceName destination , ObjectPath objectPath ) : connection_(std::move(connection)) @@ -79,7 +79,7 @@ Proxy::Proxy( std::unique_ptr&& connection connection_->enterEventLoopAsync(); } -Proxy::Proxy( std::unique_ptr&& connection +Proxy::Proxy( std::unique_ptr&& connection , ServiceName destination , ObjectPath objectPath , dont_run_event_loop_thread_t ) @@ -132,6 +132,7 @@ PendingAsyncCall Proxy::callMethodAsync(const MethodCall& message, async_reply_h auto asyncCallInfo = std::make_shared(AsyncCallInfo{ .callback = std::move(asyncReplyCallback) , .proxy = *this + , .slot = {} , .floating = false }); asyncCallInfo->slot = message.send(reinterpret_cast(&Proxy::sdbus_async_reply_handler), asyncCallInfo.get(), timeout, return_slot); @@ -149,6 +150,7 @@ Slot Proxy::callMethodAsync(const MethodCall& message, async_reply_handler async auto asyncCallInfo = std::make_unique(AsyncCallInfo{ .callback = std::move(asyncReplyCallback) , .proxy = *this + , .slot = {} , .floating = true }); asyncCallInfo->slot = message.send(reinterpret_cast(&Proxy::sdbus_async_reply_handler), asyncCallInfo.get(), timeout, return_slot); @@ -368,82 +370,82 @@ bool PendingAsyncCall::isPending() const namespace sdbus { -std::unique_ptr createProxy( IConnection& connection +std::unique_ptr createProxy( IConnection& connection , ServiceName destination , ObjectPath objectPath ) { - auto* sdbusConnection = dynamic_cast(&connection); + auto* sdbusConnection = dynamic_cast(&connection); SDBUS_THROW_ERROR_IF(!sdbusConnection, "Connection is not a real sdbus-c++ connection", EINVAL); - return std::make_unique( *sdbusConnection + return std::make_unique( *sdbusConnection , std::move(destination) , std::move(objectPath) ); } // NOLINTNEXTLINE(cppcoreguidelines-rvalue-reference-param-not-moved): connection is moved but cast to an internal type -std::unique_ptr createProxy( std::unique_ptr&& connection - , ServiceName destination - , ObjectPath objectPath ) +std::unique_ptr createProxy( std::unique_ptr&& connection + , ServiceName destination + , ObjectPath objectPath ) { - auto* sdbusConnection = dynamic_cast(connection.release()); + auto* sdbusConnection = dynamic_cast(connection.release()); SDBUS_THROW_ERROR_IF(!sdbusConnection, "Connection is not a real sdbus-c++ connection", EINVAL); - return std::make_unique( std::unique_ptr(sdbusConnection) - , std::move(destination) - , std::move(objectPath) ); + return std::make_unique( std::unique_ptr(sdbusConnection) + , std::move(destination) + , std::move(objectPath) ); } // NOLINTNEXTLINE(cppcoreguidelines-rvalue-reference-param-not-moved): connection is moved cast to an internal type -std::unique_ptr createProxy( std::unique_ptr&& connection - , ServiceName destination - , ObjectPath objectPath - , dont_run_event_loop_thread_t ) +std::unique_ptr createProxy( std::unique_ptr&& connection + , ServiceName destination + , ObjectPath objectPath + , dont_run_event_loop_thread_t ) { - auto* sdbusConnection = dynamic_cast(connection.release()); + auto* sdbusConnection = dynamic_cast(connection.release()); SDBUS_THROW_ERROR_IF(!sdbusConnection, "Connection is not a real sdbus-c++ connection", EINVAL); - return std::make_unique( std::unique_ptr(sdbusConnection) - , std::move(destination) - , std::move(objectPath) - , dont_run_event_loop_thread ); + return std::make_unique( std::unique_ptr(sdbusConnection) + , std::move(destination) + , std::move(objectPath) + , dont_run_event_loop_thread ); } -std::unique_ptr createLightWeightProxy( std::unique_ptr&& connection - , ServiceName destination - , ObjectPath objectPath ) +std::unique_ptr createLightWeightProxy( std::unique_ptr&& connection + , ServiceName destination + , ObjectPath objectPath ) { return createProxy(std::move(connection), std::move(destination), std::move(objectPath), dont_run_event_loop_thread); } -std::unique_ptr createProxy( ServiceName destination - , ObjectPath objectPath ) +std::unique_ptr createProxy( ServiceName destination + , ObjectPath objectPath ) { - auto connection = sdbus::createBusConnection(); + auto connection = createBusConnection(); - auto sdbusConnection = std::unique_ptr(dynamic_cast(connection.release())); + auto sdbusConnection = std::unique_ptr(dynamic_cast(connection.release())); assert(sdbusConnection != nullptr); - return std::make_unique( std::move(sdbusConnection) - , std::move(destination) - , std::move(objectPath) ); + return std::make_unique( std::move(sdbusConnection) + , std::move(destination) + , std::move(objectPath) ); } -std::unique_ptr createProxy( ServiceName destination +std::unique_ptr createProxy( ServiceName destination , ObjectPath objectPath , dont_run_event_loop_thread_t ) { - auto connection = sdbus::createBusConnection(); + auto connection = createBusConnection(); - auto sdbusConnection = std::unique_ptr(dynamic_cast(connection.release())); + auto sdbusConnection = std::unique_ptr(dynamic_cast(connection.release())); assert(sdbusConnection != nullptr); - return std::make_unique( std::move(sdbusConnection) - , std::move(destination) - , std::move(objectPath) - , dont_run_event_loop_thread ); + return std::make_unique( std::move(sdbusConnection) + , std::move(destination) + , std::move(objectPath) + , dont_run_event_loop_thread ); } -std::unique_ptr createLightWeightProxy(ServiceName destination, ObjectPath objectPath) +std::unique_ptr createLightWeightProxy(ServiceName destination, ObjectPath objectPath) { return createProxy(std::move(destination), std::move(objectPath), dont_run_event_loop_thread); } diff --git a/src/Proxy.h b/src/Proxy.h index f11c312d..d474e42b 100644 --- a/src/Proxy.h +++ b/src/Proxy.h @@ -45,13 +45,13 @@ namespace sdbus::internal { : public IProxy { public: - Proxy( sdbus::internal::IConnection& connection + Proxy( IConnection& connection , ServiceName destination , ObjectPath objectPath ); - Proxy( std::unique_ptr&& connection + Proxy( std::unique_ptr&& connection , ServiceName destination , ObjectPath objectPath ); - Proxy( std::unique_ptr&& connection + Proxy( std::unique_ptr&& connection , ServiceName destination , ObjectPath objectPath , dont_run_event_loop_thread_t ); @@ -100,9 +100,7 @@ namespace sdbus::internal { friend PendingAsyncCall; - std::unique_ptr< sdbus::internal::IConnection - , std::function - > connection_; + std::unique_ptr> connection_; ServiceName destination_; ObjectPath objectPath_; From af525fc05d3a97b2046ff2d90c430619374d8c00 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stanislav=20Angelovi=C4=8D?= Date: Thu, 15 Jan 2026 13:46:48 +0100 Subject: [PATCH 13/13] fix: address other clang-tidy suggestions --- include/sdbus-c++/AdaptorInterfaces.h | 2 +- include/sdbus-c++/IConnection.h | 8 ++++---- include/sdbus-c++/IProxy.h | 2 -- include/sdbus-c++/ProxyInterfaces.h | 3 +-- include/sdbus-c++/StandardInterfaces.h | 4 ++-- include/sdbus-c++/TypeTraits.h | 8 ++++---- include/sdbus-c++/Types.h | 5 ++--- include/sdbus-c++/VTableItems.inl | 4 ++-- src/Connection.h | 1 - src/IConnection.h | 2 -- src/Object.h | 9 ++++++++- src/ScopeGuard.h | 2 +- src/SdBus.h | 2 +- tests/integrationtests/DBusAsyncMethodsTests.cpp | 10 +++++----- tests/integrationtests/DBusGeneralTests.cpp | 10 +++++----- tests/integrationtests/DBusMethodsTests.cpp | 2 +- tests/integrationtests/DBusStandardInterfacesTests.cpp | 10 +++++----- tests/stresstests/sdbus-c++-stress-tests.cpp | 10 +++++----- 18 files changed, 47 insertions(+), 47 deletions(-) diff --git a/include/sdbus-c++/AdaptorInterfaces.h b/include/sdbus-c++/AdaptorInterfaces.h index a11a539e..6edfc079 100644 --- a/include/sdbus-c++/AdaptorInterfaces.h +++ b/include/sdbus-c++/AdaptorInterfaces.h @@ -126,7 +126,7 @@ namespace sdbus { } /*! - * @brief Unregisters adaptors's API and removes it from the bus + * @brief Unregisters adaptor's API and removes it from the bus * * This function must be called in the destructor of the final adaptor class that implements AdaptorInterfaces. * diff --git a/include/sdbus-c++/IConnection.h b/include/sdbus-c++/IConnection.h index 636874b7..f9758c71 100644 --- a/include/sdbus-c++/IConnection.h +++ b/include/sdbus-c++/IConnection.h @@ -92,7 +92,7 @@ namespace sdbus { virtual void leaveEventLoop() = 0; /*! - * @brief Attaches the bus connection to an sd-event event loop + * @brief Attaches the bus connection to a sd-event event loop * * @param[in] event sd-event event loop object * @param[in] priority Specified priority @@ -104,7 +104,7 @@ namespace sdbus { virtual void attachSdEventLoop(sd_event *event, int priority = 0) = 0; /*! - * @brief Detaches the bus connection from an sd-event event loop + * @brief Detaches the bus connection from a sd-event event loop * * @throws sdbus::Error in case of failure */ @@ -144,7 +144,7 @@ namespace sdbus { * in a form that can be passed to poll(2). * * The bus connection conveniently integrates sd-event event loop. - * To attach the bus connection to an sd-event event loop, use + * To attach the bus connection to a sd-event event loop, use * attachSdEventLoop() function. * * @throws sdbus::Error in case of failure @@ -168,7 +168,7 @@ namespace sdbus { * You don't need to directly call this method or getEventLoopPollData() method * when using convenient, internal bus connection event loops through * enterEventLoop() or enterEventLoopAsync() calls, or when the bus is - * connected to an sd-event event loop through attachSdEventLoop(). + * connected to a sd-event event loop through attachSdEventLoop(). * It is invoked automatically when necessary. * * @throws sdbus::Error in case of failure diff --git a/include/sdbus-c++/IProxy.h b/include/sdbus-c++/IProxy.h index 8eb067b8..b93c1542 100644 --- a/include/sdbus-c++/IProxy.h +++ b/include/sdbus-c++/IProxy.h @@ -557,7 +557,6 @@ namespace sdbus { * @brief Calls method on the D-Bus object asynchronously * * @param[in] message Message representing an async method call - * @param[in] Tag denoting a std::future-based overload * @return Future object providing access to the future method reply message * * This is a std::future-based way of asynchronously calling a remote D-Bus method. @@ -579,7 +578,6 @@ namespace sdbus { * * @param[in] message Message representing an async method call * @param[in] timeout Method call timeout - * @param[in] Tag denoting a std::future-based overload * @return Future object providing access to the future method reply message * * This is a std::future-based way of asynchronously calling a remote D-Bus method. diff --git a/include/sdbus-c++/ProxyInterfaces.h b/include/sdbus-c++/ProxyInterfaces.h index 3337c172..d5fbeba8 100644 --- a/include/sdbus-c++/ProxyInterfaces.h +++ b/include/sdbus-c++/ProxyInterfaces.h @@ -29,7 +29,6 @@ #include #include -#include #include // Forward declarations @@ -215,4 +214,4 @@ namespace sdbus { } // namespace sdbus -#endif /* SDBUS_CXX_INTERFACES_H_ */ +#endif /* SDBUS_CXX_PROXYINTERFACES_H_ */ diff --git a/include/sdbus-c++/StandardInterfaces.h b/include/sdbus-c++/StandardInterfaces.h index 934245d7..7afc41a6 100644 --- a/include/sdbus-c++/StandardInterfaces.h +++ b/include/sdbus-c++/StandardInterfaces.h @@ -458,8 +458,8 @@ namespace sdbus { * will extend the resulting object adaptor with emitInterfacesAddedSignal()/emitInterfacesRemovedSignal() * according to org.freedesktop.DBus.ObjectManager.InterfacesAdded/.InterfacesRemoved. * - * Note that objects which implement this adaptor require an object manager (e.g via ObjectManager_adaptor) to be - * instantiated on one of it's parent object paths or the same path. InterfacesAdded/InterfacesRemoved + * Note that objects which implement this adaptor require an object manager (e.g., via ObjectManager_adaptor) to be + * instantiated on one of its parent object paths or the same path. InterfacesAdded/InterfacesRemoved * signals are sent from the closest object manager at either the same path or the closest parent path of an object. */ class ManagedObject_adaptor diff --git a/include/sdbus-c++/TypeTraits.h b/include/sdbus-c++/TypeTraits.h index 6751abdf..39ed6351 100644 --- a/include/sdbus-c++/TypeTraits.h +++ b/include/sdbus-c++/TypeTraits.h @@ -351,7 +351,7 @@ namespace sdbus { #endif template // is_const_v and is_volatile_v to avoid ambiguity conflicts with const and volatile specializations of signature_of - struct signature_of && !std::is_const_v && !std::is_volatile_v>> + struct signature_of && !std::is_const_v && !std::is_volatile_v>> : signature_of> {}; @@ -665,7 +665,7 @@ namespace sdbus { { return detail::apply_impl( std::forward(fun) , std::forward(tuple) - , std::make_index_sequence>::value>{} ); + , std::make_index_sequence>>{} ); } // Convert tuple `t' of values into a list of arguments @@ -676,7 +676,7 @@ namespace sdbus { return detail::apply_impl( std::forward(fun) , std::move(res) , std::forward(tuple) - , std::make_index_sequence>::value>{} ); + , std::make_index_sequence>>{} ); } // Convert tuple `t' of values into a list of arguments @@ -687,7 +687,7 @@ namespace sdbus { return detail::apply_impl( std::forward(fun) , std::move(err) , std::forward(tuple) - , std::make_index_sequence>::value>{} ); + , std::make_index_sequence>>{} ); } // Convenient concatenation of arrays diff --git a/include/sdbus-c++/Types.h b/include/sdbus-c++/Types.h index b8a93bc6..58d4402f 100644 --- a/include/sdbus-c++/Types.h +++ b/include/sdbus-c++/Types.h @@ -36,7 +36,6 @@ #include #include #include -#include #include namespace sdbus { @@ -50,7 +49,7 @@ namespace sdbus { * Some const methods are conceptually const, but not physically const, * thus are not thread-safe. This is by design: normally, clients * should process a single Variant object in a single thread at a time. - * Otherwise they need to take care of synchronization by themselves. + * Otherwise, they need to take care of synchronization by themselves. * ***********************************************/ class Variant @@ -188,7 +187,7 @@ namespace sdbus { constexpr Struct...> make_struct(Elements&&... args) { - typedef Struct...> result_type; + using result_type = Struct...>; return result_type(std::forward(args)...); } diff --git a/include/sdbus-c++/VTableItems.inl b/include/sdbus-c++/VTableItems.inl index 4cc1a851..ee4e4e32 100644 --- a/include/sdbus-c++/VTableItems.inl +++ b/include/sdbus-c++/VTableItems.inl @@ -189,7 +189,7 @@ namespace sdbus { inline PropertyVTableItem& PropertyVTableItem::withGetter(Function&& callback) { static_assert(function_argument_count_v == 0, "Property getter function must not take any arguments"); - static_assert(!std::is_void>::value, "Property getter function must return property value"); + static_assert(!std::is_void_v>, "Property getter function must return property value"); if (signature.empty()) signature = signature_of_function_output_arguments_v; @@ -207,7 +207,7 @@ namespace sdbus { inline PropertyVTableItem& PropertyVTableItem::withSetter(Function&& callback) { static_assert(function_argument_count_v == 1, "Property setter function must take one parameter - the property value"); - static_assert(std::is_void>::value, "Property setter function must not return any value"); + static_assert(std::is_void_v>, "Property setter function must not return any value"); if (signature.empty()) signature = signature_of_function_input_arguments_v; diff --git a/src/Connection.h b/src/Connection.h index 6673c70c..0e63aa6b 100644 --- a/src/Connection.h +++ b/src/Connection.h @@ -33,7 +33,6 @@ #include "IConnection.h" #include "ISdBus.h" -#include "ScopeGuard.h" #include #include diff --git a/src/IConnection.h b/src/IConnection.h index 54a3298f..c185a8f4 100644 --- a/src/IConnection.h +++ b/src/IConnection.h @@ -31,9 +31,7 @@ #include "sdbus-c++/TypeTraits.h" -#include #include -#include #include SDBUS_HEADER #include diff --git a/src/Object.h b/src/Object.h index 5a30b002..4dafa6b3 100644 --- a/src/Object.h +++ b/src/Object.h @@ -29,7 +29,6 @@ #include "sdbus-c++/IObject.h" -#include "IConnection.h" #include "sdbus-c++/Types.h" #include @@ -41,6 +40,14 @@ #include SDBUS_HEADER #include +// Forward declarations +namespace sdbus { + class IConnection; + namespace internal { + class IConnection; + } // namespace internal +} // namespace sdbus + namespace sdbus::internal { class Object diff --git a/src/ScopeGuard.h b/src/ScopeGuard.h index e159faca..d5c2f1c2 100644 --- a/src/ScopeGuard.h +++ b/src/ScopeGuard.h @@ -118,7 +118,7 @@ namespace sdbus::internal { ScopeGuard() = delete; ScopeGuard(const ScopeGuard&) = delete; ScopeGuard& operator=(const ScopeGuard&) = delete; - ScopeGuard(ScopeGuard&& rhs) noexcept : fnc_(std::move(rhs.fnc_)), active_(rhs.active_), exceptions_(rhs.exceptions_) + ScopeGuard(ScopeGuard&& rhs) noexcept : fnc_(std::move(rhs.fnc_)), exceptions_(rhs.exceptions_), active_(rhs.active_) { rhs.dismiss(); } diff --git a/src/SdBus.h b/src/SdBus.h index aa53b2d4..a3effbfc 100644 --- a/src/SdBus.h +++ b/src/SdBus.h @@ -107,4 +107,4 @@ class SdBus final : public ISdBus } // namespace sdbus::internal -#endif //SDBUS_C_SDBUS_H +#endif // SDBUS_CXX_SDBUS_H diff --git a/tests/integrationtests/DBusAsyncMethodsTests.cpp b/tests/integrationtests/DBusAsyncMethodsTests.cpp index 4c17a995..14942ba5 100644 --- a/tests/integrationtests/DBusAsyncMethodsTests.cpp +++ b/tests/integrationtests/DBusAsyncMethodsTests.cpp @@ -95,15 +95,15 @@ TYPED_TEST(AsyncSdbusTestObject, RunsServerSideAsynchronousMethodAsynchronously) // Yeah, this is kinda timing-dependent test, but times should be safe... std::mutex mtx; std::vector results; - std::atomic invoke{}; - std::atomic startedCount{}; + std::atomic invoke{false}; + std::atomic startedCount{0}; auto call = [&](uint32_t param) { TestProxy proxy{SERVICE_NAME, OBJECT_PATH}; ++startedCount; while (!invoke) ; auto result = proxy.doOperationAsync(param); - std::lock_guard const guard(mtx); + std::lock_guard const guard(mtx); results.push_back(result); }; @@ -118,8 +118,8 @@ TYPED_TEST(AsyncSdbusTestObject, RunsServerSideAsynchronousMethodAsynchronously) TYPED_TEST(AsyncSdbusTestObject, HandlesCorrectlyABulkOfParallelServerSideAsyncMethods) { std::atomic resultCount{}; - std::atomic invoke{}; - std::atomic startedCount{}; + std::atomic invoke{false}; + std::atomic startedCount{0}; auto call = [&]() { TestProxy proxy{SERVICE_NAME, OBJECT_PATH}; diff --git a/tests/integrationtests/DBusGeneralTests.cpp b/tests/integrationtests/DBusGeneralTests.cpp index a3269803..508c5e83 100644 --- a/tests/integrationtests/DBusGeneralTests.cpp +++ b/tests/integrationtests/DBusGeneralTests.cpp @@ -76,7 +76,7 @@ TEST(AnAdaptor, DoesNotSupportMoveSemantics) TYPED_TEST(AConnection, WillCallCallbackHandlerForIncomingMessageMatchingMatchRule) { auto matchRule = "sender='" + SERVICE_NAME + "',path='" + OBJECT_PATH + "'"; - std::atomic matchingMessageReceived{false}; + std::atomic matchingMessageReceived{false}; auto slot = this->s_proxyConnection->addMatch(matchRule, [&](const sdbus::Message& msg) { if(msg.getPath() == OBJECT_PATH) @@ -91,8 +91,8 @@ TYPED_TEST(AConnection, WillCallCallbackHandlerForIncomingMessageMatchingMatchRu TYPED_TEST(AConnection, CanInstallMatchRuleAsynchronously) { auto matchRule = "sender='" + SERVICE_NAME + "',path='" + OBJECT_PATH + "'"; - std::atomic matchingMessageReceived{false}; - std::atomic matchRuleInstalled{false}; + std::atomic matchingMessageReceived{false}; + std::atomic matchRuleInstalled{false}; auto slot = this->s_proxyConnection->addMatchAsync( matchRule , [&](const sdbus::Message& msg) { @@ -115,7 +115,7 @@ TYPED_TEST(AConnection, CanInstallMatchRuleAsynchronously) TYPED_TEST(AConnection, WillUnsubscribeMatchRuleWhenClientDestroysTheAssociatedSlot) { auto matchRule = "sender='" + SERVICE_NAME + "',path='" + OBJECT_PATH + "'"; - std::atomic matchingMessageReceived{false}; + std::atomic matchingMessageReceived{false}; auto slot = this->s_proxyConnection->addMatch(matchRule, [&](const sdbus::Message& msg) { if(msg.getPath() == OBJECT_PATH) @@ -131,7 +131,7 @@ TYPED_TEST(AConnection, WillUnsubscribeMatchRuleWhenClientDestroysTheAssociatedS TYPED_TEST(AConnection, CanAddFloatingMatchRule) { auto matchRule = "sender='" + SERVICE_NAME + "',path='" + OBJECT_PATH + "'"; - std::atomic matchingMessageReceived{false}; + std::atomic matchingMessageReceived{false}; auto con = sdbus::createBusConnection(); con->enterEventLoopAsync(); auto callback = [&](const sdbus::Message& msg) diff --git a/tests/integrationtests/DBusMethodsTests.cpp b/tests/integrationtests/DBusMethodsTests.cpp index 92ca927f..345cf4e4 100644 --- a/tests/integrationtests/DBusMethodsTests.cpp +++ b/tests/integrationtests/DBusMethodsTests.cpp @@ -115,7 +115,7 @@ TYPED_TEST(SdbusTestObject, CallsMethodWithStdVariantSuccessfully) TYPED_TEST(SdbusTestObject, CallsMethodWithStructVariantsAndGetMapSuccessfully) { - std::vector const vec{-2, 0, 2}; + std::vector const vec{-2, 0, 2}; sdbus::Struct const strct{false, true}; std::map mapOfVariants = this->m_proxy->getMapOfVariants(vec, strct); decltype(mapOfVariants) res{ {-2, sdbus::Variant{false}} diff --git a/tests/integrationtests/DBusStandardInterfacesTests.cpp b/tests/integrationtests/DBusStandardInterfacesTests.cpp index 83a7c335..9e396e32 100644 --- a/tests/integrationtests/DBusStandardInterfacesTests.cpp +++ b/tests/integrationtests/DBusStandardInterfacesTests.cpp @@ -205,7 +205,7 @@ TYPED_TEST(SdbusTestObject, GetsAllPropertiesAsynchronouslyViaPropertiesInterfac TYPED_TEST(SdbusTestObject, EmitsPropertyChangedSignalForSelectedProperties) { - std::atomic signalReceived{false}; + std::atomic signalReceived{false}; this->m_proxy->m_onPropertiesChangedHandler = [&signalReceived]( const sdbus::InterfaceName& interfaceName , const std::map& changedProperties , const std::vector& /*invalidatedProperties*/ ) @@ -225,7 +225,7 @@ TYPED_TEST(SdbusTestObject, EmitsPropertyChangedSignalForSelectedProperties) TYPED_TEST(SdbusTestObject, EmitsPropertyChangedSignalForAllProperties) // NOLINT(readability-function-cognitive-complexity) { - std::atomic signalReceived{false}; + std::atomic signalReceived{false}; this->m_proxy->m_onPropertiesChangedHandler = [&signalReceived]( const sdbus::InterfaceName& interfaceName , const std::map& changedProperties , const std::vector& invalidatedProperties ) @@ -338,7 +338,7 @@ TYPED_TEST(SdbusTestObject, EmitsInterfacesAddedSignalForSelectedObjectInterface TYPED_TEST(SdbusTestObject, EmitsInterfacesAddedSignalForAllObjectInterfaces) // NOLINT(readability-function-cognitive-complexity) { - std::atomic signalReceived{false}; + std::atomic signalReceived{false}; this->m_objectManagerProxy->m_onInterfacesAddedHandler = [&signalReceived]( const sdbus::ObjectPath& objectPath , const std::map>& interfacesAndProperties ) { @@ -376,7 +376,7 @@ TYPED_TEST(SdbusTestObject, EmitsInterfacesAddedSignalForAllObjectInterfaces) // TYPED_TEST(SdbusTestObject, EmitsInterfacesRemovedSignalForSelectedObjectInterfaces) { - std::atomic signalReceived{false}; + std::atomic signalReceived{false}; this->m_objectManagerProxy->m_onInterfacesRemovedHandler = [&signalReceived]( const sdbus::ObjectPath& objectPath , const std::vector& interfaces ) { @@ -393,7 +393,7 @@ TYPED_TEST(SdbusTestObject, EmitsInterfacesRemovedSignalForSelectedObjectInterfa TYPED_TEST(SdbusTestObject, EmitsInterfacesRemovedSignalForAllObjectInterfaces) { - std::atomic signalReceived{false}; + std::atomic signalReceived{false}; this->m_objectManagerProxy->m_onInterfacesRemovedHandler = [&signalReceived]( const sdbus::ObjectPath& objectPath , const std::vector& interfaces ) { diff --git a/tests/stresstests/sdbus-c++-stress-tests.cpp b/tests/stresstests/sdbus-c++-stress-tests.cpp index 497db3bc..7b17a6f7 100644 --- a/tests/stresstests/sdbus-c++-stress-tests.cpp +++ b/tests/stresstests/sdbus-c++-stress-tests.cpp @@ -158,7 +158,7 @@ class FahrenheitThermometerAdaptor final : public sdbus::AdaptorInterfaces< org: { // Destroy existing delegate object // Here we are testing dynamic removal of a D-Bus object in an async way - const std::lock_guard lock{childrenMutex_}; + const std::lock_guard lock{childrenMutex_}; children_.erase(request.delegateObjectPath); } } @@ -406,7 +406,7 @@ int main(int argc, char *argv[]) // NOLINT(bugprone-exception-escape, readabilit std::atomic concatenationSignalsReceived{0}; std::atomic thermometerCallsMade{0}; - std::atomic exitLogger{}; + std::atomic exitLogger{false}; std::thread loggerThread([&]() { while (!exitLogger) @@ -423,7 +423,7 @@ int main(int argc, char *argv[]) // NOLINT(bugprone-exception-escape, readabilit std::cout << "Entering loop " << loop+1 << '\n'; auto service2Connection = sdbus::createSystemBusConnection(SERVICE_2_BUS_NAME); - std::atomic service2ThreadReady{}; + std::atomic service2ThreadReady{false}; std::thread service2Thread([&con = *service2Connection, &service2ThreadReady]() { // NOLINTNEXTLINE(misc-const-correctness) @@ -433,7 +433,7 @@ int main(int argc, char *argv[]) // NOLINT(bugprone-exception-escape, readabilit }); auto service1Connection = sdbus::createSystemBusConnection(SERVICE_1_BUS_NAME); - std::atomic service1ThreadReady{}; + std::atomic service1ThreadReady{false}; std::thread service1Thread([&con = *service1Connection, &service1ThreadReady]() { // NOLINTNEXTLINE(misc-const-correctness) @@ -454,7 +454,7 @@ int main(int argc, char *argv[]) // NOLINT(bugprone-exception-escape, readabilit bool clientThreadExit{}; std::thread clientThread([&, &con = *clientConnection]() { - std::atomic stopClients{false}; + std::atomic stopClients{false}; std::thread concatenatorThread([&]() {