[PATCH v2 048/113] commands: time: refactor into new strjoin
Ahmad Fatoum
a.fatoum at pengutronix.de
Mon Mar 4 10:59:33 PST 2024
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 at pengutronix.de>
---
v1 -> v2:
- swapped order with previous commit (Sascha)
Originally posted at: https://lore.barebox.org/barebox/20221027073334.GS6702@pengutronix.de/
Changes:
- remove if statemnt in loop (Sascha)
---
commands/time.c | 17 +++--------------
include/string.h | 2 ++
lib/string.c | 28 ++++++++++++++++++++++++++++
3 files changed, 33 insertions(+), 14 deletions(-)
diff --git a/commands/time.c b/commands/time.c
index 0a38db61845d..a3f270407122 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 71810180b5ba..2f2af85b554f 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 bf0f0455ab3f..695e50bc8fc1 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);
--
2.39.2
More information about the barebox
mailing list