Skip to content

Commit

Permalink
Remove temporary buffer in ConfigFile.ino
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
bblanchon committed Sep 16, 2021
1 parent 211606f commit ada9fe9
Showing 1 changed file with 4 additions and 15 deletions.
19 changes: 4 additions & 15 deletions libraries/esp8266/examples/ConfigFile/ConfigFile.ino
Original file line number Diff line number Diff line change
Expand Up @@ -11,29 +11,18 @@
#include "FS.h"
#include <LittleFS.h>

// 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) {
Serial.println("Failed to open config file");
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<char[]> 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;
Expand Down

0 comments on commit ada9fe9

Please sign in to comment.