Merge pull request #104389 from Ivorforce/color-string-append

Optimize `Color::to_html` by allocating less.
This commit is contained in:
Rémi Verschelde 2025-03-28 14:32:54 +01:00
commit 10799d0b44
No known key found for this signature in database
GPG Key ID: C3336907360768E1
3 changed files with 16 additions and 21 deletions

View File

@ -109,36 +109,29 @@ uint64_t Color::to_rgba64() const {
return c;
}
String _to_hex(float p_val) {
void _append_hex(float p_val, char32_t *string) {
int v = Math::round(p_val * 255.0f);
v = CLAMP(v, 0, 255);
String ret;
for (int i = 0; i < 2; i++) {
char32_t c[2] = { 0, 0 };
int lv = v & 0xF;
if (lv < 10) {
c[0] = '0' + lv;
} else {
c[0] = 'a' + lv - 10;
}
string[i] = hex_char_table_lower[v & 0xF];
v >>= 4;
String cs = (const char32_t *)c;
ret = cs + ret;
}
return ret;
}
String Color::to_html(bool p_alpha) const {
String txt;
txt += _to_hex(r);
txt += _to_hex(g);
txt += _to_hex(b);
txt.resize(p_alpha ? 9 : 7);
char32_t *ptr = txt.ptrw();
_append_hex(r, ptr + 0);
_append_hex(g, ptr + 2);
_append_hex(b, ptr + 4);
if (p_alpha) {
txt += _to_hex(a);
_append_hex(a, ptr + 6);
}
ptr[txt.size() - 1] = '\0';
return txt;
}

View File

@ -36,6 +36,9 @@
#include <iterator>
static constexpr char hex_char_table_upper[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
static constexpr char hex_char_table_lower[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
#define BSEARCH_CHAR_RANGE(m_array) \
int low = 0; \
int high = std::size(m_array) - 1; \

View File

@ -4729,9 +4729,8 @@ String String::uri_encode() const {
res += ord;
} else {
char p[4] = { '%', 0, 0, 0 };
static const char hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
p[1] = hex[ord >> 4];
p[2] = hex[ord & 0xF];
p[1] = hex_char_table_upper[ord >> 4];
p[2] = hex_char_table_upper[ord & 0xF];
res += p;
}
}