Skip to content

Commit

Permalink
Clean up String::find to remove duplicate code, and speed up comparis…
Browse files Browse the repository at this point in the history
…on slightly.
  • Loading branch information
Ivorforce committed Jan 7, 2025
1 parent aa65940 commit 22cebbb
Showing 1 changed file with 13 additions and 40 deletions.
53 changes: 13 additions & 40 deletions core/string/ustring.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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;
}
Expand All @@ -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) {
Expand All @@ -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;
}
}

Expand Down

0 comments on commit 22cebbb

Please sign in to comment.