From ada9fe912cd3ad11da09d5e33355e6a1b1082480 Mon Sep 17 00:00:00 2001 From: Benoit Blanchon Date: Fri, 3 Sep 2021 08:47:22 +0200 Subject: [PATCH] Remove temporary buffer in ConfigFile.ino When reading from a `Stream`, like `File`, using a temporary buffer is counterproductive because it complexifies the code and increases memory usage. It's also a source of confusion because it can create dangling pointers in the `JsonDocument`. The only benefit of using a buffer is the reading speed, but I don't think speed is the focus in this example; if it were, it would use a buffer in `saveConfig()` too. --- .../examples/ConfigFile/ConfigFile.ino | 19 ++++--------------- 1 file changed, 4 insertions(+), 15 deletions(-) diff --git a/libraries/esp8266/examples/ConfigFile/ConfigFile.ino b/libraries/esp8266/examples/ConfigFile/ConfigFile.ino index cb1d25be07..59693edb31 100644 --- a/libraries/esp8266/examples/ConfigFile/ConfigFile.ino +++ b/libraries/esp8266/examples/ConfigFile/ConfigFile.ino @@ -11,6 +11,9 @@ #include "FS.h" #include +// more and possibly updated information can be found at: +// https://arduinojson.org/v6/example/config/ + bool loadConfig() { File configFile = LittleFS.open("/config.json", "r"); if (!configFile) { @@ -18,22 +21,8 @@ bool loadConfig() { return false; } - size_t size = configFile.size(); - if (size > 1024) { - Serial.println("Config file size is too large"); - return false; - } - - // Allocate a buffer to store contents of the file. - std::unique_ptr buf(new char[size]); - - // We don't use String here because ArduinoJson library requires the input - // buffer to be mutable. If you don't use ArduinoJson, you may as well - // use configFile.readString instead. - configFile.readBytes(buf.get(), size); - StaticJsonDocument<200> doc; - auto error = deserializeJson(doc, buf.get()); + auto error = deserializeJson(doc, configFile); if (error) { Serial.println("Failed to parse config file"); return false;