From 22cebbbbeec3a8401e79c21ca03aee817743df1b Mon Sep 17 00:00:00 2001 From: Lukas Tenbrink Date: Tue, 7 Jan 2025 22:34:45 +0100 Subject: [PATCH] Clean up String::find to remove duplicate code, and speed up comparison slightly. --- core/string/ustring.cpp | 53 ++++++++++------------------------------- 1 file changed, 13 insertions(+), 40 deletions(-) diff --git a/core/string/ustring.cpp b/core/string/ustring.cpp index be50b0b4e91d..c864054c5e48 100644 --- a/core/string/ustring.cpp +++ b/core/string/ustring.cpp @@ -3135,11 +3135,10 @@ int String::find(const String &p_str, int p_from) const { } const int src_len = p_str.length(); - const int len = length(); - if (src_len == 0 || len == 0) { - return -1; // won't find anything! + if (src_len == 0 || len == 0 || src_len > len - p_from) { + return -1; // Won't find anything! } if (src_len == 1) { @@ -3152,14 +3151,7 @@ int String::find(const String &p_str, int p_from) const { for (int i = p_from; i <= (len - src_len); i++) { bool found = true; for (int j = 0; j < src_len; j++) { - int read_pos = i + j; - - if (read_pos >= len) { - ERR_PRINT("read_pos>=len"); - return -1; - } - - if (src[read_pos] != str[j]) { + if (src[i + j] != str[j]) { found = false; break; } @@ -3179,11 +3171,10 @@ int String::find(const char *p_str, int p_from) const { } const int src_len = strlen(p_str); - const int len = length(); - if (len == 0 || src_len == 0) { - return -1; // won't find anything! + if (len == 0 || src_len == 0 || src_len > len - p_from) { + return -1; // Won't find anything! } if (src_len == 1) { @@ -3192,35 +3183,17 @@ int String::find(const char *p_str, int p_from) const { const char32_t *src = get_data(); - if (src_len == 1) { - const char32_t needle = p_str[0]; - - for (int i = p_from; i < len; i++) { - if (src[i] == needle) { - return i; + for (int i = p_from; i <= (len - src_len); i++) { + bool found = true; + for (int j = 0; j < src_len; j++) { + if (src[i + j] != (char32_t)p_str[j]) { + found = false; + break; } } - } else { - for (int i = p_from; i <= (len - src_len); i++) { - bool found = true; - for (int j = 0; j < src_len; j++) { - int read_pos = i + j; - - if (read_pos >= len) { - ERR_PRINT("read_pos>=len"); - return -1; - } - - if (src[read_pos] != (char32_t)p_str[j]) { - found = false; - break; - } - } - - if (found) { - return i; - } + if (found) { + return i; } }