@@ -80,6 +80,20 @@ void string_list_remove(struct string_list *list, const char *string,
}
}
+void string_list_pop(struct string_list *list, int free_util)
+{
+ if (list->nr == 0)
+ BUG("tried to remove an item from empty string list");
+
+ if (list->strdup_strings)
+ free(list->items[list->nr - 1].string);
+
+ if (free_util)
+ free(list->items[list->nr - 1].util);
+
+ list->nr--;
+}
+
int string_list_has_string(const struct string_list *list, const char *string)
{
int exact_match;
@@ -191,6 +191,21 @@ extern void string_list_remove(struct string_list *list, const char *string,
*/
struct string_list_item *string_list_lookup(struct string_list *list, const char *string);
+/**
+ * Removes the last item from the list.
+ * The caller must ensure that the list is not empty.
+ */
+void string_list_pop(struct string_list *list, int free_util);
+
+/*
+ * Returns the last item of the list. As it returns the raw access, do not
+ * modify the list while holding onto the returned pointer.
+ */
+static inline struct string_list_item *string_list_last(struct string_list *list)
+{
+ return &list->items[list->nr - 1];
+}
+
/*
* Remove all but the first of consecutive entries with the same
* string value. If free_util is true, call free() on the util
Add a few functions to allow a string-list to be used as a stack: - string_list_last() lets a caller peek the string_list_item at the end of the string list. The caller needs to be aware that it is borrowing a pointer, which can become invalid if/when the string_list is resized. - string_list_pop() removes the string_list_item at the end of the string list. - there is no string_list_push(); string_list_append() can be used in its place. You can use them in this pattern: while (list.nr) { struct string_list_item *item = string_list_last(&list); work_on(item); string_list_pop(&list, free_util); } Helped-by: Junio C Hamano <gitster@pobox.com> Signed-off-by: Stefan Beller <sbeller@google.com> --- string-list.c | 14 ++++++++++++++ string-list.h | 15 +++++++++++++++ 2 files changed, 29 insertions(+)