argv-array: add detach function
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 <peff@peff.net> Signed-off-by: Junio C Hamano <gitster@pobox.com>
Jeff King committed
Feb 22, 2016 at 17:44 UTC
b992657ed0e2720e20302b0ac8c210dff55950b2
3 files changed
+19
Documentation/technical/api-argv-array.txt
+7
@@ -56,3 +56,10 @@ Functions
56
`argv_array_clear`::
57
Free all memory associated with the array and return it to the
58
initial, empty state.
59
+
60
+`argv_array_detach`::
61
+ Disconnect the `argv` member from the `argv_array` struct and
62
+ return it. The caller is responsible for freeing the memory used
63
+ by the array, and by the strings it references. After detaching,
64
+ the `argv_array` is in a reinitialized state and can be pushed
65
+ into again.
argv-array.c
+11
@@ -74,3 +74,14 @@ void argv_array_clear(struct argv_array *array)
74
}
75
argv_array_init(array);
76
}
77
+
78
+const char **argv_array_detach(struct argv_array *array)
79
+{
80
+ if (array->argv == empty_argv)
81
+ return xcalloc(1, sizeof(const char *));
82
+ else {
83
+ const char **ret = array->argv;
84
+ argv_array_init(array);
85
+ return ret;
86
+ }
87
+}
argv-array.h
+1
@@ -20,5 +20,6 @@ void argv_array_pushl(struct argv_array *, ...);
20
void argv_array_pushv(struct argv_array *, const char **);
21
void argv_array_pop(struct argv_array *);
22
void argv_array_clear(struct argv_array *);
23
+const char **argv_array_detach(struct argv_array *);
24
25
#endif /* ARGV_ARRAY_H */