1
0
mirror of https://github.com/esphome/esphome.git synced 2025-09-23 05:32:22 +01:00
This commit is contained in:
J. Nick Koston
2025-09-15 21:28:42 -05:00
parent 0091a2b92b
commit 35f50b710e
2 changed files with 9 additions and 14 deletions

View File

@@ -31,6 +31,7 @@ struct SpiRamAllocator : ArduinoJson::Allocator {
protected:
RAMAllocator<uint8_t> allocator_{RAMAllocator<uint8_t>(RAMAllocator<uint8_t>::NONE)};
};
#endif
std::string build_json(const json_build_t &f) {
@@ -73,22 +74,14 @@ bool parse_json(const std::string &data, const json_parse_t &f) {
JsonBuilder::JsonBuilder()
: doc_(
#ifdef USE_PSRAM
[this]() {
auto *alloc = new SpiRamAllocator(); // NOLINT(cppcoreguidelines-owning-memory)
allocator_ = alloc;
return alloc;
}()
(allocator_ = std::make_unique<SpiRamAllocator>(), allocator_.get())
#else
nullptr
#endif
) {
}
JsonBuilder::~JsonBuilder() {
#ifdef USE_PSRAM
delete static_cast<SpiRamAllocator *>(allocator_); // NOLINT(cppcoreguidelines-owning-memory)
#endif
}
JsonBuilder::~JsonBuilder() = default;
std::string JsonBuilder::serialize() {
if (doc_.overflowed()) {

View File

@@ -25,6 +25,9 @@ std::string build_json(const json_build_t &f);
/// Parse a JSON string and run the provided json parse function if it's valid.
bool parse_json(const std::string &data, const json_parse_t &f);
// Forward declaration to avoid exposing implementation details
struct SpiRamAllocator;
/// Builder class for creating JSON documents without lambdas
class JsonBuilder {
public:
@@ -42,13 +45,12 @@ class JsonBuilder {
std::string serialize();
private:
#ifdef USE_PSRAM
std::unique_ptr<SpiRamAllocator> allocator_; // One heap allocation, but keeps code clean
#endif
JsonDocument doc_;
JsonObject root_;
bool root_created_{false};
// Allocator must be last member to ensure it's destroyed after doc_
#ifdef USE_PSRAM
void *allocator_{nullptr}; // Will store SpiRamAllocator*, managed in cpp file
#endif
};
} // namespace json