1
0
Fork 0
mirror of https://github.com/polybar/polybar.git synced 2024-11-25 13:55:47 -05:00

fix(string_util): Prevent replace_all lock

This commit is contained in:
Michael Carlberg 2016-10-19 01:26:10 +02:00
parent 7e960a3966
commit 37e367eb79
2 changed files with 16 additions and 5 deletions

View file

@ -55,17 +55,26 @@ namespace string_util {
* Replace all occurences of needle in haystack
*/
inline auto replace_all(const string& haystack, string needle, string replacement) {
auto result = haystack;
while (needle != replacement && result.find(needle) != string::npos)
result = replace(result, needle, replacement);
return result;
string replaced;
for (int i = 0; i < haystack.length(); i++) {
if (haystack.compare(i, needle.length(), needle) == 0) {
replaced += replacement;
i += needle.length()-1;
} else {
replaced += haystack[i];
}
}
return replaced;
}
/**
* Replace all consecutive occurrences of needle in haystack
*/
inline auto squeeze(const string& haystack, char needle) {
return replace_all(haystack, {needle, needle}, {needle});
auto result = haystack;
while (result.find({needle, needle}) != string::npos)
result = replace_all(result, {needle, needle}, {needle});
return result;
}
/**

View file

@ -43,6 +43,8 @@ class test_string : public unit_test {
void test_replace_all() {
CPPUNIT_ASSERT_EQUAL(string{"Foo bxr bxz"}, string_util::replace_all("Foo bar baz", "a", "x"));
CPPUNIT_ASSERT_EQUAL(string{"hoohoohoo"}, string_util::replace_all("hehehe", "he", "hoo"));
CPPUNIT_ASSERT_EQUAL(string{"113113113"}, string_util::replace_all("131313", "3", "13"));
}
void test_squeeze() {