allocVariant.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. // ArduinoJson - https://arduinojson.org
  2. // Copyright © 2014-2025, Benoit BLANCHON
  3. // MIT License
  4. #include <ArduinoJson.hpp>
  5. #include <catch.hpp>
  6. #include <ArduinoJson/Memory/Alignment.hpp>
  7. #include "Allocators.hpp"
  8. using namespace ArduinoJson::detail;
  9. TEST_CASE("ResourceManager::allocVariant()") {
  10. SECTION("Returns different pointer") {
  11. ResourceManager resources;
  12. auto s1 = resources.allocVariant();
  13. REQUIRE(s1.ptr() != nullptr);
  14. auto s2 = resources.allocVariant();
  15. REQUIRE(s2.ptr() != nullptr);
  16. REQUIRE(s1.ptr() != s2.ptr());
  17. }
  18. SECTION("Returns the same slot after calling freeVariant()") {
  19. ResourceManager resources;
  20. auto s1 = resources.allocVariant();
  21. auto s2 = resources.allocVariant();
  22. resources.freeVariant(s1);
  23. resources.freeVariant(s2);
  24. auto s3 = resources.allocVariant();
  25. auto s4 = resources.allocVariant();
  26. auto s5 = resources.allocVariant();
  27. REQUIRE(s2.id() != s1.id());
  28. REQUIRE(s3.id() == s2.id());
  29. REQUIRE(s4.id() == s1.id());
  30. REQUIRE(s5.id() != s1.id());
  31. REQUIRE(s5.id() != s2.id());
  32. }
  33. SECTION("Returns aligned pointers") {
  34. ResourceManager resources;
  35. REQUIRE(isAligned(resources.allocVariant().ptr()));
  36. REQUIRE(isAligned(resources.allocVariant().ptr()));
  37. }
  38. SECTION("Returns null if pool list allocation fails") {
  39. ResourceManager resources(FailingAllocator::instance());
  40. auto variant = resources.allocVariant();
  41. REQUIRE(variant.id() == NULL_SLOT);
  42. REQUIRE(variant.ptr() == nullptr);
  43. }
  44. SECTION("Returns null if pool allocation fails") {
  45. ResourceManager resources(FailingAllocator::instance());
  46. resources.allocVariant();
  47. auto variant = resources.allocVariant();
  48. REQUIRE(variant.id() == NULL_SLOT);
  49. REQUIRE(variant.ptr() == nullptr);
  50. }
  51. SECTION("Try overflow pool counter") {
  52. ResourceManager resources;
  53. // this test assumes SlotId is 8-bit; otherwise it consumes a lot of memory
  54. // tyhe GitHub Workflow gets killed
  55. REQUIRE(NULL_SLOT == 255);
  56. // fill all the pools
  57. for (SlotId i = 0; i < NULL_SLOT; i++) {
  58. auto slot = resources.allocVariant();
  59. REQUIRE(slot.id() == i); // or != NULL_SLOT
  60. REQUIRE(slot.ptr() != nullptr);
  61. }
  62. REQUIRE(resources.overflowed() == false);
  63. // now all allocations should fail
  64. for (int i = 0; i < 10; i++) {
  65. auto slot = resources.allocVariant();
  66. REQUIRE(slot.id() == NULL_SLOT);
  67. REQUIRE(slot.ptr() == nullptr);
  68. }
  69. REQUIRE(resources.overflowed() == true);
  70. }
  71. }