From: Joel Rosdahl Date: Wed, 22 Sep 2021 19:58:47 +0000 (+0200) Subject: enhance: Add util::replace_all function X-Git-Tag: v4.4.2~6 X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=ae1153fbff700d9e17a90bfdf1d465612aa86398;p=thirdparty%2Fccache.git enhance: Add util::replace_all function --- diff --git a/src/util/string.cpp b/src/util/string.cpp index 38df7d99a..aa0ff368e 100644 --- a/src/util/string.cpp +++ b/src/util/string.cpp @@ -18,6 +18,7 @@ #include "string.hpp" +#include #include #include @@ -150,6 +151,31 @@ percent_decode(nonstd::string_view string) return result; } +std::string +replace_all(const nonstd::string_view string, + const nonstd::string_view from, + const nonstd::string_view to) +{ + if (from.empty()) { + return std::string(string); + } + + std::string result; + size_t left = 0; + size_t right = 0; + while (left < string.size()) { + right = string.find(from, left); + if (right == nonstd::string_view::npos) { + result.append(string.data() + left); + break; + } + result.append(string.data() + left, right - left); + result.append(to.data(), to.size()); + left = right + from.size(); + } + return result; +} + std::string replace_first(const nonstd::string_view string, const nonstd::string_view from, diff --git a/src/util/string.hpp b/src/util/string.hpp index 62b0670bb..19f211904 100644 --- a/src/util/string.hpp +++ b/src/util/string.hpp @@ -86,6 +86,11 @@ parse_unsigned(const std::string& value, nonstd::expected percent_decode(nonstd::string_view string); +// Replace the all occurrences of `from` to `to` in `string`. +std::string replace_all(nonstd::string_view string, + nonstd::string_view from, + nonstd::string_view to); + // Replace the first occurrence of `from` to `to` in `string`. std::string replace_first(nonstd::string_view string, nonstd::string_view from, diff --git a/unittest/test_util_string.cpp b/unittest/test_util_string.cpp index 275430413..f914f3d4c 100644 --- a/unittest/test_util_string.cpp +++ b/unittest/test_util_string.cpp @@ -200,6 +200,20 @@ TEST_CASE("util::percent_decode") == "invalid percent-encoded string at position 1: a%0g"); } +TEST_CASE("util::replace_all") +{ + CHECK(util::replace_all("", "", "") == ""); + CHECK(util::replace_all("x", "", "") == "x"); + CHECK(util::replace_all("", "x", "") == ""); + CHECK(util::replace_all("", "", "x") == ""); + CHECK(util::replace_all("x", "y", "z") == "x"); + CHECK(util::replace_all("x", "x", "y") == "y"); + CHECK(util::replace_all("abc", "abc", "defdef") == "defdef"); + CHECK(util::replace_all("xabc", "abc", "defdef") == "xdefdef"); + CHECK(util::replace_all("abcx", "abc", "defdef") == "defdefx"); + CHECK(util::replace_all("xabcyabcz", "abc", "defdef") == "xdefdefydefdefz"); +} + TEST_CASE("util::replace_first") { CHECK(util::replace_first("", "", "") == "");