refactor: add util tr_strvstrip() to strip string_views (#2077)

This commit is contained in:
Charles Kerr 2021-11-01 13:50:53 -05:00 committed by GitHub
parent 3318430455
commit da51a17c30
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 26 additions and 0 deletions

View File

@ -591,6 +591,22 @@ char* tr_strsep(char** str, char const* delims)
#endif
}
std::string_view tr_strvstrip(std::string_view str)
{
auto constexpr test = [](auto ch)
{
return isspace(ch);
};
auto const it = std::find_if_not(std::begin(str), std::end(str), test);
str.remove_prefix(std::distance(std::begin(str), it));
auto const rit = std::find_if_not(std::rbegin(str), std::rend(str), test);
str.remove_suffix(std::distance(std::rbegin(str), rit));
return str;
}
char* tr_strstrip(char* str)
{
if (str != nullptr)

View File

@ -256,6 +256,8 @@ char const* tr_strerror(int errnum);
@return the stripped string */
char* tr_strstrip(char* str);
std::string_view tr_strvstrip(std::string_view str);
/** @brief Returns true if the string ends with the specified case-insensitive suffix */
bool tr_str_has_suffix(char const* str, char const* suffix);

View File

@ -68,6 +68,14 @@ TEST_F(UtilsTest, trStrstrip)
EXPECT_EQ(in, out);
EXPECT_STREQ("test", out);
tr_free(in);
EXPECT_EQ(""sv, tr_strvstrip(" "sv));
EXPECT_EQ("test test"sv, tr_strvstrip(" test test "sv));
EXPECT_EQ("test"sv, tr_strvstrip(" test "sv));
EXPECT_EQ("test"sv, tr_strvstrip(" test "sv));
EXPECT_EQ("test"sv, tr_strvstrip(" test "sv));
EXPECT_EQ("test"sv, tr_strvstrip(" test "sv));
EXPECT_EQ("test"sv, tr_strvstrip("test"sv));
}
TEST_F(UtilsTest, trBuildpath)