saveString.cpp 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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 const char* saveString(MemoryPool& pool, const char* s) {
  10. return pool.saveString(adaptString(s));
  11. }
  12. static const char* 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. const char* a = saveString(pool, "hello");
  19. const char* b = saveString(pool, "world");
  20. REQUIRE(a != b);
  21. REQUIRE(pool.size() == 2 * sizeofString(5));
  22. }
  23. SECTION("Deduplicates identical strings") {
  24. const char* a = saveString(pool, "hello");
  25. const char* b = saveString(pool, "hello");
  26. REQUIRE(a == b);
  27. REQUIRE(pool.size() == sizeofString(5));
  28. }
  29. SECTION("Deduplicates identical strings that contain NUL") {
  30. const char* a = saveString(pool, "hello\0world", 11);
  31. const char* b = saveString(pool, "hello\0world", 11);
  32. REQUIRE(a == b);
  33. REQUIRE(pool.size() == sizeofString(11));
  34. }
  35. SECTION("Don't stop on first NUL") {
  36. const char* a = saveString(pool, "hello");
  37. const char* b = saveString(pool, "hello\0world", 11);
  38. REQUIRE(a != b);
  39. REQUIRE(pool.size() == sizeofString(5) + sizeofString(11));
  40. }
  41. SECTION("Returns NULL when allocation fails") {
  42. MemoryPool pool2(32, FailingAllocator::instance());
  43. REQUIRE(0 == saveString(pool2, "a"));
  44. }
  45. }