From 41d8eaca5bbe16144cbb0d98c8522c8f6a137c1d Mon Sep 17 00:00:00 2001 From: Thomas Schmucker Date: Wed, 13 Sep 2023 10:53:05 +0200 Subject: Allgemeine Funktion zum Vergrößern eines Array implementiert MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- csv.c | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/csv.c b/csv.c index 0915029..1ef0bde 100644 --- a/csv.c +++ b/csv.c @@ -1,6 +1,7 @@ #include "csv.h" #include +#include #include #include #include @@ -100,16 +101,22 @@ csv_string_isempty(csv_string_t *csv_string) return (csv_string->pos == 0) ? 1 : 0; } +static inline size_t +growth_strategy(size_t current_cap) +{ + static const size_t INITIAL_CAP = 16; + + return (current_cap == 0) ? INITIAL_CAP : (current_cap * 3) / 2; +} + static inline void csv_string_grow_if_needed(csv_string_t *csv_string, const csv_options_t *const csv_options) { assert(csv_string != NULL); assert(csv_options != NULL); - static const size_t INITIAL_CAP = 16; - if ( csv_string->pos == csv_string->cap ) { - size_t cap = (csv_string->str == NULL) ? INITIAL_CAP : (csv_string->cap * 3) / 2; + size_t cap = growth_strategy(csv_string->cap); char *str = csv_options->cb_reallocate(csv_string->str, cap, 1, csv_options->cb_memory_arg); if ( str == NULL ) { csv_fatal_error(CSV_ERR_OUT_OF_MEMORY, csv_options); @@ -169,10 +176,8 @@ csv_field_grow_if_needed(csv_field_t *csv_field, const csv_options_t *const csv_ assert(csv_field != NULL); assert(csv_options != NULL); - static const size_t INITIAL_CAP = 16; - if ( csv_field->pos == csv_field->cap ) { - size_t cap = (csv_field->fields == NULL) ? INITIAL_CAP : (csv_field->cap * 3) / 2; + size_t cap = growth_strategy(csv_field->cap); size_t *fields = csv_options->cb_reallocate(csv_field->fields, cap, sizeof(csv_field->fields[0]), csv_options->cb_memory_arg); if ( fields == NULL ) { csv_fatal_error(CSV_ERR_OUT_OF_MEMORY, csv_options); -- cgit v1.3