StringCopier.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // ArduinoJson - https://arduinojson.org
  2. // Copyright Benoit Blanchon 2014-2021
  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(6)));
  11. StringCopier str(pool);
  12. str.startString();
  13. str.append("hello");
  14. str.append('\0');
  15. REQUIRE(str.isValid() == true);
  16. REQUIRE(std::string(str.str()) == "hello");
  17. REQUIRE(pool.overflowed() == false);
  18. }
  19. SECTION("Returns null when too small") {
  20. MemoryPool pool(buffer, sizeof(void*));
  21. StringCopier str(pool);
  22. str.startString();
  23. str.append("hello world!");
  24. REQUIRE(str.isValid() == false);
  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.append('h');
  31. str.save();
  32. REQUIRE(1 == pool.size());
  33. }
  34. }
  35. static const char* addStringToPool(MemoryPool& pool, const char* s) {
  36. StringCopier str(pool);
  37. str.startString();
  38. str.append(s);
  39. str.append('\0');
  40. return str.save().c_str();
  41. }
  42. TEST_CASE("StringCopier::save() deduplicates strings") {
  43. char buffer[4096];
  44. MemoryPool pool(buffer, 4096);
  45. SECTION("Basic") {
  46. const char* s1 = addStringToPool(pool, "hello");
  47. const char* s2 = addStringToPool(pool, "world");
  48. const char* s3 = addStringToPool(pool, "hello");
  49. REQUIRE(s1 == s3);
  50. REQUIRE(s2 != s3);
  51. REQUIRE(pool.size() == 12);
  52. }
  53. SECTION("Requires terminator") {
  54. const char* s1 = addStringToPool(pool, "hello world");
  55. const char* s2 = addStringToPool(pool, "hello");
  56. REQUIRE(s2 != s1);
  57. REQUIRE(pool.size() == 12 + 6);
  58. }
  59. SECTION("Don't overrun") {
  60. const char* s1 = addStringToPool(pool, "hello world");
  61. const char* s2 = addStringToPool(pool, "wor");
  62. REQUIRE(s2 != s1);
  63. REQUIRE(pool.size() == 12 + 4);
  64. }
  65. }