[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]

[Libguestfs] [PATCH 5/7] daemon: New utility functions 'join_strings', 'concat_strings'.



From: "Richard W.M. Jones" <rjones redhat com>

Useful functions for concatenating strings together.
---
 daemon/daemon.h   |    7 +++++++
 daemon/guestfsd.c |   41 +++++++++++++++++++++++++++++++++++++++++
 2 files changed, 48 insertions(+)

diff --git a/daemon/daemon.h b/daemon/daemon.h
index 85eec45..b9dba13 100644
--- a/daemon/daemon.h
+++ b/daemon/daemon.h
@@ -82,6 +82,13 @@ extern void free_stringslen (char **argv, size_t len);
 extern void sort_device_names (char **argv, size_t len);
 extern int compare_device_names (const char *a, const char *b);
 
+/* Concatenate strings, optionally with a separator string between
+ * each.  On error, these return NULL but do NOT call reply_with_* nor
+ * free anything.
+ */
+extern char *concat_strings (const struct stringsbuf *sb);
+extern char *join_strings (const char *separator, const struct stringsbuf *sb);
+
 extern char **split_lines (char *str);
 
 #define command(out,err,name,...) commandf((out),(err),0,(name),__VA_ARGS__)
diff --git a/daemon/guestfsd.c b/daemon/guestfsd.c
index 2b0acf9..17a0aa0 100644
--- a/daemon/guestfsd.c
+++ b/daemon/guestfsd.c
@@ -578,6 +578,47 @@ sort_device_names (char **argv, size_t len)
   qsort (argv, len, sizeof (char *), compare_device_names_vp);
 }
 
+char *
+concat_strings (const struct stringsbuf *sb)
+{
+  return join_strings ("", sb);
+}
+
+char *
+join_strings (const char *separator, const struct stringsbuf *sb)
+{
+  size_t i, len, seplen, rlen;
+  char *r;
+
+  seplen = strlen (separator);
+
+  len = 0;
+  for (i = 0; i < sb->size; ++i) {
+    if (i > 0)
+      len += seplen;
+    len += strlen (sb->argv[i]);
+  }
+  len++; /* for final \0 */
+
+  r = malloc (len);
+  if (r == NULL)
+    return NULL;
+
+  rlen = 0;
+  for (i = 0; i < sb->size; ++i) {
+    if (i > 0) {
+      memcpy (&r[rlen], separator, seplen);
+      rlen += seplen;
+    }
+    len = strlen (sb->argv[i]);
+    memcpy (&r[rlen], sb->argv[i], len);
+    rlen += len;
+  }
+  r[rlen] = '\0';
+
+  return r;
+}
+
 /* Easy ways to run external commands.  For full documentation, see
  * 'commandrvf' below.
  */
-- 
1.7.10.4


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]