Skip to content

Commit

Permalink
[SKV-627] feat(utils): add an utility function to find string prefix …
Browse files Browse the repository at this point in the history
…by separator (apache#1338)
  • Loading branch information
acelyc111 committed Apr 26, 2023
1 parent 14e89c6 commit 94c0297
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/rdsn/include/dsn/utility/strings.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
9 changes: 9 additions & 0 deletions src/rdsn/src/utils/strings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
22 changes: 22 additions & 0 deletions src/rdsn/src/utils/test/utils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down

0 comments on commit 94c0297

Please sign in to comment.