avoid malloc/free for duplicate check in got_pathlists_insert() ok op@
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
diff --git a/lib/path.c b/lib/path.c
index d0ec896..f4b3d33 100644
--- a/lib/path.c
+++ b/lib/path.c
@@ -224,17 +224,11 @@ got_pathlist_insert(struct got_pathlist_entry **inserted,
struct got_pathlist_head *pathlist, const char *path, void *data)
{
struct got_pathlist_entry *new, *pe;
+ size_t path_len = strlen(path);
if (inserted)
*inserted = NULL;
- new = malloc(sizeof(*new));
- if (new == NULL)
- return got_error_from_errno("malloc");
- new->path = path;
- new->path_len = strlen(path);
- new->data = data;
-
/*
* Many callers will provide paths in a somewhat sorted order while
* constructing a path list from inputs such as tree objects or
@@ -244,21 +238,24 @@ got_pathlist_insert(struct got_pathlist_entry **inserted,
*/
pe = TAILQ_LAST(pathlist, got_pathlist_head);
while (pe) {
- int cmp = got_path_cmp(pe->path, new->path,
- pe->path_len, new->path_len);
- if (cmp == 0) {
- free(new); /* duplicate */
- return NULL;
- } else if (cmp < 0) {
- TAILQ_INSERT_AFTER(pathlist, pe, new, entry);
- if (inserted)
- *inserted = new;
- return NULL;
- }
+ int cmp = got_path_cmp(pe->path, path, pe->path_len, path_len);
+ if (cmp == 0)
+ return NULL; /* duplicate */
+ else if (cmp < 0)
+ break;
pe = TAILQ_PREV(pe, got_pathlist_head, entry);
}
- TAILQ_INSERT_HEAD(pathlist, new, entry);
+ new = malloc(sizeof(*new));
+ if (new == NULL)
+ return got_error_from_errno("malloc");
+ new->path = path;
+ new->path_len = path_len;
+ new->data = data;
+ if (pe)
+ TAILQ_INSERT_AFTER(pathlist, pe, new, entry);
+ else
+ TAILQ_INSERT_HEAD(pathlist, new, entry);
if (inserted)
*inserted = new;
return NULL;