mirror of
https://github.com/LadybirdBrowser/ladybird.git
synced 2024-11-21 23:20:20 +00:00
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:
parent
12a42edd13
commit
f3fda59abd
Notes:
sideshowbarker
2024-07-18 17:03:25 +09:00
Author: https://github.com/MaxWipfli Commit: https://github.com/SerenityOS/serenity/commit/f3fda59abd4 Pull-request: https://github.com/SerenityOS/serenity/pull/7656
2 changed files with 49 additions and 0 deletions
|
@ -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();
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue