The usual pattern for an argv array is to initialize it,
push in some strings, and then clear it when done. Very
occasionally, though, we must do other exotic things with
the memory, like freeing the list but keeping the strings.
Let's provide a detach function so that callers can make use
of our API to build up the array, and then take ownership of
it.

Signed-off-by: Jeff King <p...@peff.net>
---
 Documentation/technical/api-argv-array.txt |  7 +++++++
 argv-array.c                               | 11 +++++++++++
 argv-array.h                               |  1 +
 3 files changed, 19 insertions(+)

diff --git a/Documentation/technical/api-argv-array.txt 
b/Documentation/technical/api-argv-array.txt
index 8076172..cfc0630 100644
--- a/Documentation/technical/api-argv-array.txt
+++ b/Documentation/technical/api-argv-array.txt
@@ -56,3 +56,10 @@ Functions
 `argv_array_clear`::
        Free all memory associated with the array and return it to the
        initial, empty state.
+
+`argv_array_detach`::
+       Disconnect the `argv` member from the `argv_array` struct and
+       return it. The caller is responsible for freeing the memory used
+       by the array, and by the strings it references. After detaching,
+       the `argv_array` is in a reinitialized state and can be pushed
+       into again.
diff --git a/argv-array.c b/argv-array.c
index eaed477..5d370fa 100644
--- a/argv-array.c
+++ b/argv-array.c
@@ -74,3 +74,14 @@ void argv_array_clear(struct argv_array *array)
        }
        argv_array_init(array);
 }
+
+const char **argv_array_detach(struct argv_array *array)
+{
+       if (array->argv == empty_argv)
+               return xcalloc(1, sizeof(const char *));
+       else {
+               const char **ret = array->argv;
+               argv_array_init(array);
+               return ret;
+       }
+}
diff --git a/argv-array.h b/argv-array.h
index a2fa0aa..29056e4 100644
--- a/argv-array.h
+++ b/argv-array.h
@@ -20,5 +20,6 @@ void argv_array_pushl(struct argv_array *, ...);
 void argv_array_pushv(struct argv_array *, const char **);
 void argv_array_pop(struct argv_array *);
 void argv_array_clear(struct argv_array *);
+const char **argv_array_detach(struct argv_array *);
 
 #endif /* ARGV_ARRAY_H */
-- 
2.7.2.645.g4e1306c

--
To unsubscribe from this list: send the line "unsubscribe git" in
the body of a message to majord...@vger.kernel.org
More majordomo info at  http://vger.kernel.org/majordomo-info.html

Reply via email to