blocks.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // ArduinoJson - arduinojson.org
  2. // Copyright Benoit Blanchon 2014-2018
  3. // MIT License
  4. #include <ArduinoJson/Memory/DynamicMemoryPool.hpp>
  5. #include <catch.hpp>
  6. #include <sstream>
  7. using namespace ARDUINOJSON_NAMESPACE;
  8. std::stringstream allocatorLog;
  9. struct SpyingAllocator : DefaultAllocator {
  10. void* allocate(size_t n) {
  11. allocatorLog << "A" << (n - DynamicMemoryPool::EmptyBlockSize);
  12. return DefaultAllocator::allocate(n);
  13. }
  14. void deallocate(void* p) {
  15. allocatorLog << "F";
  16. return DefaultAllocator::deallocate(p);
  17. }
  18. };
  19. TEST_CASE("DynamicMemoryPool blocks") {
  20. SECTION("Doubles allocation size when full") {
  21. allocatorLog.str("");
  22. {
  23. DynamicMemoryPoolBase<SpyingAllocator> memoryPool(sizeof(VariantSlot));
  24. memoryPool.allocVariant();
  25. memoryPool.allocVariant();
  26. }
  27. std::stringstream expected;
  28. expected << "A" << sizeof(VariantSlot) // block 1
  29. << "A" << 2 * sizeof(VariantSlot) // block 2, twice bigger
  30. << "FF";
  31. REQUIRE(allocatorLog.str() == expected.str());
  32. }
  33. SECTION("Resets allocation size after clear()") {
  34. allocatorLog.str("");
  35. {
  36. DynamicMemoryPoolBase<SpyingAllocator> memoryPool(sizeof(VariantSlot));
  37. memoryPool.allocVariant();
  38. memoryPool.allocVariant();
  39. memoryPool.clear();
  40. memoryPool.allocVariant();
  41. }
  42. std::stringstream expected;
  43. expected << "A" << sizeof(VariantSlot) // block 1
  44. << "A" << 2 * sizeof(VariantSlot) // block 2, twice bigger
  45. << "FF" // clear
  46. << "A" << sizeof(VariantSlot) // block 1
  47. << "F";
  48. REQUIRE(allocatorLog.str() == expected.str());
  49. }
  50. /* SECTION("Alloc big block for large string") {
  51. allocatorLog.str("");
  52. {
  53. DynamicMemoryPoolBase<SpyingAllocator> memoryPool(1);
  54. memoryPool.allocString(42);
  55. }
  56. std::stringstream expected;
  57. expected << "A" << JSON_STRING_SIZE(42) // block 1
  58. << "F";
  59. REQUIRE(allocatorLog.str() == expected.str());
  60. }*/
  61. }