in-place CString replace when possible

This commit is contained in:
Mathias Agopian
2025-09-26 08:07:55 -07:00
committed by Mathias Agopian
parent d11a6b4467
commit 98f8c93950
2 changed files with 72 additions and 1 deletions
+16 -1
View File
@@ -77,9 +77,24 @@ CString& CString::replace(size_type const pos, size_type len, char const* str, s
len = std::min(len, size() - pos);
// The new size of the string, after the replacement.
const size_type newSize = size() - len + l;
// if the new string is not longer, we can do it in-place, which is much faster.
if (newSize <= size()) {
if (mCStr) {
// This is equivalent to l <= len because capacity() == size()
// move the tail of the string. +1 to move the null-terminator
std::copy(mCStr + pos + len, mCStr + size() + 1, mCStr + pos + l);
// copy the new content
std::copy_n(str, l, mCStr + pos);
// update the size
(mData - 1)->length = newSize;
}
// if mCStr is null, newSize<=size() implies l<=len and since size is 0, len is 0, so l is 0.
// so we're replacing nothing with nothing and there is nothing to do.
return *this;
}
// Allocate enough memory to hold the new string.
Data* const p = static_cast<Data*>(std::malloc(sizeof(Data) + newSize + 1));
assert(p);