From c50e78e6e0aadbbceccfbe6267891d97ba9f1528 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20Blanchon?= Date: Wed, 21 Jun 2017 22:35:36 +0200 Subject: [PATCH] Clone an object or an array --- Bag-of-Tricks.md | 52 ++++++++++++++++++++++++------------------------ 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/Bag-of-Tricks.md b/Bag-of-Tricks.md index 5c0abab..e43f21f 100644 --- a/Bag-of-Tricks.md +++ b/Bag-of-Tricks.md @@ -401,35 +401,35 @@ Throwing jsonBuffer; See issue [#205](https://github.com/bblanchon/ArduinoJson/issues/205). -## Reuse JsonBuffer - -:warning: **JsonBuffer are designed to be non reusable.** - -:warning: **This is on purpose and this is actually here to help!** - -:warning: **It prevents memory leaks and dangling pointer.** - -:warning: **This section is only intended to insane people who deliberately ignores the recommendation of the library author.** - -:warning: [READ THE FAQ BEFORE USING THIS!!!!!!!](https://bblanchon.github.io/ArduinoJson/faq/how-to-reuse-a-jsonbuffer/) - - -Here is how you can write your own `clear()` function: +## Clone an object or an array ```c++ -template -void clear(T& instance) +JsonVariant clone(JsonBuffer& jb, JsonVariant prototype) { - instance = T(); + if (prototype.is()) { + const JsonObject& protoObj = prototype; + JsonObject& newObj = jb.createObject(); + for (const auto& kvp : protoObj) { + newObj[kvp.key] = clone(jb, kvp.value); + } + return newObj; + } + + if (prototype.is()) { + const JsonArray& protoArr = prototype; + JsonArray& newArr = jb.createArray(); + for (const auto& elem : protoArr) { + newArr.add(clone(jb, elem)); + } + return newArr; + } + + if (prototype.is()) { + return jb.strdup(prototype.as()); + } + + return prototype; } ``` -To use it in your code: - -```c++ -clear(jsonBuffer); -``` - -See issues [#72](https://github.com/bblanchon/ArduinoJson/issues/72), [#115](https://github.com/bblanchon/ArduinoJson/issues/115), [#141](https://github.com/bblanchon/ArduinoJson/issues/141) - -See [ArduinoJson: Avoiding pitfalls](https://bblanchon.github.io/ArduinoJson/doc/pitfalls/#4-dont-reuse-the-same-jsonbuffer) \ No newline at end of file +See issue [#533](https://github.com/bblanchon/ArduinoJson/issues/533) \ No newline at end of file