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