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

index 88f1c9b5426c76e5e813d1fd2766b682062a3a63..87055605eb184971566847593ef1ba778e9ed470 100644 (file)
@@ -21,6 +21,7 @@
 #include <fmtmacros.hpp>
 
 #include <cctype>
+#include <iostream>
 
 namespace util {
 
@@ -129,6 +130,27 @@ percent_decode(nonstd::string_view string)
   return result;
 }
 
+std::string
+replace_first(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;
+  const auto pos = string.find(from);
+  if (pos != nonstd::string_view::npos) {
+    result.append(string.data(), pos);
+    result.append(to.data(), to.length());
+    result.append(string.data() + pos + from.size());
+  } else {
+    result = std::string(string);
+  }
+  return result;
+}
+
 std::pair<nonstd::string_view, nonstd::optional<nonstd::string_view>>
 split_once(const nonstd::string_view string, const char split_char)
 {
index aa9fccf51e274285b0e1bd8550b940928fbf84ae..4f782c37ae0c62b1d0abf2c973699cc2390e6341 100644 (file)
@@ -81,6 +81,11 @@ parse_unsigned(const std::string& value,
 nonstd::expected<std::string, std::string>
 percent_decode(nonstd::string_view string);
 
+// Replace the first occurrence of `from` to `to` in `string`.
+std::string replace_first(nonstd::string_view string,
+                          nonstd::string_view from,
+                          nonstd::string_view to);
+
 // Split `string` into two parts using `split_char` as the delimiter. The second
 // part will be `nullopt` if there is no `split_char` in `string.`
 std::pair<nonstd::string_view, nonstd::optional<nonstd::string_view>>
index e53238ef612f3118d32dc50beeb157b1d3fd01b0..294cdb1eac11609834cfabf9628411077dd075bd 100644 (file)
@@ -187,6 +187,17 @@ TEST_CASE("util::percent_decode")
         == "invalid percent-encoded string at position 1: a%0g");
 }
 
+TEST_CASE("util::replace_first")
+{
+  CHECK(util::replace_first("", "", "") == "");
+  CHECK(util::replace_first("x", "", "") == "x");
+  CHECK(util::replace_first("", "x", "") == "");
+  CHECK(util::replace_first("", "", "x") == "");
+  CHECK(util::replace_first("x", "y", "z") == "x");
+  CHECK(util::replace_first("x", "x", "y") == "y");
+  CHECK(util::replace_first("xabcyabcz", "abc", "defdef") == "xdefdefyabcz");
+}
+
 TEST_CASE("util::split_once")
 {
   using nonstd::nullopt;