[Libguestfs] [PATCH 4/4] daemon: add split_lines_sb

Pino Toscano ptoscano at redhat.com
Wed Jun 17 16:09:58 UTC 2015


Mold split_lines_sb from split_lines, so it returns the strings buffer
with the result of the split. This way, we can have the number of lines
in the array, with no need to count them again later.

split_lines is rewritten to take the ownership of the result of
split_lines_sb.
---
 daemon/daemon.h   |  1 +
 daemon/guestfsd.c | 37 ++++++++++++++++++++++++++++---------
 2 files changed, 29 insertions(+), 9 deletions(-)

diff --git a/daemon/daemon.h b/daemon/daemon.h
index f2244b0..136e9a9 100644
--- a/daemon/daemon.h
+++ b/daemon/daemon.h
@@ -110,6 +110,7 @@ extern int compare_device_names (const char *a, const char *b);
 extern char *concat_strings (char *const *argv);
 extern char *join_strings (const char *separator, char *const *argv);
 
+extern struct stringsbuf split_lines_sb (char *str);
 extern char **split_lines (char *str);
 
 extern char **empty_list (void);
diff --git a/daemon/guestfsd.c b/daemon/guestfsd.c
index 198b2b2..21b3600 100644
--- a/daemon/guestfsd.c
+++ b/daemon/guestfsd.c
@@ -1115,7 +1115,8 @@ commandrvf (char **stdoutput, char **stderror, int flags,
     return -1;
 }
 
-/* Split an output string into a NULL-terminated list of lines.
+/* Split an output string into a NULL-terminated list of lines,
+ * wrapped into a stringsbuf.
  * Typically this is used where we have run an external command
  * which has printed out a list of things, and we want to return
  * an actual list.
@@ -1132,15 +1133,23 @@ commandrvf (char **stdoutput, char **stderror, int flags,
  * function (which is usually OK because it's the 'out' string
  * from command()).  You can free the original string, because
  * add_string() strdups the strings.
+ *
+ * argv in the stringsbuf will be NULL in case of errors.
  */
-char **
-split_lines (char *str)
+struct stringsbuf
+split_lines_sb (char *str)
 {
   DECLARE_STRINGSBUF (lines);
+  DECLARE_STRINGSBUF (null);
   char *p, *pend;
 
-  if (STREQ (str, ""))
-    return empty_list ();
+  if (STREQ (str, "")) {
+    /* No need to check the return value, as the stringsbuf will be
+     * returned as it is anyway.
+     */
+    end_stringsbuf (&lines);
+    return lines;
+  }
 
   p = str;
   while (p) {
@@ -1155,16 +1164,26 @@ split_lines (char *str)
     }
 
     if (add_string (&lines, p) == -1) {
-      return NULL;
+      free_stringsbuf (&lines);
+      return null;
     }
 
     p = pend;
   }
 
-  if (end_stringsbuf (&lines) == -1)
-    return NULL;
+  if (end_stringsbuf (&lines) == -1) {
+    free_stringsbuf (&lines);
+    return null;
+  }
+
+  return lines;
+}
 
-  return lines.argv;
+char **
+split_lines (char *str)
+{
+  struct stringsbuf sb = split_lines_sb (str);
+  return take_stringsbuf (&sb);
 }
 
 char **
-- 
2.1.0




More information about the Libguestfs mailing list