diff --git a/system/jlib/jstring.cpp b/system/jlib/jstring.cpp index 14e26205c1f..1692c94aeef 100644 --- a/system/jlib/jstring.cpp +++ b/system/jlib/jstring.cpp @@ -1072,9 +1072,17 @@ StringBuffer & StringBuffer::replaceString(const char* oldStr, const char* newSt { if (memcmp(buffer, oldStr, oldlen) == 0) { - ensureCapacity(newlen); - memcpy(buffer, newStr, newlen); - curLen = newlen; + if (newlen <= curLen) + { + memmove(buffer, newStr, newlen); + curLen = newlen; + } + else + { + ensureCapacity(newlen); + memcpy(buffer, newStr, newlen); + curLen = newlen; + } } } else diff --git a/testing/unittests/jlibtests.cpp b/testing/unittests/jlibtests.cpp index 53500b8ca15..19d2bfcf4bf 100644 --- a/testing/unittests/jlibtests.cpp +++ b/testing/unittests/jlibtests.cpp @@ -914,12 +914,22 @@ void testEncodeCSVColumn() source.replaceString("ab", "xxx"); CPPUNIT_ASSERT_EQUAL_STR("xxxbxxxxxx", source.str()); - // Search String has same length as source string and matches + // Search string has same length as source string and matches source.set("ababab"); source.replaceString("ababab", "xxxxxx"); CPPUNIT_ASSERT_EQUAL_STR("xxxxxx", source.str()); - // Search String has same length as source string and does not match + // Search string has same length as source string and replace is smaller than source + source.set("ababab"); + source.replaceString("ababab", "xxx"); + CPPUNIT_ASSERT_EQUAL_STR("xxx", source.str()); + + // Search string has same length as source string and replace is larger than source + source.set("ababab"); + source.replaceString("ababab", "xxxxxxxxx"); + CPPUNIT_ASSERT_EQUAL_STR("xxxxxxxxx", source.str()); + + // Search string has same length as source string and does not match source.set("ababab"); source.replaceString("ababac", "xxxxxx"); CPPUNIT_ASSERT_EQUAL_STR("ababab", source.str());