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:
parent
7e960a3966
commit
37e367eb79
2 changed files with 16 additions and 5 deletions
|
@ -55,17 +55,26 @@ namespace string_util {
|
||||||
* Replace all occurences of needle in haystack
|
* Replace all occurences of needle in haystack
|
||||||
*/
|
*/
|
||||||
inline auto replace_all(const string& haystack, string needle, string replacement) {
|
inline auto replace_all(const string& haystack, string needle, string replacement) {
|
||||||
auto result = haystack;
|
string replaced;
|
||||||
while (needle != replacement && result.find(needle) != string::npos)
|
for (int i = 0; i < haystack.length(); i++) {
|
||||||
result = replace(result, needle, replacement);
|
if (haystack.compare(i, needle.length(), needle) == 0) {
|
||||||
return result;
|
replaced += replacement;
|
||||||
|
i += needle.length()-1;
|
||||||
|
} else {
|
||||||
|
replaced += haystack[i];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return replaced;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Replace all consecutive occurrences of needle in haystack
|
* Replace all consecutive occurrences of needle in haystack
|
||||||
*/
|
*/
|
||||||
inline auto squeeze(const string& haystack, char needle) {
|
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;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
@ -43,6 +43,8 @@ class test_string : public unit_test {
|
||||||
|
|
||||||
void test_replace_all() {
|
void test_replace_all() {
|
||||||
CPPUNIT_ASSERT_EQUAL(string{"Foo bxr bxz"}, string_util::replace_all("Foo bar baz", "a", "x"));
|
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() {
|
void test_squeeze() {
|
||||||
|
|
Loading…
Reference in a new issue