From d6e0c1a0fe5717af567fb3737e5c7975dc645ade Mon Sep 17 00:00:00 2001 From: Sergey Polyakov Date: Wed, 12 Jul 2023 15:35:12 +0200 Subject: [PATCH] Wrap the C-style callback in an std::function --- wiring/src/spark_wiring_ledger.cpp | 43 +++++++----------------------- 1 file changed, 10 insertions(+), 33 deletions(-) diff --git a/wiring/src/spark_wiring_ledger.cpp b/wiring/src/spark_wiring_ledger.cpp index dd5f62615d..0d5c22dc5b 100644 --- a/wiring/src/spark_wiring_ledger.cpp +++ b/wiring/src/spark_wiring_ledger.cpp @@ -19,7 +19,6 @@ #if Wiring_Ledger -#include #include #include "spark_wiring_ledger.h" @@ -36,27 +35,8 @@ namespace particle { namespace { -struct OnSyncCallbackData { - Ledger::OnSyncCallback callback; - void* arg; - - OnSyncCallbackData() : - callback(nullptr), - arg(nullptr) { - } - - OnSyncCallbackData(Ledger::OnSyncCallback callback, void* arg) : - callback(callback), - arg(arg) { - } - - explicit operator bool() const { - return callback; - } -}; - struct LedgerAppData { - std::variant onSync; + Ledger::OnSyncFunction onSync; }; void destroyAppData(void* appData) { @@ -72,15 +52,8 @@ void syncCallbackApp(void* data) { ledger_release(ledger, nullptr); }); auto appData = static_cast(ledger_get_app_data(ledger, nullptr)); - if (!appData) { - return; - } - if (std::holds_alternative(appData->onSync)) { // C callback - auto& d = std::get(appData->onSync); - d.callback(Ledger(ledger), d.arg); - } else { // Functor callback - auto &f = std::get(appData->onSync); - f(Ledger(ledger)); + if (appData && appData->onSync) { + appData->onSync(Ledger(ledger)); } } @@ -95,8 +68,7 @@ void syncCallbackSystem(ledger_instance* ledger, void* appData) { } // TODO: Generalize this code when there are more callbacks -template -int setSyncCallback(ledger_instance* ledger, CallbackT&& callback) { +int setSyncCallback(ledger_instance* ledger, Ledger::OnSyncFunction callback) { ledger_lock(ledger, nullptr); SCOPE_GUARD({ ledger_unlock(ledger, nullptr); @@ -289,7 +261,12 @@ int Ledger::onSync(OnSyncCallback callback, void* arg) { if (!isValid()) { return Error::INVALID_STATE; } - return setSyncCallback(instance_, OnSyncCallbackData(callback, arg)); + if (!callback) { + return onSync(Ledger::OnSyncFunction()); + } + return onSync([callback, arg](Ledger ledger) { + callback(std::move(ledger), arg); + }); } int Ledger::onSync(OnSyncFunction callback) {