Skip to content

Commit

Permalink
NamedType: validate in ++ and --
Browse files Browse the repository at this point in the history
the mess here is to make sure that the new value is valid without
changing the old value, to make sure that the value stays valid even when
an exception is thrown

fixes #192
  • Loading branch information
tomjnixon committed Jan 16, 2024
1 parent 4bce7c5 commit 01685d6
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
10 changes: 8 additions & 2 deletions include/adm/detail/named_type.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,10 @@ namespace adm {
}

NamedType<T, Tag, Validator>& operator++() {
++value_;
T tmp = value_;
tmp++;
Validator::validate(tmp);
value_ = std::move(tmp);
return *this;
}

Expand All @@ -123,7 +126,10 @@ namespace adm {
}

NamedType<T, Tag, Validator>& operator--() {
--value_;
T tmp = value_;
tmp--;
Validator::validate(tmp);
value_ = std::move(tmp);
return *this;
}

Expand Down
10 changes: 10 additions & 0 deletions tests/named_type_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,16 @@ TEST_CASE("NamedType_range_check") {
NamedIntegerRange goodValue(5);
REQUIRE_THROWS_AS(NamedIntegerRange(12), OutOfRangeError);
REQUIRE_THROWS_AS(NamedIntegerRange(-1), OutOfRangeError);

NamedIntegerRange lower_limit(0);
REQUIRE_THROWS_AS(lower_limit--, OutOfRangeError);
REQUIRE_THROWS_AS(--lower_limit, OutOfRangeError);
REQUIRE(lower_limit == 0);

NamedIntegerRange upper_limit(10);
REQUIRE_THROWS_AS(upper_limit++, OutOfRangeError);
REQUIRE_THROWS_AS(++upper_limit, OutOfRangeError);
REQUIRE(upper_limit == 10);
}

TEST_CASE("screen_edge_validator") {
Expand Down

0 comments on commit 01685d6

Please sign in to comment.