Skip to content

Commit

Permalink
Add write actions.
Browse files Browse the repository at this point in the history
  • Loading branch information
tmadden committed Sep 24, 2020
1 parent 2cd14ac commit 2000a9f
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
35 changes: 35 additions & 0 deletions src/alia/flow/actions.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -467,6 +467,41 @@ actionize(Callable x)
return lambda_action(std::move(x));
}

// add_write_action(signal, on_write) wraps signal in a similar signal that
// will invoke on_write whenever the signal is written to. (on_write will be
// passed the value that was written to the signal.)
template<class Wrapped, class OnWrite>
struct write_action_signal
: signal_wrapper<write_action_signal<Wrapped, OnWrite>, Wrapped>
{
write_action_signal(Wrapped wrapped, OnWrite on_write)
: write_action_signal::signal_wrapper(std::move(wrapped)),
on_write_(std::move(on_write))
{
}
bool
ready_to_write() const
{
return this->wrapped_.ready_to_write() && on_write_.is_ready();
}
void
write(typename Wrapped::value_type value) const
{
perform_action(on_write_, value);
this->wrapped_.write(std::move(value));
}

private:
OnWrite on_write_;
};
template<class Wrapped, class OnWrite>
auto
add_write_action(Wrapped wrapped, OnWrite on_write)
{
return write_action_signal<Wrapped, OnWrite>(
std::move(wrapped), std::move(on_write));
}

} // namespace alia

#endif
30 changes: 30 additions & 0 deletions unit_tests/flow/actions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -293,3 +293,33 @@ TEST_CASE("actionize a lambda", "[flow][actions]")
perform_action(a);
REQUIRE(x == 1);
}

TEST_CASE("add_write_action", "[flow][actions]")
{
int x = 0;
bool written = false;
auto s = add_write_action(
direct(x), lambda_action([&](int) { written = true; }));

typedef decltype(s) signal_t;
REQUIRE(signal_is_readable<signal_t>::value);
REQUIRE(signal_is_writable<signal_t>::value);

REQUIRE(written == false);
REQUIRE(signal_ready_to_write(s));
write_signal(s, 1);
REQUIRE(x == 1);
REQUIRE(written == true);
}

TEST_CASE("unready add_write_action", "[flow][actions]")
{
int x = 0;
auto s = add_write_action(direct(x), unready_action<int>());

typedef decltype(s) signal_t;
REQUIRE(signal_is_readable<signal_t>::value);
REQUIRE(signal_is_writable<signal_t>::value);

REQUIRE(!signal_ready_to_write(s));
}

0 comments on commit 2000a9f

Please sign in to comment.