diff options
author | Ali Mohammad Pur <ali.mpfard@gmail.com> | 2021-06-08 17:54:06 +0430 |
---|---|---|
committer | Andreas Kling <kling@serenityos.org> | 2021-06-08 19:14:24 +0200 |
commit | 3d94b5051d8a783858cde04eb4d2e1ecf63ac180 (patch) | |
tree | b5248245957e652408beba570bfe8dd248d0d5da /Tests/AK | |
parent | 48195b7c30c30c17b34666657475eb0c9d24ed2d (diff) | |
download | serenity-3d94b5051d8a783858cde04eb4d2e1ecf63ac180.zip |
AK: Make Vector capable of holding reference types
This commit makes it possible to instantiate `Vector<T&>` and use it
to store references to `T` in a vector.
All non-pointer observers are made to return the reference, and the
pointer observers simply yield the underlying pointer.
Note that the 'find_*' methods act on the values and not the pointers
that are stored in the vector.
This commit also makes errors in various vector methods much more
readable by directly using requires-clauses on them.
And finally, it should be noted that Vector cannot hold temporaries :^)
Diffstat (limited to 'Tests/AK')
-rw-r--r-- | Tests/AK/TestVector.cpp | 71 |
1 files changed, 71 insertions, 0 deletions
diff --git a/Tests/AK/TestVector.cpp b/Tests/AK/TestVector.cpp index 673838a368..bbae27fa56 100644 --- a/Tests/AK/TestVector.cpp +++ b/Tests/AK/TestVector.cpp @@ -439,3 +439,74 @@ TEST_CASE(should_not_contain_present_not_in_range) EXPECT(!v.contains_in_range(2, 2, 4)); } + +TEST_CASE(can_store_references) +{ + int my_integer = 42; + Vector<int&> references; + references.append(my_integer); + references.prepend(my_integer); + EXPECT_EQ(&references.first(), &references.last()); + + { + Vector<int&> other_references; + other_references.append(references); + EXPECT_EQ(&other_references.first(), &my_integer); + } + + { + Vector<int&> other_references; + other_references = references; + EXPECT_EQ(&other_references.first(), &my_integer); + } + + { + auto it = references.find(my_integer); + EXPECT(!it.is_end()); + EXPECT_EQ(*it, my_integer); + } + + { + int other_integer = 42; + auto index = references.find_first_index(other_integer); + EXPECT(index.has_value()); + EXPECT_EQ(index.value_or(99999u), 0u); + } + + { + auto integer = 42; + EXPECT(references.contains_slow(integer)); + } + + { + references.remove(0); + references.ensure_capacity(10); + EXPECT_EQ(&references.take_first(), &my_integer); + } +} + +TEST_CASE(reference_deletion_should_not_affect_object) +{ + size_t times_deleted = 0; + struct DeleteCounter { + explicit DeleteCounter(size_t& deleted) + : deleted(deleted) + { + } + + ~DeleteCounter() + { + ++deleted; + } + + size_t& deleted; + }; + + { + DeleteCounter counter { times_deleted }; + Vector<DeleteCounter&> references; + for (size_t i = 0; i < 16; ++i) + references.append(counter); + } + EXPECT_EQ(times_deleted, 1u); +} |