From 41d2678d55b6d7987d2ec38e85008cf44f20a403 Mon Sep 17 00:00:00 2001 From: Michael Tremer Date: Tue, 31 Dec 2024 11:52:35 +0000 Subject: [PATCH] filelist: Fix removing items This also now shrinks the array whenever possible so that we won't waste any memory if the filelist shrinks by a large amount. Signed-off-by: Michael Tremer --- src/libpakfire/filelist.c | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/libpakfire/filelist.c b/src/libpakfire/filelist.c index bac931411..b4f93ebd8 100644 --- a/src/libpakfire/filelist.c +++ b/src/libpakfire/filelist.c @@ -202,21 +202,29 @@ PAKFIRE_EXPORT int pakfire_filelist_add(struct pakfire_filelist* list, struct pa static int pakfire_filelist_remove(struct pakfire_filelist* list, struct pakfire_file* file) { // Check if the file is on the list - int i = pakfire_filelist_has_file(list, file); + int pos = pakfire_filelist_has_file(list, file); // Do nothing if the file is not on the list - if (i < 0) + if (pos < 0) return 0; // Remove the reference - pakfire_file_unref(list->files[i]); + pakfire_file_unref(list->files[pos]); // Fill the gap - memmove(list->files + i, list->files + i + 1, list->num_files - i - 1); + for (unsigned int i = pos; i < list->num_files - 1; i++) + list->files[i] = list->files[i + 1]; // The list is now shorter --list->num_files; + // Downsize the array + list->files = reallocarray(list->files, list->num_files, sizeof(*list->files)); + if (!list->files) { + ERROR(list->ctx, "Could not shrink the filelist: %m\n"); + return -errno; + } + return 0; } -- 2.47.3