Compare commits

...

1 Commits

Author SHA1 Message Date
J. Nick Koston
062f223876 [json, core] Remove stored RAMAllocator, make constructors constexpr
RAMAllocator with default flags is stateless — it's just a dispatch
wrapper over heap_caps_malloc/realloc/free. Remove the stored member
from SpiRamAllocator, using stack-local instances at each call site.

Also make RAMAllocator constructors constexpr so the compiler can
fully evaluate flag logic at compile time.

Note: SpiRamAllocator was initialized with RAMAllocator::NONE (0),
which is equivalent to default construction since the constructor
preserves the default ALLOC_INTERNAL | ALLOC_EXTERNAL flags when
no valid allocation flags are provided.

Co-Authored-By: J. Nick Koston <nick@koston.org>
2026-02-14 15:43:50 -07:00
2 changed files with 10 additions and 12 deletions

View File

@@ -18,7 +18,10 @@ namespace json {
// Build an allocator for the JSON Library using the RAMAllocator class
// This is only compiled when PSRAM is enabled
struct SpiRamAllocator : ArduinoJson::Allocator {
void *allocate(size_t size) override { return allocator_.allocate(size); }
void *allocate(size_t size) override {
RAMAllocator<uint8_t> allocator;
return allocator.allocate(size);
}
void deallocate(void *ptr) override {
// ArduinoJson's Allocator interface doesn't provide the size parameter in deallocate.
@@ -31,11 +34,9 @@ struct SpiRamAllocator : ArduinoJson::Allocator {
}
void *reallocate(void *ptr, size_t new_size) override {
return allocator_.reallocate(static_cast<uint8_t *>(ptr), new_size);
RAMAllocator<uint8_t> allocator;
return allocator.reallocate(static_cast<uint8_t *>(ptr), new_size);
}
protected:
RAMAllocator<uint8_t> allocator_{RAMAllocator<uint8_t>::NONE};
};
#endif

View File

@@ -1673,13 +1673,10 @@ template<class T> class RAMAllocator {
ALLOW_FAILURE = 1 << 2, // Does nothing. Kept for compatibility.
};
RAMAllocator() = default;
RAMAllocator(uint8_t flags) {
// default is both external and internal
flags &= ALLOC_INTERNAL | ALLOC_EXTERNAL;
if (flags != 0)
this->flags_ = flags;
}
constexpr RAMAllocator() = default;
constexpr RAMAllocator(uint8_t flags)
: flags_((flags & (ALLOC_INTERNAL | ALLOC_EXTERNAL)) != 0 ? (flags & (ALLOC_INTERNAL | ALLOC_EXTERNAL))
: (ALLOC_INTERNAL | ALLOC_EXTERNAL)) {}
template<class U> constexpr RAMAllocator(const RAMAllocator<U> &other) : flags_{other.flags_} {}
T *allocate(size_t n) { return this->allocate(n, sizeof(T)); }