swap.cpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // ArduinoJson - https://arduinojson.org
  2. // Copyright © 2014-2025, Benoit BLANCHON
  3. // MIT License
  4. #include <ArduinoJson/Memory/Alignment.hpp>
  5. #include <ArduinoJson/Memory/ResourceManager.hpp>
  6. #include <ArduinoJson/Memory/ResourceManagerImpl.hpp>
  7. #include <catch.hpp>
  8. #include "Allocators.hpp"
  9. using namespace ArduinoJson::detail;
  10. static void fullPreallocatedPools(ResourceManager& resources) {
  11. for (int i = 0;
  12. i < ARDUINOJSON_INITIAL_POOL_COUNT * ARDUINOJSON_POOL_CAPACITY; i++)
  13. resources.allocVariant();
  14. }
  15. TEST_CASE("ResourceManager::swap()") {
  16. SECTION("Both using preallocated pool list") {
  17. SpyingAllocator spy;
  18. ResourceManager a(&spy);
  19. ResourceManager b(&spy);
  20. auto a1 = a.allocVariant();
  21. auto b1 = b.allocVariant();
  22. swap(a, b);
  23. REQUIRE(a1.ptr() == b.getVariant(a1.id()));
  24. REQUIRE(b1.ptr() == a.getVariant(b1.id()));
  25. REQUIRE(spy.log() == AllocatorLog{
  26. Allocate(sizeofPool()) * 2,
  27. });
  28. }
  29. SECTION("Only left using preallocated pool list") {
  30. SpyingAllocator spy;
  31. ResourceManager a(&spy);
  32. ResourceManager b(&spy);
  33. fullPreallocatedPools(b);
  34. auto a1 = a.allocVariant();
  35. auto b1 = b.allocVariant();
  36. swap(a, b);
  37. REQUIRE(a1.ptr() == b.getVariant(a1.id()));
  38. REQUIRE(b1.ptr() == a.getVariant(b1.id()));
  39. REQUIRE(spy.log() ==
  40. AllocatorLog{
  41. Allocate(sizeofPool()) * (ARDUINOJSON_INITIAL_POOL_COUNT + 1),
  42. Allocate(sizeofPoolList(ARDUINOJSON_INITIAL_POOL_COUNT * 2)),
  43. Allocate(sizeofPool()),
  44. });
  45. }
  46. SECTION("Only right using preallocated pool list") {
  47. SpyingAllocator spy;
  48. ResourceManager a(&spy);
  49. fullPreallocatedPools(a);
  50. ResourceManager b(&spy);
  51. auto a1 = a.allocVariant();
  52. auto b1 = b.allocVariant();
  53. swap(a, b);
  54. REQUIRE(a1.ptr() == b.getVariant(a1.id()));
  55. REQUIRE(b1.ptr() == a.getVariant(b1.id()));
  56. REQUIRE(spy.log() ==
  57. AllocatorLog{
  58. Allocate(sizeofPool()) * ARDUINOJSON_INITIAL_POOL_COUNT,
  59. Allocate(sizeofPoolList(ARDUINOJSON_INITIAL_POOL_COUNT * 2)),
  60. Allocate(sizeofPool()) * 2,
  61. });
  62. }
  63. SECTION("None is using preallocated pool list") {
  64. SpyingAllocator spy;
  65. ResourceManager a(&spy);
  66. fullPreallocatedPools(a);
  67. ResourceManager b(&spy);
  68. fullPreallocatedPools(b);
  69. auto a1 = a.allocVariant();
  70. auto b1 = b.allocVariant();
  71. swap(a, b);
  72. REQUIRE(a1.ptr() == b.getVariant(a1.id()));
  73. REQUIRE(b1.ptr() == a.getVariant(b1.id()));
  74. }
  75. }