This is an automated email from the ASF dual-hosted git repository.
laiyingchun pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-pegasus.git
The following commit(s) were added to refs/heads/master by this push:
new 390ccf8ff feat(utils): add an utility function to find string prefix
by separator (#1338)
390ccf8ff is described below
commit 390ccf8ffd6d599ab4b9bdeba19ffb0fdbc66b0a
Author: WHBANG <[email protected]>
AuthorDate: Fri Feb 3 15:14:19 2023 +0800
feat(utils): add an utility function to find string prefix by separator
(#1338)
---
src/utils/strings.cpp | 9 +++++++++
src/utils/strings.h | 4 ++++
src/utils/test/utils.cpp | 22 ++++++++++++++++++++++
3 files changed, 35 insertions(+)
diff --git a/src/utils/strings.cpp b/src/utils/strings.cpp
index 81f352a91..0d06e4046 100644
--- a/src/utils/strings.cpp
+++ b/src/utils/strings.cpp
@@ -417,5 +417,14 @@ std::string string_md5(const char *buffer, unsigned length)
return result;
}
+
+std::string find_string_prefix(const std::string &input, char separator)
+{
+ auto current = input.find(separator);
+ if (current == 0 || current == std::string::npos) {
+ return std::string();
+ }
+ return input.substr(0, current);
+}
} // namespace utils
} // namespace dsn
diff --git a/src/utils/strings.h b/src/utils/strings.h
index f5c03f479..c831ed0b7 100644
--- a/src/utils/strings.h
+++ b/src/utils/strings.h
@@ -115,5 +115,9 @@ char *trim_string(char *s);
// calculate the md5 checksum of buffer
std::string string_md5(const char *buffer, unsigned int length);
+
+// splits the "input" string by the only character "separator" to get the
string prefix.
+// if there is no prefix or the first character is "separator", it will return
"".
+std::string find_string_prefix(const std::string &input, char separator);
} // namespace utils
} // namespace dsn
diff --git a/src/utils/test/utils.cpp b/src/utils/test/utils.cpp
index df65ba536..2f6ccab77 100644
--- a/src/utils/test/utils.cpp
+++ b/src/utils/test/utils.cpp
@@ -443,6 +443,28 @@ TEST(core, dlink)
EXPECT_TRUE(count == 0);
}
+TEST(core, find_string_prefix)
+{
+ struct test_case
+ {
+ std::string input;
+ char separator;
+ std::string expected_prefix;
+ } tests[] = {{"", ' ', ""},
+ {"abc.def", ' ', ""},
+ {"abc.def", '.', "abc"},
+ {"ab.cd.ef", '.', "ab"},
+ {"abc...def", '.', "abc"},
+ {".abc.def", '.', ""},
+ {" ", ' ', ""},
+ {"..", '.', ""},
+ {". ", ' ', "."}};
+ for (const auto &test : tests) {
+ auto actual_output = find_string_prefix(test.input, test.separator);
+ EXPECT_EQ(actual_output, test.expected_prefix);
+ }
+}
+
class foo : public ::dsn::ref_counter
{
public:
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]