Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions Str.h
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,7 @@ class STR_API Str
int append_from(int idx, const char* s, const char* s_end = NULL); // If you know the string length or want to append from a certain point
int appendf_from(int idx, const char* fmt, ...);
int appendfv_from(int idx, const char* fmt, va_list args);
void replace(const char* find, const char* repl);

void clear();
void reserve(int cap);
Expand Down Expand Up @@ -651,6 +652,56 @@ int Str::appendf(const char* fmt, ...)
return len;
}

void Str::replace(const char* find, const char* repl)
{
STR_ASSERT(find != NULL && *find);
STR_ASSERT(repl != NULL);
int find_len = (int)strlen(find);
int repl_len = (int)strlen(repl);
int repl_diff = repl_len - find_len;

// Estimate required length of new buffer if string size increases.
int need_capacity = Capacity;
int num_matches = INT_MAX;
if (repl_diff > 0)
{
num_matches = 0;
need_capacity = length() + 1;
for (char* p = Data, *end = Data + length(); p != NULL && p < end;)
{
p = (char*)memmem(p, end - p, find, find_len);
if (p)
{
need_capacity += repl_diff;
p += find_len;
num_matches++;
}
}
}

if (num_matches == 0)
return;

const char* not_owned_data = Owned ? NULL : Data;
if (!Owned || need_capacity > Capacity)
reserve(need_capacity);
if (not_owned_data != NULL)
set(not_owned_data);

// Replace data.
for (char* p = Data, *end = Data + length(); p != NULL && p < end && num_matches--;)
{
p = (char*)memmem(p, end - p, find, find_len);
if (p)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe avoid looping fully if no match or end when last match?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That was already the case. memmem() would return NULL and loop would not continue due to p != NULL check in for

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

By definition if memmem returns null it means the string has been read entirely. Whereas you already have a match counter you can use to early out.

{
memmove(p + repl_len, p + find_len, end - p - find_len + 1);
memcpy(p, repl, repl_len);
p += repl_len;
end += repl_diff;
}
}
}

#endif // #define STR_IMPLEMENTATION

//-------------------------------------------------------------------------