From f2781a8b6d5c37d1fa3c0d0291a01a8bd918dddd Mon Sep 17 00:00:00 2001 From: Romain Vimont Date: Wed, 17 Nov 2021 18:25:56 +0100 Subject: [PATCH] Expose util function to truncate first line Move the local implementation from adb functions to the string util functions. --- app/src/adb.c | 13 +------------ app/src/util/str.c | 11 +++++++++++ app/src/util/str.h | 11 +++++++++++ app/tests/test_str.c | 9 +++++++++ 4 files changed, 32 insertions(+), 12 deletions(-) diff --git a/app/src/adb.c b/app/src/adb.c index 4f50ee5f..efeef4f8 100644 --- a/app/src/adb.c +++ b/app/src/adb.c @@ -253,17 +253,6 @@ adb_execute_for_output(const char *serial, const char *const adb_cmd[], return r; } -static size_t -truncate_first_line(char *data, size_t len) { - data[len - 1] = '\0'; - char *eol = strpbrk(data, "\r\n"); - if (eol) { - *eol = '\0'; - len = eol - data; - } - return len; -} - char * adb_get_serialno(void) { char buf[128]; @@ -275,6 +264,6 @@ adb_get_serialno(void) { return NULL; } - truncate_first_line(buf, r); + sc_str_truncate_first_line(buf, r); return strdup(buf); } diff --git a/app/src/util/str.c b/app/src/util/str.c index 7935c6bb..e63b0270 100644 --- a/app/src/util/str.c +++ b/app/src/util/str.c @@ -291,3 +291,14 @@ error: free(buf.s); return NULL; } + +size_t +sc_str_truncate_first_line(char *data, size_t len) { + data[len - 1] = '\0'; + char *eol = strpbrk(data, "\r\n"); + if (eol) { + *eol = '\0'; + len = eol - data; + } + return len; +} diff --git a/app/src/util/str.h b/app/src/util/str.h index 54e32808..77017e90 100644 --- a/app/src/util/str.h +++ b/app/src/util/str.h @@ -103,4 +103,15 @@ sc_str_from_wchars(const wchar_t *s); char * sc_str_wrap_lines(const char *input, unsigned columns, unsigned indent); +/** + * Truncate the data after the first line + * + * An '\0' is always written at the end of the data, even if no newline + * character is encountered. + * + * Return the size of the resulting line. + */ +size_t +sc_str_truncate_first_line(char *data, size_t len); + #endif diff --git a/app/tests/test_str.c b/app/tests/test_str.c index 2b030885..1cd9a37d 100644 --- a/app/tests/test_str.c +++ b/app/tests/test_str.c @@ -337,6 +337,14 @@ static void test_wrap_lines(void) { free(formatted); } +static void test_truncate_first_line(void) { + char s[] = "hello\nworld\n!"; + size_t len = sc_str_truncate_first_line(s, sizeof(s)); + + assert(len == 5); + assert(!strcmp("hello", s)); +} + int main(int argc, char *argv[]) { (void) argc; (void) argv; @@ -356,5 +364,6 @@ int main(int argc, char *argv[]) { test_parse_integer_with_suffix(); test_strlist_contains(); test_wrap_lines(); + test_truncate_first_line(); return 0; }