Skip to content

Commit

Permalink
adding support for Lambda that returns a CHIP_ERROR to LambdaBridge
Browse files Browse the repository at this point in the history
  • Loading branch information
Alami-Amine committed Sep 25, 2024
1 parent d9f7861 commit 0ba09e4
Showing 1 changed file with 26 additions and 3 deletions.
29 changes: 26 additions & 3 deletions src/lib/support/LambdaBridge.h
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,38 @@ class LambdaBridge
static_assert(CHIP_CONFIG_LAMBDA_EVENT_ALIGN % alignof(Lambda) == 0, "lambda align too large");

// Implicit cast a capture-less lambda into a raw function pointer.
mLambdaProxy = [](const LambdaStorage & body) { (*reinterpret_cast<const Lambda *>(&body))(); };
if constexpr (std::is_same_v<decltype(lambda()), void>)
{
mLambdaVoidProxy = [](const LambdaStorage & body) { (*reinterpret_cast<const Lambda *>(&body))(); };
}
else if constexpr (std::is_same_v<decltype(lambda()), CHIP_ERROR>)
{
mLambdaProxy = [](const LambdaStorage & body) { return (*reinterpret_cast<const Lambda *>(&body))(); };
}

::memcpy(&mLambdaBody, &lambda, sizeof(Lambda));
}

void operator()() const { mLambdaProxy(mLambdaBody); }
void operator()() const
{
if (mLambdaVoidProxy != nullptr)
{
mLambdaVoidProxy(mLambdaBody);
}
}
CHIP_ERROR CallLambdaWithErrorReturn() const
{
if (mLambdaProxy != nullptr)
{
return mLambdaProxy(mLambdaBody);
}
return CHIP_ERROR_INTERNAL; // Return an error if the proxy is not for CHIP_ERROR
}

private:
using LambdaStorage = std::aligned_storage_t<CHIP_CONFIG_LAMBDA_EVENT_SIZE, CHIP_CONFIG_LAMBDA_EVENT_ALIGN>;
void (*mLambdaProxy)(const LambdaStorage & body);
void (*mLambdaVoidProxy)(const LambdaStorage & body);
CHIP_ERROR (*mLambdaProxy)(const LambdaStorage & body);
LambdaStorage mLambdaBody;
};

Expand Down

0 comments on commit 0ba09e4

Please sign in to comment.