StringCopier.cpp 2.2 KB

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