saveString.cpp 1.9 KB

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