mirror of
https://github.com/libretro/RetroArch
synced 2025-04-07 13:23:32 +00:00
stdstring: Get rid of some strlen calls
Now the function doesn't traverse strings more than necessary.
This commit is contained in:
parent
4f2547976c
commit
1f1cdae621
@ -27,21 +27,26 @@ char *string_replace_substring(const char *in, const char *pattern, const char *
|
|||||||
char *needle = NULL;
|
char *needle = NULL;
|
||||||
char *newstr = NULL;
|
char *newstr = NULL;
|
||||||
char *head = NULL;
|
char *head = NULL;
|
||||||
|
size_t pattern_len = 0;
|
||||||
|
size_t replacement_len = 0;
|
||||||
|
|
||||||
/* if either pattern or replacement is NULL,
|
/* if either pattern or replacement is NULL,
|
||||||
* duplicate in and let caller handle it. */
|
* duplicate in and let caller handle it. */
|
||||||
if (!pattern || !replacement)
|
if (!pattern || !replacement)
|
||||||
return strdup(in);
|
return strdup(in);
|
||||||
|
|
||||||
|
pattern_len = strlen(pattern);
|
||||||
|
replacement_len = strlen(replacement);
|
||||||
|
|
||||||
newstr = strdup(in);
|
newstr = strdup(in);
|
||||||
head = newstr;
|
head = newstr;
|
||||||
|
|
||||||
while ((needle = strstr (head, pattern)))
|
while ((needle = strstr(head, pattern)))
|
||||||
{
|
{
|
||||||
char* oldstr = newstr;
|
char* oldstr = newstr;
|
||||||
newstr = (char*)malloc(
|
size_t oldstr_len = strlen(oldstr);
|
||||||
strlen(oldstr) - strlen(pattern) + strlen(replacement) + 1);
|
|
||||||
|
|
||||||
|
newstr = (char*)malloc(oldstr_len - pattern_len + replacement_len + 1);
|
||||||
if (!newstr)
|
if (!newstr)
|
||||||
{
|
{
|
||||||
/* Failed to allocate memory,
|
/* Failed to allocate memory,
|
||||||
@ -51,14 +56,14 @@ char *string_replace_substring(const char *in, const char *pattern, const char *
|
|||||||
}
|
}
|
||||||
|
|
||||||
memcpy(newstr, oldstr, needle - oldstr);
|
memcpy(newstr, oldstr, needle - oldstr);
|
||||||
memcpy(newstr + (needle - oldstr), replacement, strlen(replacement));
|
memcpy(newstr + (needle - oldstr), replacement, replacement_len);
|
||||||
memcpy(newstr + (needle - oldstr) + strlen(replacement),
|
memcpy(newstr + (needle - oldstr) + replacement_len,
|
||||||
needle + strlen(pattern),
|
needle + pattern_len,
|
||||||
strlen(oldstr) - strlen(pattern) - (needle - oldstr));
|
oldstr_len - pattern_len - (needle - oldstr));
|
||||||
newstr[strlen(oldstr) - strlen(pattern) + strlen(replacement)] = '\0';
|
newstr[oldstr_len - pattern_len + replacement_len] = '\0';
|
||||||
|
|
||||||
/* Move back head right after the last replacement. */
|
/* Move back head right after the last replacement. */
|
||||||
head = newstr + (needle - oldstr) + strlen(replacement);
|
head = newstr + (needle - oldstr) + replacement_len;
|
||||||
free(oldstr);
|
free(oldstr);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user