allocVariant.cpp 2.4 KB

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