diff --git a/lib/linux_string.c b/lib/linux_string.c index d5a5e08d98c..4b92cd923f2 100644 --- a/lib/linux_string.c +++ b/lib/linux_string.c @@ -31,13 +31,15 @@ char *skip_spaces(const char *str) * Note that the first trailing whitespace is replaced with a %NUL-terminator * in the given string @s. Returns a pointer to the first non-whitespace * character in @s. + * + * Note that if the string consist of only spaces, then the terminator is placed + * at the start of the string, with the return value pointing there also. */ char *strim(char *s) { size_t size; char *end; - s = skip_spaces(s); size = strlen(s); if (!size) return s; @@ -47,5 +49,5 @@ char *strim(char *s) end--; *(end + 1) = '\0'; - return s; + return skip_spaces(s); } diff --git a/test/lib/string.c b/test/lib/string.c index 31391a387b9..f56c2e4c946 100644 --- a/test/lib/string.c +++ b/test/lib/string.c @@ -261,3 +261,40 @@ static int lib_strstr(struct unit_test_state *uts) return 0; } LIB_TEST(lib_strstr, 0); + +static int lib_strim(struct unit_test_state *uts) +{ + char buf[BUFLEN], *p; + + strcpy(buf, "abc"); + ut_asserteq_str("abc", strim(buf)); + + /* leading space */ + strcpy(buf, " abc"); + ut_asserteq_str("abc", strim(buf)); + + /* multiple leading spaces */ + strcpy(buf, " abc"); + ut_asserteq_str("abc", strim(buf)); + + /* multiple internal spaces */ + strcpy(buf, " a bc"); + ut_asserteq_str("a bc", strim(buf)); + + /* with trailing space */ + strcpy(buf, " a bc "); + ut_asserteq_str("a bc", strim(buf)); + + /* with multiple trailing spaces */ + strcpy(buf, " a bc "); + ut_asserteq_str("a bc", strim(buf)); + + /* with only spaces */ + strcpy(buf, " "); + p = strim(buf); + ut_asserteq_ptr(p, buf); + ut_asserteq_str("", p); + + return 0; +} +LIB_TEST(lib_strim, 0);