]> git.ipfire.org Git - people/ric9/pakfire.git/commitdiff
filelist: Fix removing items
authorMichael Tremer <michael.tremer@ipfire.org>
Tue, 31 Dec 2024 11:52:35 +0000 (11:52 +0000)
committerMichael Tremer <michael.tremer@ipfire.org>
Tue, 31 Dec 2024 11:52:35 +0000 (11:52 +0000)
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 <michael.tremer@ipfire.org>
src/libpakfire/filelist.c

index bac931411b53534a4ce624de075876da78bdbec5..b4f93ebd88e9f862cd2928b9f8df08cac57de2e2 100644 (file)
@@ -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;
 }