diff options
author | Ahmad Fatoum <a.fatoum@pengutronix.de> | 2024-03-04 19:59:33 +0100 |
---|---|---|
committer | Sascha Hauer <s.hauer@pengutronix.de> | 2024-03-05 16:28:05 +0100 |
commit | 788f616946df66732ed8fde05f56b6329debdba3 (patch) | |
tree | 79536a35ce4bbf42dbd198d2ecf2294546e17361 | |
parent | 35a903414ddcf8cef180a29a8271f59e0b1623cd (diff) | |
download | barebox-788f616946df.tar.gz barebox-788f616946df.tar.xz |
commands: time: refactor into new strjoin
time concatenates all its remaining arguments with a space in-between
and then passes that to the command executor. This can be useful
elsewhere as well, so factor it out into a new strjoin function.
No functional change.
Signed-off-by: Ahmad Fatoum <a.fatoum@pengutronix.de>
Link: https://lore.barebox.org/20240304190038.3486881-49-a.fatoum@pengutronix.de
Signed-off-by: Sascha Hauer <s.hauer@pengutronix.de>
-rw-r--r-- | commands/time.c | 17 | ||||
-rw-r--r-- | include/string.h | 2 | ||||
-rw-r--r-- | lib/string.c | 28 |
3 files changed, 33 insertions, 14 deletions
diff --git a/commands/time.c b/commands/time.c index 0a38db6184..a3f2704071 100644 --- a/commands/time.c +++ b/commands/time.c @@ -9,11 +9,10 @@ static int do_time(int argc, char *argv[]) { - int i, opt; - unsigned char *buf, *p; + int opt; + unsigned char *buf; u64 start, end, diff64; bool nanoseconds = false; - int len = 1; /* '\0' */ while ((opt = getopt(argc, argv, "+n")) > 0) { switch (opt) { @@ -31,17 +30,7 @@ static int do_time(int argc, char *argv[]) if (argc < 1) return COMMAND_ERROR_USAGE; - for (i = 0; i < argc; i++) - len += strlen(argv[i]) + 1; - - p = buf = xmalloc(len); - - for (i = 0; i < argc - 1; i++) { - p = stpcpy(p, argv[i]); - p = mempcpy(p, " ", strlen(" ")); - } - - stpcpy(p, argv[i]); + buf = strjoin(" ", argv, argc); start = get_time_ns(); diff --git a/include/string.h b/include/string.h index 71810180b5..2f2af85b55 100644 --- a/include/string.h +++ b/include/string.h @@ -21,6 +21,8 @@ char *parse_assignment(char *str); int strverscmp(const char *a, const char *b); +char *strjoin(const char *separator, char **array, size_t len); + static inline int strcmp_ptr(const char *a, const char *b) { return a && b ? strcmp(a, b) : compare3(a, b); diff --git a/lib/string.c b/lib/string.c index bf0f0455ab..695e50bc8f 100644 --- a/lib/string.c +++ b/lib/string.c @@ -1000,3 +1000,31 @@ char *parse_assignment(char *str) return value; } + +char *strjoin(const char *separator, char **arr, size_t arrlen) +{ + size_t separatorlen; + int len = 1; /* '\0' */ + char *buf, *p; + int i; + + separatorlen = strlen(separator); + + for (i = 0; i < arrlen; i++) + len += strlen(arr[i]) + separatorlen; + + if (!arrlen) + return xzalloc(1); + + p = buf = xmalloc(len); + + for (i = 0; i < arrlen - 1; i++) { + p = stpcpy(p, arr[i]); + p = mempcpy(p, separator, separatorlen); + } + + stpcpy(p, arr[i]); + + return buf; +} +EXPORT_SYMBOL(strjoin); |