serializeObject.cpp 2.2 KB

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