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 <[email protected]>
Signed-off-by: Stefan Beller <[email protected]>
---
I will be resending this series shortly, but it will not contain this patch,
as I will have no need for these any longer.
For the record, this is the final state of this patch.
It may be useful on its own.
Thanks,
Stefan
string-list.c | 14 ++++++++++++++
string-list.h | 15 +++++++++++++++
2 files changed, 29 insertions(+)
diff --git a/string-list.c b/string-list.c
index 771c4550980..04db2b537c0 100644
--- a/string-list.c
+++ b/string-list.c
@@ -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;
diff --git a/string-list.h b/string-list.h
index ff8f6094a33..15f2936e337 100644
--- a/string-list.h
+++ b/string-list.h
@@ -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
--
2.19.0.444.g18242da7ef-goog