Skip to content

Commit

Permalink
Merge pull request #608 from elbeno/fix-handler-short-circuit
Browse files Browse the repository at this point in the history
🐛 Fix handler short-circuiting
  • Loading branch information
lukevalenty authored Aug 30, 2024
2 parents 3a04050 + 253b163 commit 84d426e
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
6 changes: 4 additions & 2 deletions include/msg/handler.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,10 @@ struct handler : handler_interface<BaseMsg, ExtraCallbackArgs...> {

auto handle(BaseMsg const &msg,
ExtraCallbackArgs... args) const -> bool final {
bool const found_valid_callback = stdx::any_of(
[&](auto &callback) { return callback.handle(msg, args...); },
auto const found_valid_callback = stdx::apply(
[&](auto &...cbs) -> bool {
return (0u | ... | cbs.handle(msg, args...));
},
callbacks);
if (!found_valid_callback) {
CIB_ERROR("None of the registered callbacks claimed this message:");
Expand Down
21 changes: 20 additions & 1 deletion test/msg/handler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ TEST_CASE("log mismatch when no match", "[handler]") {

TEST_CASE("match and dispatch only one callback", "[handler]") {
auto callback1 = msg::callback<"cb1", msg_defn>(
id_match<0x80>, [&](msg::const_view<msg_defn>) { CHECK(false); });
id_match<0x80>, [](msg::const_view<msg_defn>) { CHECK(false); });
auto callback2 = msg::callback<"cb2", msg_defn>(
id_match<0x44>, [](msg::const_view<msg_defn>) { dispatched = true; });
auto const msg = std::array{0x4400ba11u, 0x0042d00du};
Expand All @@ -107,6 +107,25 @@ TEST_CASE("match and dispatch only one callback", "[handler]") {
CHECK(dispatched);
}

TEST_CASE("dispatch all callbacks that match", "[handler]") {
int count{};

auto callback1 = msg::callback<"cb1", msg_defn>(
id_match<0x80>, [](msg::const_view<msg_defn>) { CHECK(false); });
auto callback2 = msg::callback<"cb2", msg_defn>(
id_match<0x44>, [&](msg::const_view<msg_defn>) { ++count; });
auto callback3 = msg::callback<"cb3", msg_defn>(
id_match<0x44>, [&](msg::const_view<msg_defn>) { ++count; });
auto const msg = std::array{0x4400ba11u, 0x0042d00du};

auto callbacks = stdx::make_tuple(callback1, callback2, callback3);
static auto handler =
msg::handler<decltype(callbacks), decltype(msg)>{callbacks};

CHECK(handler.handle(msg));
CHECK(count == 2);
}

namespace {
template <typename T>
using uint8_view =
Expand Down

0 comments on commit 84d426e

Please sign in to comment.