[text] Store pattern as const char* to reduce memory usage (#12335)

This commit is contained in:
J. Nick Koston
2025-12-07 15:33:15 -06:00
committed by GitHub
parent 3d5d89ff00
commit 68a7634228
4 changed files with 8 additions and 8 deletions

View File

@@ -15,7 +15,7 @@ void TemplateText::setup() {
uint32_t key = this->get_preference_hash();
key += this->traits.get_min_length() << 2;
key += this->traits.get_max_length() << 4;
key += fnv1_hash(this->traits.get_pattern()) << 6;
key += fnv1_hash(this->traits.get_pattern_c_str()) << 6;
this->pref_->setup(key, value);
}
if (!value.empty())

View File

@@ -1,8 +1,7 @@
#pragma once
#include <utility>
#include <string>
#include "esphome/core/helpers.h"
#include "esphome/core/string_ref.h"
namespace esphome {
@@ -22,8 +21,9 @@ class TextTraits {
int get_max_length() const { return this->max_length_; }
// Set/get the pattern.
void set_pattern(std::string pattern) { this->pattern_ = std::move(pattern); }
std::string get_pattern() const { return this->pattern_; }
void set_pattern(const char *pattern) { this->pattern_ = pattern; }
std::string get_pattern() const { return std::string(this->pattern_); }
const char *get_pattern_c_str() const { return this->pattern_; }
StringRef get_pattern_ref() const { return StringRef(this->pattern_); }
// Set/get the frontend mode.
@@ -33,7 +33,7 @@ class TextTraits {
protected:
int min_length_;
int max_length_;
std::string pattern_;
const char *pattern_{""};
TextMode mode_{TEXT_MODE_TEXT};
};

View File

@@ -1211,7 +1211,7 @@ std::string WebServer::text_json(text::Text *obj, const std::string &value, Json
set_json_icon_state_value(root, obj, "text", state, value, start_config);
root[ESPHOME_F("min_length")] = obj->traits.get_min_length();
root[ESPHOME_F("max_length")] = obj->traits.get_max_length();
root[ESPHOME_F("pattern")] = obj->traits.get_pattern();
root[ESPHOME_F("pattern")] = obj->traits.get_pattern_c_str();
if (start_config == DETAIL_ALL) {
root[ESPHOME_F("mode")] = (int) obj->traits.get_mode();
this->add_sorting_info_(root, obj);

View File

@@ -142,7 +142,7 @@ void WebServer::handle_index_request(AsyncWebServerRequest *request) {
stream.print(R"(" maxlength=")");
stream.print(text->traits.get_max_length());
stream.print(R"(" pattern=")");
stream.print(text->traits.get_pattern().c_str());
stream.print(text->traits.get_pattern_c_str());
stream.print(R"(" value=")");
stream.print(text->state.c_str());
stream.print(R"("/>)");