diff --git a/AK/Tests/TestVector.cpp b/AK/Tests/TestVector.cpp index ad281d3b0c..ea5f7a9526 100644 --- a/AK/Tests/TestVector.cpp +++ b/AK/Tests/TestVector.cpp @@ -65,4 +65,37 @@ TEST_CASE(strings_insert_ordered) EXPECT_EQ(strings[3], "ghi"); } +TEST_CASE(prepend_vector) +{ + Vector ints; + ints.append(1); + ints.append(2); + ints.append(3); + + Vector more_ints; + more_ints.append(4); + more_ints.append(5); + more_ints.append(6); + + ints.prepend(move(more_ints)); + + EXPECT_EQ(ints.size(), 6); + EXPECT_EQ(more_ints.size(), 0); + + EXPECT_EQ(ints[0], 4); + EXPECT_EQ(ints[1], 5); + EXPECT_EQ(ints[2], 6); + EXPECT_EQ(ints[3], 1); + EXPECT_EQ(ints[4], 2); + EXPECT_EQ(ints[5], 3); + + ints.prepend(move(more_ints)); + EXPECT_EQ(ints.size(), 6); + EXPECT_EQ(more_ints.size(), 0); + + more_ints.prepend(move(ints)); + EXPECT_EQ(more_ints.size(), 6); + EXPECT_EQ(ints.size(), 0); +} + TEST_MAIN(Vector) diff --git a/AK/Vector.h b/AK/Vector.h index 09568a9adc..f8e85cb197 100644 --- a/AK/Vector.h +++ b/AK/Vector.h @@ -349,6 +349,31 @@ public: ++m_size; } + void prepend(Vector&& other) + { + if (other.is_empty()) + return; + + if (is_empty()) { + *this = move(other); + return; + } + + auto other_size = other.size(); + grow_capacity(size() + other_size); + + for (int i = size() + other_size - 1; i > other.size(); --i) { + new (slot(i)) T(move(at(i - other_size))); + at(i - other_size).~T(); + } + + Vector tmp = move(other); + for (int i = 0; i < tmp.size(); ++i) + new (slot(i)) T(move(tmp.at(i))); + + m_size += other_size; + } + void append(const T* values, int count) { if (!count)