Skip to content

Commit b992657

Browse files
peffgitster
authored andcommitted
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 <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent 3689539 commit b992657

File tree

3 files changed

+19
-0
lines changed

3 files changed

+19
-0
lines changed

Documentation/technical/api-argv-array.txt

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,3 +56,10 @@ Functions
5656
`argv_array_clear`::
5757
Free all memory associated with the array and return it to the
5858
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

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,3 +74,14 @@ void argv_array_clear(struct argv_array *array)
7474
}
7575
argv_array_init(array);
7676
}
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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,5 +20,6 @@ void argv_array_pushl(struct argv_array *, ...);
2020
void argv_array_pushv(struct argv_array *, const char **);
2121
void argv_array_pop(struct argv_array *);
2222
void argv_array_clear(struct argv_array *);
23+
const char **argv_array_detach(struct argv_array *);
2324

2425
#endif /* ARGV_ARRAY_H */

0 commit comments

Comments
 (0)