From 94c0297649d229113dea545eb6c4473c5fd669a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B5=96=E8=BF=8E=E6=98=A5?= Date: Wed, 26 Apr 2023 14:05:11 +0800 Subject: [PATCH] [SKV-627] feat(utils): add an utility function to find string prefix by separator (#1338) --- src/rdsn/include/dsn/utility/strings.h | 4 ++++ src/rdsn/src/utils/strings.cpp | 9 +++++++++ src/rdsn/src/utils/test/utils.cpp | 22 ++++++++++++++++++++++ 3 files changed, 35 insertions(+) diff --git a/src/rdsn/include/dsn/utility/strings.h b/src/rdsn/include/dsn/utility/strings.h index 5fbb5af10d..2b6548b77c 100644 --- a/src/rdsn/include/dsn/utility/strings.h +++ b/src/rdsn/include/dsn/utility/strings.h @@ -81,5 +81,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/rdsn/src/utils/strings.cpp b/src/rdsn/src/utils/strings.cpp index 412d3e17d8..0ae8578b2c 100644 --- a/src/rdsn/src/utils/strings.cpp +++ b/src/rdsn/src/utils/strings.cpp @@ -219,5 +219,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/rdsn/src/utils/test/utils.cpp b/src/rdsn/src/utils/test/utils.cpp index 7cf009aa73..a0940b115c 100644 --- a/src/rdsn/src/utils/test/utils.cpp +++ b/src/rdsn/src/utils/test/utils.cpp @@ -212,6 +212,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: