diff --git a/src/lol/base/array.h b/src/lol/base/array.h index b60f066b..9fd90427 100644 --- a/src/lol/base/array.h +++ b/src/lol/base/array.h @@ -187,9 +187,12 @@ public: void Remove(int pos, int todelete = 1) { - ASSERT(pos >= 0); ASSERT(todelete >= 0); + ASSERT(pos - todelete >= -m_count - 1); ASSERT(pos + todelete <= m_count); + if (pos < 0) + pos = m_count + pos; + for (int i = pos; i + todelete < m_count; i++) m_data[i] = m_data[i + todelete]; for (int i = m_count - todelete; i < m_count; i++) @@ -197,6 +200,23 @@ public: m_count -= todelete; } + void RemoveSwap(int pos, int todelete = 1) + { + ASSERT(todelete >= 0); + ASSERT(pos - todelete >= -m_count - 1); + ASSERT(pos + todelete <= m_count); + if (pos < 0) + pos = m_count + pos; + + for (int i = 0; i < todelete; i++) + { + if (pos + i < m_count - 1 - i) + m_data[pos + i] = m_data[m_count - 1 - i]; + m_data[m_count - 1 - i].~Element(); + } + m_count -= todelete; + } + void Resize(int count, Element e = Element()) { ASSERT(count > 0); diff --git a/test/unit/array.cpp b/test/unit/array.cpp index f71bf0bf..91067f89 100644 --- a/test/unit/array.cpp +++ b/test/unit/array.cpp @@ -83,9 +83,39 @@ LOLUNIT_FIXTURE(ArrayTest) a << 0 << 1 << 2 << 3; a.Remove(1); + LOLUNIT_ASSERT_EQUAL(a.Count(), 3); LOLUNIT_ASSERT_EQUAL(a[0], 0); LOLUNIT_ASSERT_EQUAL(a[1], 2); LOLUNIT_ASSERT_EQUAL(a[2], 3); + + Array b; + b << 0 << 1 << 2 << 3; + b.Remove(-2); + + LOLUNIT_ASSERT_EQUAL(b.Count(), 3); + LOLUNIT_ASSERT_EQUAL(b[0], 0); + LOLUNIT_ASSERT_EQUAL(b[1], 1); + LOLUNIT_ASSERT_EQUAL(b[2], 3); + } + + LOLUNIT_TEST(ArrayRemoveSwap) + { + Array a; + a << 0 << 1 << 2 << 3; + a.RemoveSwap(1); + + LOLUNIT_ASSERT_EQUAL(a.Count(), 3); + LOLUNIT_ASSERT_EQUAL(a[0], 0); + LOLUNIT_ASSERT_EQUAL(a[1], 3); + LOLUNIT_ASSERT_EQUAL(a[2], 2); + + Array b; + b << 0 << 1 << 2 << 3; + b.Remove(1, 2); + + LOLUNIT_ASSERT_EQUAL(b.Count(), 2); + LOLUNIT_ASSERT_EQUAL(b[0], 0); + LOLUNIT_ASSERT_EQUAL(b[1], 3); } #endif