Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Str::replace(find, repl) function. #15

Open
wants to merge 3 commits into
base: master
Choose a base branch
from

Conversation

rokups
Copy link
Contributor

@rokups rokups commented Jun 16, 2021

No description provided.

Str.h Outdated
@@ -651,6 +652,49 @@ int Str::appendf(const char* fmt, ...)
return len;
}

void Str::replace(const char* find, const char* repl)
{
STR_ASSERT(Owned == 1);
Copy link
Owner

Choose a reason for hiding this comment

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

Can take ownership after we know that replacements are needed (ideally without a double rewrite)

for (char* p = Data, *end = Data + length(); p != NULL && p < end;)
{
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.

@ocornut
Copy link
Owner

ocornut commented Jul 6, 2021

When num_matches == 0 in the repl_diff > 0 we could early out to avoid owning/copying a non-owned string.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants