Expose util function to truncate first line

Move the local implementation from adb functions to the string util
functions.
This commit is contained in:
Romain Vimont 2021-11-17 18:25:56 +01:00
parent 443cb14d6e
commit f2781a8b6d
4 changed files with 32 additions and 12 deletions

View file

@ -253,17 +253,6 @@ adb_execute_for_output(const char *serial, const char *const adb_cmd[],
return r; 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 * char *
adb_get_serialno(void) { adb_get_serialno(void) {
char buf[128]; char buf[128];
@ -275,6 +264,6 @@ adb_get_serialno(void) {
return NULL; return NULL;
} }
truncate_first_line(buf, r); sc_str_truncate_first_line(buf, r);
return strdup(buf); return strdup(buf);
} }

View file

@ -291,3 +291,14 @@ error:
free(buf.s); free(buf.s);
return NULL; 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;
}

View file

@ -103,4 +103,15 @@ sc_str_from_wchars(const wchar_t *s);
char * char *
sc_str_wrap_lines(const char *input, unsigned columns, unsigned indent); 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 #endif

View file

@ -337,6 +337,14 @@ static void test_wrap_lines(void) {
free(formatted); 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[]) { int main(int argc, char *argv[]) {
(void) argc; (void) argc;
(void) argv; (void) argv;
@ -356,5 +364,6 @@ int main(int argc, char *argv[]) {
test_parse_integer_with_suffix(); test_parse_integer_with_suffix();
test_strlist_contains(); test_strlist_contains();
test_wrap_lines(); test_wrap_lines();
test_truncate_first_line();
return 0; return 0;
} }