-
Notifications
You must be signed in to change notification settings - Fork 0
/
barser.c
2883 lines (2232 loc) · 71 KB
/
barser.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* BSD 2-Clause License
*
* Copyright (c) 2018, Wojciech Owczarek
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file barser.c
* @date Sun Apr15 13:40:12 2018
*
* @brief Configuration file parser and searchable dictionary
*
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <stdbool.h>
#include "rbt/st_inline.h"
#include "xalloc.h"
#include "xxh.h"
#include "itoa.h"
#include "barser.h"
#include "barser_index.h"
#include "barser_defaults.h"
/*
* if the defaults file wants to handle a smaller token cache,
* let it have it, otherwise the barser.h constant is in effect
*/
#if (BS_BUILD_MAX_TOKENS < BS_MAX_TOKENS)
#undef BS_MAX_TOKENS
#define BS_MAX_TOKENS BS_BUILD_MAX_TOKENS
#endif /* (BS_BUILD_MAX_TOKENS < BS_MAX_TOKENS) */
/* stdin block size */
#define BS_STDIN_BLKSIZE 2048
/* stdin block growth */
#define BS_STDIN_BLKEXTENT 10
/* root node hash - a large 32-bit prime with a healthy bit mix */
#define BS_ROOT_HASH 0xace6cabd
/* hash mixing function */
#define BS_MIX_HASH(a, b, len) ((a ^ rol32(b, 31)))
/* an alternative */
/* #define BS_MIX_HASH(a, b, len) (rol32(a, 1) + rol32(b, 7)) */
/* declare a string buffer of given length (+1) and initialise it */
#ifndef tmpstr
#define tmpstr(name, len) char name[len + 1];\
int name ## _len = len + 1;\
memset(name, 0, name ## _len);
#endif
/* clear a string buffer (assuming _len suffix declared using tmpstr() */
#ifndef clearstr
#define clearstr(name)\
memset(name, 0, name ## _len);
#endif
/* size of a string to fit an int safely - log 2(10) ~ 3, room for error, sign, NUL */
#ifndef INT_STRSIZE
#define INT_STRSIZE (3 * sizeof(int) + 3)
#endif
/* shorthand to dump the token stack contents */
#define tdump()\
fprintf(stderr, "Token cache with %d items: ", state.tokenCount);\
for(int i = 0; i < state.tokenCount; i++) {\
fprintf(stderr, "'");\
if(state.tokenCache[i].data != NULL) {\
for(int j = 0; j < state.tokenCache[i].len; j++) {\
fprintf(stderr, "%c", *(state.tokenCache[i].data + j));\
}\
}\
fprintf(stderr, "' ");\
}\
fprintf(stderr, "\n");
/* shorthand to 'safely' clean up the token cache */
#define tokencleanup()\
for(int i = 0; i < BS_MAX_TOKENS; i++) {\
if(state.tokenCache[i].quoted && state.tokenCache[i].data != NULL) {\
free(state.tokenCache[i].data);\
state.tokenCache[i].data = NULL;\
}\
}\
state.tokenCount = 0;\
state.tokenOffset = 0;
/* shorthant to reset token cache */
#define tokenreset() \
state.tokenCount = 0;\
state.tokenOffset = 0;\
state.flags = 0;
/* shorthand to get token data and quoted check flags */
#define td(n) getTokenData(&state.tokenCache[n + state.tokenOffset])
#define ts(n) state.tokenCache[n + state.tokenOffset].data
#define tq(n) state.tokenCache[n + state.tokenOffset].quoted
#define tl(n) state.tokenCache[n + state.tokenOffset].len
/* get the existing child of node 'parent' named as token #n in cache */
#define gch(parent, n) _bsGetChild(dict, parent, state.tokenCache[n].data, state.tokenCache[n].len)
/* string scan state machine */
enum {
BS_NOOP = 0, /* do nothing (?) */
BS_SKIP_WHITESPACE, /* skipping whitespace (newlines are part of this) */
BS_SKIP_NEWLINE, /* skipping newlines when explicitly required */
BS_GET_TOKEN, /* acquiring a token */
BS_GET_QUOTED, /* acquiring a quoted / escaped string */
BS_SKIP_COMMENT, /* skipping a comment until after next newline */
BS_SKIP_MLCOMMENT /* skipping a multiline comment until end of comment */
};
/* parser events */
enum {
BS_NOEVENT = 0, /* nothing happened, keep scanning */
BS_GOT_TOKEN, /* received a string */
BS_GOT_ENDVAL, /* received "end of value", such as ';' */
BS_GOT_BLOCK, /* received beginning of block, such as '{' */
BS_END_BLOCK, /* received end of block, such as '}' */
BS_GOT_ARRAY, /* received opening of an array, such as '[' */
BS_END_ARRAY, /* received end of array, such as ']' */
BS_GOT_EOF, /* received EOF */
BS_ERROR /* parse error */
};
/* 'c' class check shorthand, assumes the presence of 'c' int variable */
#define cclass(cl) (chflags[(unsigned char)c] & (cl))
/* save state when we encounter a section that can have unmatched or unterminated bounds */
#define savestate(st) st->slinestart = st->linestart;\
st->slineno = st->lineno;\
st->slinepos = st->linepos;
/* restore state, say when printing an error */
#define restorestate(st) st->linestart = st->slinestart;\
st->lineno = st->slineno;\
st->linepos = st->slinepos;
/* ========= static function declarations ========= */
/* initialise parser state */
static void bsInitState(BsState *state, char* buf, const size_t bufsize);
/* return a pointer to token data / name, duplicating / copying if necessary */
static inline char* getTokenData(BsToken *token);
/* fetch next character from buffer and advance, return it as int or EOF if end reached */
static inline int bsForward(BsState *state);
/* peek at the next character without moving forward */
static inline int bsPeek(BsState *state);
/* dump a quoted string (if quoted) and escape characters where needed */
static inline int bsDumpQuoted(FILE* fl, char *src, bool quoted);
/* Dump node contents recursively to a file pointer. */
static int _bsDumpNode(FILE* fl, BsNode *node, int level);
/* Create a node in dict at given parent with given name and (optionally) value */
static inline BsNode* _bsCreateNode(BsDict *dict, BsNode *parent,
const unsigned int type, char* name,
const size_t namelen, char* value, size_t valuelen);
/* [get|check if] parent node has a child with specified name */
static inline BsNode* _bsGetChild(BsDict* dict, BsNode *parent,
const char* name, const size_t namelen);
/* get a list of children of node with specified name. Returns a dynamic LList* that needs freed */
static inline LList* _bsGetChildren(LList* out, BsDict* dict, BsNode *parent,
const char* name, const size_t namelen);
/* walk through string @in, and write to + return next token between the 'sep' character */
static inline BsToken* unescapeToken(BsToken* out, char** in, const char sep);
/* recursive node rehash callback */
static void* bsRehashCallback(BsDict *dict, BsNode *node, void* user, void* feedback, bool* stop);
/* print error hint from state structure */
static void bsErrorHint(BsState *state);
/* main buffer scanner / lexer state machine */
static inline void bsScan(BsState *state);
/* node indexing callback - used when indexing a previously unindexed dictionary */
static void* bsIndexCallback(BsDict *dict, BsNode *node, void* user, void* feedback, bool* stop);
/* node reindexing callback - used when forcing a reindex */
static void* bsReindexCallback(BsDict *dict, BsNode *node, void* user, void* feedback, bool* stop);
/* expand escape sequences and produce a clean query trimmed on both ends, matching the bsGetPath output */
static inline size_t cleanupQuery(char* query);
/* return a new string containing cleaned up query */
static inline char* getCleanQuery(const char* query);
/* compute the compound hash of a query path rooted ad node @root */
static inline uint32_t bsGetPathHash(BsNode* root, const char* query);
/* dictionary / node duplication callback */
static void *bsDupCallback(BsDict *dict, BsNode *node, void* user, void* feedback, bool* stop);
/* ========= function definitions ========= */
/* initialise parser state */
static void bsInitState(BsState *state, char* buf, const size_t bufsize) {
state->current = buf;
state->prev = '\0';
state->c = buf[0];
state->end = buf + bufsize;
state->linestart = buf;
state->slinestart = buf;
memset(&state->tokenCache, 0, BS_MAX_TOKENS * sizeof(BsToken));
state->linepos = 0;
state->lineno = 1;
state->slinepos = 0;
state->slineno = 1;
state->scanState = BS_SKIP_WHITESPACE;
state->parseEvent = BS_NOEVENT;
state->parseError = BS_PERROR_NONE;
state->tokenCount = 0;
state->tokenOffset = 0;
state->flags = BS_NONE;
}
/* return a pointer to token data / name, duplicating / copying if necessary */
static inline char* getTokenData(BsToken *token) {
char* out;
/*
* a quoted string is always dynamically allocated to we can take it as is,
* we only need to trim it, because they are resized by 2 when parsing,
* so get rid of extra memory by cutting it to the required size only.
*/
if(token->quoted) {
xrealloc(out, token->data, token->len + 1);
/* this way we know this has been used, so we will not attempt to free it */
token->data = NULL;
/* otherwise token->data is in an existing buffer, so we duplicate */
} else {
xmalloc(out, token->len + 1);
memcpy(out, token->data, token->len);
}
/* good boy! */
out[token->len] = '\0';
return out;
}
/* fetch next character from buffer and advance, return it as int or EOF if end reached */
static inline int bsForward(BsState *state) {
int c;
if(state->current >= state->end) {
return EOF;
}
state->prev = state->c;
state->current++;
c = *state->current;
if(c == '\0') {
state->c = EOF;
return EOF;
}
/* we have a newline */
if(cclass(BF_NLN)) {
/*
* If we came across two different newline characters, advance line number only once.
* This is a cheap trick to handle Windows' CR-LF. Let me know if this even lands on Window.
*/
if(!(chflags[state->prev] & BF_NLN) || c == state->prev) {
state->linestart = state->current + 1;
state->lineno++;
state->linepos = 0;
}
} else {
state->linepos++;
}
return (state->c = c);
}
/* peek at the next character without moving forward */
static inline int bsPeek(BsState *state) {
if(state->current >= state->end) {
return EOF;
}
return (int)*(state->current + 1);
}
/* allocate buffer. put file in buffer. return size. file can be '-' */
size_t getFileBuf(char **out, const char *fileName) {
char *buf = NULL;
size_t size = 0;
FILE* fl;
/* read from stdin in blocks */
if(!strncmp(fileName, "-", 1)) {
size_t bufsize = BS_STDIN_BLKSIZE;
xmalloc(buf, bufsize + 1);
if(buf == NULL) {
goto failure;
}
while(!feof(stdin)) {
size_t got = fread(buf + size, 1, BS_STDIN_BLKSIZE, stdin);
size += got;
/* if we got less than block size, we have probably reached the end */
if(got < BS_STDIN_BLKSIZE) {
/* shrink to fit */
xrealloc(buf, buf, size + 1);
/* otherwise grow, realloc */
} else if(size == bufsize) {
bufsize += BS_STDIN_BLKEXTENT * BS_STDIN_BLKSIZE;
xrealloc(buf, buf, bufsize + 1);
}
}
} else {
/* open file, seek to end, ftell to know the size */
if((fl = fopen(fileName, "r")) == NULL || fseek(fl, 0, SEEK_END) < 0 || (size = ftell(fl)) < 0) {
goto failure;
}
rewind(fl);
xmalloc(buf, size + 1);
size_t ret = fread(buf, 1, size, fl);
if(ret < size) {
if(feof(fl)) {
fprintf(stderr, "Error: Truncated data while reading '%s': file size %zu bytes, read %zu bytes\n", fileName, size, ret);
}
if(ferror(fl)) {
fprintf(stderr, "Error while reading '%s': file size %zu bytes, read %zu bytes\n", fileName, size, ret);
}
goto failure;
}
fclose(fl);
}
*out = buf;
buf[size] = '\0';
return(size + 1);
failure:
if(buf != NULL) {
free(buf);
}
*out = NULL;
return 0;
}
/* dump a quoted string (if quoted) and escape characters where needed */
static inline int bsDumpQuoted(FILE* fl, char *src, bool quoted) {
int ret;
int c;
if(quoted) {
ret = fprintf(fl, "%c", BS_QUOTE_CHAR);
if(ret < 0) {
return -1;
}
for(char *marker = src; c = *marker, c != '\0'; marker++) {
/* since we only print with double quotes, do not escape other quotes */
if(cclass(BF_ESC)
#ifdef BS_QUOTE1_CHAR
&& c != BS_QUOTE1_CHAR
#endif
#ifdef BS_QUOTE2_CHAR
&& c != BS_QUOTE2_CHAR
#endif
#ifdef BS_QUOTE2_CHAR
&& c != BS_QUOTE3_CHAR
#endif
) {
ret = fprintf(fl, "%c%c", BS_ESCAPE_CHAR, esccodes[c]);
if(ret < 0) {
return -1;
}
} else {
ret = fprintf(fl, "%c", c);
if(ret < 0) {
return -1;
}
}
}
ret = fprintf(fl, "%c", BS_QUOTE_CHAR);
} else {
ret = fprintf(fl, "%s", src);
if(ret < 0) {
return -1;
}
}
return 0;
}
/*
* This is so inconceivably fugly it makes me want to take a rusty screwdriver
* to my neck and stab myself repeatedly with it. But it will have to do for now.
*
* Dump node contents recursively to a file pointer.
*/
static int _bsDumpNode(FILE* fl, BsNode *node, int level)
{
bool noIndentArray = true;
/* allocate enough indentation space for current level + 1 */
int maxwidth = (level + 1) * BS_INDENT_WIDTH;
char indent[ maxwidth + 1];
BsNode *n = NULL;
bool inArray = (node->parent != NULL && node->parent->type == BS_NODE_ARRAY);
bool isArray = (node->type == BS_NODE_ARRAY);
bool hadBranchSibling = inArray && node->_prev != NULL && node->_prev->type != BS_NODE_LEAF;
/* fill up the buffer with indent char, but up to current level only */
memset(indent, BS_INDENT_CHAR, maxwidth);
memset(indent + level * BS_INDENT_WIDTH, '\0', BS_INDENT_WIDTH);
#ifdef COLL_DEBUG
fprintf(fl, "\n// hash: 0x%08x\n", node->hash);
#endif /* COLL_DEBUG */
/* yessir... */
indent[maxwidth] = '\0';
fprintf(fl, "%s", inArray && noIndentArray && !hadBranchSibling ? " " : indent);
if(node->parent != NULL) {
if(!inArray) {
if(node->flags & BS_INACTIVE) {
fprintf(fl, "inactive: ");
}
bsDumpQuoted(fl, node->name, node->flags & BS_QUOTED_NAME);
if(node->type == BS_NODE_INSTANCE) {
fprintf(fl, " ");
node = node->_firstChild;
inArray = (node->parent != NULL && node->parent->type == BS_NODE_ARRAY);
isArray = (node->type == BS_NODE_ARRAY);
bsDumpQuoted(fl, node->name, node->flags & BS_QUOTED_NAME);
if(node->childCount == 1) {
BsNode *tmp = (BsNode*)node->_firstChild;
if(tmp != NULL && tmp->type == BS_NODE_LEAF) {
fprintf(fl, " ");
bsDumpQuoted(fl, tmp->name, tmp->flags & BS_QUOTED_NAME);
if(tmp->value != NULL) {
fprintf(fl, " ");
bsDumpQuoted(fl, tmp->value, tmp->flags & BS_QUOTED_VALUE);
}
fprintf(fl, "%c\n", BS_ENDVAL_CHAR);
return 0;
}
}
}
}
}
if(node->childCount == 0) {
if(node->type != BS_NODE_ROOT) {
if(node->value && node->valueLen > 0) {
if(!inArray) {
fprintf(fl, " ");
}
bsDumpQuoted(fl, node->value, node->flags & BS_QUOTED_VALUE);
if(!inArray) {
fprintf(fl, "%c", BS_ENDVAL_CHAR);
}
if(!inArray) {
fprintf(fl, "\n");
}
} else {
if(!inArray) {
fprintf(fl, "%c", BS_ENDVAL_CHAR);
}
if(!isArray || !noIndentArray) {
fprintf(fl, "\n");
}
}
}
} else {
if(node->type != BS_NODE_ROOT) {
fprintf(fl, "%s%c", strlen(node->name) ? " " : "",
isArray ? BS_STARTARRAY_CHAR : BS_STARTBLOCK_CHAR);
if(!isArray || !noIndentArray) {
fprintf(fl, "\n");
}
}
/* increase indent in case if we want to print something here later */
memset(indent + level * BS_INDENT_WIDTH, BS_INDENT_CHAR, BS_INDENT_WIDTH);
LL_FOREACH_DYNAMIC(node, n) {
if(_bsDumpNode(fl, n, level + (node->parent != NULL)) < 0) {
return -1;
}
}
/* decrease indent again */
memset(indent + (level) * BS_INDENT_WIDTH, '\0', BS_INDENT_WIDTH);
if(node->type != BS_NODE_ROOT) {
fprintf(fl, "%s", isArray && noIndentArray ? " " : indent);
if(isArray) {
fprintf(fl, "%c", BS_ENDARRAY_CHAR);
if(!inArray) {
fprintf(fl, "%c", BS_ENDVAL_CHAR);
}
} else {
fprintf(fl, "%c", BS_ENDBLOCK_CHAR);
}
}
fprintf(fl, "\n");
}
if(ferror(fl)) {
return -1;
}
return 0;
}
/* dump a single node recursively to file, return number of bytes written */
int bsDumpNode(FILE* fl, BsNode *node) {
if(node == NULL) {
return fprintf(fl, "null\n");
}
return _bsDumpNode(fl, node, 0);
}
/* dump the whole dictionary */
void bsDump(FILE* fl, BsDict *dict) {
_bsDumpNode(fl, dict->root, 0);
}
/* free a single node */
void bsFreeNode(BsNode *node)
{
if(node == NULL) {
return;
}
if(node->name != NULL) {
free(node->name);
}
if(node->value != NULL) {
free(node->value);
}
free(node);
}
/*
* Create a node in dict with parent parent of type type using name 'name' of length 'namelen',
* and with a value of 'value' and length 'valuelen'. This is the internal version of this function
* (underscore), which only attaches the name + value to the node. If called directly,
* the name should have been passed throuh getTokenData() first or otherwise be malloc'd,
* so that the name is guaranteed not to come from a buffer that will later be destroyed.
* If zero lengths are given for namelen or valuelen, strlen() is performed.
*/
static inline BsNode* _bsCreateNode(BsDict *dict, BsNode *parent, const unsigned int type, char* name, const size_t namelen, char* value, size_t valuelen)
{
BsNode *ret;
size_t slen = 0;
size_t vlen = 0;
if(dict == NULL) {
return NULL;
}
xmalloc(ret, sizeof(BsNode));
/* could have calloc'd, but... */
ret->value = NULL;
ret->parent = parent;
ret->_indexNext = NULL;
LL_CLEAR_HOLDER(ret);
LL_CLEAR_MEMBER(ret);
ret->nameLen = 0;
ret->valueLen = 0;
ret->childCount = 0;
ret->type = type;
ret->flags = 0;
#ifdef COLL_DEBUG
ret->collcount = 0;
#endif /* COLL_DEBUG */
if(parent != NULL) {
/* inherit flags */
/* parent's inheritable flags shifted */
unsigned int iflags = (parent->flags & BS_INHERITED_FLAGS) << BS_INHERITED_SHIFT;
/* also apply parent's already shifted inherited flags */
iflags |= parent->flags & (BS_INHERITED_FLAGS << BS_INHERITED_SHIFT);
ret->flags |= iflags;
/* if we are adding an array member, call it by number, ignoring the name */
if(parent->type == BS_NODE_ARRAY) {
char numname[INT_STRSIZE + 1];
/* major win over snprintf, 30% total performance difference for citylots.json */
char* endname = u32toa(numname, parent->childCount);
slen = endname - numname;
xmalloc(ret->name, slen + 1);
memcpy(ret->name, numname, slen + 1);
} else {
if(name == NULL) {
goto onerror;
}
ret->name = name;
if(namelen == 0) {
slen = strlen(name);
} else {
slen = namelen;
}
}
ret->value = value;
if(value != NULL && valuelen == 0) {
vlen = strlen(value);
} else {
vlen = valuelen;
}
/* mix this node's name's hash with parent's hash */
ret->hash = BS_MIX_HASH(xxHash32(ret->name, slen), parent->hash, slen);
#if 0
/* if this is an instance, also mix it with value */
if(type == BS_NODE_INSTANCE) {
ret->hash = BS_MIX_HASH(xxHash32(ret->value, vlen), ret->hash, vlen);
}
#endif
ret->nameLen = slen;
ret->valueLen = vlen;
if(!(dict->flags & BS_NOINDEX)) {
bsIndexPut(dict, ret);
}
LL_APPEND_DYNAMIC(parent, ret);
parent->childCount++;
} else {
if(dict->root != NULL) {
fprintf(stderr, "Error: will not replace dictionary '%s' root with node '%s'\n", dict->name, name);
goto onerror;
} else {
dict->root = ret;
ret->type = BS_NODE_ROOT;
xmalloc(ret->name, 1);
ret->name[0] = '\0';
ret->hash = BS_ROOT_HASH;
}
}
dict->nodecount++;
return ret;
onerror:
bsFreeNode(ret);
return NULL;
}
/*
* Public node creation wrapper.
*
* Create a new node in @dict, attached to @parent, of type @type with name @name.
* If the parent is an array, we do not need a name. If it's not, the name is duplicated
* and length is calculated.
*/
BsNode* bsCreateNode(BsDict *dict, BsNode *parent, const unsigned int type, const char* name, const char *value) {
char* nout = NULL;
size_t nlen = 0;
char* vout = NULL;
size_t vlen = 0;
if(parent == NULL) {
return NULL;
}
if(value != NULL) {
/* only leafs and instances can have values */
if(type != BS_NODE_LEAF) {
return NULL;
}
vlen = strlen(name);
xmalloc(vout, vlen + 1);
if(vlen > 0) {
memcpy(vout, value, vlen);
}
*(vout + vlen) = '\0';
}
if(parent != NULL && parent->type == BS_NODE_ARRAY) {
return _bsCreateNode(dict, parent, type, NULL, 0, vout, vlen);
} else {
if(name == NULL || ((nlen = strlen(name)) == 0)) {
xmalloc(nout, 1);
} else {
nlen = strlen(name);
xmalloc(nout, nlen + 1);
memcpy(nout, name, nlen);
}
*(nout + nlen) = '\0';
return _bsCreateNode(dict, parent, type, nout, nlen, vout, vlen);
}
}
/* [get|check if] parent node has a child with specified name */
static inline BsNode* _bsGetChild(BsDict* dict, BsNode *parent, const char* name, const size_t namelen) {
uint32_t hash;
BsNode *n, *m;
if(name != NULL && namelen > 0) {
hash = BS_MIX_HASH(xxHash32(name, namelen), parent->hash, namelen);
/* grab node from index if we can */
if(!(dict->flags & BS_NOINDEX)) {
/* if we wanted to do a Robin Hood, bsIndexGet() would have to be rewritten to do this part */
for(n = bsIndexGet(dict->index, hash); n != NULL; n = n->_indexNext) {
if(n->parent == parent && n->nameLen == namelen && !strncmp(name, n->name, namelen)) {
return n;
}
}
/* otherwise do a naive search */
} else {
/*
* (todo: investigate skip lists - but that would be an index)
* for now, search from both ends of the list simultaneously.
*/
n = parent->_firstChild;
m = parent->_lastChild;
/* until we meet */
while( m != NULL && n != NULL) {
if(n->hash == hash && n->nameLen == namelen && !strncmp(name, n->name, namelen)) {
return n;
}
/* we've met */
if(m == n) {
break;
}
if(m->hash == hash && m->nameLen == namelen && !strncmp(name, m->name, namelen)) {
return m;
}
n = n->_next;
/* we're about to pass each other */
if(m == n) {
break;
}
m = m->_prev;
}
}
}
return NULL;
}
/* get a list of children of node with specified name. Returns a dynamic LList* that needs freed */
static inline LList* _bsGetChildren(LList* out, BsDict* dict, BsNode *parent, const char* name, const size_t namelen) {
uint32_t hash;
BsNode *n, *m;
if(out == NULL) {
out = llCreate();
}
if(name != NULL && namelen > 0) {
hash = BS_MIX_HASH(xxHash32(name, namelen), parent->hash, namelen);
/* grab node from index if we can */
if(!(dict->flags & BS_NOINDEX)) {
/* if we wanted to do a Robin Hood, bsIndexGet() would have to be rewritten to do that (put last item in front) */
for(n = bsIndexGet(dict->index, hash); n != NULL; n = n->_indexNext) {
if(n->parent == parent && n->nameLen == namelen && !strncmp(name, n->name, namelen)) {
llAppendItem(out, n);
}
}
/* otherwise do a naive search */
} else {
/*
* (todo: investigate skip lists - but that would be an index)
* for now, search from both ends of the list simultaneously.
*/
n = parent->_firstChild;
m = parent->_lastChild;
/* until we meet */
while( m != NULL && n != NULL) {
if(n->hash == hash && n->nameLen == namelen && !strncmp(name, n->name, namelen)) {
llAppendItem(out, n);
}
/* we've met */
if(m == n) {
break;
}
if(m->hash == hash && m->nameLen == namelen && !strncmp(name, m->name, namelen)) {
llAppendItem(out, m);
}
n = n->_next;
/* we're about to pass each other */
if(m == n) {
break;
}
m = m->_prev;
}
}
}
return out;
}
/* delete node from the dictionary */
unsigned int bsDeleteNode(BsDict *dict, BsNode *node)
{
if(node == NULL) {
return BS_NODE_NOT_FOUND;
}
/* remove node from index */
if(!(dict->flags & BS_NOINDEX)) {
bsIndexDelete(dict->index, node);
}
/* remove all children recursively first */
for ( BsNode *child = node->_firstChild; child != NULL; child = node->_firstChild) {
bsDeleteNode(dict, child);
}
/* root node is persistent, otherwise remove node */
if(node->parent != NULL) {
LL_REMOVE_DYNAMIC(node->parent, node); /* remove self from parent's list */
node->parent->childCount--;
bsFreeNode(node);
}
dict->nodecount--;
return BS_NODE_OK;
}
/* create a (named) dictionary */
BsDict* bsCreate(const char *name, const uint32_t flags) {