mirror of
https://github.com/esphome/esphome.git
synced 2026-09-20 19:48:39 +00:00
Use init_array_from helper for optimal codegen
Uses memcpy for trivially copyable types, element-wise copy otherwise. ESPHOME_DEBUG_ASSERT catches size mismatches in integration tests.
This commit is contained in:
@@ -165,11 +165,7 @@ bool map_filter_apply(const Substitution *mappings, size_t count, std::string &v
|
||||
template<size_t N> class MapFilter : public Filter {
|
||||
public:
|
||||
explicit MapFilter(const std::initializer_list<Substitution> &mappings) {
|
||||
ESPHOME_DEBUG_ASSERT(mappings.size() == N);
|
||||
size_t i = 0;
|
||||
for (const auto &m : mappings) {
|
||||
this->mappings_[i++] = m;
|
||||
}
|
||||
init_array_from(this->mappings_, mappings);
|
||||
}
|
||||
bool new_value(std::string &value) override { return map_filter_apply(this->mappings_.data(), N, value); }
|
||||
|
||||
|
||||
@@ -497,6 +497,21 @@ template<typename T, size_t MAX_CAPACITY = std::numeric_limits<uint16_t>::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<typename T, size_t N> inline void init_array_from(std::array<T, N> &dest, std::initializer_list<T> src) {
|
||||
ESPHOME_DEBUG_ASSERT(src.size() == N);
|
||||
if constexpr (std::is_trivially_copyable_v<T>) {
|
||||
__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
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
# Gitignore settings for ESPHome
|
||||
# This is an example and may include too much for your use-case.
|
||||
# You can modify this file to suit your needs.
|
||||
/.esphome/
|
||||
/secrets.yaml
|
||||
Reference in New Issue
Block a user