From: Michael Tremer Date: Sun, 29 Dec 2024 17:42:30 +0000 (+0000) Subject: filelist: Actually sort when adding files X-Git-Tag: 0.9.30~663 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=30ef077c996e68ebba8bec238426fd4f41d82d38;p=pakfire.git filelist: Actually sort when adding files Signed-off-by: Michael Tremer --- diff --git a/src/libpakfire/filelist.c b/src/libpakfire/filelist.c index 9f26059e8..6a5df68c6 100644 --- a/src/libpakfire/filelist.c +++ b/src/libpakfire/filelist.c @@ -144,30 +144,25 @@ static int pakfire_filelist_search(struct pakfire_filelist* list, struct pakfire // Set starting points int lo = 0; - int hi = list->num_files - 1; + int hi = list->num_files; - while (lo <= hi) { + while (lo < hi) { // Find the middle - i = lo + (hi - lo) / 2; + i = (lo + hi) / 2; // Compare the files r = pakfire_file_cmp(list->files[i], file); - // We have an exact match! - if (r == 0) - return i; + // If the file is greater than the middle, we only need to search in the left half + if (r >= 0) + hi = i; - // Move to the right - else if (r < 0) + // Otherwise we need to search in the right half + else lo = i + 1; - - // Move to the left - else if (r > 0) - hi = i - 1; } - // Not found (so put it at the end) - return list->num_files; + return lo; } PAKFIRE_EXPORT int pakfire_filelist_add(struct pakfire_filelist* list, struct pakfire_file* file) { @@ -176,7 +171,7 @@ PAKFIRE_EXPORT int pakfire_filelist_add(struct pakfire_filelist* list, struct pa return 0; // Find the index where the file should go - int i = pakfire_filelist_search(list, file); + int pos = pakfire_filelist_search(list, file); // Make space list->files = reallocarray(list->files, list->num_files + 1, sizeof(*list->files)); @@ -186,10 +181,11 @@ PAKFIRE_EXPORT int pakfire_filelist_add(struct pakfire_filelist* list, struct pa } // Move everything up one slot - memmove(list->files + i + 1, list->files + i, list->num_files - i); + for (int i = list->num_files; i > pos; i--) + list->files[i] = list->files[i - 1]; // Store the file - list->files[i] = pakfire_file_ref(file); + list->files[pos] = pakfire_file_ref(file); // The list is now longer ++list->num_files;