[core] Add zero-allocation get_object_id_to() method

This commit is contained in:
J. Nick Koston
2025-12-19 15:03:27 -10:00
parent c9fccdff25
commit cd6240541b
8 changed files with 46 additions and 56 deletions
+2 -1
View File
@@ -404,8 +404,9 @@ void WebServer::handle_js_request(AsyncWebServerRequest *request) {
// Helper functions to reduce code size by avoiding macro expansion
static void set_json_id(JsonObject &root, EntityBase *obj, const char *prefix, JsonDetail start_config) {
char object_id_buf[OBJECT_ID_MAX_LEN];
StringRef object_id = obj->get_object_id_to(object_id_buf);
char id_buf[160]; // object_id can be up to 128 chars + prefix + dash + null
const auto &object_id = obj->get_object_id();
snprintf(id_buf, sizeof(id_buf), "%s-%s", prefix, object_id.c_str());
root[ESPHOME_F("id")] = id_buf;
if (start_config == DETAIL_ALL) {
+4 -8
View File
@@ -52,14 +52,10 @@ struct UrlMatch {
}
bool id_equals_entity(EntityBase *entity) const {
// Zero-copy comparison using StringRef
StringRef static_ref = entity->get_object_id_ref_for_api_();
if (!static_ref.empty()) {
return id && id_len == static_ref.size() && memcmp(id, static_ref.c_str(), id_len) == 0;
}
// Fallback to allocation (rare)
const auto &obj_id = entity->get_object_id();
return id && id_len == obj_id.length() && memcmp(id, obj_id.c_str(), id_len) == 0;
// Get object_id with zero heap allocation
char object_id_buf[OBJECT_ID_MAX_LEN];
StringRef object_id = entity->get_object_id_to(object_id_buf);
return id && id_len == object_id.size() && memcmp(id, object_id.c_str(), id_len) == 0;
}
bool method_equals(const char *str) const {
@@ -15,7 +15,8 @@ void write_row(AsyncResponseStream *stream, EntityBase *obj, const std::string &
stream->print("\" id=\"");
stream->print(klass.c_str());
stream->print("-");
stream->print(obj->get_object_id().c_str());
char object_id_buf[OBJECT_ID_MAX_LEN];
stream->print(obj->get_object_id_to(object_id_buf).c_str());
stream->print("\"><td>");
stream->print(obj->get_name().c_str());
stream->print("</td><td></td><td>");