From 7eca8905eac9f09c3990c7d9a024cbb096809638 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Fri, 19 Dec 2025 15:13:16 -1000 Subject: [PATCH] refactor --- esphome/core/entity_base.cpp | 39 ++++++++++++++++++------------------ 1 file changed, 20 insertions(+), 19 deletions(-) diff --git a/esphome/core/entity_base.cpp b/esphome/core/entity_base.cpp index f83fc3b9d6..b7616a9ad3 100644 --- a/esphome/core/entity_base.cpp +++ b/esphome/core/entity_base.cpp @@ -78,18 +78,8 @@ void EntityBase::calc_object_id_() { this->object_id_hash_ = fnv1_hash(object_id.c_str()); } -size_t EntityBase::write_object_id_to(char *buf, size_t buf_size) const { - if (!this->is_object_id_dynamic_()) { - // Static case: copy from stored c_str - const char *src = this->object_id_c_str_ == nullptr ? "" : this->object_id_c_str_; - size_t len = strlen(src); - if (len >= buf_size) - len = buf_size - 1; - memcpy(buf, src, len); - buf[len] = '\0'; - return len; - } - // Dynamic case: format into buffer +// Format dynamic object_id: sanitized snake_case of friendly_name +static size_t format_dynamic_object_id(char *buf, size_t buf_size) { const std::string &name = App.get_friendly_name(); size_t len = std::min(name.size(), buf_size - 1); for (size_t i = 0; i < len; i++) { @@ -99,14 +89,25 @@ size_t EntityBase::write_object_id_to(char *buf, size_t buf_size) const { return len; } -StringRef EntityBase::get_object_id_to(std::span buf) const { - if (!this->is_object_id_dynamic_()) { - // Static case: return direct reference, buffer unused - return this->object_id_c_str_ == nullptr ? StringRef() : StringRef(this->object_id_c_str_); +size_t EntityBase::write_object_id_to(char *buf, size_t buf_size) const { + if (this->is_object_id_dynamic_()) { + return format_dynamic_object_id(buf, buf_size); } - // Dynamic case: write to buffer and return StringRef - size_t len = this->write_object_id_to(buf.data(), buf.size()); - return StringRef(buf.data(), len); + const char *src = this->object_id_c_str_ == nullptr ? "" : this->object_id_c_str_; + size_t len = strlen(src); + if (len >= buf_size) + len = buf_size - 1; + memcpy(buf, src, len); + buf[len] = '\0'; + return len; +} + +StringRef EntityBase::get_object_id_to(std::span buf) const { + if (this->is_object_id_dynamic_()) { + size_t len = format_dynamic_object_id(buf.data(), buf.size()); + return StringRef(buf.data(), len); + } + return this->object_id_c_str_ == nullptr ? StringRef() : StringRef(this->object_id_c_str_); } uint32_t EntityBase::get_object_id_hash() { return this->object_id_hash_; }