Commit 2d4975924ce5391b01ebd64d11499b485e19aace

Stefan Sperling 2021-11-20T10:40:33

implement got_reflist_sort() which sorts a ref list in-place

diff --git a/include/got_reference.h b/include/got_reference.h
index 927c10b..dedfb8f 100644
--- a/include/got_reference.h
+++ b/include/got_reference.h
@@ -140,6 +140,11 @@ const struct got_error *
 got_reflist_insert(struct got_reflist_entry **newp, struct got_reflist_head *refs,
     struct got_reference *ref, got_ref_cmp_cb cmp_cb, void *cmp_arg);
 
+/* Sort a list of references with the provided comparison callback. */
+const struct got_error *
+got_reflist_sort(struct got_reflist_head *refs, got_ref_cmp_cb cmp_cb,
+    void *cmp_arg);
+
 /* Indicate whether the provided reference is symbolic (points at another
  * refernce) or not (points at an object ID). */
 int got_ref_is_symbolic(struct got_reference *);
diff --git a/lib/reference.c b/lib/reference.c
index 436888f..f1b5c18 100644
--- a/lib/reference.c
+++ b/lib/reference.c
@@ -890,6 +890,31 @@ got_reflist_insert(struct got_reflist_entry **newp, struct got_reflist_head *ref
 	return NULL;
 }
 
+const struct got_error *
+got_reflist_sort(struct got_reflist_head *refs,
+    got_ref_cmp_cb cmp_cb, void *cmp_arg)
+{
+	const struct got_error *err = NULL;
+	struct got_reflist_entry *re, *tmp, *new;
+	struct got_reflist_head sorted;
+
+	TAILQ_INIT(&sorted);
+
+	TAILQ_FOREACH_SAFE(re, refs, entry, tmp) {
+		struct got_reference *ref = re->ref;
+		TAILQ_REMOVE(refs, re, entry);
+		free(re);
+		err = got_reflist_insert(&new, &sorted, ref, cmp_cb, cmp_arg);
+		if (err || new == NULL /* duplicate */)
+			got_ref_close(ref);
+		if (err)
+			return err;
+	}
+
+	TAILQ_CONCAT(refs, &sorted, entry);
+	return NULL;
+}
+
 static const struct got_error *
 gather_on_disk_refs(struct got_reflist_head *refs, const char *path_refs,
     const char *subdir, struct got_repository *repo,