diff --git a/esphome/components/sensor/filter.h b/esphome/components/sensor/filter.h index a3bd7b6b511..be63f99faee 100644 --- a/esphome/components/sensor/filter.h +++ b/esphome/components/sensor/filter.h @@ -506,11 +506,7 @@ optional calibrate_polynomial_compute(const float *coefficients, size_t c template class CalibratePolynomialFilter : public Filter { public: explicit CalibratePolynomialFilter(std::initializer_list coefficients) { - ESPHOME_DEBUG_ASSERT(coefficients.size() == N); - size_t i = 0; - for (float c : coefficients) { - this->coefficients_[i++] = c; - } + init_array_from(this->coefficients_, coefficients); } optional new_value(float value) override { return calibrate_polynomial_compute(this->coefficients_.data(), N, value); diff --git a/esphome/core/helpers.h b/esphome/core/helpers.h index 82c6b3833ce..51feaa57c50 100644 --- a/esphome/core/helpers.h +++ b/esphome/core/helpers.h @@ -497,6 +497,21 @@ template::max()> index_type capacity_{0}; }; +/// Initialize a std::array from an initializer_list. Uses memcpy for trivially copyable types (optimal codegen), +/// falls back to element-wise copy for non-trivially copyable types (e.g. TemplatableValue). +/// N is set by code generation; ESPHOME_DEBUG_ASSERT catches mismatches in debug/integration tests. +template inline void init_array_from(std::array &dest, std::initializer_list src) { + ESPHOME_DEBUG_ASSERT(src.size() == N); + if constexpr (std::is_trivially_copyable_v) { + __builtin_memcpy(dest.data(), src.begin(), N * sizeof(T)); + } else { + size_t i = 0; + for (const auto &v : src) { + dest[i++] = v; + } + } +} + /// Fixed-capacity vector - allocates once at runtime, never reallocates /// This avoids std::vector template overhead (_M_realloc_insert, _M_default_append) /// when size is known at initialization but not at compile time