saveString.cpp 2.1 KB

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