[PATCH 2/6] commands: time: refactor into new strjoin
Ahmad Fatoum
a.fatoum at pengutronix.de
Tue Oct 25 23:42:01 PDT 2022
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>
---
commands/time.c | 11 +----------
include/string.h | 2 ++
lib/string.c | 22 ++++++++++++++++++++++
3 files changed, 25 insertions(+), 10 deletions(-)
diff --git a/commands/time.c b/commands/time.c
index 5b8933ea6553..336128f6a9be 100644
--- a/commands/time.c
+++ b/commands/time.c
@@ -12,26 +12,17 @@ static int do_time(int argc, char *argv[])
unsigned char *buf;
u64 start, end, diff64;
bool nanoseconds = false;
- int len = 1; /* '\0' */
if (argc < 2)
return COMMAND_ERROR_USAGE;
- for (i = 1; i < argc; i++)
- len += strlen(argv[i]) + 1;
-
- buf = xzalloc(len);
-
i = 1;
if (!strcmp(argv[i], "-n")) {
nanoseconds = true;
i++;
}
- for (; i < argc; i++) {
- strcat(buf, argv[i]);
- strcat(buf, " ");
- }
+ buf = strjoin(" ", &argv[i], argc - i);
start = get_time_ns();
diff --git a/include/string.h b/include/string.h
index d423bee6fba5..2cc727fd1d7a 100644
--- a/include/string.h
+++ b/include/string.h
@@ -17,4 +17,6 @@ void *__nokasan_default_memcpy(void * dest,const void *src,size_t count);
char *parse_assignment(char *str);
+char *strjoin(const char *separator, char **array, size_t len);
+
#endif /* __STRING_H */
diff --git a/lib/string.c b/lib/string.c
index 6389217d5b41..a500e8a3d1ba 100644
--- a/lib/string.c
+++ b/lib/string.c
@@ -938,3 +938,25 @@ 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;
+ int i;
+
+ separatorlen = strlen(separator);
+
+ for (i = 0; i < arrlen; i++)
+ len += strlen(arr[i]) + separatorlen;
+
+ buf = xzalloc(len);
+
+ for (i = 0; i < arrlen; i++) {
+ strcat(buf, arr[i]);
+ strcat(buf, separator);
+ }
+
+ return buf;
+}
--
2.30.2
More information about the barebox
mailing list