# HG changeset patch # User Mike Becker # Date 1730222106 -3600 # Node ID a1d87e8fff6db7e1407efe9dfdf0f1dd905cedec # Parent 581ad4fd01e997bd9c51f9039b1f9cdd68d327cb use cx_array_add() instead of reimplementing the magic diff -r 581ad4fd01e9 -r a1d87e8fff6d src/cx/json.h --- a/src/cx/json.h Tue Oct 29 18:14:02 2024 +0100 +++ b/src/cx/json.h Tue Oct 29 18:15:06 2024 +0100 @@ -121,8 +121,8 @@ int tokenizer_escape; int *states; - unsigned nstates; - unsigned states_alloc; + size_t nstates; + size_t states_alloc; int states_internal[8]; CxJsonToken reader_token; diff -r 581ad4fd01e9 -r a1d87e8fff6d src/json.c --- a/src/json.c Tue Oct 29 18:14:02 2024 +0100 +++ b/src/json.c Tue Oct 29 18:15:06 2024 +0100 @@ -30,14 +30,13 @@ #include #include "cx/json.h" -#include "cx/allocator.h" +#include "cx/array_list.h" /* * RFC 8259 * https://tools.ietf.org/html/rfc8259 */ -#define PARSER_STATES_ALLOC 32 #define PARSER_READVALUE_ALLOC 32 static CxJsonValue cx_json_value_nothing = {.type = CX_JSON_NOTHING}; @@ -340,24 +339,24 @@ } static int add_state(CxJson *p, int state) { - // TODO: this is such a common pattern, try to reuse code here - if (p->nstates >= p->states_alloc) { - unsigned newcap = PARSER_STATES_ALLOC; - if (p->states == p->states_internal) { - void *mem = malloc(newcap * sizeof(int)); - if (mem == NULL) return 1; - memcpy(mem, p->states, p->nstates * sizeof(int)); - p->states = mem; - } else { - newcap += p->states_alloc; - if (cx_reallocate(&p->states, newcap * sizeof(int))) { - return 1; - } - } - p->states_alloc = newcap; + CxArrayReallocator alloc = cx_array_reallocator(NULL, p->states_internal); + size_t size = p->nstates + 1; + size_t capacity = p->states_alloc; + // TODO: fix that nstates does not denote the size of the array + // TODO: replace with a 16 bit (or maybe even 8 bit) version of cx_array_add() + int result = cx_array_add( + &p->states, + &size, + &capacity, + sizeof(int), + &state, + &alloc + ); + if (result == 0) { + p->nstates = size - 1; + p->states_alloc = capacity; } - p->states[++p->nstates] = state; - return 0; + return result; } static void end_elm(CxJson *p, CxJsonReaderType type) {