Skip to content

Commit 39c8e1b

Browse files
committed
[SQUASH] Take ownership of non-owned string when replacing and fix allocating too small buffer when buffer resize is needed.
1 parent d6d1fd3 commit 39c8e1b

File tree

1 file changed

+9
-8
lines changed

1 file changed

+9
-8
lines changed

Str.h

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -652,19 +652,19 @@ int Str::appendf(const char* fmt, ...)
652652
return len;
653653
}
654654

655-
void Str::replace(const char* find, const char* repl)
655+
void Str::replace(const char* find, const char* repl)
656656
{
657-
STR_ASSERT(Owned == 1);
658657
STR_ASSERT(find != NULL && *find);
659658
STR_ASSERT(repl != NULL);
660659
int find_len = (int)strlen(find);
661660
int repl_len = (int)strlen(repl);
662661
int repl_diff = repl_len - find_len;
663662

664663
// Estimate required length of new buffer if string size increases.
664+
int need_capacity = Capacity;
665665
if (repl_diff > 0)
666666
{
667-
int need_capacity = length();
667+
need_capacity = length() + 1;
668668
for (char* p = Data, *end = Data + length(); p != NULL && p < end;)
669669
{
670670
p = (char*)memmem(p, end - p, find, find_len);
@@ -674,13 +674,14 @@ void Str::replace(const char* find, const char* repl)
674674
p += find_len;
675675
}
676676
}
677-
if (need_capacity > Capacity)
678-
{
679-
reserve(need_capacity);
680-
STR_ASSERT(Capacity >= need_capacity);
681-
}
682677
}
683678

679+
const char* not_owned_data = Owned ? NULL : Data;
680+
if (!Owned || need_capacity > Capacity)
681+
reserve(need_capacity);
682+
if (not_owned_data != NULL)
683+
set(not_owned_data);
684+
684685
// Replace data.
685686
for (char* p = Data, *end = Data + length(); p != NULL && p < end;)
686687
{

0 commit comments

Comments
 (0)