Browse Source

base: fix Array::Insert to avoid copying the whole array and add a unit test.

undefined
Sam Hocevar 10 years ago
parent
commit
90786652e8
2 changed files with 38 additions and 8 deletions
  1. +14
    -8
      src/lol/base/array.h
  2. +24
    -0
      test/unit/array.cpp

+ 14
- 8
src/lol/base/array.h View File

@@ -193,12 +193,13 @@ public:
{ {
T tmp = x; T tmp = x;
Reserve(m_count * 13 / 8 + 8); Reserve(m_count * 13 / 8 + 8);
new (&m_data[m_count++]) Element(tmp);
new (&m_data[m_count]) Element(tmp);
} }
else else
{ {
new (&m_data[m_count++]) Element(x);
new (&m_data[m_count]) Element(x);
} }
++m_count;
return *this; return *this;
} }


@@ -246,14 +247,19 @@ public:


inline void Insert(T const &x, int pos) inline void Insert(T const &x, int pos)
{ {
ArrayBase<T, ARRAY> tmp;
for (int i = 0; i < m_count; i++)
ASSERT(pos >= 0);
ASSERT(pos <= m_count);

if (m_count >= m_reserved)
Reserve(m_count * 13 / 8 + 8);

for (int i = m_count; i > pos; --i)
{ {
if (i == pos)
tmp.Push(x);
tmp.Push(m_data[i]);
new (&m_data[i]) Element(m_data[i - 1]);
m_data[i - 1].~Element();
} }
*this = tmp;
new (&m_data[pos]) Element(x);
++m_count;
} }


inline int Find(T const &x) inline int Find(T const &x)


+ 24
- 0
test/unit/array.cpp View File

@@ -147,6 +147,30 @@ LOLUNIT_FIXTURE(ArrayTest)
LOLUNIT_ASSERT_EQUAL(20, a[1].m2); LOLUNIT_ASSERT_EQUAL(20, a[1].m2);
} }


LOLUNIT_TEST(ArrayInsert)
{
Array<int> a;
a << 1 << 2;

a.Insert(5, 0);
LOLUNIT_ASSERT_EQUAL(5, a[0]);
LOLUNIT_ASSERT_EQUAL(1, a[1]);
LOLUNIT_ASSERT_EQUAL(2, a[2]);

a.Insert(6, 3);
LOLUNIT_ASSERT_EQUAL(5, a[0]);
LOLUNIT_ASSERT_EQUAL(1, a[1]);
LOLUNIT_ASSERT_EQUAL(2, a[2]);
LOLUNIT_ASSERT_EQUAL(6, a[3]);

a.Insert(7, 2);
LOLUNIT_ASSERT_EQUAL(5, a[0]);
LOLUNIT_ASSERT_EQUAL(1, a[1]);
LOLUNIT_ASSERT_EQUAL(7, a[2]);
LOLUNIT_ASSERT_EQUAL(2, a[3]);
LOLUNIT_ASSERT_EQUAL(6, a[4]);
}

LOLUNIT_TEST(ArrayConcat) LOLUNIT_TEST(ArrayConcat)
{ {
Array<int> a, b; Array<int> a, b;


Loading…
Cancel
Save