StringCopier.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // ArduinoJson - https://arduinojson.org
  2. // Copyright © 2014-2023, Benoit BLANCHON
  3. // MIT License
  4. #include <ArduinoJson/StringStorage/StringCopier.hpp>
  5. #include <catch.hpp>
  6. using namespace ArduinoJson::detail;
  7. TEST_CASE("StringCopier") {
  8. SECTION("Works when buffer is big enough") {
  9. MemoryPool pool(addPadding(sizeofString(5)));
  10. StringCopier str(&pool);
  11. str.startString();
  12. str.append("hello");
  13. REQUIRE(str.isValid() == true);
  14. REQUIRE(str.str() == "hello");
  15. REQUIRE(pool.overflowed() == false);
  16. }
  17. SECTION("Returns null when too small") {
  18. MemoryPool pool(sizeof(void*));
  19. StringCopier str(&pool);
  20. str.startString();
  21. str.append("hello world!");
  22. REQUIRE(str.isValid() == false);
  23. REQUIRE(pool.overflowed() == true);
  24. }
  25. SECTION("Increases size of memory pool") {
  26. MemoryPool pool(addPadding(sizeofString(6)));
  27. StringCopier str(&pool);
  28. str.startString();
  29. str.save();
  30. REQUIRE(1 == pool.size());
  31. REQUIRE(pool.overflowed() == false);
  32. }
  33. SECTION("Works when memory pool is 0 bytes") {
  34. MemoryPool pool(0);
  35. StringCopier str(&pool);
  36. str.startString();
  37. REQUIRE(str.isValid() == false);
  38. REQUIRE(pool.overflowed() == true);
  39. }
  40. }
  41. static const char* addStringToPool(MemoryPool& pool, const char* s) {
  42. StringCopier str(&pool);
  43. str.startString();
  44. str.append(s);
  45. return str.save().c_str();
  46. }
  47. TEST_CASE("StringCopier::save() deduplicates strings") {
  48. MemoryPool pool(4096);
  49. SECTION("Basic") {
  50. const char* s1 = addStringToPool(pool, "hello");
  51. const char* s2 = addStringToPool(pool, "world");
  52. const char* s3 = addStringToPool(pool, "hello");
  53. REQUIRE(s1 == s3);
  54. REQUIRE(s2 != s3);
  55. REQUIRE(pool.size() == 2 * sizeofString(5));
  56. }
  57. SECTION("Requires terminator") {
  58. const char* s1 = addStringToPool(pool, "hello world");
  59. const char* s2 = addStringToPool(pool, "hello");
  60. REQUIRE(s2 != s1);
  61. REQUIRE(pool.size() == sizeofString(11) + sizeofString(5));
  62. }
  63. SECTION("Don't overrun") {
  64. const char* s1 = addStringToPool(pool, "hello world");
  65. const char* s2 = addStringToPool(pool, "wor");
  66. REQUIRE(s2 != s1);
  67. REQUIRE(pool.size() == sizeofString(11) + sizeofString(3));
  68. }
  69. }