StringCopier.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // ArduinoJson - 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(str.c_str() == std::string("hello"));
  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. }
  25. SECTION("Increases size of memory pool") {
  26. MemoryPool pool(buffer, addPadding(JSON_STRING_SIZE(6)));
  27. StringCopier str(pool);
  28. str.startString();
  29. str.append('h');
  30. str.save();
  31. REQUIRE(1 == pool.size());
  32. }
  33. }
  34. static const char* addStringToPool(MemoryPool& pool, const char* s) {
  35. StringCopier str(pool);
  36. str.startString();
  37. str.append(s);
  38. str.append('\0');
  39. return str.save();
  40. }
  41. TEST_CASE("StringCopier::save() deduplicates strings") {
  42. char buffer[4096];
  43. MemoryPool pool(buffer, 4096);
  44. SECTION("Basic") {
  45. const char* s1 = addStringToPool(pool, "hello");
  46. const char* s2 = addStringToPool(pool, "world");
  47. const char* s3 = addStringToPool(pool, "hello");
  48. REQUIRE(s1 == s3);
  49. REQUIRE(s2 != s3);
  50. REQUIRE(pool.size() == 12);
  51. }
  52. SECTION("Requires terminator") {
  53. const char* s1 = addStringToPool(pool, "hello world");
  54. const char* s2 = addStringToPool(pool, "hello");
  55. REQUIRE(s2 != s1);
  56. REQUIRE(pool.size() == 12 + 6);
  57. }
  58. SECTION("Don't overrun") {
  59. const char* s1 = addStringToPool(pool, "hello world");
  60. const char* s2 = addStringToPool(pool, "wor");
  61. REQUIRE(s2 != s1);
  62. REQUIRE(pool.size() == 12 + 4);
  63. }
  64. }