Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(utils): add an utility function to find string prefix by separator #1338

Merged
merged 2 commits into from
Feb 3, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions src/utils/strings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
std::size_t current = input.find(separator);
empiredan marked this conversation as resolved.
Show resolved Hide resolved
if (current == 0 || current == std::string::npos) {
return "";
empiredan marked this conversation as resolved.
Show resolved Hide resolved
}
return input.substr(0, current);
}
} // namespace utils
} // namespace dsn
4 changes: 4 additions & 0 deletions src/utils/strings.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
20 changes: 20 additions & 0 deletions src/utils/test/utils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -443,6 +443,26 @@ 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[] = {{"", ' ', ""},
empiredan marked this conversation as resolved.
Show resolved Hide resolved
{"abc.def", ' ', ""},
{"abc.def", '.', "abc"},
{"ab.cd.ef", '.', "ab"},
{"abc...def", '.', "abc"},
{".abc.def", '.', ""}};
std::string actual_output;
for (const auto &test : tests) {
actual_output = find_string_prefix(test.input, test.separator);
empiredan marked this conversation as resolved.
Show resolved Hide resolved
EXPECT_EQ(actual_output, test.expected_prefix);
}
}

class foo : public ::dsn::ref_counter
{
public:
Expand Down