]> git.ipfire.org Git - thirdparty/ccache.git/commitdiff
enhance: Add util::replace_all function
authorJoel Rosdahl <joel@rosdahl.net>
Wed, 22 Sep 2021 19:58:47 +0000 (21:58 +0200)
committerJoel Rosdahl <joel@rosdahl.net>
Wed, 22 Sep 2021 19:58:47 +0000 (21:58 +0200)
src/util/string.cpp
src/util/string.hpp
unittest/test_util_string.cpp

index 38df7d99af23c28578197bef0c3ccf8c4a498d5d..aa0ff368e76c3c7df7d68d9506e56062ff99ea4b 100644 (file)
@@ -18,6 +18,7 @@
 
 #include "string.hpp"
 
+#include <assertions.hpp>
 #include <fmtmacros.hpp>
 
 #include <cctype>
@@ -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,
index 62b0670bb35f3fc1006163dd2160280b69443a2e..19f21190414134ab450d552a81ca245a00ef4b8e 100644 (file)
@@ -86,6 +86,11 @@ parse_unsigned(const std::string& value,
 nonstd::expected<std::string, std::string>
 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,
index 27543041343ffb9bcec246b040298cb6f4e6dd8a..f914f3d4c4b8c639fc8650ca443ef9646b8c5263 100644 (file)
@@ -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("", "", "") == "");