AK: Enable direct comparsion of Optional<T> and T

This patch introduces a new operator== to compare an Optional to its
contained type directly. If the Optional does not contain a value, the
comparison will always return false.

This also adds a test case for the new behavior as well as comparison
between Optional objects themselves.
This commit is contained in:
Max Wipfli 2021-06-01 10:12:53 +02:00 committed by Andreas Kling
parent 12a42edd13
commit f3fda59abd
2 changed files with 49 additions and 0 deletions

View file

@ -100,6 +100,12 @@ public:
return has_value() == other.has_value() && (!has_value() || value() == other.value());
}
template<typename O>
ALWAYS_INLINE bool operator==(O const& other) const
{
return has_value() && value() == other;
}
ALWAYS_INLINE ~Optional()
{
clear();

View file

@ -53,3 +53,46 @@ TEST_CASE(short_notation)
EXPECT_EQ(value->length(), 3u);
EXPECT_EQ(*value, "foo");
}
TEST_CASE(comparison_without_values)
{
Optional<StringView> opt0;
Optional<StringView> opt1;
Optional<String> opt2;
EXPECT_EQ(opt0, opt1);
EXPECT_EQ(opt0, opt2);
}
TEST_CASE(comparison_with_values)
{
Optional<StringView> opt0;
Optional<StringView> opt1 = "foo";
Optional<String> opt2 = "foo";
Optional<StringView> opt3 = "bar";
EXPECT_NE(opt0, opt1);
EXPECT_EQ(opt1, opt2);
EXPECT_NE(opt1, opt3);
}
TEST_CASE(comparison_to_underlying_types)
{
Optional<String> opt0;
EXPECT_NE(opt0, String());
EXPECT_NE(opt0, "foo");
Optional<StringView> opt1 = "foo";
EXPECT_EQ(opt1, "foo");
EXPECT_NE(opt1, "bar");
EXPECT_EQ(opt1, String("foo"));
}
TEST_CASE(comparison_with_numeric_types)
{
Optional<u8> opt0;
EXPECT_NE(opt0, 0);
Optional<u8> opt1 = 7;
EXPECT_EQ(opt1, 7);
EXPECT_EQ(opt1, 7.0);
EXPECT_EQ(opt1, 7u);
EXPECT_NE(opt1, -2);
}