saveStaticString.cpp 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // ArduinoJson - https://arduinojson.org
  2. // Copyright © 2014-2025, Benoit BLANCHON
  3. // MIT License
  4. #include <ArduinoJson/Memory/ResourceManager.hpp>
  5. #include <ArduinoJson/Strings/StringAdapters.hpp>
  6. #include <catch.hpp>
  7. #include "Allocators.hpp"
  8. using namespace ArduinoJson::detail;
  9. TEST_CASE("ResourceManager::saveStaticString() deduplicates strings") {
  10. SpyingAllocator spy;
  11. ResourceManager resources(&spy);
  12. auto str1 = "hello";
  13. auto str2 = "world";
  14. auto id1 = resources.saveStaticString(str1);
  15. auto id2 = resources.saveStaticString(str2);
  16. REQUIRE(id1 != id2);
  17. auto id3 = resources.saveStaticString(str1);
  18. REQUIRE(id1 == id3);
  19. resources.shrinkToFit();
  20. REQUIRE(spy.log() ==
  21. AllocatorLog{
  22. Allocate(sizeofStaticStringPool()),
  23. Reallocate(sizeofStaticStringPool(), sizeofStaticStringPool(2)),
  24. });
  25. REQUIRE(resources.overflowed() == false);
  26. }
  27. TEST_CASE("ResourceManager::saveStaticString() when allocation fails") {
  28. SpyingAllocator spy(FailingAllocator::instance());
  29. ResourceManager resources(&spy);
  30. auto slotId = resources.saveStaticString("hello");
  31. REQUIRE(slotId == NULL_SLOT);
  32. REQUIRE(resources.overflowed() == true);
  33. REQUIRE(spy.log() == AllocatorLog{
  34. AllocateFail(sizeofStaticStringPool()),
  35. });
  36. }