diff --git a/esphome/core/helpers.h b/esphome/core/helpers.h index 3f371cd829..7866eaa9bd 100644 --- a/esphome/core/helpers.h +++ b/esphome/core/helpers.h @@ -719,6 +719,25 @@ template class RAMAllocator { return ptr; } + T *reallocate(T *p, size_t n) { return this->reallocate(p, n, sizeof(T)); } + + T *reallocate(T *p, size_t n, size_t manual_size) { + size_t size = n * sizeof(T); + T *ptr = nullptr; +#ifdef USE_ESP32 + if (this->flags_ & Flags::ALLOC_EXTERNAL) { + ptr = static_cast(heap_caps_realloc(p, size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT)); + } + if (ptr == nullptr && this->flags_ & Flags::ALLOC_INTERNAL) { + ptr = static_cast(heap_caps_realloc(p, size, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT)); + } +#else + // Ignore ALLOC_EXTERNAL/ALLOC_INTERNAL flags if external allocation is not supported + ptr = static_cast(realloc(p, size)); // NOLINT(cppcoreguidelines-owning-memory,cppcoreguidelines-no-malloc) +#endif + return ptr; + } + void deallocate(T *p, size_t n) { free(p); // NOLINT(cppcoreguidelines-owning-memory,cppcoreguidelines-no-malloc) }