diff --git a/include/common/string-helpers.h b/include/common/string-helpers.h index e95b4e4a..b37da83b 100644 --- a/include/common/string-helpers.h +++ b/include/common/string-helpers.h @@ -73,4 +73,12 @@ char *str_join(const char *const parts[], */ bool str_endswith(const char *const string, const char *const suffix); +/** + * str_starts_with - indicate whether a string starts with a given character + * @string: string to test + * @needle: character to expect in string + * @ignore_chars: characters to ignore at start such as space and "\t" + */ +bool str_starts_with(const char *s, char needle, const char *ignore_chars); + #endif /* LABWC_STRING_HELPERS_H */ diff --git a/src/common/string-helpers.c b/src/common/string-helpers.c index 10978507..a1d873dd 100644 --- a/src/common/string-helpers.c +++ b/src/common/string-helpers.c @@ -170,3 +170,10 @@ str_endswith(const char *const string, const char *const suffix) return strcmp(string + len_str - len_sfx, suffix) == 0; } + +bool +str_starts_with(const char *s, char needle, const char *ignore_chars) +{ + return (s + strspn(s, ignore_chars))[0] == needle; +} + diff --git a/src/menu/menu.c b/src/menu/menu.c index d1f85901..6a0f5ce8 100644 --- a/src/menu/menu.c +++ b/src/menu/menu.c @@ -1419,12 +1419,6 @@ handle_pipemenu_timeout(void *_ctx) return 0; } -static bool -starts_with_less_than(const char *s) -{ - return (s + strspn(s, " \t\r\n"))[0] == '<'; -} - static int handle_pipemenu_readable(int fd, uint32_t mask, void *_ctx) { @@ -1468,7 +1462,7 @@ handle_pipemenu_readable(int fd, uint32_t mask, void *_ctx) } /* Guard against badly formed data such as binary input */ - if (!starts_with_less_than(ctx->buf.data)) { + if (!str_starts_with(ctx->buf.data, '<', " \t\r\n")) { wlr_log(WLR_ERROR, "expect xml data to start with '<'; abort pipemenu"); goto clean_up; } diff --git a/t/meson.build b/t/meson.build index 5517b973..eb997fe2 100644 --- a/t/meson.build +++ b/t/meson.build @@ -11,6 +11,7 @@ test_lib = static_library( tests = [ 'buf-simple', + 'str', ] foreach t : tests diff --git a/t/str.c b/t/str.c new file mode 100644 index 00000000..79debb1c --- /dev/null +++ b/t/str.c @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: GPL-2.0-only +#define _POSIX_C_SOURCE 200809L +#include +#include +#include +#include +#include +#include +#include "common/string-helpers.h" + +static void +test_str_starts_with(void **state) +{ + (void)state; + + assert_true(str_starts_with(" foo", 'f', " \t\r\n")); + assert_true(str_starts_with("f", 'f', " \t\r\n")); + assert_false(str_starts_with(" foo", '<', " ")); +} + +int main(int argc, char **argv) +{ + const struct CMUnitTest tests[] = { + cmocka_unit_test(test_str_starts_with), + }; + + return cmocka_run_group_tests(tests, NULL, NULL); +}