tables: Adjust pre-allocated CS entry queue on Cs::setLimit call

Change-Id: I7611dfb671060864e40cadb707ad0a89f0359c07
Fixes: #1646
diff --git a/daemon/table/cs.cpp b/daemon/table/cs.cpp
index 80312c8..f750b61 100644
--- a/daemon/table/cs.cpp
+++ b/daemon/table/cs.cpp
@@ -71,13 +71,24 @@
 void
 Cs::setLimit(size_t nMaxPackets)
 {
+  size_t oldNMaxPackets = m_nMaxPackets;
   m_nMaxPackets = nMaxPackets;
 
-  while (isFull())
-    {
-      if (!evictItem())
-        break;
+  while (size() > m_nMaxPackets) {
+    evictItem();
+  }
+
+  if (m_nMaxPackets >= oldNMaxPackets) {
+    for (size_t i = oldNMaxPackets; i < m_nMaxPackets; i++) {
+      m_freeCsEntries.push(new cs::Entry());
     }
+  }
+  else {
+    for (size_t i = oldNMaxPackets; i > m_nMaxPackets; i--) {
+      delete m_freeCsEntries.front();
+      m_freeCsEntries.pop();
+    }
+  }
 }
 
 size_t
diff --git a/tests/daemon/table/cs.cpp b/tests/daemon/table/cs.cpp
index cdcc0db..3e41781 100644
--- a/tests/daemon/table/cs.cpp
+++ b/tests/daemon/table/cs.cpp
@@ -44,6 +44,24 @@
 
 BOOST_FIXTURE_TEST_SUITE(TableCs, BaseFixture)
 
+BOOST_AUTO_TEST_CASE(SetLimit)
+{
+  Cs cs(1);
+
+  BOOST_CHECK_EQUAL(cs.insert(*makeData("/1")), true);
+  BOOST_CHECK_EQUAL(cs.insert(*makeData("/2")), true);
+  BOOST_CHECK_EQUAL(cs.size(), 1);
+
+  cs.setLimit(3);
+  BOOST_CHECK_EQUAL(cs.insert(*makeData("/3")), true);
+  BOOST_CHECK_EQUAL(cs.insert(*makeData("/4")), true);
+  BOOST_CHECK_EQUAL(cs.insert(*makeData("/5")), true);
+  BOOST_CHECK_EQUAL(cs.size(), 3);
+
+  cs.setLimit(2);
+  BOOST_CHECK_EQUAL(cs.size(), 2);
+}
+
 BOOST_AUTO_TEST_CASE(Insertion)
 {
   Cs cs;