Skip to content

Commit 86d4b52

Browse files
Johannes Sixtgitster
authored andcommitted
string-list: Add API to remove an item from an unsorted list
Teach the string-list API how to remove an entry in O(1) runtime by moving the last entry to the vacated spot. As such, the routine works only for unsorted lists. Signed-off-by: Johannes Sixt <j6t@kdbg.org> Signed-off-by: Elijah Newren <newren@gmail.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>
1 parent aacb82d commit 86d4b52

File tree

3 files changed

+20
-0
lines changed

3 files changed

+20
-0
lines changed

Documentation/technical/api-string-list.txt

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,9 @@ member (you need this if you add things later) and you should set the
2929

3030
. Can sort an unsorted list using `sort_string_list`.
3131

32+
. Can remove individual items of an unsorted list using
33+
`unsorted_string_list_delete_item`.
34+
3235
. Finally it should free the list using `string_list_clear`.
3336

3437
Example:
@@ -112,6 +115,13 @@ write `string_list_insert(...)->util = ...;`.
112115
The above two functions need to look through all items, as opposed to their
113116
counterpart for sorted lists, which performs a binary search.
114117

118+
`unsorted_string_list_delete_item`::
119+
120+
Remove an item from a string_list. The `string` pointer of the items
121+
will be freed in case the `strdup_strings` member of the string_list
122+
is set. The third parameter controls if the `util` pointer of the
123+
items should be freed or not.
124+
115125
Data structures
116126
---------------
117127

string-list.c

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,3 +185,12 @@ int unsorted_string_list_has_string(struct string_list *list,
185185
return unsorted_string_list_lookup(list, string) != NULL;
186186
}
187187

188+
void unsorted_string_list_delete_item(struct string_list *list, int i, int free_util)
189+
{
190+
if (list->strdup_strings)
191+
free(list->items[i].string);
192+
if (free_util)
193+
free(list->items[i].util);
194+
list->items[i] = list->items[list->nr-1];
195+
list->nr--;
196+
}

string-list.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,4 +44,5 @@ void sort_string_list(struct string_list *list);
4444
int unsorted_string_list_has_string(struct string_list *list, const char *string);
4545
struct string_list_item *unsorted_string_list_lookup(struct string_list *list,
4646
const char *string);
47+
void unsorted_string_list_delete_item(struct string_list *list, int i, int free_util);
4748
#endif /* STRING_LIST_H */

0 commit comments

Comments
 (0)