serializeObject.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // ArduinoJson - https://arduinojson.org
  2. // Copyright © 2014-2025, Benoit BLANCHON
  3. // MIT License
  4. #include <ArduinoJson.h>
  5. #include <stdio.h>
  6. #include <catch.hpp>
  7. #include "Literals.hpp"
  8. static void check(const JsonObject object, const char* expected_data,
  9. size_t expected_len) {
  10. std::string expected(expected_data, expected_data + expected_len);
  11. std::string actual;
  12. size_t len = serializeMsgPack(object, actual);
  13. CAPTURE(object);
  14. REQUIRE(len == expected_len);
  15. REQUIRE(actual == expected);
  16. }
  17. template <size_t N>
  18. static void check(const JsonObject object, const char (&expected_data)[N]) {
  19. const size_t expected_len = N - 1;
  20. check(object, expected_data, expected_len);
  21. }
  22. // TODO: used by the commented test
  23. // static void check(const JsonObject object, const std::string& expected) {
  24. // check(object, expected.data(), expected.length());
  25. //}
  26. TEST_CASE("serialize MsgPack object") {
  27. JsonDocument doc;
  28. JsonObject object = doc.to<JsonObject>();
  29. SECTION("empty") {
  30. check(object, "\x80");
  31. }
  32. SECTION("fixmap") {
  33. object["hello"] = "world";
  34. check(object, "\x81\xA5hello\xA5world");
  35. }
  36. SECTION("map 16") {
  37. for (int i = 0; i < 16; ++i) {
  38. char key[16];
  39. snprintf(key, sizeof(key), "i%X", i);
  40. object[key] = i;
  41. }
  42. check(object,
  43. "\xDE\x00\x10\xA2i0\x00\xA2i1\x01\xA2i2\x02\xA2i3\x03\xA2i4\x04\xA2i5"
  44. "\x05\xA2i6\x06\xA2i7\x07\xA2i8\x08\xA2i9\x09\xA2iA\x0A\xA2iB\x0B\xA2"
  45. "iC\x0C\xA2iD\x0D\xA2iE\x0E\xA2iF\x0F");
  46. }
  47. // TODO: improve performance and uncomment
  48. // SECTION("map 32") {
  49. // std::string expected("\xDF\x00\x01\x00\x00", 5);
  50. //
  51. // for (int i = 0; i < 65536; ++i) {
  52. // char kv[16];
  53. // snprintf(kv, sizeof(kv), "%04x", i);
  54. // object[kv] = kv;
  55. // expected += '\xA4';
  56. // expected += kv;
  57. // expected += '\xA4';
  58. // expected += kv;
  59. // }
  60. //
  61. // check(object, expected);
  62. // }
  63. SECTION("serialized(const char*)") {
  64. object["hello"] = serialized("\xDB\x00\x01\x00\x00", 5);
  65. check(object, "\x81\xA5hello\xDB\x00\x01\x00\x00");
  66. }
  67. SECTION("serialized(std::string)") {
  68. object["hello"] = serialized("\xDB\x00\x01\x00\x00"_s);
  69. check(object, "\x81\xA5hello\xDB\x00\x01\x00\x00");
  70. }
  71. }