From 9619ade706824a92ea387bdc9d0d27816bf79da5 Mon Sep 17 00:00:00 2001 From: Romain Vimont Date: Wed, 17 Nov 2021 21:38:59 +0100 Subject: [PATCH] Generalize string trunctation util function Add an additional argument to let the client pass the possible end chars. --- app/src/adb.c | 2 +- app/src/util/str.c | 4 ++-- app/src/util/str.h | 4 ++-- app/tests/test_str.c | 24 +++++++++++++++++++++--- 4 files changed, 26 insertions(+), 8 deletions(-) diff --git a/app/src/adb.c b/app/src/adb.c index efeef4f8..a8712bf4 100644 --- a/app/src/adb.c +++ b/app/src/adb.c @@ -264,6 +264,6 @@ adb_get_serialno(void) { return NULL; } - sc_str_truncate_first_line(buf, r); + sc_str_truncate(buf, r, "\r\n"); return strdup(buf); } diff --git a/app/src/util/str.c b/app/src/util/str.c index e63b0270..fdc1a8b3 100644 --- a/app/src/util/str.c +++ b/app/src/util/str.c @@ -293,9 +293,9 @@ error: } size_t -sc_str_truncate_first_line(char *data, size_t len) { +sc_str_truncate(char *data, size_t len, const char *endchars) { data[len - 1] = '\0'; - char *eol = strpbrk(data, "\r\n"); + char *eol = strpbrk(data, endchars); if (eol) { *eol = '\0'; len = eol - data; diff --git a/app/src/util/str.h b/app/src/util/str.h index 77017e90..521dfff5 100644 --- a/app/src/util/str.h +++ b/app/src/util/str.h @@ -104,7 +104,7 @@ char * sc_str_wrap_lines(const char *input, unsigned columns, unsigned indent); /** - * Truncate the data after the first line + * Truncate the data after any of the characters from `endchars` * * An '\0' is always written at the end of the data, even if no newline * character is encountered. @@ -112,6 +112,6 @@ sc_str_wrap_lines(const char *input, unsigned columns, unsigned indent); * Return the size of the resulting line. */ size_t -sc_str_truncate_first_line(char *data, size_t len); +sc_str_truncate(char *data, size_t len, const char *endchars); #endif diff --git a/app/tests/test_str.c b/app/tests/test_str.c index 1cd9a37d..770ddd95 100644 --- a/app/tests/test_str.c +++ b/app/tests/test_str.c @@ -337,12 +337,30 @@ static void test_wrap_lines(void) { free(formatted); } -static void test_truncate_first_line(void) { +static void test_truncate(void) { char s[] = "hello\nworld\n!"; - size_t len = sc_str_truncate_first_line(s, sizeof(s)); + size_t len = sc_str_truncate(s, sizeof(s), "\n"); assert(len == 5); assert(!strcmp("hello", s)); + + char s2[] = "hello\r\nworkd\r\n!"; + len = sc_str_truncate(s2, sizeof(s2), "\n\r"); + + assert(len == 5); + assert(!strcmp("hello", s)); + + char s3[] = "hello world\n!"; + len = sc_str_truncate(s3, sizeof(s3), " \n\r"); + + assert(len == 5); + assert(!strcmp("hello", s3)); + + char s4[] = "hello "; + len = sc_str_truncate(s4, sizeof(s4), " \n\r"); + + assert(len == 5); + assert(!strcmp("hello", s4)); } int main(int argc, char *argv[]) { @@ -364,6 +382,6 @@ int main(int argc, char *argv[]) { test_parse_integer_with_suffix(); test_strlist_contains(); test_wrap_lines(); - test_truncate_first_line(); + test_truncate(); return 0; }