use cx_array_add() instead of reimplementing the magic

Tue, 29 Oct 2024 18:15:06 +0100

author
Mike Becker <universe@uap-core.de>
date
Tue, 29 Oct 2024 18:15:06 +0100
changeset 954
a1d87e8fff6d
parent 953
581ad4fd01e9
child 955
18741059da47

use cx_array_add() instead of reimplementing the magic

src/cx/json.h file | annotate | diff | comparison | revisions
src/json.c file | annotate | diff | comparison | revisions
--- 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;
--- 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 <ctype.h>
 
 #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) {

mercurial