From 01fb2ba5b61952c8c08eea976ff44582b918e256 Mon Sep 17 00:00:00 2001
From: Bensong Liu <bensl@microsoft.com>
Date: Tue, 28 Jul 2020 17:13:58 +0800
Subject: [PATCH] add rlib::string.starts_with, ends_with

---
 string.hpp         | 20 ++++++++++++++++++++
 test/src/string.cc | 12 ++++++++++++
 2 files changed, 32 insertions(+)

diff --git a/string.hpp b/string.hpp
index 9fe7968..c8789c1 100644
--- a/string.hpp
+++ b/string.hpp
@@ -374,6 +374,26 @@ namespace rlib {
             return *this;
         }
 
+        bool starts_with(const std::string &what) const {
+            if(size() < what.size()) return false;
+
+            std::string::value_type diffBits = 0;
+            for(auto i = 0; i < what.size(); ++i) {
+                diffBits = diffBits | (what[i] ^ (*this)[i]);
+            }
+            return diffBits == 0;
+        }
+        bool ends_with(const std::string &what) const {
+            if(size() < what.size()) return false;
+
+            std::string::value_type diffBits = 0;
+            auto offset = size() - what.size();
+            for(auto i = 0; i < what.size(); ++i) {
+                diffBits = diffBits | (what[i] ^ (*this)[offset+i]);
+            }
+            return diffBits == 0;
+        }
+
         template <typename... Args>
         string &format(Args... args) {
             return operator=(std::move(impl::format_string(*this, args ...)));
diff --git a/test/src/string.cc b/test/src/string.cc
index 82d7846..681d446 100644
--- a/test/src/string.cc
+++ b/test/src/string.cc
@@ -49,6 +49,18 @@ TEST_CASE("rlib::string others", "[string_op]") {
     test_str = "hello world \n abc def some   random  ";
     auto test_str2 = test_str;
     REQUIRE(" "_rs.join(test_str.split(' ')) == test_str2);
+
+    const rlib::string test_str3 = "|123||";
+    REQUIRE(test_str3.starts_with("") == true);
+    REQUIRE(test_str3.starts_with("|") == true);
+    REQUIRE(test_str3.starts_with("|123||") == true);
+    REQUIRE(test_str3.starts_with("1123||") == false);
+    REQUIRE(test_str3.starts_with("|123|||") == false);
+    REQUIRE(test_str3.ends_with("") == true);
+    REQUIRE(test_str3.ends_with("|") == true);
+    REQUIRE(test_str3.ends_with("23||") == true);
+    REQUIRE(test_str3.ends_with("1123||") == false);
+    REQUIRE(test_str3.ends_with("123|||") == false);
 }
 
 
-- 
GitLab