Skip to content

Commit

Permalink
Allow clearing of state storage.
Browse files Browse the repository at this point in the history
  • Loading branch information
tmadden committed Sep 9, 2020
1 parent a1f784c commit e30b654
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 10 deletions.
52 changes: 44 additions & 8 deletions src/alia/signals/state.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ struct state_storage
bool
is_initialized() const
{
return version_ != 0;
return (version_ & 1) != 0;
}

Value const&
Expand All @@ -45,7 +45,15 @@ struct state_storage
set(Value value)
{
value_ = std::move(value);
handle_change();
set_valid_flag();
handle_tracked_change();
}

void
clear()
{
clear_valid_flag();
handle_tracked_change();
}

// If you REALLY need direct, non-const access to the underlying state,
Expand All @@ -64,7 +72,8 @@ struct state_storage
Value&
nonconst_ref()
{
handle_change();
set_valid_flag();
handle_tracked_change();
return value_;
}

Expand All @@ -74,10 +83,19 @@ struct state_storage
Value&
untracked_nonconst_ref()
{
++version_;
set_valid_flag();
inc_version();
return value_;
}

// Similarly unsafe way to clear the value.
void
untracked_clear()
{
clear_valid_flag();
inc_version();
}

// Update the container that the state is part of.
void
refresh_container(component_container_ptr const& container)
Expand All @@ -87,15 +105,33 @@ struct state_storage

private:
void
handle_change()
set_valid_flag()
{
version_ |= 1;
}

void
clear_valid_flag()
{
version_ &= ~1;
}

void
inc_version()
{
version_ += 2;
}

void
handle_tracked_change()
{
++version_;
inc_version();
mark_dirty_component(container_);
}

Value value_;
// version_ is incremented for each change in the value of the state.
// If this is 0, the state is considered uninitialized.
// version_ is incremented for each change in the value (or validity) of
// the state. The lowest bit of this indicates if the value is valid.
unsigned version_;
component_container_ptr container_;
};
Expand Down
14 changes: 12 additions & 2 deletions unit_tests/signals/state.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,24 @@ TEST_CASE("state_storage", "[signals][state]")
state_storage<int> s;
REQUIRE(!s.is_initialized());
REQUIRE(s.version() == 0);
unsigned version = 0;

s.set(1);
REQUIRE(s.is_initialized());
REQUIRE(s.version() == 1);
REQUIRE(s.version() != 0);
version = s.version();
REQUIRE(s.get() == 1);

s.nonconst_ref() = 4;
REQUIRE(s.is_initialized());
REQUIRE(s.version() == 2);
REQUIRE(s.version() != version);
version = s.version();
REQUIRE(s.get() == 4);

s.clear();
REQUIRE(!s.is_initialized());
REQUIRE(s.version() != version);
version = s.version();
}

TEST_CASE("basic get_state", "[signals][state]")
Expand Down

0 comments on commit e30b654

Please sign in to comment.