-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsjson.h
2402 lines (2072 loc) · 73.6 KB
/
sjson.h
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
//
// Copyright 2018 Sepehr Taghdisian (septag@github). All rights reserved.
// License: https://github.com/septag/sjson#license-bsd-2-clause
//
// Original code by Joseph A. Adams (joeyadams3.14159@gmail.com)
//
// sjson.h - v1.2.0 - Fast single header json encoder/decoder
// This is actually a fork of Joseph's awesome Json encoder/decoder code from his repo:
// https://github.com/rustyrussell/ccan/tree/master/ccan/json
// The encoder/decoder code is almost the same. What I did was adding object pools and string pages (sjson_context)
// that eliminates many micro memory allocations, which improves encode/decode speed and data access performance
// I also added malloc/free and libc API overrides, and made the library single header
//
// FEATURES:
// - Single header C-file
// - UTF8 support
// - Fast with minimal allocations (Object pool, String pool, ..)
// - Overriable malloc/free/memcpy/..
// - Have both Json Decoder/Encoder
// - Encoder supports pretify
// - No dependencies
// - Simple and easy to use C api
//
// USAGE:
// Data types:
// sjson_tag Json object tag type, string, number, object, etc..
// sjson_node Data structure that represents json DOM node
// sjson_context Encoder/decoder context, almost all API functions need a context to allocate and manage memory
// It's not thread-safe, so don't use the same context in multiple threads
// API:
// --- CREATION
// sjson_create_context creates a json context:
// @PARAM pool_size number of initial items in object pool (default=512)
// this is actually the number of DOM nodes in json and can be grown
// for large files with lots of elements, you can set this paramter to higher values
// @PARAM str_buffer_size String buffer size in bytes (default=4096)
// Strings in json decoder, encoder uses a special allocator that allocates string from a pool
// String pool will be grown from the initial size to store more json string data
// Depending on the size of the json data, you can set this value higher or lower
// @PARAM alloc_user A user-defined pointer that is passed to allocations, in case you override memory alloc functions
// sjson_destroy_context Destroys a json context and frees all memory
// after the context destroys, all created json nodes will become invalid
//
// sjson_reset_context Resets the context. No memory will be freed, just resets the buffers so they can be reused
// but the DOM nodes and strings will be invalidated next time you parse or decode a json
//
// --- DECODE/ENCODE/VALIDATE
// sjson_decode Decodes the json text and returns DOM document root node
// sjson_encode Encodes the json root node to json string, does not prettify
// Generated string can be freed by calling 'sjson_free_string' on the returned pointer
// sjson_stringify Encodes the json root node to pretty json string
// @PARAM space sets number of spaces for tab, example two-space for a tab is " "
// sjson_free_string String pointer returned by stringify and encode should be freed by calling this function
// sjson_validate Validates the json string, returns false if json string is invalid
//
// --- LOOKUP/TRAVERSE
// sjson_find_element Finds an element by index inside array
// sjson_find_member Finds an element by name inside object
// sjson_find_member_nocase Finds an element by name inside object, ignores case
// sjson_first_child Gets first child of Object or Array types
// sjson_foreach Iterates through an Object or array child elements, first parameter should be a pre-defined json_node*
//
// --- HIGHER LEVEL LOOKUP
// sjson_get_int Gets an integer value from a child of the specified parent node, sets to 'default_val' if node is not found
// sjson_get_int64 Gets an 64-bit integer value from a child of the specified parent node, sets to 'default_val' if node is not found
// sjson_get_float Gets a float value from a child of the specified parent node, sets to 'default_val' if node is not found
// sjson_get_double Gets a double value from a child of the specified parent node, sets to 'default_val' if node is not found
// sjson_get_string Gets a string value from a child of the specified parent node, sets to 'default_val' if node is not found
// sjson_get_bool Gets a boolean value from a child of the specified parent node, sets to 'default_val' if node is not found
// sjson_get_floats Returns float array from a child of the specified parent node, returns false if node is not found or does not have enough elements to fill the variable
// sjson_get_ints Returns integer array from a child of the specified parent node, returns false if node is not found or does not have enough elements to fill the variable
//
// --- CONSTRUCTION
// sjson_mknull Creates a NULL type json node
// sjson_mknumber Creates and sets a number type json node
// sjson_mkstring Creates and sets a string type json node
// sjson_mkobject Creates an object type json node
// sjson_mkarray Creates an array type json node
// sjson_mkbool Creates and sets boolean type json node
// sjson_append_element Appends the node to the end of an array
// sjson_prepend_element Prepends the node to the beginning of an array
// sjson_append_member Appends the node to the members of an object, should provide the key name to the element
// sjson_prepend_member Prepends the node to the members of an object, should provide the key name to the element
// sjson_remove_from_parent Removes the node from it's parrent, if there is any
// sjson_delete_node Deletes the node and all of it's children (object/array)
//
// --- HIGHER LEVEL CONSTRUCTION these functions use a combination of above to facilitate some operations
// sjson_put_obj Add an object with a key(name) to the child of the parent node
// sjson_put_array Add an array with a key(name) to the child of the parent node
// sjson_put_int Add an integer value with a key(name) to the child of the specified parent node
// sjson_put_float Add float value with a key(name) to the child of the specified parent node
// sjson_put_double Add double value with a key(name) to the child of the specified parent node
// sjson_put_bool Add boolean value with a key(name) to the child of the specified parent node
// sjson_put_string Add string value with a key(name) to the child of the specified parent node
// sjson_put_floats Add float array with a key(name) to the child of the specified parent node
// sjson_put_ints Add integer array with a key(name) to the child of the specified parent node
// sjson_put_string Add string array with a key(name) to the child of the specified parent node
//
// --- DEBUG
// sjson_check Checks and validates the json DOM node recursively
// Returns false and writes a report to 'errmsg' parameter if DOM document has any encoding problems
//
// IMPLEMENTATION:
//
// To include and implement sjson in your project, you should define SJSON_IMPLEMENT before including sjson.h
// You can also override memory allocation or any libc functions that the library uses to your own
// Here's a list of stuff that can be overriden:
// ALLOCATIONS
// - sjson_malloc(user, size) 'user' is the pointer that is passed in sjson_create_context
// - sjson_free(user, ptr)
// - sjson_realloc(user, ptr, size)
// DEBUG/ASSERT
// - sjson_assert
// STRINGS
// - sjson_stricmp
// - sjson_strcpy
// - sjson_strcmp
// - sjson_snprintf
// MEMORY
// - sjson_memcpy
// - sjson_memset
// - sjson_out_of_memory happens when sjson cannot allocate memory internally
// Default behaviour is that it asserts and exits the program
// Example:
// #define SJSON_IMPLEMENT
// #define sjson_malloc(user, size) MyMalloc(user, size)
// #define sjson_free(user, ptr) MyFree(user, ptr)
// #define sjson_realloc(user, ptr, size) MyRealloc(user, ptr, size)
// #include "sjson.h"
// ...
//
// NOTE: on sjson_reset_context
// what reset_context does is that is resets the internal buffers without freeing them
// this makes context re-usable for the next json document, so don't have to regrow buffers or create another context
// Example:
// sjson_context* ctx = sjson_create_context(0, 0, NULL); // initial creation
// sjson_decode(ctx, json1); // decode json1
// ... // do some work on data
// sjson_reset_context(ctx); // reset the buffers, make sure you don't need json1 data
// sjson_decode(ctx, json2); // decode another json
// ...
//
#pragma once
#ifndef SJSON_H_
#define SJSON_H_
#ifdef _MSC_VER
# ifndef __cplusplus
# define false 0
# define true 1
# define bool _Bool
/* For compilers that don't have the builtin _Bool type. */
# if ((defined(_MSC_VER) && _MSC_VER < 1800) || \
(defined __GNUC__&& __STDC_VERSION__ < 199901L && __GNUC__ < 3)) && !defined(_lint)
typedef unsigned char _Bool;
# endif
# endif /* !__cplusplus */
#define __bool_true_false_are_defined 1
#else
# include <stdbool.h>
#endif
#include <stddef.h>
#include <stdint.h>
// Json DOM object type
typedef enum sjson_tag {
SJSON_NULL,
SJSON_BOOL,
SJSON_STRING,
SJSON_NUMBER,
SJSON_ARRAY,
SJSON_OBJECT,
} sjson_tag;
// Json DOM node struct
typedef struct sjson_node
{
struct sjson_node* parent; // only if parent is an object or array (NULL otherwise)
struct sjson_node* prev;
struct sjson_node* next;
char* key; // only if parent is an object (NULL otherwise). Must be valid UTF-8.
sjson_tag tag;
union {
bool bool_; // SJSON_BOOL
char* string_; // SJSON_STRING: Must be valid UTF-8.
double number_; // SJSON_NUMBER
struct {
struct sjson_node* head;
struct sjson_node* tail;
} children; // SJSON_ARRAY, SJSON_OBJECT
};
} sjson_node;
// Json context, handles memory, pools, etc.
// Almost every API needs a valid context to work
// Not multi-threaded. Do not use the same context in multiple threads
typedef struct sjson_context sjson_context;
#ifdef __cplusplus
extern "C" {
#endif
sjson_context* sjson_create_context(int pool_size, int str_buffer_size, void* alloc_user);
void sjson_destroy_context(sjson_context* ctx);
void sjson_reset_context(sjson_context* ctx);
// Encoding, decoding, and validation
sjson_node* sjson_decode(sjson_context* ctx, const char* json);
char* sjson_encode(sjson_context* ctx, const sjson_node* node);
char* sjson_encode_string(sjson_context* ctx, const char* str);
char* sjson_stringify(sjson_context* ctx, const sjson_node* node, const char* space);
void sjson_free_string(sjson_context* ctx, char* str);
bool sjson_validate(sjson_context* ctx, const char* json);
// Lookup and traversal
sjson_node* sjson_find_element(sjson_node* array, int index);
sjson_node* sjson_find_member(sjson_node* object, const char* key);
sjson_node* sjson_find_member_nocase(sjson_node* object, const char *name);
sjson_node* sjson_first_child(const sjson_node* node);
int sjson_child_count(const sjson_node* node);
// Higher level lookup/get functions
int sjson_get_int(sjson_node* parent, const char* key, int default_val);
int64_t sjson_get_int64(sjson_node* parent, const char* key, int64_t default_val);
float sjson_get_float(sjson_node* parent, const char* key, float default_val);
double sjson_get_double(sjson_node* parent, const char* key, double default_val);
const char* sjson_get_string(sjson_node* parent, const char* key, const char* default_val);
bool sjson_get_bool(sjson_node* parent, const char* key, bool default_val);
bool sjson_get_floats(float* out, int count, sjson_node* parent, const char* key);
bool sjson_get_ints(int* out, int count, sjson_node* parent, const char* key);
bool sjson_get_uints(uint32_t* out, int count, sjson_node* parent, const char* key);
bool sjson_get_int16s(int16_t* out, int count, sjson_node* parent, const char* key);
bool sjson_get_uint16s(uint16_t* out, int count, sjson_node* parent, const char* key);
#define sjson_foreach(i, object_or_array) \
for ((i) = sjson_first_child(object_or_array); \
(i) != NULL; \
(i) = (i)->next)
// Construction and manipulation
sjson_node* sjson_mknull(sjson_context* ctx);
sjson_node* sjson_mkbool(sjson_context* ctx, bool b);
sjson_node* sjson_mkstring(sjson_context* ctx, const char *s);
sjson_node* sjson_mknumber(sjson_context* ctx, double n);
sjson_node* sjson_mkarray(sjson_context* ctx);
sjson_node* sjson_mkobject(sjson_context* ctx);
void sjson_append_element(sjson_node* array, sjson_node* element);
void sjson_prepend_element(sjson_node* array, sjson_node* element);
void sjson_append_member(sjson_context* ctx, sjson_node* object, const char* key, sjson_node* value);
void sjson_prepend_member(sjson_context* ctx, sjson_node* object, const char* key, sjson_node* value);
void sjson_remove_from_parent(sjson_node* node);
void sjson_delete_node(sjson_context* ctx, sjson_node* node);
// Higher level construction
sjson_node* sjson_put_obj(sjson_context* ctx, sjson_node* parent, const char* key);
sjson_node* sjson_put_array(sjson_context* ctx, sjson_node* parent, const char* key);
sjson_node* sjson_put_int(sjson_context* ctx, sjson_node* parent, const char* key, int val);
sjson_node* sjson_put_int64(sjson_context* ctx, sjson_node* parent, const char* key, int64_t val);
sjson_node* sjson_put_float(sjson_context* ctx, sjson_node* parent, const char* key, float val);
sjson_node* sjson_put_double(sjson_context* ctx, sjson_node* parent, const char* key, double val);
sjson_node* sjson_put_bool(sjson_context* ctx, sjson_node* parent, const char* key, bool val);
sjson_node* sjson_put_string(sjson_context* ctx, sjson_node* parent, const char* key, const char* val);
sjson_node* sjson_put_floats(sjson_context* ctx, sjson_node* parent, const char* key, const float* vals, int count);
sjson_node* sjson_put_ints(sjson_context* ctx, sjson_node* parent, const char* key, const int* vals, int count);
sjson_node* sjson_put_strings(sjson_context* ctx, sjson_node* parent, const char* key, const char** vals, int count);
sjson_node* sjson_put_uints(sjson_context* ctx, sjson_node* parent, const char* key, const uint32_t* vals, int count);
sjson_node* sjson_put_int16s(sjson_context* ctx, sjson_node* parent, const char* key, const int16_t* vals, int count);
sjson_node* sjson_put_uint16s(sjson_context* ctx, sjson_node* parent, const char* key, const uint16_t* vals, int count);
// Debugging
/*
* Look for structure and encoding problems in a sjson_node or its descendents.
*
* If a problem is detected, return false, writing a description of the problem
* to errmsg (unless errmsg is NULL).
*/
bool sjson_check(const sjson_node* node, char errmsg[256]);
#ifdef __cplusplus
}
#endif
#endif // SJSON_H_
#if defined(SJSON_IMPLEMENT)
/*
Copyright (C) 2011 Joseph A. Adams (joeyadams3.14159@gmail.com)
All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef sjson_strcpy
# define __STDC_WANT_LIB_EXT1__ 1
#endif
#include <stdlib.h>
#ifndef sjson_malloc
# include <string.h>
# define sjson_malloc(user, size) malloc(size)
# define sjson_free(user, ptr) free(ptr)
# define sjson_realloc(user, ptr, size) realloc(ptr, size)
#endif
#ifndef sjson_assert
# include <assert.h>
# define sjson_assert(_e) assert(_e)
#endif
#ifndef sjson_out_of_memory
# define sjson_out_of_memory() do { sjson_assert(0 && "Out of memory"); exit(EXIT_FAILURE); } while(0)
#endif
#ifndef sjson_snprintf
# include <stdio.h>
# define sjson_snprintf snprintf
#endif
#ifndef sjson_strcmp
# include <string.h>
# define sjson_strcmp(_a, _b) strcmp(_a, _b)
#endif
#ifndef sjson_memset
# include <string.h>
# define sjson_memset(_p, _b, _n) memset(_p, _b, _n)
#endif
#ifndef sjson_memcpy
# include <string.h>
# define sjson_memcpy(_a, _b, _n) memcpy(_a, _b, _n)
#endif
#ifndef sjson_stricmp
# ifdef _WIN32
# include <string.h>
# define sjson_stricmp(_a, _b) _stricmp(_a, _b)
# else
# include <string.h>
# define sjson_stricmp(_a, _b) strcasecmp(_a, _b)
# endif
#endif
#ifndef sjson_strlen
# include <string.h>
# define sjson_strlen(_str) strlen(_str)
#endif
#ifndef sjson_strcpy
# include <string.h>
# ifdef _MSC_VER
# define sjson_strcpy(_a, _s, _b) strcpy_s(_a, _s, _b)
# else
# define sjson_strcpy(_a, _s, _b) strcpy(_a, _b)
# endif
#endif
#define sjson__align_mask(_value, _mask) ( ( (_value)+(_mask) ) & ( (~0)&(~(_mask) ) ) )
typedef struct sjson__str_page
{
int offset;
int size;
struct sjson__str_page* next;
struct sjson__str_page* prev;
} sjson__str_page;
typedef struct sjson__node_page
{
int iter;
int capacity;
sjson_node** ptrs;
sjson_node* buff;
struct sjson__node_page* next;
struct sjson__node_page* prev;
} sjson__node_page;
typedef struct sjson_context
{
void* alloc_user;
int pool_size;
int str_buffer_size;
sjson__node_page* node_pages;
sjson__str_page* str_pages;
sjson__str_page* cur_str_page;
char* cur_str;
} sjson_context;
////////////////////////////////////////////////////////////////////////////////////////////////////
// Growable string buffer
typedef struct sjson__sb
{
char *cur;
char *end;
char *start;
} sjson__sb;
static inline void sjson__sb_init(sjson_context* ctx, sjson__sb* sb, int reserve_sz)
{
int ssize = reserve_sz >= ctx->str_buffer_size ? reserve_sz : ctx->str_buffer_size;
sb->start = (char*) sjson_malloc(ctx->alloc_user, ssize);
if (sb->start == NULL)
sjson_out_of_memory();
sb->cur = sb->start;
sb->end = sb->start + ssize - 1;
}
/* sb and need may be evaluated multiple times. */
#define sjson__sb_need(ctx, sb, need) do { \
if ((sb)->end - (sb)->cur < (need)) \
sjson__sb_grow(ctx, sb, need); \
} while (0)
static inline void sjson__sb_grow(sjson_context* ctx, sjson__sb* sb, int need)
{
size_t length = sb->cur - sb->start;
size_t alloc = sb->end - sb->start + 1;
do {
alloc <<= 1;
} while (alloc <= length + need);
sb->start = (char*)sjson_realloc(ctx->alloc_user, sb->start, alloc);
if (sb->start == NULL) {
sjson_out_of_memory();
}
sb->cur = sb->start + length;
sb->end = sb->start + alloc - 1;
}
static inline void sjson__sb_put(sjson_context* ctx, sjson__sb* sb, const char *bytes, int count)
{
sjson__sb_need(ctx, sb, count);
sjson_memcpy(sb->cur, bytes, count);
sb->cur += count;
}
#define sjson__sb_putc(ctx, sb, c) do { \
if ((sb)->cur >= (sb)->end) \
sjson__sb_grow(ctx, sb, 1); \
*(sb)->cur++ = (c); \
} while (0)
static inline void sjson__sb_puts(sjson_context* ctx, sjson__sb* sb, const char *str)
{
sjson__sb_put(ctx, sb, str, (int)sjson_strlen(str));
}
static inline char* sjson__sb_finish(sjson__sb* sb)
{
*sb->cur = 0;
sjson_assert(sb->start <= sb->cur && sjson_strlen(sb->start) == (int)(intptr_t)(sb->cur - sb->start));
return sb->start;
}
static inline void sjson__sb_free(sjson_context* ctx, sjson__sb* sb)
{
sjson_free(ctx->alloc_user, sb->start);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// Node page
static inline sjson__node_page* sjson__page_create(void* alloc_user, int capacity)
{
capacity = sjson__align_mask(capacity, 15);
uint8_t* buff = (uint8_t*)sjson_malloc(alloc_user,
sizeof(sjson__node_page) + (sizeof(sjson_node) + sizeof(sjson_node*))*capacity);
if (!buff) {
sjson_out_of_memory();
return NULL;
}
sjson__node_page* page = (sjson__node_page*)buff;
page->iter = capacity;
page->capacity = capacity;
page->next = page->prev = NULL;
buff += sizeof(sjson__node_page);
page->ptrs = (sjson_node**)buff;
buff += sizeof(sjson_node*)*capacity;
page->buff = (sjson_node*)buff;
for (int i = 0; i < capacity; i++)
page->ptrs[capacity - i - 1] = &page->buff[i];
return page;
}
static inline void sjson__page_destroy(sjson__node_page* page, void* alloc_user)
{
sjson_assert(page);
page->capacity = page->iter = 0;
sjson_free(alloc_user, page);
}
static inline sjson_node* sjson__page_new(sjson__node_page* page)
{
if (page->iter > 0) {
return page->ptrs[--page->iter];
} else {
sjson_assert(0 && "Node page capacity is full");
return NULL;
}
}
static inline bool sjson__page_full(const sjson__node_page* page)
{
return page->iter == 0;
}
static inline bool sjson__page_valid(const sjson__node_page* page, sjson_node* ptr)
{
uintptr_t uptr = (uintptr_t)ptr;
bool inbuf = uptr >= (uintptr_t)page->buff &&
uptr < (uintptr_t)(page->buff + page->capacity*sizeof(sjson_node));
bool valid = (uintptr_t)((uint8_t*)ptr - (uint8_t*)page->buff) % sizeof(sjson_node) == 0;
return inbuf & valid;
}
static inline void sjson__page_del(sjson__node_page* page, sjson_node* ptr)
{
sjson_assert(page->iter != page->capacity && "Cannot delete more objects");
sjson_assert(sjson__page_valid(page, ptr) && "Pointer does not belong to page");
page->ptrs[page->iter++] = ptr;
}
static inline void sjson__page_add_list(sjson__node_page** pfirst, sjson__node_page* node)
{
if (*pfirst) {
(*pfirst)->prev = node;
node->next = *pfirst;
}
*pfirst = node;
}
static inline void sjson__page_remove_list(sjson__node_page** pfirst, sjson__node_page* node)
{
if (node->prev)
node->prev->next = node->next;
if (node->next)
node->next->prev = node->prev;
if (*pfirst == node)
*pfirst = node->next;
node->prev = node->next = NULL;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// json string buffer page
static inline sjson__str_page* sjson__str_page_create(void* alloc_user, int size)
{
size = sjson__align_mask(size, 7);
// allocate the page and reserve memory for string-buffer after the struct
sjson__str_page* page = (sjson__str_page*)sjson_malloc(alloc_user, size + sizeof(sjson__str_page));
if (!page) {
sjson_out_of_memory();
return NULL;
}
page->offset = 0;
page->size = size;
page->next = page->prev = NULL;
return page;
}
static inline void sjson__str_page_destroy(sjson__str_page* page, void* alloc_user)
{
sjson_assert(page);
sjson_free(alloc_user, page);
}
static inline char* sjson__str_page_ptr(sjson__str_page* page)
{
char* buff = (char*)(page + 1);
return buff + page->offset;
}
static inline char* sjson__str_page_startptr(sjson__str_page* page)
{
return (char*)(page + 1);
}
static inline bool sjson__str_page_grow(sjson__str_page* page, int size)
{
if (page->offset + size <= page->size) {
page->offset += size;
return true;
} else {
return false;
}
}
static inline void sjson__str_page_add_list(sjson__str_page** pfirst, sjson__str_page* node)
{
if (*pfirst) {
(*pfirst)->prev = node;
node->next = *pfirst;
}
*pfirst = node;
}
static inline void sjson__str_page_remove_list(sjson__str_page** pfirst, sjson__str_page* node)
{
if (node->prev)
node->prev->next = node->next;
if (node->next)
node->next->prev = node->prev;
if (*pfirst == node)
*pfirst = node->next;
node->prev = node->next = NULL;
}
sjson_context* sjson_create_context(int pool_size, int str_buffer_size, void* alloc_user)
{
sjson_context* ctx = (sjson_context*)sjson_malloc(alloc_user, sizeof(sjson_context));
if (!ctx) {
sjson_out_of_memory();
return NULL;
}
sjson_memset(ctx, 0x00, sizeof(sjson_context));
if (pool_size <= 0)
pool_size = 512;
if (str_buffer_size <= 0)
str_buffer_size = 4096;
ctx->alloc_user = alloc_user;
ctx->pool_size = pool_size;
ctx->str_buffer_size = str_buffer_size;
// Create first pool page
ctx->node_pages = sjson__page_create(alloc_user, pool_size);
if (!ctx->node_pages)
return NULL;
ctx->str_pages = NULL;
ctx->cur_str_page = NULL;
return ctx;
}
void sjson_destroy_context(sjson_context* ctx)
{
sjson_assert(ctx);
// destroy node pages
sjson__node_page* npage = ctx->node_pages;
while (npage) {
sjson__node_page* next = npage->next;
sjson__page_destroy(npage, ctx->alloc_user);
npage = next;
}
sjson__str_page* spage = ctx->str_pages;
while (spage) {
sjson__str_page* next = spage->next;
sjson__str_page_destroy(spage, ctx->alloc_user);
spage = next;
}
sjson_free(ctx->alloc_user, ctx);
}
void sjson_reset_context(sjson_context* ctx)
{
//
for (sjson__node_page* npage = ctx->node_pages; npage; npage = npage->next) {
int capacity = npage->capacity;
npage->iter = capacity;
for (int i = 0; i < capacity; i++)
npage->ptrs[capacity - i - 1] = &npage->buff[i];
}
//
for (sjson__str_page* spage = ctx->str_pages; spage; spage = spage->next) {
spage->offset = 0;
}
// TODO: maybe we can reverse the linked-lists to get better cache coherency
}
static inline sjson_node* sjson__new_node(sjson_context* ctx, sjson_tag tag)
{
sjson__node_page* npage = ctx->node_pages;
while (npage && sjson__page_full(npage))
npage = npage->next;
if (npage == NULL) {
npage = sjson__page_create(ctx->alloc_user, ctx->pool_size);
sjson_assert(npage);
sjson__page_add_list(&ctx->node_pages, npage);
}
sjson_node* node = sjson__page_new(npage);
sjson_memset(node, 0x0, sizeof(sjson_node));
node->tag = tag;
return node;
}
static inline void sjson__del_node(sjson_context* ctx, sjson_node* node)
{
sjson__node_page* npage = ctx->node_pages;
while (npage && !sjson__page_valid(npage, node))
npage = npage->next;
sjson_assert(npage && "sjson_node doesn't belong to any page - check the pointer");
sjson__page_del(npage, node);
}
// Usage:
static inline char* sjson__str_begin(sjson_context* ctx, int init_sz)
{
sjson_assert (ctx->cur_str_page == NULL && "Should call sjson__str_end before begin");
// find a page that can grow to requested size
sjson__str_page* spage = ctx->str_pages;
while (spage && (spage->offset + init_sz) <= spage->size)
spage = spage->next;
// create a new string page
if (spage == NULL) {
int page_sz = ctx->str_buffer_size;
if (init_sz > (page_sz >> 1)) {
page_sz = page_sz << 1;
page_sz = sjson__align_mask(init_sz, page_sz-1);
}
spage = sjson__str_page_create(ctx->alloc_user, page_sz);
sjson_assert(spage);
sjson__str_page_add_list(&ctx->str_pages, spage);
}
sjson_assert(spage->offset + init_sz <= spage->size);
char* ptr = sjson__str_page_ptr(spage);
spage->offset += init_sz;
ctx->cur_str_page = spage;
ctx->cur_str = ptr;
return ptr;
}
// Returns the pointer to the begining of the string, pointer may be reallocated and changed from sjson__str_begin
static inline char* sjson__str_grow(sjson_context* ctx, int grow_sz)
{
sjson_assert (ctx->cur_str_page && "Should call sjson__str_begin before grow");
sjson__str_page* spage = ctx->cur_str_page;
if (sjson__str_page_grow(spage, grow_sz)) {
return ctx->cur_str;
} else {
int page_sz = spage->size;
int cur_str_sz = (int)(uintptr_t)(sjson__str_page_ptr(spage) - ctx->cur_str);
int total_sz = cur_str_sz + grow_sz;
if (total_sz > (page_sz >> 1)) {
page_sz <<= 1;
page_sz = total_sz > page_sz ? total_sz : page_sz;
}
sjson__str_page* newspage = sjson__str_page_create(ctx->alloc_user, page_sz);
sjson_assert(newspage);
sjson_assert(total_sz <= newspage->size);
char* ptr = sjson__str_page_startptr(newspage);
newspage->offset += total_sz;
// copy previous buffer into the new one
if (cur_str_sz > 0)
sjson_memcpy(ptr, ctx->cur_str, cur_str_sz);
// check and see if we can remove the old page completely
if (ctx->cur_str == sjson__str_page_startptr(spage)) {
sjson__str_page_remove_list(&ctx->str_pages, spage);
sjson__str_page_destroy(spage, ctx->alloc_user);
}
ctx->cur_str_page = newspage;
ctx->cur_str = ptr;
return ptr;
}
}
static inline char* sjson__str_end(sjson_context* ctx)
{
sjson_assert (ctx->cur_str_page && "Should call sjson__str_begin before end");
char* ptr = ctx->cur_str;
ctx->cur_str_page = NULL;
ctx->cur_str = NULL;
return ptr;
}
static char* sjson__strdup(sjson_context* ctx, const char *str)
{
int len = (int)sjson_strlen(str);
char* ret = sjson__str_begin(ctx, len + 1);
sjson_memcpy(ret, str, len);
ret[len] = '\0';
sjson__str_end(ctx);
return ret;
}
/*
* Unicode helper functions
*
* These are taken from the ccan/charset module and customized a bit.
* Putting them here means the compiler can (choose to) inline them,
* and it keeps ccan/json from having a dependency.
*/
/*
* Type for Unicode codepoints.
* We need our own because wchar_t might be 16 bits.
*/
typedef uint32_t json__uchar_t;
/*
* Validate a single UTF-8 character starting at @s.
* The string must be null-terminated.
*
* If it's valid, return its length (1 thru 4).
* If it's invalid or clipped, return 0.
*
* This function implements the syntax given in RFC3629, which is
* the same as that given in The Unicode Standard, Version 6.0.
*
* It has the following properties:
*
* * All codepoints U+0000..U+10FFFF may be encoded,
* except for U+D800..U+DFFF, which are reserved
* for UTF-16 surrogate pair encoding.
* * UTF-8 byte sequences longer than 4 bytes are not permitted,
* as they exceed the range of Unicode.
* * The sixty-six Unicode "non-characters" are permitted
* (namely, U+FDD0..U+FDEF, U+xxFFFE, and U+xxFFFF).
*/
static int sjson__utf8_validate_cz(const char *s)
{
unsigned char c = *s++;
if (c <= 0x7F) { /* 00..7F */
return 1;
} else if (c <= 0xC1) { /* 80..C1 */
/* Disallow overlong 2-byte sequence. */
return 0;
} else if (c <= 0xDF) { /* C2..DF */
/* Make sure subsequent byte is in the range 0x80..0xBF. */
if (((unsigned char)*s++ & 0xC0) != 0x80)
return 0;
return 2;
} else if (c <= 0xEF) { /* E0..EF */
/* Disallow overlong 3-byte sequence. */
if (c == 0xE0 && (unsigned char)*s < 0xA0)
return 0;
/* Disallow U+D800..U+DFFF. */
if (c == 0xED && (unsigned char)*s > 0x9F)
return 0;
/* Make sure subsequent bytes are in the range 0x80..0xBF. */
if (((unsigned char)*s++ & 0xC0) != 0x80)
return 0;
if (((unsigned char)*s++ & 0xC0) != 0x80)
return 0;
return 3;
} else if (c <= 0xF4) { /* F0..F4 */
/* Disallow overlong 4-byte sequence. */
if (c == 0xF0 && (unsigned char)*s < 0x90)
return 0;
/* Disallow codepoints beyond U+10FFFF. */
if (c == 0xF4 && (unsigned char)*s > 0x8F)
return 0;
/* Make sure subsequent bytes are in the range 0x80..0xBF. */
if (((unsigned char)*s++ & 0xC0) != 0x80)
return 0;
if (((unsigned char)*s++ & 0xC0) != 0x80)
return 0;
if (((unsigned char)*s++ & 0xC0) != 0x80)
return 0;
return 4;
} else { /* F5..FF */
return 0;
}
}
/* Validate a null-terminated UTF-8 string. */
static bool sjson__utf8_validate(const char *s)
{
int len;
for (; *s != 0; s += len) {
len = sjson__utf8_validate_cz(s);
if (len == 0)
return false;
}
return true;
}
/*
* Read a single UTF-8 character starting at @s,
* returning the length, in bytes, of the character read.
*
* This function assumes input is valid UTF-8,
* and that there are enough characters in front of @s.
*/
static int sjson__utf8_read_char(const char *s, json__uchar_t *out)
{
const unsigned char *c = (const unsigned char*) s;
sjson_assert(sjson__utf8_validate_cz(s));
if (c[0] <= 0x7F) {
/* 00..7F */
*out = c[0];
return 1;
} else if (c[0] <= 0xDF) {
/* C2..DF (unless input is invalid) */
*out = ((json__uchar_t)c[0] & 0x1F) << 6 |
((json__uchar_t)c[1] & 0x3F);
return 2;
} else if (c[0] <= 0xEF) {
/* E0..EF */
*out = ((json__uchar_t)c[0] & 0xF) << 12 |
((json__uchar_t)c[1] & 0x3F) << 6 |
((json__uchar_t)c[2] & 0x3F);
return 3;
} else {
/* F0..F4 (unless input is invalid) */
*out = ((json__uchar_t)c[0] & 0x7) << 18 |
((json__uchar_t)c[1] & 0x3F) << 12 |
((json__uchar_t)c[2] & 0x3F) << 6 |
((json__uchar_t)c[3] & 0x3F);
return 4;
}
}
/*
* Write a single UTF-8 character to @s,
* returning the length, in bytes, of the character written.
*
* @unicode must be U+0000..U+10FFFF, but not U+D800..U+DFFF.
*
* This function will write up to 4 bytes to @out.
*/
static int sjson__utf8_write_char(json__uchar_t unicode, char *out)
{
unsigned char *o = (unsigned char*) out;
sjson_assert(unicode <= 0x10FFFF && !(unicode >= 0xD800 && unicode <= 0xDFFF));
if (unicode <= 0x7F) {
/* U+0000..U+007F */
*o++ = unicode;
return 1;
} else if (unicode <= 0x7FF) {
/* U+0080..U+07FF */
*o++ = 0xC0 | unicode >> 6;
*o++ = 0x80 | (unicode & 0x3F);
return 2;
} else if (unicode <= 0xFFFF) {
/* U+0800..U+FFFF */
*o++ = 0xE0 | unicode >> 12;
*o++ = 0x80 | (unicode >> 6 & 0x3F);
*o++ = 0x80 | (unicode & 0x3F);
return 3;
} else {