The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

219 lines
9.8KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. namespace juce
  18. {
  19. var JSONUtils::makeObject (const std::map<Identifier, var>& source)
  20. {
  21. auto result = std::make_unique<DynamicObject>();
  22. for (const auto& [name, value] : source)
  23. result->setProperty (name, value);
  24. return var (result.release());
  25. }
  26. var JSONUtils::makeObjectWithKeyFirst (const std::map<Identifier, var>& source,
  27. Identifier key)
  28. {
  29. auto result = std::make_unique<DynamicObject>();
  30. if (const auto iter = source.find (key); iter != source.end())
  31. result->setProperty (key, iter->second);
  32. for (const auto& [name, value] : source)
  33. if (name != key)
  34. result->setProperty (name, value);
  35. return var (result.release());
  36. }
  37. std::optional<var> JSONUtils::setPointer (const var& v,
  38. String pointer,
  39. const var& newValue)
  40. {
  41. if (pointer.isEmpty())
  42. return newValue;
  43. if (! pointer.startsWith ("/"))
  44. {
  45. // This is not a well-formed JSON pointer
  46. jassertfalse;
  47. return {};
  48. }
  49. const auto findResult = pointer.indexOfChar (1, '/');
  50. const auto pos = findResult < 0 ? pointer.length() : findResult;
  51. const String head (pointer.begin() + 1, pointer.begin() + pos);
  52. const String tail (pointer.begin() + pos, pointer.end());
  53. const auto unescaped = head.replace ("~1", "/").replace ("~0", "~");
  54. if (auto* object = v.getDynamicObject())
  55. {
  56. if (const auto newProperty = setPointer (object->getProperty (unescaped), tail, newValue))
  57. {
  58. auto cloned = object->clone();
  59. cloned->setProperty (unescaped, *newProperty);
  60. return var (cloned.release());
  61. }
  62. }
  63. else if (auto* array = v.getArray())
  64. {
  65. const auto index = [&]() -> size_t
  66. {
  67. if (unescaped == "-")
  68. return (size_t) array->size();
  69. if (unescaped == "0")
  70. return 0;
  71. if (! unescaped.startsWith ("0"))
  72. return (size_t) unescaped.getLargeIntValue();
  73. return std::numeric_limits<size_t>::max();
  74. }();
  75. if (const auto newIndex = setPointer ((*array)[(int) index], tail, newValue))
  76. {
  77. auto copied = *array;
  78. if ((int) index == copied.size())
  79. copied.add ({});
  80. if (isPositiveAndBelow (index, copied.size()))
  81. {
  82. copied.getReference ((int) index) = *newIndex;
  83. return var (copied);
  84. }
  85. }
  86. }
  87. return {};
  88. }
  89. bool JSONUtils::deepEqual (const var& a, const var& b)
  90. {
  91. const auto compareObjects = [] (const DynamicObject& x, const DynamicObject& y)
  92. {
  93. if (x.getProperties().size() != y.getProperties().size())
  94. return false;
  95. for (const auto& [key, value] : x.getProperties())
  96. {
  97. if (! y.hasProperty (key))
  98. return false;
  99. if (! deepEqual (value, y.getProperty (key)))
  100. return false;
  101. }
  102. return true;
  103. };
  104. if (auto* i = a.getDynamicObject())
  105. if (auto* j = b.getDynamicObject())
  106. return compareObjects (*i, *j);
  107. if (auto* i = a.getArray())
  108. if (auto* j = b.getArray())
  109. return std::equal (i->begin(), i->end(), j->begin(), j->end(), [] (const var& x, const var& y) { return deepEqual (x, y); });
  110. return a == b;
  111. }
  112. //==============================================================================
  113. //==============================================================================
  114. #if JUCE_UNIT_TESTS
  115. class JSONUtilsTests final : public UnitTest
  116. {
  117. public:
  118. JSONUtilsTests() : UnitTest ("JSONUtils", UnitTestCategories::json) {}
  119. void runTest() override
  120. {
  121. beginTest ("JSON pointers");
  122. {
  123. const auto obj = JSON::parse (R"({ "name": "PIANO 4"
  124. , "lfoSpeed": 30
  125. , "lfoWaveform": "triangle"
  126. , "pitchEnvelope": { "rates": [94,67,95,60], "levels": [50,50,50,50] }
  127. })");
  128. expectDeepEqual (JSONUtils::setPointer (obj, "", "hello world"), var ("hello world"));
  129. expectDeepEqual (JSONUtils::setPointer (obj, "/lfoWaveform/foobar", "str"), std::nullopt);
  130. expectDeepEqual (JSONUtils::setPointer (JSON::parse (R"({"foo":0,"bar":1})"), "/foo", 2), JSON::parse (R"({"foo":2,"bar":1})"));
  131. expectDeepEqual (JSONUtils::setPointer (JSON::parse (R"({"foo":0,"bar":1})"), "/baz", 2), JSON::parse (R"({"foo":0,"bar":1,"baz":2})"));
  132. expectDeepEqual (JSONUtils::setPointer (JSON::parse (R"({"foo":{},"bar":{}})"), "/foo/bar", 2), JSON::parse (R"({"foo":{"bar":2},"bar":{}})"));
  133. expectDeepEqual (JSONUtils::setPointer (obj, "/pitchEnvelope/rates/01", "str"), std::nullopt);
  134. expectDeepEqual (JSONUtils::setPointer (obj, "/pitchEnvelope/rates/10", "str"), std::nullopt);
  135. expectDeepEqual (JSONUtils::setPointer (obj, "/lfoSpeed", 10), JSON::parse (R"({ "name": "PIANO 4"
  136. , "lfoSpeed": 10
  137. , "lfoWaveform": "triangle"
  138. , "pitchEnvelope": { "rates": [94,67,95,60], "levels": [50,50,50,50] }
  139. })"));
  140. expectDeepEqual (JSONUtils::setPointer (JSON::parse (R"([0,1,2])"), "/0", "bang"), JSON::parse (R"(["bang",1,2])"));
  141. expectDeepEqual (JSONUtils::setPointer (JSON::parse (R"([0,1,2])"), "/0", "bang"), JSON::parse (R"(["bang",1,2])"));
  142. expectDeepEqual (JSONUtils::setPointer (JSON::parse (R"({"/":"fizz"})"), "/~1", "buzz"), JSON::parse (R"({"/":"buzz"})"));
  143. expectDeepEqual (JSONUtils::setPointer (JSON::parse (R"({"~":"fizz"})"), "/~0", "buzz"), JSON::parse (R"({"~":"buzz"})"));
  144. expectDeepEqual (JSONUtils::setPointer (obj, "/pitchEnvelope/rates/0", 80), JSON::parse (R"({ "name": "PIANO 4"
  145. , "lfoSpeed": 30
  146. , "lfoWaveform": "triangle"
  147. , "pitchEnvelope": { "rates": [80,67,95,60], "levels": [50,50,50,50] }
  148. })"));
  149. expectDeepEqual (JSONUtils::setPointer (obj, "/pitchEnvelope/levels/0", 80), JSON::parse (R"({ "name": "PIANO 4"
  150. , "lfoSpeed": 30
  151. , "lfoWaveform": "triangle"
  152. , "pitchEnvelope": { "rates": [94,67,95,60], "levels": [80,50,50,50] }
  153. })"));
  154. expectDeepEqual (JSONUtils::setPointer (obj, "/pitchEnvelope/levels/-", 100), JSON::parse (R"({ "name": "PIANO 4"
  155. , "lfoSpeed": 30
  156. , "lfoWaveform": "triangle"
  157. , "pitchEnvelope": { "rates": [94,67,95,60], "levels": [50,50,50,50,100] }
  158. })"));
  159. }
  160. }
  161. void expectDeepEqual (const std::optional<var>& a, const std::optional<var>& b)
  162. {
  163. const auto text = a.has_value() && b.has_value()
  164. ? JSON::toString (*a) + " != " + JSON::toString (*b)
  165. : String();
  166. expect (deepEqual (a, b), text);
  167. }
  168. static bool deepEqual (const std::optional<var>& a, const std::optional<var>& b)
  169. {
  170. if (a.has_value() && b.has_value())
  171. return JSONUtils::deepEqual (*a, *b);
  172. return a == b;
  173. }
  174. };
  175. static JSONUtilsTests jsonUtilsTests;
  176. #endif
  177. } // namespace juce