diff --git a/libtransmission/utils.cc b/libtransmission/utils.cc index 2f03b229e..df5f5211f 100644 --- a/libtransmission/utils.cc +++ b/libtransmission/utils.cc @@ -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) diff --git a/libtransmission/utils.h b/libtransmission/utils.h index bf266ad7b..ee1a64ec3 100644 --- a/libtransmission/utils.h +++ b/libtransmission/utils.h @@ -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); diff --git a/tests/libtransmission/utils-test.cc b/tests/libtransmission/utils-test.cc index 200538dcf..79d206c71 100644 --- a/tests/libtransmission/utils-test.cc +++ b/tests/libtransmission/utils-test.cc @@ -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)