From 8429e871f84a5cf11e8c207ceafb02b755aa0e3a Mon Sep 17 00:00:00 2001 From: Scott Anderson Date: Wed, 10 May 2017 13:11:49 +1200 Subject: [PATCH] Added list shrinking. --- common/list.c | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/common/list.c b/common/list.c index 962ed6318..3fd4fad93 100644 --- a/common/list.c +++ b/common/list.c @@ -88,6 +88,21 @@ void list_delete(list_t *list, size_t index) { memmove(&array[index], &array[index + 1], size * (list->length - index)); --list->length; + + /* We shrink very sparse lists, but only down to a certain size. + * The choice of >= 8 is somewhat arbitrary, but leaves a minimum + * size of 4 elements. + */ + if (list->length <= list->capacity / 4 && list->capacity >= 8) { + size_t new_cap = list->capacity / 2; + void *data = realloc(list->data, list->memb_size * new_cap); + if (!data) { + return; + } + + list->data = data; + list->capacity = new_cap; + } } void list_swap(list_t *list, size_t i1, size_t i2) {