clear.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // ArduinoJson - arduinojson.org
  2. // Copyright Benoit Blanchon 2014-2018
  3. // MIT License
  4. #include <ArduinoJson/Memory/MemoryPool.hpp>
  5. #include <catch.hpp>
  6. using namespace ARDUINOJSON_NAMESPACE;
  7. static const size_t poolCapacity = 512;
  8. TEST_CASE("MemoryPool::clear()") {
  9. char buffer[poolCapacity];
  10. MemoryPool memoryPool(buffer, sizeof(buffer));
  11. SECTION("Discards allocated variants") {
  12. memoryPool.allocVariant();
  13. memoryPool.clear();
  14. REQUIRE(memoryPool.size() == 0);
  15. }
  16. SECTION("Discards allocated strings") {
  17. memoryPool.allocFrozenString(10);
  18. REQUIRE(memoryPool.size() > 0);
  19. memoryPool.clear();
  20. REQUIRE(memoryPool.size() == 0);
  21. }
  22. SECTION("Purges variant cache") {
  23. VariantSlot* a = memoryPool.allocVariant();
  24. REQUIRE(a != 0);
  25. VariantSlot* b = memoryPool.allocVariant();
  26. REQUIRE(b != 0);
  27. // place slot a in the pool of free slots
  28. memoryPool.freeVariant(a);
  29. memoryPool.clear();
  30. REQUIRE(memoryPool.size() == 0);
  31. }
  32. SECTION("Purges string cache") {
  33. StringSlot* a = memoryPool.allocFrozenString(10);
  34. REQUIRE(a != 0);
  35. StringSlot* b = memoryPool.allocFrozenString(10);
  36. REQUIRE(b != 0);
  37. // place slot a in the pool of free slots
  38. memoryPool.freeString(a);
  39. memoryPool.clear();
  40. REQUIRE(memoryPool.size() == 0);
  41. }
  42. SECTION("Purges list of string") {
  43. StringSlot* a = memoryPool.allocFrozenString(6);
  44. REQUIRE(a != 0);
  45. strcpy(a->value, "hello");
  46. StringSlot* b = memoryPool.allocFrozenString(6);
  47. REQUIRE(b != 0);
  48. strcpy(b->value, "world");
  49. memoryPool.clear(); // ACT!
  50. StringSlot* c = memoryPool.allocFrozenString(2);
  51. REQUIRE(c != 0);
  52. strcpy(c->value, "H");
  53. StringSlot* d = memoryPool.allocFrozenString(2);
  54. REQUIRE(d != 0);
  55. strcpy(d->value, "W");
  56. // if the memory pool keeps pointer to the old strings
  57. // it will try to compact the strings
  58. memoryPool.freeString(c);
  59. REQUIRE(d->value == std::string("W"));
  60. }
  61. }