saveString.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // ArduinoJson - https://arduinojson.org
  2. // Copyright © 2014-2024, Benoit BLANCHON
  3. // MIT License
  4. #include <ArduinoJson/Memory/ResourceManager.hpp>
  5. #include <ArduinoJson/Memory/VariantPoolImpl.hpp>
  6. #include <ArduinoJson/Strings/StringAdapters.hpp>
  7. #include <catch.hpp>
  8. #include "Allocators.hpp"
  9. using namespace ArduinoJson::detail;
  10. static StringNode* saveString(ResourceManager& resources, const char* s) {
  11. return resources.saveString(adaptString(s));
  12. }
  13. static StringNode* saveString(ResourceManager& resources, const char* s,
  14. size_t n) {
  15. return resources.saveString(adaptString(s, n));
  16. }
  17. TEST_CASE("ResourceManager::saveString()") {
  18. ResourceManager resources;
  19. SECTION("Duplicates different strings") {
  20. auto a = saveString(resources, "hello");
  21. auto b = saveString(resources, "world");
  22. REQUIRE(+a->data != +b->data);
  23. REQUIRE(a->length == 5);
  24. REQUIRE(b->length == 5);
  25. REQUIRE(a->references == 1);
  26. REQUIRE(b->references == 1);
  27. REQUIRE(resources.size() == sizeofString("hello") + sizeofString("world"));
  28. }
  29. SECTION("Deduplicates identical strings") {
  30. auto a = saveString(resources, "hello");
  31. auto b = saveString(resources, "hello");
  32. REQUIRE(a == b);
  33. REQUIRE(a->length == 5);
  34. REQUIRE(a->references == 2);
  35. REQUIRE(resources.size() == sizeofString("hello"));
  36. }
  37. SECTION("Deduplicates identical strings that contain NUL") {
  38. auto a = saveString(resources, "hello\0world", 11);
  39. auto b = saveString(resources, "hello\0world", 11);
  40. REQUIRE(a == b);
  41. REQUIRE(a->length == 11);
  42. REQUIRE(a->references == 2);
  43. REQUIRE(resources.size() == sizeofString("hello world"));
  44. }
  45. SECTION("Don't stop on first NUL") {
  46. auto a = saveString(resources, "hello");
  47. auto b = saveString(resources, "hello\0world", 11);
  48. REQUIRE(a != b);
  49. REQUIRE(a->length == 5);
  50. REQUIRE(b->length == 11);
  51. REQUIRE(a->references == 1);
  52. REQUIRE(b->references == 1);
  53. REQUIRE(resources.size() ==
  54. sizeofString("hello") + sizeofString("hello world"));
  55. }
  56. SECTION("Returns NULL when allocation fails") {
  57. ResourceManager pool2(FailingAllocator::instance());
  58. REQUIRE(saveString(pool2, "a") == nullptr);
  59. }
  60. }