src/json.c

changeset 954
a1d87e8fff6d
parent 946
b428424c0214
equal deleted inserted replaced
953:581ad4fd01e9 954:a1d87e8fff6d
28 28
29 #include <string.h> 29 #include <string.h>
30 #include <ctype.h> 30 #include <ctype.h>
31 31
32 #include "cx/json.h" 32 #include "cx/json.h"
33 #include "cx/allocator.h" 33 #include "cx/array_list.h"
34 34
35 /* 35 /*
36 * RFC 8259 36 * RFC 8259
37 * https://tools.ietf.org/html/rfc8259 37 * https://tools.ietf.org/html/rfc8259
38 */ 38 */
39 39
40 #define PARSER_STATES_ALLOC 32
41 #define PARSER_READVALUE_ALLOC 32 40 #define PARSER_READVALUE_ALLOC 32
42 41
43 static CxJsonValue cx_json_value_nothing = {.type = CX_JSON_NOTHING}; 42 static CxJsonValue cx_json_value_nothing = {.type = CX_JSON_NOTHING};
44 43
45 44
338 337
339 return 0; 338 return 0;
340 } 339 }
341 340
342 static int add_state(CxJson *p, int state) { 341 static int add_state(CxJson *p, int state) {
343 // TODO: this is such a common pattern, try to reuse code here 342 CxArrayReallocator alloc = cx_array_reallocator(NULL, p->states_internal);
344 if (p->nstates >= p->states_alloc) { 343 size_t size = p->nstates + 1;
345 unsigned newcap = PARSER_STATES_ALLOC; 344 size_t capacity = p->states_alloc;
346 if (p->states == p->states_internal) { 345 // TODO: fix that nstates does not denote the size of the array
347 void *mem = malloc(newcap * sizeof(int)); 346 // TODO: replace with a 16 bit (or maybe even 8 bit) version of cx_array_add()
348 if (mem == NULL) return 1; 347 int result = cx_array_add(
349 memcpy(mem, p->states, p->nstates * sizeof(int)); 348 &p->states,
350 p->states = mem; 349 &size,
351 } else { 350 &capacity,
352 newcap += p->states_alloc; 351 sizeof(int),
353 if (cx_reallocate(&p->states, newcap * sizeof(int))) { 352 &state,
354 return 1; 353 &alloc
355 } 354 );
356 } 355 if (result == 0) {
357 p->states_alloc = newcap; 356 p->nstates = size - 1;
358 } 357 p->states_alloc = capacity;
359 p->states[++p->nstates] = state; 358 }
360 return 0; 359 return result;
361 } 360 }
362 361
363 static void end_elm(CxJson *p, CxJsonReaderType type) { 362 static void end_elm(CxJson *p, CxJsonReaderType type) {
364 p->reader_type = type; 363 p->reader_type = type;
365 p->nstates--; 364 p->nstates--;

mercurial