// 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) {
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));
}
// 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;