]> git.ipfire.org Git - thirdparty/ccache.git/commitdiff
Add util::ends_with
authorJoel Rosdahl <joel@rosdahl.net>
Sun, 25 Aug 2019 20:17:22 +0000 (22:17 +0200)
committerJoel Rosdahl <joel@rosdahl.net>
Thu, 5 Sep 2019 20:04:43 +0000 (22:04 +0200)
src/util.cpp
src/util.hpp
unittest/test_util.cpp

index f3d462b2e6fa429f57121779871eb975e13cf147..0c46fea4e497bebf8aacba48251efd121426c9b1 100644 (file)
@@ -1764,6 +1764,15 @@ dir_name(const std::string& path)
   return n == 0 ? "/" : path.substr(0, n);
 }
 
+bool
+ends_with(const std::string& string, const std::string& suffix)
+{
+  return suffix.length() <= string.length()
+         && string.compare(
+              string.length() - suffix.length(), suffix.length(), suffix)
+              == 0;
+}
+
 std::string
 read_file(const std::string& path)
 {
index 7be3b5b131665d5b4bfcf7ec8550eb687ab4969f..dc3bf86fc2d501bff1435ef170b1aeb077bf9f6b 100644 (file)
@@ -35,6 +35,9 @@ bool create_dir(const std::string& dir);
 // Get directory name of path.
 std::string dir_name(const std::string& path);
 
+// Return true if suffix is a suffix of string.
+bool ends_with(const std::string& string, const std::string& suffix);
+
 // Read file data as a string.
 //
 // Throws Error on error.
index 9520834464eefa3e11af79cb814ebba697b98f6d..7fabf181a19b4d04f67a8add52363707b09d1169 100644 (file)
@@ -53,6 +53,24 @@ TEST_CASE("util::dir_name")
   CHECK(util::dir_name("/foo/bar/f.txt") == "/foo/bar");
 }
 
+TEST_CASE("util::ends_with")
+{
+  CHECK(util::ends_with("", ""));
+  CHECK(util::ends_with("x", ""));
+  CHECK(util::ends_with("x", "x"));
+  CHECK(util::ends_with("xy", ""));
+  CHECK(util::ends_with("xy", "y"));
+  CHECK(util::ends_with("xy", "xy"));
+  CHECK(util::ends_with("xyz", ""));
+  CHECK(util::ends_with("xyz", "z"));
+  CHECK(util::ends_with("xyz", "yz"));
+  CHECK(util::ends_with("xyz", "xyz"));
+
+  CHECK_FALSE(util::ends_with("", "x"));
+  CHECK_FALSE(util::ends_with("x", "y"));
+  CHECK_FALSE(util::ends_with("x", "xy"));
+}
+
 TEST_CASE("util::read_file and util::write_file")
 {
   util::write_file("test", "foo\nbar\n");