Fossil SCM

fossil-scm / extsrc / cson_amalgamation.h
Blame History Raw 2872 lines
1
#ifdef FOSSIL_ENABLE_JSON
2
#ifndef CSON_FOSSIL_MODE
3
#define CSON_FOSSIL_MODE
4
#endif
5
/* auto-generated! Do not edit! */
6
/* begin file include/wh/cson/cson.h */
7
#if !defined(WANDERINGHORSE_NET_CSON_H_INCLUDED)
8
#define WANDERINGHORSE_NET_CSON_H_INCLUDED 1
9
10
/*#include <stdint.h> C99: fixed-size int types. */
11
#include <stdio.h> /* FILE decl */
12
13
#include <stdarg.h>
14
15
/** @page page_cson cson JSON API
16
17
cson (pronounced "season") is an object-oriented C API for generating
18
and consuming JSON (http://www.json.org) data.
19
20
Its main claim to fame is that it can parse JSON from, and output it
21
to, damned near anywhere. The i/o routines use a callback function to
22
fetch/emit JSON data, allowing clients to easily plug in their own
23
implementations. Implementations are provided for string- and
24
FILE-based i/o.
25
26
Project home page: https://fossil.wanderinghorse.net/r/cson
27
28
Author: Stephan Beal (https://www.wanderinghorse.net/home/stephan/)
29
30
License: Dual Public Domain/MIT
31
32
The full license text is at the bottom of the main header file
33
(cson.h).
34
35
Examples of how to use the library are scattered throughout
36
the API documentation, in the test.c file in the source repo,
37
and in the wiki on the project's home page.
38
*/
39
40
#if defined(__cplusplus)
41
extern "C" {
42
#endif
43
44
#if defined(_WIN32) || defined(_WIN64)
45
# define CSON_ENABLE_UNIX 0
46
#else
47
# define CSON_ENABLE_UNIX 1
48
#endif
49
50
51
/** @typedef some_long_int_type cson_int_t
52
53
Typedef for JSON-like integer types. This is (long long) where feasible,
54
otherwise (long).
55
*/
56
#ifdef _WIN32
57
typedef __int64 cson_int_t;
58
#define CSON_INT_T_SFMT "I64d"
59
#define CSON_INT_T_PFMT "I64d"
60
#elif (__STDC_VERSION__ >= 199901L) || (HAVE_LONG_LONG == 1)
61
typedef long long cson_int_t;
62
#define CSON_INT_T_SFMT "lld"
63
#define CSON_INT_T_PFMT "lld"
64
#else
65
typedef long cson_int_t;
66
#define CSON_INT_T_SFMT "ld"
67
#define CSON_INT_T_PFMT "ld"
68
#endif
69
70
/** @typedef double_or_long_double cson_double_t
71
72
This is the type of double value used by the library.
73
It is only lightly tested with long double, and when using
74
long double the memory requirements for such values goes
75
up.
76
77
Note that by default cson uses C-API defaults for numeric
78
precision. To use a custom precision throughout the library, one
79
needs to define the macros CSON_DOUBLE_T_SFMT and/or
80
CSON_DOUBLE_T_PFMT macros to include their desired precision, and
81
must build BOTH cson AND the client using these same values. For
82
example:
83
84
@code
85
#define CSON_DOUBLE_T_PFMT ".8Lf" // for Modified Julian Day values
86
#define HAVE_LONG_DOUBLE
87
@endcode
88
89
(Only CSON_DOUBLE_T_PFTM should be needed for most
90
purposes.)
91
*/
92
93
#if defined(HAVE_LONG_DOUBLE)
94
typedef long double cson_double_t;
95
# ifndef CSON_DOUBLE_T_SFMT
96
# define CSON_DOUBLE_T_SFMT "Lf"
97
# endif
98
# ifndef CSON_DOUBLE_T_PFMT
99
# define CSON_DOUBLE_T_PFMT "Lf"
100
# endif
101
#else
102
typedef double cson_double_t;
103
# ifndef CSON_DOUBLE_T_SFMT
104
# define CSON_DOUBLE_T_SFMT "f"
105
# endif
106
# ifndef CSON_DOUBLE_T_PFMT
107
# define CSON_DOUBLE_T_PFMT "f"
108
# endif
109
#endif
110
111
/** @def CSON_VOID_PTR_IS_BIG
112
113
ONLY define this to a true value if you know that
114
115
(sizeof(cson_int_t) <= sizeof(void*))
116
117
If that is the case, cson does not need to dynamically
118
allocate integers. However, enabling this may cause
119
compilation warnings in 32-bit builds even though the code
120
being warned about cannot ever be called. To get around such
121
warnings, when building on a 64-bit environment you can define
122
this to 1 to get "big" integer support. HOWEVER, all clients must
123
also use the same value for this macro. If i knew a halfway reliable
124
way to determine this automatically at preprocessor-time, i would
125
automate this. We might be able to do halfway reliably by looking
126
for a large INT_MAX value?
127
*/
128
#if !defined(CSON_VOID_PTR_IS_BIG)
129
130
/* Largely taken from http://predef.sourceforge.net/prearch.html
131
132
See also: http://poshlib.hookatooka.com/poshlib/trac.cgi/browser/posh.h
133
*/
134
# if defined(_WIN64) || defined(__LP64__)/*gcc*/ \
135
|| defined(_M_X64) || defined(__amd64__) || defined(__amd64) \
136
|| defined(__x86_64__) || defined(__x86_64) \
137
|| defined(__ia64__) || defined(__ia64) || defined(_IA64) || defined(__IA64__) \
138
|| defined(_M_IA64) \
139
|| defined(__sparc_v9__) || defined(__sparcv9) || defined(_ADDR64) \
140
|| defined(__64BIT__)
141
# define CSON_VOID_PTR_IS_BIG 1
142
# else
143
# define CSON_VOID_PTR_IS_BIG 0
144
# endif
145
#endif
146
147
/** @def CSON_INT_T_SFMT
148
149
scanf()-compatible format token for cson_int_t.
150
*/
151
152
/** @def CSON_INT_T_PFMT
153
154
printf()-compatible format token for cson_int_t.
155
*/
156
157
158
/** @def CSON_DOUBLE_T_SFMT
159
160
scanf()-compatible format token for cson_double_t.
161
*/
162
163
/** @def CSON_DOUBLE_T_PFMT
164
165
printf()-compatible format token for cson_double_t.
166
*/
167
168
/**
169
Type IDs corresponding to JavaScript/JSON types.
170
171
These are only in the public API to allow O(1) client-side
172
dispatching based on cson_value types.
173
*/
174
enum cson_type_id {
175
/**
176
The special "undefined" value constant.
177
178
Its value must be 0 for internal reasons.
179
*/
180
CSON_TYPE_UNDEF = 0,
181
/**
182
The special "null" value constant.
183
*/
184
CSON_TYPE_NULL = 1,
185
/**
186
The bool value type.
187
*/
188
CSON_TYPE_BOOL = 2,
189
/**
190
The integer value type, represented in this library
191
by cson_int_t.
192
*/
193
CSON_TYPE_INTEGER = 3,
194
/**
195
The double value type, represented in this library
196
by cson_double_t.
197
*/
198
CSON_TYPE_DOUBLE = 4,
199
/** The immutable string type. This library stores strings
200
as immutable UTF8.
201
*/
202
CSON_TYPE_STRING = 5,
203
/** The "Array" type. */
204
CSON_TYPE_ARRAY = 6,
205
/** The "Object" type. */
206
CSON_TYPE_OBJECT = 7
207
};
208
/**
209
Convenience typedef.
210
*/
211
typedef enum cson_type_id cson_type_id;
212
213
214
/**
215
Convenience typedef.
216
*/
217
typedef struct cson_value cson_value;
218
219
/** @struct cson_value
220
221
The core value type of this API. It is opaque to clients, and
222
only the cson public API should be used for setting or
223
inspecting their values.
224
225
This class is opaque because stack-based usage can easily cause
226
leaks if one does not intimately understand the underlying
227
internal memory management (which sometimes changes).
228
229
It is (as of 20110323) legal to insert a given value instance into
230
multiple containers (they will share ownership using reference
231
counting) as long as those insertions do not cause cycles. However,
232
be very aware that such value re-use uses a reference to the
233
original copy, meaning that if its value is changed once, it is
234
changed everywhere. Also beware that multi-threaded write
235
operations on such references leads to undefined behaviour.
236
237
PLEASE read the ACHTUNGEN below...
238
239
ACHTUNG #1:
240
241
cson_values MUST NOT form cycles (e.g. via object or array
242
entries).
243
244
Not abiding th Holy Law Of No Cycles will lead to double-frees and
245
the like (i.e. undefined behaviour, likely crashes due to infinite
246
recursion or stepping on invalid (freed) pointers).
247
248
ACHTUNG #2:
249
250
ALL cson_values returned as non-const cson_value pointers from any
251
public functions in the cson API are to be treated as if they are
252
heap-allocated, and MUST be freed by client by doing ONE of:
253
254
- Passing it to cson_value_free().
255
256
- Adding it to an Object or Array, in which case the object/array
257
takes over ownership. As of 20110323, a value may be inserted into
258
a single container multiple times, or into multiple containers,
259
in which case they all share ownership (via reference counting)
260
of the original value (meaning any changes to it are visible in
261
all references to it).
262
263
Each call to cson_value_new_xxx() MUST eventually be followed up
264
by one of those options.
265
266
Some cson_value_new_XXX() implementations do not actually allocate
267
memory, but this is an internal implementation detail. Client code
268
MUST NOT rely on this behaviour and MUST treat each object
269
returned by such a function as if it was a freshly-allocated copy
270
(even if their pointer addresses are the same).
271
272
ACHTUNG #3:
273
274
Note that ACHTUNG #2 tells us that we must always free (or transfer
275
ownership of) all pointers returned bycson_value_new_xxx(), but
276
that two calls to (e.g.) cson_value_new_bool(1) will (or might)
277
return the same address. The client must not rely on the
278
"non-allocation" policy of such special cases, and must pass each
279
returned value to cson_value_free(), even if two of them have the
280
same address. Some special values (e.g. null, true, false, integer
281
0, double 0.0, and empty strings) use shared copies and in other
282
places reference counting is used internally to figure out when it
283
is safe to destroy an object.
284
285
286
@see cson_value_new_array()
287
@see cson_value_new_object()
288
@see cson_value_new_string()
289
@see cson_value_new_integer()
290
@see cson_value_new_double()
291
@see cson_value_new_bool()
292
@see cson_value_true()
293
@see cson_value_false()
294
@see cson_value_null()
295
@see cson_value_free()
296
@see cson_value_type_id()
297
*/
298
299
/** @var cson_rc
300
301
Deprecated: clients are encouraged to use the CSON_RC_xxx values
302
which correspond to cson_rc.xxx, as those are more efficient. Some
303
docs and code may still refer to cson_rc, though.
304
305
This object defines the error codes used by cson.
306
307
Library routines which return int values almost always return a
308
value from this structure. None of the members in this struct have
309
published values except for the OK member, which has the value 0.
310
All other values might be incidentally defined where clients
311
can see them, but the numbers might change from release to
312
release, so clients should only use the symbolic names.
313
314
Client code is expected to access these values via the shared
315
cson_rc object, and use them as demonstrated here:
316
317
@code
318
int rc = cson_some_func(...);
319
if( 0 == rc ) {...success...}
320
else if( cson_rc.ArgError == rc ) { ... some argument was wrong ... }
321
else if( cson_rc.AllocError == rc ) { ... allocation error ... }
322
...
323
@endcode
324
325
Or with the preferred/newer method:
326
327
@code
328
int rc = cson_some_func(...);
329
switch(rc){
330
case 0: ...success...;
331
case CSON_RC_ArgError: ... some argument was wrong ...
332
case CSON_RC_AllocError: ... allocation error ...
333
...
334
}
335
@endcode
336
337
The entries named Parse_XXX are generally only returned by
338
cson_parse() and friends.
339
340
@deprecated
341
*/
342
343
/**
344
The CSON_RC_xxx values are intended to replace the older
345
cson_rc.xxx values.
346
*/
347
enum cson_rc_values {
348
/** The generic success value. Guaranteed to be 0. */
349
CSON_RC_OK = 0,
350
/** Signifies an error in one or more arguments (e.g. NULL where it is not allowed). */
351
CSON_RC_ArgError,
352
/** Signifies that some argument is not in a valid range. */
353
CSON_RC_RangeError,
354
/** Signifies that some argument is not of the correct logical cson type. */
355
CSON_RC_TypeError,
356
/** Signifies an input/ouput error. */
357
CSON_RC_IOError,
358
/** Signifies an out-of-memory error. */
359
CSON_RC_AllocError,
360
/** Signifies that the called code is "NYI" (Not Yet Implemented). */
361
CSON_RC_NYIError,
362
/** Signifies that an internal error was triggered. If it happens, please report this as a bug! */
363
CSON_RC_InternalError,
364
/** Signifies that the called operation is not supported in the
365
current environment. e.g. missing support from 3rd-party or
366
platform-specific code.
367
*/
368
CSON_RC_UnsupportedError,
369
/**
370
Signifies that the request resource could not be found.
371
*/
372
CSON_RC_NotFoundError,
373
/**
374
Signifies an unknown error, possibly because an underlying
375
3rd-party API produced an error and we have no other reasonable
376
error code to convert it to.
377
*/
378
CSON_RC_UnknownError,
379
/**
380
Signifies that the parser found an unexpected character.
381
*/
382
CSON_RC_Parse_INVALID_CHAR,
383
/**
384
Signifies that the parser found an invalid keyword (possibly
385
an unquoted string).
386
*/
387
CSON_RC_Parse_INVALID_KEYWORD,
388
/**
389
Signifies that the parser found an invalid escape sequence.
390
*/
391
CSON_RC_Parse_INVALID_ESCAPE_SEQUENCE,
392
/**
393
Signifies that the parser found an invalid Unicode character
394
sequence.
395
*/
396
CSON_RC_Parse_INVALID_UNICODE_SEQUENCE,
397
/**
398
Signifies that the parser found an invalid numeric token.
399
*/
400
CSON_RC_Parse_INVALID_NUMBER,
401
/**
402
Signifies that the parser reached its maximum defined
403
parsing depth before finishing the input.
404
*/
405
CSON_RC_Parse_NESTING_DEPTH_REACHED,
406
/**
407
Signifies that the parser found an unclosed object or array.
408
*/
409
CSON_RC_Parse_UNBALANCED_COLLECTION,
410
/**
411
Signifies that the parser found an key in an unexpected place.
412
*/
413
CSON_RC_Parse_EXPECTED_KEY,
414
/**
415
Signifies that the parser expected to find a colon but
416
found none (e.g. between keys and values in an object).
417
*/
418
CSON_RC_Parse_EXPECTED_COLON
419
};
420
421
/** @struct cson_rc_
422
See \ref cson_rc for details.
423
*/
424
static const struct cson_rc_
425
{
426
/** The generic success value. Guaranteed to be 0. */
427
const int OK;
428
/** Signifies an error in one or more arguments (e.g. NULL where it is not allowed). */
429
const int ArgError;
430
/** Signifies that some argument is not in a valid range. */
431
const int RangeError;
432
/** Signifies that some argument is not of the correct logical cson type. */
433
const int TypeError;
434
/** Signifies an input/ouput error. */
435
const int IOError;
436
/** Signifies an out-of-memory error. */
437
const int AllocError;
438
/** Signifies that the called code is "NYI" (Not Yet Implemented). */
439
const int NYIError;
440
/** Signifies that an internal error was triggered. If it happens, please report this as a bug! */
441
const int InternalError;
442
/** Signifies that the called operation is not supported in the
443
current environment. e.g. missing support from 3rd-party or
444
platform-specific code.
445
*/
446
const int UnsupportedError;
447
/**
448
Signifies that the request resource could not be found.
449
*/
450
const int NotFoundError;
451
/**
452
Signifies an unknown error, possibly because an underlying
453
3rd-party API produced an error and we have no other reasonable
454
error code to convert it to.
455
*/
456
const int UnknownError;
457
/**
458
Signifies that the parser found an unexpected character.
459
*/
460
const int Parse_INVALID_CHAR;
461
/**
462
Signifies that the parser found an invalid keyword (possibly
463
an unquoted string).
464
*/
465
const int Parse_INVALID_KEYWORD;
466
/**
467
Signifies that the parser found an invalid escape sequence.
468
*/
469
const int Parse_INVALID_ESCAPE_SEQUENCE;
470
/**
471
Signifies that the parser found an invalid Unicode character
472
sequence.
473
*/
474
const int Parse_INVALID_UNICODE_SEQUENCE;
475
/**
476
Signifies that the parser found an invalid numeric token.
477
*/
478
const int Parse_INVALID_NUMBER;
479
/**
480
Signifies that the parser reached its maximum defined
481
parsing depth before finishing the input.
482
*/
483
const int Parse_NESTING_DEPTH_REACHED;
484
/**
485
Signifies that the parser found an unclosed object or array.
486
*/
487
const int Parse_UNBALANCED_COLLECTION;
488
/**
489
Signifies that the parser found an key in an unexpected place.
490
*/
491
const int Parse_EXPECTED_KEY;
492
/**
493
Signifies that the parser expected to find a colon but
494
found none (e.g. between keys and values in an object).
495
*/
496
const int Parse_EXPECTED_COLON;
497
} cson_rc = {
498
CSON_RC_OK,
499
CSON_RC_ArgError,
500
CSON_RC_RangeError,
501
CSON_RC_TypeError,
502
CSON_RC_IOError,
503
CSON_RC_AllocError,
504
CSON_RC_NYIError,
505
CSON_RC_InternalError,
506
CSON_RC_UnsupportedError,
507
CSON_RC_NotFoundError,
508
CSON_RC_UnknownError,
509
CSON_RC_Parse_INVALID_CHAR,
510
CSON_RC_Parse_INVALID_KEYWORD,
511
CSON_RC_Parse_INVALID_ESCAPE_SEQUENCE,
512
CSON_RC_Parse_INVALID_UNICODE_SEQUENCE,
513
CSON_RC_Parse_INVALID_NUMBER,
514
CSON_RC_Parse_NESTING_DEPTH_REACHED,
515
CSON_RC_Parse_UNBALANCED_COLLECTION,
516
CSON_RC_Parse_EXPECTED_KEY,
517
CSON_RC_Parse_EXPECTED_COLON
518
};
519
520
/**
521
Returns the string form of the cson_rc code corresponding to rc, or
522
some unspecified, non-NULL string if it is an unknown code.
523
524
The returned bytes are static and do not changing during the
525
lifetime of the application.
526
*/
527
char const * cson_rc_string(int rc);
528
529
/** @struct cson_parse_opt
530
Client-configurable options for the cson_parse() family of
531
functions.
532
*/
533
struct cson_parse_opt
534
{
535
/**
536
Maximum object/array depth to traverse.
537
*/
538
unsigned short maxDepth;
539
/**
540
Whether or not to allow C-style comments. Do not rely on this
541
option being available. If the underlying parser is replaced,
542
this option might no longer be supported.
543
*/
544
char allowComments;
545
};
546
typedef struct cson_parse_opt cson_parse_opt;
547
548
/**
549
Empty-initialized cson_parse_opt object.
550
*/
551
#define cson_parse_opt_empty_m { 25/*maxDepth*/, 0/*allowComments*/}
552
553
554
/**
555
A class for holding JSON parser information. It is primarily
556
intended for finding the position of a parse error.
557
*/
558
struct cson_parse_info
559
{
560
/**
561
1-based line number.
562
*/
563
unsigned int line;
564
/**
565
0-based column number.
566
*/
567
unsigned int col;
568
569
/**
570
Length, in bytes.
571
*/
572
unsigned int length;
573
574
/**
575
Error code of the parse run (0 for no error).
576
*/
577
int errorCode;
578
579
/**
580
The total number of object keys successfully processed by the
581
parser.
582
*/
583
unsigned int totalKeyCount;
584
585
/**
586
The total number of object/array values successfully processed
587
by the parser, including the root node.
588
*/
589
unsigned int totalValueCount;
590
};
591
typedef struct cson_parse_info cson_parse_info;
592
593
/**
594
Empty-initialized cson_parse_info object.
595
*/
596
#define cson_parse_info_empty_m {1/*line*/,\
597
0/*col*/, \
598
0/*length*/, \
599
0/*errorCode*/, \
600
0/*totalKeyCount*/, \
601
0/*totalValueCount*/ \
602
}
603
/**
604
Empty-initialized cson_parse_info object.
605
*/
606
extern const cson_parse_info cson_parse_info_empty;
607
608
/**
609
Empty-initialized cson_parse_opt object.
610
*/
611
extern const cson_parse_opt cson_parse_opt_empty;
612
613
/**
614
Client-configurable options for the cson_output() family of
615
functions.
616
*/
617
struct cson_output_opt
618
{
619
/**
620
Specifies how to indent (or not) output. The values
621
are:
622
623
(0) == no extra indentation.
624
625
(1) == 1 TAB character for each level.
626
627
(>1) == that number of SPACES for each level.
628
*/
629
unsigned char indentation;
630
631
/**
632
Maximum object/array depth to traverse. Traversing deeply can
633
be indicative of cycles in the object/array tree, and this
634
value is used to figure out when to abort the traversal.
635
*/
636
unsigned short maxDepth;
637
638
/**
639
If true, a newline will be added to generated output,
640
else not.
641
*/
642
char addNewline;
643
644
/**
645
If true, a space will be added after the colon operator
646
in objects' key/value pairs.
647
*/
648
char addSpaceAfterColon;
649
650
/**
651
If set to 1 then objects/arrays containing only a single value
652
will not indent an extra level for that value (but will indent
653
on subsequent levels if that value contains multiple values).
654
*/
655
char indentSingleMemberValues;
656
657
/**
658
The JSON format allows, but does not require, JSON generators
659
to backslash-escape forward slashes. This option enables/disables
660
that feature. According to JSON's inventor, Douglas Crockford:
661
662
<quote>
663
It is allowed, not required. It is allowed so that JSON can be
664
safely embedded in HTML, which can freak out when seeing
665
strings containing "</". JSON tolerates "<\/" for this reason.
666
</quote>
667
668
(from an email on 2011-04-08)
669
670
The default value is 0 (because it's just damned ugly).
671
*/
672
char escapeForwardSlashes;
673
};
674
typedef struct cson_output_opt cson_output_opt;
675
676
/**
677
Empty-initialized cson_output_opt object.
678
*/
679
#define cson_output_opt_empty_m { 0/*indentation*/,\
680
25/*maxDepth*/, \
681
0/*addNewline*/, \
682
0/*addSpaceAfterColon*/, \
683
0/*indentSingleMemberValues*/, \
684
0/*escapeForwardSlashes*/ \
685
}
686
687
/**
688
Empty-initialized cson_output_opt object.
689
*/
690
extern const cson_output_opt cson_output_opt_empty;
691
692
/**
693
Typedef for functions which act as an input source for
694
the cson JSON parser.
695
696
The arguments are:
697
698
- state: implementation-specific state needed by the function.
699
700
- n: when called, *n will be the number of bytes the function
701
should read and copy to dest. The function MUST NOT copy more than
702
*n bytes to dest. Before returning, *n must be set to the number of
703
bytes actually copied to dest. If that number is smaller than the
704
original *n value, the input is assumed to be completed (thus this
705
is not useful with non-blocking readers).
706
707
- dest: the destination memory to copy the data do.
708
709
Must return 0 on success, non-0 on error (preferably a value from
710
cson_rc).
711
712
The parser allows this routine to return a partial character from a
713
UTF multi-byte character. The input routine does not need to
714
concern itself with character boundaries.
715
*/
716
typedef int (*cson_data_source_f)( void * state, void * dest, unsigned int * n );
717
718
/**
719
Typedef for functions which act as an output destination for
720
generated JSON.
721
722
The arguments are:
723
724
- state: implementation-specific state needed by the function.
725
726
- n: the length, in bytes, of src.
727
728
- src: the source bytes which the output function should consume.
729
The src pointer will be invalidated shortly after this function
730
returns, so the implementation must copy or ignore the data, but not
731
hold a copy of the src pointer.
732
733
Must return 0 on success, non-0 on error (preferably a value from
734
cson_rc).
735
736
These functions are called relatively often during the JSON-output
737
process, and should try to be fast.
738
*/
739
typedef int (*cson_data_dest_f)( void * state, void const * src, unsigned int n );
740
741
/**
742
Reads JSON-formatted string data (in ASCII, UTF8, or UTF16), using the
743
src function to fetch all input. This function fetches each input character
744
from the source function, which is calls like src(srcState, buffer, bufferSize),
745
and processes them. If anything is not JSON-kosher then this function
746
fails and returns one of the non-0 cson_rc codes.
747
748
This function is only intended to read root nodes of a JSON tree, either
749
a single object or a single array, containing any number of child elements.
750
751
On success, *tgt is assigned the value of the root node of the
752
JSON input, and the caller takes over ownership of that memory.
753
On error, *tgt is not modified and the caller need not do any
754
special cleanup, except possibly for the input source.
755
756
757
The opt argument may point to an initialized cson_parse_opt object
758
which contains any settings the caller wants. If it is NULL then
759
default settings (the values defined in cson_parse_opt_empty) are
760
used.
761
762
The info argument may be NULL. If it is not NULL then the parser
763
populates it with information which is useful in error
764
reporting. Namely, it contains the line/column of parse errors.
765
766
The srcState argument is ignored by this function but is passed on to src,
767
so any output-destination-specific state can be stored there and accessed
768
via the src callback.
769
770
Non-parse error conditions include:
771
772
- (!tgt) or !src: CSON_RC_ArgError
773
- CSON_RC_AllocError can happen at any time during the input phase
774
775
Here's a complete example of using a custom input source:
776
777
@code
778
// Internal type to hold state for a JSON input string.
779
typedef struct
780
{
781
char const * str; // start of input string
782
char const * pos; // current internal cursor position
783
char const * end; // logical EOF (one-past-the-end)
784
} StringSource;
785
786
// cson_data_source_f() impl which uses StringSource.
787
static int cson_data_source_StringSource( void * state, void * dest,
788
unsigned int * n )
789
{
790
StringSource * ss = (StringSource*) state;
791
unsigned int i;
792
unsigned char * tgt = (unsigned char *)dest;
793
if( ! ss || ! n || !dest ) return CSON_RC_ArgError;
794
else if( !*n ) return CSON_RC_RangeError;
795
for( i = 0;
796
(i < *n) && (ss->pos < ss->end);
797
++i, ++ss->pos, ++tgt )
798
{
799
*tgt = *ss->pos;
800
}
801
*n = i;
802
return 0;
803
}
804
805
...
806
// Now use StringSource together with cson_parse()
807
StringSource ss;
808
cson_value * root = NULL;
809
char const * json = "{\"k1\":123}";
810
ss.str = ss.pos = json;
811
ss.end = json + strlen(json);
812
int rc = cson_parse( &root, cson_data_source_StringSource, &ss, NULL, NULL );
813
@endcode
814
815
It is recommended that clients wrap such utility code into
816
type-safe wrapper functions which also initialize the internal
817
state object and check the user-provided parameters for legality
818
before passing them on to cson_parse(). For examples of this, see
819
cson_parse_FILE() or cson_parse_string().
820
821
TODOs:
822
823
- Buffer the input in larger chunks. We currently read
824
byte-by-byte, but i'm too tired to write/test the looping code for
825
the buffering.
826
827
@see cson_parse_FILE()
828
@see cson_parse_string()
829
*/
830
int cson_parse( cson_value ** tgt, cson_data_source_f src, void * srcState,
831
cson_parse_opt const * opt, cson_parse_info * info );
832
/**
833
A cson_data_source_f() implementation which requires the state argument
834
to be a readable (FILE*) handle.
835
*/
836
int cson_data_source_FILE( void * state, void * dest, unsigned int * n );
837
838
/**
839
Equivalent to cson_parse( tgt, cson_data_source_FILE, src, opt ).
840
841
@see cson_parse_filename()
842
*/
843
int cson_parse_FILE( cson_value ** tgt, FILE * src,
844
cson_parse_opt const * opt, cson_parse_info * info );
845
846
/**
847
Convenience wrapper around cson_parse_FILE() which opens the given filename.
848
849
Returns CSON_RC_IOError if the file cannot be opened.
850
851
@see cson_parse_FILE()
852
*/
853
int cson_parse_filename( cson_value ** tgt, char const * src,
854
cson_parse_opt const * opt, cson_parse_info * info );
855
856
/**
857
Uses an internal helper class to pass src through cson_parse().
858
See that function for the return value and argument semantics.
859
860
src must be a string containing JSON code, at least len bytes long,
861
and the parser will attempt to parse exactly len bytes from src.
862
863
If len is less than 2 (the minimum length of a legal top-node JSON
864
object) then CSON_RC_RangeError is returned.
865
*/
866
int cson_parse_string( cson_value ** tgt, char const * src, unsigned int len,
867
cson_parse_opt const * opt, cson_parse_info * info );
868
869
870
871
/**
872
Outputs the given value as a JSON-formatted string, sending all
873
output to the given callback function. It is intended for top-level
874
objects or arrays, but can be used with any cson_value.
875
876
If opt is NULL then default options (the values defined in
877
cson_output_opt_empty) are used.
878
879
If opt->maxDepth is exceeded while traversing the value tree,
880
CSON_RC_RangeError is returned.
881
882
The destState parameter is ignored by this function and is passed
883
on to the dest function.
884
885
Returns 0 on success. On error, any amount of output might have been
886
generated before the error was triggered.
887
888
Example:
889
890
@code
891
int rc = cson_output( myValue, cson_data_dest_FILE, stdout, NULL );
892
// basically equivalent to: cson_output_FILE( myValue, stdout, NULL );
893
// but note that cson_output_FILE() actually uses different defaults
894
// for the output options.
895
@endcode
896
*/
897
int cson_output( cson_value const * src, cson_data_dest_f dest, void * destState, cson_output_opt const * opt );
898
899
900
/**
901
A cson_data_dest_f() implementation which requires the state argument
902
to be a writable (FILE*) handle.
903
*/
904
int cson_data_dest_FILE( void * state, void const * src, unsigned int n );
905
906
/**
907
Almost equivalent to cson_output( src, cson_data_dest_FILE, dest, opt ),
908
with one minor difference: if opt is NULL then the default options
909
always include the addNewline option, since that is normally desired
910
for FILE output.
911
912
@see cson_output_filename()
913
*/
914
int cson_output_FILE( cson_value const * src, FILE * dest, cson_output_opt const * opt );
915
/**
916
Convenience wrapper around cson_output_FILE() which writes to the given filename, destroying
917
any existing contents. Returns CSON_RC_IOError if the file cannot be opened.
918
919
@see cson_output_FILE()
920
*/
921
int cson_output_filename( cson_value const * src, char const * dest, cson_output_opt const * fmt );
922
923
/**
924
Returns the virtual type of v, or CSON_TYPE_UNDEF if !v.
925
*/
926
cson_type_id cson_value_type_id( cson_value const * v );
927
928
929
/** Returns true if v is null, v->api is NULL, or v holds the special undefined value. */
930
char cson_value_is_undef( cson_value const * v );
931
/** Returns true if v contains a null value. */
932
char cson_value_is_null( cson_value const * v );
933
/** Returns true if v contains a bool value. */
934
char cson_value_is_bool( cson_value const * v );
935
/** Returns true if v contains an integer value. */
936
char cson_value_is_integer( cson_value const * v );
937
/** Returns true if v contains a double value. */
938
char cson_value_is_double( cson_value const * v );
939
/** Returns true if v contains a number (double, integer) value. */
940
char cson_value_is_number( cson_value const * v );
941
/** Returns true if v contains a string value. */
942
char cson_value_is_string( cson_value const * v );
943
/** Returns true if v contains an array value. */
944
char cson_value_is_array( cson_value const * v );
945
/** Returns true if v contains an object value. */
946
char cson_value_is_object( cson_value const * v );
947
948
/** @struct cson_object
949
950
cson_object is an opaque handle to an Object value.
951
952
They are used like:
953
954
@code
955
cson_object * obj = cson_value_get_object(myValue);
956
...
957
@endcode
958
959
They can be created like:
960
961
@code
962
cson_value * objV = cson_value_new_object();
963
cson_object * obj = cson_value_get_object(objV);
964
// obj is owned by objV and objV must eventually be freed
965
// using cson_value_free() or added to a container
966
// object/array (which transfers ownership to that container).
967
@endcode
968
969
@see cson_value_new_object()
970
@see cson_value_get_object()
971
@see cson_value_free()
972
*/
973
974
typedef struct cson_object cson_object;
975
976
/** @struct cson_array
977
978
cson_array is an opaque handle to an Array value.
979
980
They are used like:
981
982
@code
983
cson_array * obj = cson_value_get_array(myValue);
984
...
985
@endcode
986
987
They can be created like:
988
989
@code
990
cson_value * arV = cson_value_new_array();
991
cson_array * ar = cson_value_get_array(arV);
992
// ar is owned by arV and arV must eventually be freed
993
// using cson_value_free() or added to a container
994
// object/array (which transfers ownership to that container).
995
@endcode
996
997
@see cson_value_new_array()
998
@see cson_value_get_array()
999
@see cson_value_free()
1000
1001
*/
1002
typedef struct cson_array cson_array;
1003
1004
/** @struct cson_string
1005
1006
cson-internal string type, opaque to client code. Strings in cson
1007
are immutable and allocated only by library internals, never
1008
directly by client code.
1009
1010
The actual string bytes are to be allocated together in the same
1011
memory chunk as the cson_string object, which saves us 1 malloc()
1012
and 1 pointer member in this type (because we no longer have a
1013
direct pointer to the memory).
1014
1015
Potential TODOs:
1016
1017
@see cson_string_cstr()
1018
*/
1019
typedef struct cson_string cson_string;
1020
1021
/**
1022
Converts the given value to a boolean, using JavaScript semantics depending
1023
on the concrete type of val:
1024
1025
undef or null: false
1026
1027
boolean: same
1028
1029
integer, double: 0 or 0.0 == false, else true
1030
1031
object, array: true
1032
1033
string: length-0 string is false, else true.
1034
1035
Returns 0 on success and assigns *v (if v is not NULL) to either 0 or 1.
1036
On error (val is NULL) then v is not modified.
1037
*/
1038
int cson_value_fetch_bool( cson_value const * val, char * v );
1039
1040
/**
1041
Similar to cson_value_fetch_bool(), but fetches an integer value.
1042
1043
The conversion, if any, depends on the concrete type of val:
1044
1045
NULL, null, undefined: *v is set to 0 and 0 is returned.
1046
1047
string, object, array: *v is set to 0 and
1048
CSON_RC_TypeError is returned. The error may normally be safely
1049
ignored, but it is provided for those wanted to know whether a direct
1050
conversion was possible.
1051
1052
integer: *v is set to the int value and 0 is returned.
1053
1054
double: *v is set to the value truncated to int and 0 is returned.
1055
*/
1056
int cson_value_fetch_integer( cson_value const * val, cson_int_t * v );
1057
1058
/**
1059
The same conversions and return values as
1060
cson_value_fetch_integer(), except that the roles of int/double are
1061
swapped.
1062
*/
1063
int cson_value_fetch_double( cson_value const * val, cson_double_t * v );
1064
1065
/**
1066
If cson_value_is_string(val) then this function assigns *str to the
1067
contents of the string. str may be NULL, in which case this function
1068
functions like cson_value_is_string() but returns 0 on success.
1069
1070
Returns 0 if val is-a string, else non-0, in which case *str is not
1071
modified.
1072
1073
The bytes are owned by the given value and may be invalidated in any of
1074
the following ways:
1075
1076
- The value is cleaned up or freed.
1077
1078
- An array or object containing the value peforms a re-allocation
1079
(it shrinks or grows).
1080
1081
And thus the bytes should be consumed before any further operations
1082
on val or any container which holds it.
1083
1084
Note that this routine does not convert non-String values to their
1085
string representations. (Adding that ability would add more
1086
overhead to every cson_value instance.)
1087
*/
1088
int cson_value_fetch_string( cson_value const * val, cson_string ** str );
1089
1090
/**
1091
If cson_value_is_object(val) then this function assigns *obj to the underlying
1092
object value and returns 0, otherwise non-0 is returned and *obj is not modified.
1093
1094
obj may be NULL, in which case this function works like cson_value_is_object()
1095
but with inverse return value semantics (0==success) (and it's a few
1096
CPU cycles slower).
1097
1098
The *obj pointer is owned by val, and will be invalidated when val
1099
is cleaned up.
1100
1101
Achtung: for best results, ALWAYS pass a pointer to NULL as the
1102
second argument, e.g.:
1103
1104
@code
1105
cson_object * obj = NULL;
1106
int rc = cson_value_fetch_object( val, &obj );
1107
1108
// Or, more simply:
1109
obj = cson_value_get_object( val );
1110
@endcode
1111
1112
@see cson_value_get_object()
1113
*/
1114
int cson_value_fetch_object( cson_value const * val, cson_object ** obj );
1115
1116
/**
1117
Identical to cson_value_fetch_object(), but works on array values.
1118
1119
@see cson_value_get_array()
1120
*/
1121
int cson_value_fetch_array( cson_value const * val, cson_array ** tgt );
1122
1123
/**
1124
Simplified form of cson_value_fetch_bool(). Returns 0 if val
1125
is NULL.
1126
*/
1127
char cson_value_get_bool( cson_value const * val );
1128
1129
/**
1130
Simplified form of cson_value_fetch_integer(). Returns 0 if val
1131
is NULL.
1132
*/
1133
cson_int_t cson_value_get_integer( cson_value const * val );
1134
1135
/**
1136
Simplified form of cson_value_fetch_double(). Returns 0.0 if val
1137
is NULL.
1138
*/
1139
cson_double_t cson_value_get_double( cson_value const * val );
1140
1141
/**
1142
Simplified form of cson_value_fetch_string(). Returns NULL if val
1143
is-not-a string value.
1144
*/
1145
cson_string * cson_value_get_string( cson_value const * val );
1146
1147
/**
1148
Returns a pointer to the NULL-terminated string bytes of str.
1149
The bytes are owned by string and will be invalided when it
1150
is cleaned up.
1151
1152
If str is NULL then NULL is returned. If the string has a length
1153
of 0 then "" is returned.
1154
1155
@see cson_string_length_bytes()
1156
@see cson_value_get_string()
1157
*/
1158
char const * cson_string_cstr( cson_string const * str );
1159
1160
/**
1161
Convenience function which returns the string bytes of
1162
the given value if it is-a string, otherwise it returns
1163
NULL. Note that this does no conversion of non-string types
1164
to strings.
1165
1166
Equivalent to cson_string_cstr(cson_value_get_string(val)).
1167
*/
1168
char const * cson_value_get_cstr( cson_value const * val );
1169
1170
/**
1171
Equivalent to cson_string_cmp_cstr_n(lhs, cson_string_cstr(rhs), cson_string_length_bytes(rhs)).
1172
*/
1173
int cson_string_cmp( cson_string const * lhs, cson_string const * rhs );
1174
1175
/**
1176
Compares lhs to rhs using memcmp()/strcmp() semantics. Generically
1177
speaking it returns a negative number if lhs is less-than rhs, 0 if
1178
they are equivalent, or a positive number if lhs is greater-than
1179
rhs. It has the following rules for equivalence:
1180
1181
- The maximum number of bytes compared is the lesser of rhsLen and
1182
the length of lhs. If the strings do not match, but compare equal
1183
up to the just-described comparison length, the shorter string is
1184
considered to be less-than the longer one.
1185
1186
- If lhs and rhs are both NULL, or both have a length of 0 then they will
1187
compare equal.
1188
1189
- If lhs is null/length-0 but rhs is not then lhs is considered to be less-than
1190
rhs.
1191
1192
- If rhs is null/length-0 but lhs is not then rhs is considered to be less-than
1193
rhs.
1194
1195
- i have no clue if the results are exactly correct for UTF strings.
1196
1197
*/
1198
int cson_string_cmp_cstr_n( cson_string const * lhs, char const * rhs, unsigned int rhsLen );
1199
1200
/**
1201
Equivalent to cson_string_cmp_cstr_n( lhs, rhs, (rhs&&*rhs)?strlen(rhs):0 ).
1202
*/
1203
int cson_string_cmp_cstr( cson_string const * lhs, char const * rhs );
1204
1205
/**
1206
Returns the length, in bytes, of str, or 0 if str is NULL. This is
1207
an O(1) operation.
1208
1209
TODO: add cson_string_length_chars() (is O(N) unless we add another
1210
member to store the char length).
1211
1212
@see cson_string_cstr()
1213
*/
1214
unsigned int cson_string_length_bytes( cson_string const * str );
1215
1216
/**
1217
Returns the number of UTF8 characters in str. This value will
1218
be at most as long as cson_string_length_bytes() for the
1219
same string, and less if it has multi-byte characters.
1220
1221
Returns 0 if str is NULL.
1222
*/
1223
unsigned int cson_string_length_utf8( cson_string const * str );
1224
1225
/**
1226
Like cson_value_get_string(), but returns a copy of the underying
1227
string bytes, which the caller owns and must eventually free
1228
using free().
1229
*/
1230
char * cson_value_get_string_copy( cson_value const * val );
1231
1232
/**
1233
Simplified form of cson_value_fetch_object(). Returns NULL if val
1234
is-not-a object value.
1235
*/
1236
cson_object * cson_value_get_object( cson_value const * val );
1237
1238
/**
1239
Simplified form of cson_value_fetch_array(). Returns NULL if val
1240
is-not-a array value.
1241
*/
1242
cson_array * cson_value_get_array( cson_value const * val );
1243
1244
/**
1245
Const-correct form of cson_value_get_array().
1246
*/
1247
cson_array const * cson_value_get_array_c( cson_value const * val );
1248
1249
/**
1250
If ar is-a array and is at least (pos+1) entries long then *v (if v is not NULL)
1251
is assigned to the value at that position (which may be NULL).
1252
1253
Ownership of the *v return value is unchanged by this call. (The
1254
containing array may share ownership of the value with other
1255
containers.)
1256
1257
If pos is out of range, non-0 is returned and *v is not modified.
1258
1259
If v is NULL then this function returns 0 if pos is in bounds, but does not
1260
otherwise return a value to the caller.
1261
*/
1262
int cson_array_value_fetch( cson_array const * ar, unsigned int pos, cson_value ** v );
1263
1264
/**
1265
Simplified form of cson_array_value_fetch() which returns NULL if
1266
ar is NULL, pos is out of bounds or if ar has no element at that
1267
position.
1268
*/
1269
cson_value * cson_array_get( cson_array const * ar, unsigned int pos );
1270
1271
/**
1272
Ensures that ar has allocated space for at least the given
1273
number of entries. This never shrinks the array and never
1274
changes its logical size, but may pre-allocate space in the
1275
array for storing new (as-yet-unassigned) values.
1276
1277
Returns 0 on success, or non-zero on error:
1278
1279
- If ar is NULL: CSON_RC_ArgError
1280
1281
- If allocation fails: CSON_RC_AllocError
1282
*/
1283
int cson_array_reserve( cson_array * ar, unsigned int size );
1284
1285
/**
1286
If ar is not NULL, sets *v (if v is not NULL) to the length of the array
1287
and returns 0. Returns CSON_RC_ArgError if ar is NULL.
1288
*/
1289
int cson_array_length_fetch( cson_array const * ar, unsigned int * v );
1290
1291
/**
1292
Simplified form of cson_array_length_fetch() which returns 0 if ar
1293
is NULL.
1294
*/
1295
unsigned int cson_array_length_get( cson_array const * ar );
1296
1297
/**
1298
Sets the given index of the given array to the given value.
1299
1300
If ar already has an item at that index then it is cleaned up and
1301
freed before inserting the new item.
1302
1303
ar is expanded, if needed, to be able to hold at least (ndx+1)
1304
items, and any new entries created by that expansion are empty
1305
(NULL values).
1306
1307
On success, 0 is returned and ownership of v is transfered to ar.
1308
1309
On error ownership of v is NOT modified, and the caller may still
1310
need to clean it up. For example, the following code will introduce
1311
a leak if this function fails:
1312
1313
@code
1314
cson_array_append( myArray, cson_value_new_integer(42) );
1315
@endcode
1316
1317
Because the value created by cson_value_new_integer() has no owner
1318
and is not cleaned up. The "more correct" way to do this is:
1319
1320
@code
1321
cson_value * v = cson_value_new_integer(42);
1322
int rc = cson_array_append( myArray, v );
1323
if( 0 != rc ) {
1324
cson_value_free( v );
1325
... handle error ...
1326
}
1327
@endcode
1328
1329
*/
1330
int cson_array_set( cson_array * ar, unsigned int ndx, cson_value * v );
1331
1332
/**
1333
Appends the given value to the given array, transfering ownership of
1334
v to ar. On error, ownership of v is not modified. Ownership of ar
1335
is never changed by this function.
1336
1337
This is functionally equivalent to
1338
cson_array_set(ar,cson_array_length_get(ar),v), but this
1339
implementation has slightly different array-preallocation policy
1340
(it grows more eagerly).
1341
1342
Returns 0 on success, non-zero on error. Error cases include:
1343
1344
- ar or v are NULL: CSON_RC_ArgError
1345
1346
- Array cannot be expanded to hold enough elements: CSON_RC_AllocError.
1347
1348
- Appending would cause a numeric overlow in the array's size:
1349
CSON_RC_RangeError. (However, you'll get an AllocError long before
1350
that happens!)
1351
1352
On error ownership of v is NOT modified, and the caller may still
1353
need to clean it up. See cson_array_set() for the details.
1354
1355
*/
1356
int cson_array_append( cson_array * ar, cson_value * v );
1357
1358
1359
/**
1360
Creates a new cson_value from the given boolean value.
1361
1362
Ownership of the new value is passed to the caller, who must
1363
eventually either free the value using cson_value_free() or
1364
inserting it into a container (array or object), which transfers
1365
ownership to the container. See the cson_value class documentation
1366
for more details.
1367
1368
Semantically speaking this function Returns NULL on allocation
1369
error, but the implementation never actually allocates for this
1370
case. Nonetheless, it must be treated as if it were an allocated
1371
value.
1372
*/
1373
cson_value * cson_value_new_bool( char v );
1374
1375
1376
/**
1377
Alias for cson_value_new_bool(v).
1378
*/
1379
cson_value * cson_new_bool(char v);
1380
1381
/**
1382
Returns the special JSON "null" value. When outputing JSON,
1383
its string representation is "null" (without the quotes).
1384
1385
See cson_value_new_bool() for notes regarding the returned
1386
value's memory.
1387
*/
1388
cson_value * cson_value_null( void );
1389
1390
/**
1391
Equivalent to cson_value_new_bool(1).
1392
*/
1393
cson_value * cson_value_true( void );
1394
1395
/**
1396
Equivalent to cson_value_new_bool(0).
1397
*/
1398
cson_value * cson_value_false( void );
1399
1400
/**
1401
Semantically the same as cson_value_new_bool(), but for integers.
1402
*/
1403
cson_value * cson_value_new_integer( cson_int_t v );
1404
1405
/**
1406
Alias for cson_value_new_integer(v).
1407
*/
1408
cson_value * cson_new_int(cson_int_t v);
1409
1410
/**
1411
Semantically the same as cson_value_new_bool(), but for doubles.
1412
*/
1413
cson_value * cson_value_new_double( cson_double_t v );
1414
1415
/**
1416
Alias for cson_value_new_double(v).
1417
*/
1418
cson_value * cson_new_double(cson_double_t v);
1419
1420
/**
1421
Semantically the same as cson_value_new_bool(), but for strings.
1422
This creates a JSON value which copies the first n bytes of str.
1423
The string will automatically be NUL-terminated.
1424
1425
Note that if str is NULL or n is 0, this function still
1426
returns non-NULL value representing that empty string.
1427
1428
Returns NULL on allocation error.
1429
1430
See cson_value_new_bool() for important information about the
1431
returned memory.
1432
*/
1433
cson_value * cson_value_new_string( char const * str, unsigned int n );
1434
1435
/**
1436
Allocates a new "object" value and transfers ownership of it to the
1437
caller. It must eventually be destroyed, by the caller or its
1438
owning container, by passing it to cson_value_free().
1439
1440
Returns NULL on allocation error.
1441
1442
Post-conditions: cson_value_is_object(value) will return true.
1443
1444
@see cson_value_new_array()
1445
@see cson_value_free()
1446
*/
1447
cson_value * cson_value_new_object( void );
1448
1449
/**
1450
This works like cson_value_new_object() but returns an Object
1451
handle directly.
1452
1453
The value handle for the returned object can be fetched with
1454
cson_object_value(theObject).
1455
1456
Ownership is transfered to the caller, who must eventually free it
1457
by passing the Value handle (NOT the Object handle) to
1458
cson_value_free() or passing ownership to a parent container.
1459
1460
Returns NULL on error (out of memory).
1461
*/
1462
cson_object * cson_new_object( void );
1463
1464
/**
1465
Identical to cson_new_object() except that it creates
1466
an Array.
1467
*/
1468
cson_array * cson_new_array( void );
1469
1470
/**
1471
Identical to cson_new_object() except that it creates
1472
a String.
1473
*/
1474
cson_string * cson_new_string(char const * val, unsigned int len);
1475
1476
/**
1477
Equivalent to cson_value_free(cson_object_value(x)).
1478
*/
1479
void cson_free_object(cson_object *x);
1480
1481
/**
1482
Equivalent to cson_value_free(cson_array_value(x)).
1483
*/
1484
void cson_free_array(cson_array *x);
1485
1486
/**
1487
Equivalent to cson_value_free(cson_string_value(x)).
1488
*/
1489
void cson_free_string(cson_string *x);
1490
1491
1492
/**
1493
Allocates a new "array" value and transfers ownership of it to the
1494
caller. It must eventually be destroyed, by the caller or its
1495
owning container, by passing it to cson_value_free().
1496
1497
Returns NULL on allocation error.
1498
1499
Post-conditions: cson_value_is_array(value) will return true.
1500
1501
@see cson_value_new_object()
1502
@see cson_value_free()
1503
*/
1504
cson_value * cson_value_new_array( void );
1505
1506
/**
1507
Frees any resources owned by v, then frees v. If v is a container
1508
type (object or array) its children are also freed (recursively).
1509
1510
If v is NULL, this is a no-op.
1511
1512
This function decrements a reference count and only destroys the
1513
value if its reference count drops to 0. Reference counts are
1514
increased by either inserting the value into a container or via
1515
cson_value_add_reference(). Even if this function does not
1516
immediately destroy the value, the value must be considered, from
1517
the perspective of that client code, to have been
1518
destroyed/invalidated by this call.
1519
1520
1521
@see cson_value_new_object()
1522
@see cson_value_new_array()
1523
@see cson_value_add_reference()
1524
*/
1525
void cson_value_free(cson_value * v);
1526
1527
/**
1528
Alias for cson_value_free().
1529
*/
1530
void cson_free_value(cson_value * v);
1531
1532
1533
/**
1534
Functionally similar to cson_array_set(), but uses a string key
1535
as an index. Like arrays, if a value already exists for the given key,
1536
it is destroyed by this function before inserting the new value.
1537
1538
If v is NULL then this call is equivalent to
1539
cson_object_unset(obj,key). Note that (v==NULL) is treated
1540
differently from v having the special null value. In the latter
1541
case, the key is set to the special null value.
1542
1543
The key may be encoded as ASCII or UTF8. Results are undefined
1544
with other encodings, and the errors won't show up here, but may
1545
show up later, e.g. during output.
1546
1547
Returns 0 on success, non-0 on error. It has the following error
1548
cases:
1549
1550
- CSON_RC_ArgError: obj or key are NULL or strlen(key) is 0.
1551
1552
- CSON_RC_AllocError: an out-of-memory error
1553
1554
On error ownership of v is NOT modified, and the caller may still
1555
need to clean it up. For example, the following code will introduce
1556
a leak if this function fails:
1557
1558
@code
1559
cson_object_set( myObj, "foo", cson_value_new_integer(42) );
1560
@endcode
1561
1562
Because the value created by cson_value_new_integer() has no owner
1563
and is not cleaned up. The "more correct" way to do this is:
1564
1565
@code
1566
cson_value * v = cson_value_new_integer(42);
1567
int rc = cson_object_set( myObj, "foo", v );
1568
if( 0 != rc ) {
1569
cson_value_free( v );
1570
... handle error ...
1571
}
1572
@endcode
1573
1574
Potential TODOs:
1575
1576
- Add an overload which takes a cson_value key instead. To get
1577
any value out of that we first need to be able to convert arbitrary
1578
value types to strings. We could simply to-JSON them and use those
1579
as keys.
1580
*/
1581
int cson_object_set( cson_object * obj, char const * key, cson_value * v );
1582
1583
/**
1584
Functionaly equivalent to cson_object_set(), but takes a
1585
cson_string() as its KEY type. The string will be reference-counted
1586
like any other values, and the key may legally be used within this
1587
same container (as a value) or others (as a key or value) at the
1588
same time.
1589
1590
Returns 0 on success. On error, ownership (i.e. refcounts) of key
1591
and value are not modified. On success key and value will get
1592
increased refcounts unless they are replacing themselves (which is
1593
a harmless no-op).
1594
*/
1595
int cson_object_set_s( cson_object * obj, cson_string * key, cson_value * v );
1596
1597
/**
1598
Removes a property from an object.
1599
1600
If obj contains the given key, it is removed and 0 is returned. If
1601
it is not found, CSON_RC_NotFoundError is returned (which can
1602
normally be ignored by client code).
1603
1604
CSON_RC_ArgError is returned if obj or key are NULL or key has
1605
a length of 0.
1606
1607
Returns 0 if the given key is found and removed.
1608
1609
This is functionally equivalent calling
1610
cson_object_set(obj,key,NULL).
1611
*/
1612
int cson_object_unset( cson_object * obj, char const * key );
1613
1614
/**
1615
Searches the given object for a property with the given key. If found,
1616
it is returned. If no match is found, or any arguments are NULL, NULL is
1617
returned. The returned object is owned by obj, and may be invalidated
1618
by ANY operations which change obj's property list (i.e. add or remove
1619
properties).
1620
1621
FIXME: allocate the key/value pairs like we do for cson_array,
1622
to get improve the lifetimes of fetched values.
1623
1624
@see cson_object_fetch_sub()
1625
@see cson_object_get_sub()
1626
*/
1627
cson_value * cson_object_get( cson_object const * obj, char const * key );
1628
1629
/**
1630
Equivalent to cson_object_get() but takes a cson_string argument
1631
instead of a C-style string.
1632
*/
1633
cson_value * cson_object_get_s( cson_object const * obj, cson_string const *key );
1634
1635
/**
1636
Similar to cson_object_get(), but removes the value from the parent
1637
object's ownership. If no item is found then NULL is returned, else
1638
the object (now owned by the caller or possibly shared with other
1639
containers) is returned.
1640
1641
Returns NULL if either obj or key are NULL or key has a length
1642
of 0.
1643
1644
This function reduces the returned value's reference count but has
1645
the specific property that it does not treat refcounts 0 and 1
1646
identically, meaning that the returned object may have a refcount
1647
of 0. This behaviour works around a corner-case where we want to
1648
extract a child element from its parent and then destroy the parent
1649
(which leaves us in an undesireable (normally) reference count
1650
state).
1651
*/
1652
cson_value * cson_object_take( cson_object * obj, char const * key );
1653
1654
/**
1655
Fetches a property from a child (or [great-]*grand-child) object.
1656
1657
obj is the object to search.
1658
1659
path is a delimited string, where the delimiter is the given
1660
separator character.
1661
1662
This function searches for the given path, starting at the given object
1663
and traversing its properties as the path specifies. If a given part of the
1664
path is not found, then this function fails with CSON_RC_NotFoundError.
1665
1666
If it finds the given path, it returns the value by assiging *tgt
1667
to it. If tgt is NULL then this function has no side-effects but
1668
will return 0 if the given path is found within the object, so it can be used
1669
to test for existence without fetching it.
1670
1671
Returns 0 if it finds an entry, CSON_RC_NotFoundError if it finds
1672
no item, and any other non-zero error code on a "real" error. Errors include:
1673
1674
- obj or path are NULL: CSON_RC_ArgError
1675
1676
- separator is 0, or path is an empty string or contains only
1677
separator characters: CSON_RC_RangeError
1678
1679
- There is an upper limit on how long a single path component may
1680
be (some "reasonable" internal size), and CSON_RC_RangeError is
1681
returned if that length is violated.
1682
1683
1684
Limitations:
1685
1686
- It has no way to fetch data from arrays this way. i could
1687
imagine, e.g., a path of "subobj.subArray.0" for
1688
subobj.subArray[0], or "0.3.1" for [0][3][1]. But i'm too
1689
lazy/tired to add this.
1690
1691
Example usage:
1692
1693
1694
Assume we have a JSON structure which abstractly looks like:
1695
1696
@code
1697
{"subobj":{"subsubobj":{"myValue":[1,2,3]}}}
1698
@endcode
1699
1700
Out goal is to get the value of myValue. We can do that with:
1701
1702
@code
1703
cson_value * v = NULL;
1704
int rc = cson_object_fetch_sub( object, &v, "subobj.subsubobj.myValue", '.' );
1705
@endcode
1706
1707
Note that because keys in JSON may legally contain a '.', the
1708
separator must be specified by the caller. e.g. the path
1709
"subobj/subsubobj/myValue" with separator='/' is equivalent the
1710
path "subobj.subsubobj.myValue" with separator='.'. The value of 0
1711
is not legal as a separator character because we cannot
1712
distinguish that use from the real end-of-string without requiring
1713
the caller to also pass in the length of the string.
1714
1715
Multiple successive separators in the list are collapsed into a
1716
single separator for parsing purposes. e.g. the path "a...b...c"
1717
(separator='.') is equivalent to "a.b.c".
1718
1719
@see cson_object_get_sub()
1720
@see cson_object_get_sub2()
1721
*/
1722
int cson_object_fetch_sub( cson_object const * obj, cson_value ** tgt, char const * path, char separator );
1723
1724
/**
1725
Similar to cson_object_fetch_sub(), but derives the path separator
1726
character from the first byte of the path argument. e.g. the
1727
following arg equivalent:
1728
1729
@code
1730
cson_object_fetch_sub( obj, &tgt, "foo.bar.baz", '.' );
1731
cson_object_fetch_sub2( obj, &tgt, ".foo.bar.baz" );
1732
@endcode
1733
*/
1734
int cson_object_fetch_sub2( cson_object const * obj, cson_value ** tgt, char const * path );
1735
1736
/**
1737
Convenience form of cson_object_fetch_sub() which returns NULL if the given
1738
item is not found.
1739
*/
1740
cson_value * cson_object_get_sub( cson_object const * obj, char const * path, char sep );
1741
1742
/**
1743
Convenience form of cson_object_fetch_sub2() which returns NULL if the given
1744
item is not found.
1745
*/
1746
cson_value * cson_object_get_sub2( cson_object const * obj, char const * path );
1747
1748
/** @enum CSON_MERGE_FLAGS
1749
1750
Flags for cson_object_merge().
1751
*/
1752
enum CSON_MERGE_FLAGS {
1753
CSON_MERGE_DEFAULT = 0,
1754
CSON_MERGE_REPLACE = 0x01,
1755
CSON_MERGE_NO_RECURSE = 0x02
1756
};
1757
1758
/**
1759
"Merges" the src object's properties into dest. Each property in
1760
src is copied (using reference counting, not cloning) into dest. If
1761
dest already has the given property then behaviour depends on the
1762
flags argument:
1763
1764
If flag has the CSON_MERGE_REPLACE bit set then this function will
1765
by default replace non-object properties with the src property. If
1766
src and dest both have the property AND it is an Object then this
1767
function operates recursively on those objects. If
1768
CSON_MERGE_NO_RECURSE is set then objects are not recursed in this
1769
manner, and will be completely replaced if CSON_MERGE_REPLACE is
1770
set.
1771
1772
Array properties in dest are NOT recursed for merging - they are
1773
either replaced or left as-is, depending on whether flags contains
1774
he CSON_MERGE_REPLACE bit.
1775
1776
Returns 0 on success. The error conditions are:
1777
1778
- dest or src are NULL or (dest==src) returns CSON_RC_ArgError.
1779
1780
- dest or src contain cyclic references - this will likely cause a
1781
crash due to endless recursion.
1782
1783
Potential TODOs:
1784
1785
- Add a flag to copy clones, not the original values.
1786
*/
1787
int cson_object_merge( cson_object * dest, cson_object const * src, int flags );
1788
1789
1790
/**
1791
An iterator type for traversing object properties.
1792
1793
Its values must be considered private, not to be touched by client
1794
code.
1795
1796
@see cson_object_iter_init()
1797
@see cson_object_iter_next()
1798
*/
1799
struct cson_object_iterator
1800
{
1801
1802
/** @internal
1803
The underlying object.
1804
*/
1805
cson_object const * obj;
1806
/** @internal
1807
Current position in the property list.
1808
*/
1809
unsigned int pos;
1810
};
1811
typedef struct cson_object_iterator cson_object_iterator;
1812
1813
/**
1814
Empty-initialized cson_object_iterator object.
1815
*/
1816
#define cson_object_iterator_empty_m {NULL/*obj*/,0/*pos*/}
1817
1818
/**
1819
Empty-initialized cson_object_iterator object.
1820
*/
1821
extern const cson_object_iterator cson_object_iterator_empty;
1822
1823
/**
1824
Initializes the given iterator to point at the start of obj's
1825
properties. Returns 0 on success or CSON_RC_ArgError if !obj
1826
or !iter.
1827
1828
obj must outlive iter, or results are undefined. Results are also
1829
undefined if obj is modified while the iterator is active.
1830
1831
@see cson_object_iter_next()
1832
*/
1833
int cson_object_iter_init( cson_object const * obj, cson_object_iterator * iter );
1834
1835
/** @struct cson_kvp
1836
1837
This class represents a key/value pair and is used for storing
1838
object properties. It is opaque to client code, and the public
1839
API only uses this type for purposes of iterating over cson_object
1840
properties using the cson_object_iterator interfaces.
1841
*/
1842
1843
typedef struct cson_kvp cson_kvp;
1844
1845
/**
1846
Returns the next property from the given iterator's object, or NULL
1847
if the end of the property list as been reached.
1848
1849
Note that the order of object properties is undefined by the API,
1850
and may change from version to version.
1851
1852
The returned memory belongs to the underlying object and may be
1853
invalidated by any changes to that object.
1854
1855
Example usage:
1856
1857
@code
1858
cson_object_iterator it;
1859
cson_object_iter_init( myObject, &it ); // only fails if either arg is 0
1860
cson_kvp * kvp;
1861
cson_string const * key;
1862
cson_value const * val;
1863
while( (kvp = cson_object_iter_next(&it) ) )
1864
{
1865
key = cson_kvp_key(kvp);
1866
val = cson_kvp_value(kvp);
1867
...
1868
}
1869
@endcode
1870
1871
There is no need to clean up an iterator, as it holds no dynamic resources.
1872
1873
@see cson_kvp_key()
1874
@see cson_kvp_value()
1875
*/
1876
cson_kvp * cson_object_iter_next( cson_object_iterator * iter );
1877
1878
1879
/**
1880
Returns the key associated with the given key/value pair,
1881
or NULL if !kvp. The memory is owned by the object which contains
1882
the key/value pair, and may be invalidated by any modifications
1883
to that object.
1884
*/
1885
cson_string * cson_kvp_key( cson_kvp const * kvp );
1886
1887
/**
1888
Returns the value associated with the given key/value pair,
1889
or NULL if !kvp. The memory is owned by the object which contains
1890
the key/value pair, and may be invalidated by any modifications
1891
to that object.
1892
*/
1893
cson_value * cson_kvp_value( cson_kvp const * kvp );
1894
1895
/** @typedef some unsigned int type cson_size_t
1896
1897
*/
1898
typedef unsigned int cson_size_t;
1899
1900
/**
1901
A generic buffer class.
1902
1903
They can be used like this:
1904
1905
@code
1906
cson_buffer b = cson_buffer_empty;
1907
int rc = cson_buffer_reserve( &buf, 100 );
1908
if( 0 != rc ) { ... allocation error ... }
1909
... use buf.mem ...
1910
... then free it up ...
1911
cson_buffer_reserve( &buf, 0 );
1912
@endcode
1913
1914
To take over ownership of a buffer's memory:
1915
1916
@code
1917
void * mem = b.mem;
1918
// mem is b.capacity bytes long, but only b.used
1919
// bytes of it has been "used" by the API.
1920
b = cson_buffer_empty;
1921
@endcode
1922
1923
The memory now belongs to the caller and must eventually be
1924
free()d.
1925
*/
1926
struct cson_buffer
1927
{
1928
/**
1929
The number of bytes allocated for this object.
1930
Use cson_buffer_reserve() to change its value.
1931
*/
1932
cson_size_t capacity;
1933
/**
1934
The number of bytes "used" by this object. It is not needed for
1935
all use cases, and management of this value (if needed) is up
1936
to the client. The cson_buffer public API does not use this
1937
member. The intention is that this can be used to track the
1938
length of strings which are allocated via cson_buffer, since
1939
they need an explicit length and/or null terminator.
1940
*/
1941
cson_size_t used;
1942
1943
/**
1944
This is a debugging/metric-counting value
1945
intended to help certain malloc()-conscious
1946
clients tweak their memory reservation sizes.
1947
Each time cson_buffer_reserve() expands the
1948
buffer, it increments this value by 1.
1949
*/
1950
cson_size_t timesExpanded;
1951
1952
/**
1953
The memory allocated for and owned by this buffer.
1954
Use cson_buffer_reserve() to change its size or
1955
free it. To take over ownership, do:
1956
1957
@code
1958
void * myptr = buf.mem;
1959
buf = cson_buffer_empty;
1960
@endcode
1961
1962
(You might also need to store buf.used and buf.capacity,
1963
depending on what you want to do with the memory.)
1964
1965
When doing so, the memory must eventually be passed to free()
1966
to deallocate it.
1967
*/
1968
unsigned char * mem;
1969
};
1970
/** Convenience typedef. */
1971
typedef struct cson_buffer cson_buffer;
1972
1973
/** An empty-initialized cson_buffer object. */
1974
#define cson_buffer_empty_m {0/*capacity*/,0/*used*/,0/*timesExpanded*/,NULL/*mem*/}
1975
/** An empty-initialized cson_buffer object. */
1976
extern const cson_buffer cson_buffer_empty;
1977
1978
/**
1979
Uses cson_output() to append all JSON output to the given buffer
1980
object. The semantics for the (v, opt) parameters, and the return
1981
value, are as documented for cson_output(). buf must be a non-NULL
1982
pointer to a properly initialized buffer (see example below).
1983
1984
Ownership of buf is not changed by calling this.
1985
1986
On success 0 is returned and the contents of buf.mem are guaranteed
1987
to be NULL-terminated. On error the buffer might contain partial
1988
contents, and it should not be used except to free its contents.
1989
1990
On error non-zero is returned. Errors include:
1991
1992
- Invalid arguments: CSON_RC_ArgError
1993
1994
- Buffer cannot be expanded (runs out of memory): CSON_RC_AllocError
1995
1996
Example usage:
1997
1998
@code
1999
cson_buffer buf = cson_buffer_empty;
2000
// optional: cson_buffer_reserve(&buf, 1024 * 10);
2001
int rc = cson_output_buffer( myValue, &buf, NULL );
2002
if( 0 != rc ) {
2003
... error! ...
2004
}
2005
else {
2006
... use buffer ...
2007
puts((char const*)buf.mem);
2008
}
2009
// In both cases, we eventually need to clean up the buffer:
2010
cson_buffer_reserve( &buf, 0 );
2011
// Or take over ownership of its memory:
2012
{
2013
char * mem = (char *)buf.mem;
2014
buf = cson_buffer_empty;
2015
...
2016
free(mem);
2017
}
2018
@endcode
2019
2020
@see cson_output()
2021
2022
*/
2023
int cson_output_buffer( cson_value const * v, cson_buffer * buf,
2024
cson_output_opt const * opt );
2025
2026
/**
2027
This works identically to cson_parse_string(), but takes a
2028
cson_buffer object as its input. buf->used bytes of buf->mem are
2029
assumed to be valid JSON input, but it need not be NUL-terminated
2030
(we only read up to buf->used bytes). The value of buf->used is
2031
assumed to be the "string length" of buf->mem, i.e. not including
2032
the NUL terminator.
2033
2034
Returns 0 on success, non-0 on error.
2035
2036
See cson_parse() for the semantics of the tgt, opt, and err
2037
parameters.
2038
*/
2039
int cson_parse_buffer( cson_value ** tgt, cson_buffer const * buf,
2040
cson_parse_opt const * opt, cson_parse_info * err );
2041
2042
2043
/**
2044
Reserves the given amount of memory for the given buffer object.
2045
2046
If n is 0 then buf->mem is freed and its state is set to
2047
NULL/0 values.
2048
2049
If buf->capacity is less than or equal to n then 0 is returned and
2050
buf is not modified.
2051
2052
If n is larger than buf->capacity then buf->mem is (re)allocated
2053
and buf->capacity contains the new length. Newly-allocated bytes
2054
are filled with zeroes.
2055
2056
On success 0 is returned. On error non-0 is returned and buf is not
2057
modified.
2058
2059
buf->mem is owned by buf and must eventually be freed by passing an
2060
n value of 0 to this function.
2061
2062
buf->used is never modified by this function unless n is 0, in which case
2063
it is reset.
2064
*/
2065
int cson_buffer_reserve( cson_buffer * buf, cson_size_t n );
2066
2067
/**
2068
Fills all bytes of the given buffer with the given character.
2069
Returns the number of bytes set (buf->capacity), or 0 if
2070
!buf or buf has no memory allocated to it.
2071
*/
2072
cson_size_t cson_buffer_fill( cson_buffer * buf, char c );
2073
2074
/**
2075
Uses a cson_data_source_f() function to buffer input into a
2076
cson_buffer.
2077
2078
dest must be a non-NULL, initialized (though possibly empty)
2079
cson_buffer object. Its contents, if any, will be overwritten by
2080
this function, and any memory it holds might be re-used.
2081
2082
The src function is called, and passed the state parameter, to
2083
fetch the input. If it returns non-0, this function returns that
2084
error code. src() is called, possibly repeatedly, until it reports
2085
that there is no more data.
2086
2087
Whether or not this function succeeds, dest still owns any memory
2088
pointed to by dest->mem, and the client must eventually free it by
2089
calling cson_buffer_reserve(dest,0).
2090
2091
dest->mem might (and possibly will) be (re)allocated by this
2092
function, so any pointers to it held from before this call might be
2093
invalidated by this call.
2094
2095
On error non-0 is returned and dest has almost certainly been
2096
modified but its state must be considered incomplete.
2097
2098
Errors include:
2099
2100
- dest or src are NULL (CSON_RC_ArgError)
2101
2102
- Allocation error (CSON_RC_AllocError)
2103
2104
- src() returns an error code
2105
2106
Whether or not the state parameter may be NULL depends on
2107
the src implementation requirements.
2108
2109
On success dest will contain the contents read from the input
2110
source. dest->used will be the length of the read-in data, and
2111
dest->mem will point to the memory. dest->mem is automatically
2112
NUL-terminated if this function succeeds, but dest->used does not
2113
count that terminator. On error the state of dest->mem must be
2114
considered incomplete, and is not guaranteed to be NUL-terminated.
2115
2116
Example usage:
2117
2118
@code
2119
cson_buffer buf = cson_buffer_empty;
2120
int rc = cson_buffer_fill_from( &buf,
2121
cson_data_source_FILE,
2122
stdin );
2123
if( rc )
2124
{
2125
fprintf(stderr,"Error %d (%s) while filling buffer.\n",
2126
rc, cson_rc_string(rc));
2127
cson_buffer_reserve( &buf, 0 );
2128
return ...;
2129
}
2130
... use the buf->mem ...
2131
... clean up the buffer ...
2132
cson_buffer_reserve( &buf, 0 );
2133
@endcode
2134
2135
To take over ownership of the buffer's memory, do:
2136
2137
@code
2138
void * mem = buf.mem;
2139
buf = cson_buffer_empty;
2140
@endcode
2141
2142
In which case the memory must eventually be passed to free() to
2143
free it.
2144
*/
2145
int cson_buffer_fill_from( cson_buffer * dest, cson_data_source_f src, void * state );
2146
2147
2148
/**
2149
Increments the reference count for the given value. This is a
2150
low-level operation and should not normally be used by client code
2151
without understanding exactly what side-effects it introduces.
2152
Mis-use can lead to premature destruction or cause a value instance
2153
to never be properly destructed (i.e. a memory leak).
2154
2155
This function is probably only useful for the following cases:
2156
2157
- You want to hold a reference to a value which is itself contained
2158
in one or more containers, and you need to be sure that your
2159
reference outlives the container(s) and/or that you can free your
2160
copy of the reference without invaliding any references to the same
2161
value held in containers.
2162
2163
- You want to implement "value sharing" behaviour without using an
2164
object or array to contain the shared value. This can be used to
2165
ensure the lifetime of the shared value instance. Each sharing
2166
point adds a reference and simply passed the value to
2167
cson_value_free() when they're done. The object will be kept alive
2168
for other sharing points which added a reference.
2169
2170
Normally any such value handles would be invalidated when the
2171
parent container(s) is/are cleaned up, but this function can be
2172
used to effectively delay the cleanup.
2173
2174
This function, at its lowest level, increments the value's
2175
reference count by 1.
2176
2177
To decrement the reference count, pass the value to
2178
cson_value_free(), after which the value must be considered, from
2179
the perspective of that client code, to be destroyed (though it
2180
will not be if there are still other live references to
2181
it). cson_value_free() will not _actually_ destroy the value until
2182
its reference count drops to 0.
2183
2184
Returns 0 on success. The only error conditions are if v is NULL
2185
(CSON_RC_ArgError) or if the reference increment would overflow
2186
(CSON_RC_RangeError). In theory a client would get allocation
2187
errors long before the reference count could overflow (assuming
2188
those reference counts come from container insertions, as opposed
2189
to via this function).
2190
2191
Insider notes which clients really need to know:
2192
2193
For shared/constant value instances, such as those returned by
2194
cson_value_true() and cson_value_null(), this function has no side
2195
effects - it does not actually modify the reference count because
2196
(A) those instances are shared across all client code and (B) those
2197
objects are static and never get cleaned up. However, that is an
2198
implementation detail which client code should not rely on. In
2199
other words, if you call cson_value_add_reference() 3 times using
2200
the value returned by cson_value_true() (which is incidentally a
2201
shared cson_value instance), you must eventually call
2202
cson_value_free() 3 times to (semantically) remove those
2203
references. However, internally the reference count for that
2204
specific cson_value instance will not be modified and those
2205
objects will never be freed (they're stack-allocated).
2206
2207
It might be interesting to note that newly-created objects
2208
have a reference count of 0 instead of 1. This is partly because
2209
if the initial reference is counted then it makes ownership
2210
problematic when inserting values into containers. e.g. consider the
2211
following code:
2212
2213
@code
2214
// ACHTUNG: this code is hypothetical and does not reflect
2215
// what actually happens!
2216
cson_value * v =
2217
cson_value_new_integer( 42 ); // v's refcount = 1
2218
cson_array_append( myArray, v ); // v's refcount = 2
2219
@endcode
2220
2221
If that were the case, the client would be forced to free his own
2222
reference after inserting it into the container (which is a bit
2223
counter-intuitive as well as intrusive). It would look a bit like
2224
the following and would have to be done after every create/insert
2225
operation:
2226
2227
@code
2228
// ACHTUNG: this code is hypothetical and does not reflect
2229
// what actually happens!
2230
cson_array_append( myArray, v ); // v's refcount = 2
2231
cson_value_free( v ); // v's refcount = 1
2232
@endcode
2233
2234
(As i said: it's counter-intuitive and intrusive.)
2235
2236
Instead, values start with a refcount of 0 and it is only increased
2237
when the value is added to an object/array container or when this
2238
function is used to manually increment it. cson_value_free() treats
2239
a refcount of 0 or 1 equivalently, destroying the value
2240
instance. The only semantic difference between 0 and 1, for
2241
purposes of cleaning up, is that a value with a non-0 refcount has
2242
been had its refcount adjusted, whereas a 0 refcount indicates a
2243
fresh, "unowned" reference.
2244
*/
2245
int cson_value_add_reference( cson_value * v );
2246
2247
#if 0
2248
/**
2249
DO NOT use this unless you know EXACTLY what you're doing.
2250
It is only in the public API to work around a couple corner
2251
cases involving extracting child elements and discarding
2252
their parents.
2253
2254
This function sets v's reference count to the given value.
2255
It does not clean up the object if rc is 0.
2256
2257
Returns 0 on success, non-0 on error.
2258
*/
2259
int cson_value_refcount_set( cson_value * v, unsigned short rc );
2260
#endif
2261
2262
/**
2263
Deeply copies a JSON value, be it an object/array or a "plain"
2264
value (e.g. number/string/boolean). If cv is not NULL then this
2265
function makes a deep clone of it and returns that clone. Ownership
2266
of the clone is identical t transfered to the caller, who must
2267
eventually free the value using cson_value_free() or add it to a
2268
container object/array to transfer ownership to the container. The
2269
returned object will be of the same logical type as orig.
2270
2271
ACHTUNG: if orig contains any cyclic references at any depth level
2272
this function will endlessly recurse. (Having _any_ cyclic
2273
references violates this library's requirements.)
2274
2275
Returns NULL if orig is NULL or if cloning fails. Assuming that
2276
orig is in a valid state, the only "likely" error case is that an
2277
allocation fails while constructing the clone. In other words, if
2278
cloning fails due to something other than an allocation error then
2279
either orig is in an invalid state or there is a bug.
2280
2281
When this function clones Objects or Arrays it shares any immutable
2282
values (including object keys) between the parent and the
2283
clone. Mutable values (Objects and Arrays) are copied, however.
2284
For example, if we clone:
2285
2286
@code
2287
{ a: 1, b: 2, c:["hi"] }
2288
@endcode
2289
2290
The cloned object and the array "c" would be a new Object/Array
2291
instances but the object keys (a,b,b) and the values of (a,b), as
2292
well as the string value within the "c" array, would be shared
2293
between the original and the clone. The "c" array itself would be
2294
deeply cloned, such that future changes to the clone are not
2295
visible to the parent, and vice versa, but immutable values within
2296
the array are shared (in this case the string "hi"). The
2297
justification for this heuristic is that immutable values can never
2298
be changed, so there is no harm in sharing them across
2299
clones. Additionally, such types can never contribute to cycles in
2300
a JSON tree, so they are safe to share this way. Objects and
2301
Arrays, on the other hand, can be modified later and can contribute
2302
to cycles, and thus the clone needs to be an independent instance.
2303
Note, however, that if this function directly passed a
2304
non-Object/Array, that value is deeply cloned. The sharing
2305
behaviour only applies when traversing Objects/Arrays.
2306
*/
2307
cson_value * cson_value_clone( cson_value const * orig );
2308
2309
/**
2310
Returns the value handle associated with s. The handle itself owns
2311
s, and ownership of the handle is not changed by calling this
2312
function. If the returned handle is part of a container, calling
2313
cson_value_free() on the returned handle invoked undefined
2314
behaviour (quite possibly downstream when the container tries to
2315
use it).
2316
2317
This function only returns NULL if s is NULL. The length of the
2318
returned string is cson_string_length_bytes().
2319
*/
2320
cson_value * cson_string_value(cson_string const * s);
2321
/**
2322
The Object form of cson_string_value(). See that function
2323
for full details.
2324
*/
2325
cson_value * cson_object_value(cson_object const * s);
2326
2327
/**
2328
The Array form of cson_string_value(). See that function
2329
for full details.
2330
*/
2331
cson_value * cson_array_value(cson_array const * s);
2332
2333
2334
/**
2335
Calculates the approximate in-memory-allocated size of v,
2336
recursively if it is a container type, with the following caveats
2337
and limitations:
2338
2339
If a given value is reference counted and encountered multiple
2340
times within a traversed container, each reference is counted at
2341
full cost. We have no way of knowing if a given reference has been
2342
visited already and whether it should or should not be counted, so
2343
we pessimistically count them even though the _might_ not really
2344
count for the given object tree (it depends on where the other open
2345
references live).
2346
2347
This function returns 0 if any of the following are true:
2348
2349
- v is NULL
2350
2351
- v is one of the special singleton values (null, bools, empty
2352
string, int 0, double 0.0)
2353
2354
All other values require an allocation, and this will return their
2355
total memory cost, including the cson-specific internals and the
2356
native value(s).
2357
2358
Note that because arrays and objects might have more internal slots
2359
allocated than used, the alloced size of a container does not
2360
necessarily increase when a new item is inserted into it. An interesting
2361
side-effect of this is that when cson_clone()ing an array or object, the
2362
size of the clone can actually be less than the original.
2363
*/
2364
unsigned int cson_value_msize(cson_value const * v);
2365
2366
/**
2367
Parses command-line-style arguments into a JSON object.
2368
2369
It expects arguments to be in any of these forms, and any number
2370
of leading dashes are treated identically:
2371
2372
--key : Treats key as a boolean with a true value.
2373
2374
--key=VAL : Treats VAL as either a double, integer, or string.
2375
2376
--key= : Treats key as a JSON null (not literal NULL) value.
2377
2378
Arguments not starting with a dash are skipped.
2379
2380
Each key/value pair is inserted into an object. If a given key
2381
appears more than once then only the final entry is actually
2382
stored.
2383
2384
argc and argv are expected to be values from main() (or similar,
2385
possibly adjusted to remove argv[0]).
2386
2387
tgt must be either a pointer to NULL or a pointer to a
2388
client-provided Object. If (NULL==*tgt) then this function
2389
allocates a new object and on success it stores the new object in
2390
*tgt (it is owned by the caller). If (NULL!=*tgt) then it is
2391
assumed to be a properly allocated object. DO NOT pass a pointer to
2392
an unitialized pointer, as that will fool this function into
2393
thinking it is a valid object and Undefined Behaviour will ensue.
2394
2395
If count is not NULL then the number of arugments parsed by this
2396
function are assigned to it. On error, count will be the number of
2397
options successfully parsed before the error was encountered.
2398
2399
On success:
2400
2401
- 0 is returned.
2402
2403
- If (*tgt==NULL) then *tgt is assigned to a newly-allocated
2404
object, owned by the caller. Note that even if no arguments are
2405
parsed, the object is still created.
2406
2407
On error:
2408
2409
- non-0 is returned
2410
2411
- If (*tgt==NULL) then it is not modified.
2412
2413
- If (*tgt!=NULL) (i.e., the caller provides his own object) then
2414
it might contain partial results.
2415
*/
2416
int cson_parse_argv_flags( int argc, char const * const * argv,
2417
cson_object ** tgt, unsigned int * count );
2418
2419
/**
2420
Return values for the cson_pack() and cson_unpack() interfaces.
2421
*/
2422
enum cson_pack_retval {
2423
/** Signals an out-of-memory error. */
2424
CSON_PACK_ALLOC_ERROR = -1,
2425
/** Signals a syntax error in the format string. */
2426
CSON_PACK_ARG_ERROR = -2,
2427
/**
2428
Signals an that an internal error has occurred.
2429
This indicates a bug in this library.
2430
*/
2431
CSON_PACK_INTERNAL_ERROR = -3,
2432
/**
2433
Signals that the JSON document does not validate agains the format
2434
string passed to cson_unpack().
2435
*/
2436
CSON_PACK_VALIDATION_ERROR = -4
2437
};
2438
2439
/**
2440
Construct arbitrarily complex JSON documents from native C types.
2441
2442
Create a new object or array and add or merge the passed values and
2443
properties to it according to the supplied format string.
2444
2445
fmt is a format string, it must at least contain an array or object
2446
specifier as its root value. Format specifiers start with a percent sign '\%'
2447
followed by one or more modifiers and a type character. Object properties
2448
are specified as key-value pairs where the key is specified as a string and
2449
passed as an argument of const char *. Any space, tab, carriage return, line
2450
feed, colon and comma characters between format specifiers are ignored.
2451
2452
| Type | Description |
2453
| :--: | :---------- |
2454
| s | creates either a property name or a string value, in case of the former the corresponding argument is a pointer to const char which is a sequence of bytes specifying the name of the property that is to be created, in case of the latter the corresponding argument is a pointer to const char |
2455
| d | creates an integer value, the corresponding argument is an int |
2456
| i | ^ |
2457
| f | creates a floating point value, the corresponding argument is a double |
2458
| b | creates a boolean value, the corresponding argument is an int |
2459
| N | creates a null value |
2460
| [...] | creates an array, the corresponding argument is a pointer to a cson_array |
2461
| {...} | creates an array, the corresponding argument is a pointer to a cson_object |
2462
2463
| Modifier | Description |
2464
| :------: | :---------- |
2465
| l | specifies that the following d or i specifier applies to an argument which is a pointer to long |
2466
| ll | specifies that the following d or i specifier applies to an argument which is a pointer to cson_int_t |
2467
2468
| Short Form | Expands to
2469
| :--------: | :--------- |
2470
| {...} | %*{...} |
2471
| [...] | %*[...] |
2472
| \%D | \%lld |
2473
2474
2475
Returns 0 on success. The error conditions are:
2476
2477
- CSON_PACK_ARG_ERROR: fmt contains a syntax error
2478
2479
- CSON_PACK_ALLOC_ERROR: a memory allocation failed
2480
2481
- CSON_PACK_INTERNAL_ERROR: an internal error has occurred, this is a bug in
2482
cson
2483
2484
Example:
2485
@code
2486
cson_value * root_value;
2487
cson_array * arr;
2488
...
2489
rc = cson_pack( root_value, "{%s: %d, %s: %[]}", "foo", 42, "bar", arr );
2490
if( 0 != rc ) {
2491
... error ...
2492
}
2493
@endcode
2494
*/
2495
int cson_pack( cson_value **root_valuep, const char *fmt, ... );
2496
2497
/**
2498
Same as cson_pack() except that it takes a va_list instead of a variable
2499
number of arguments.
2500
*/
2501
int cson_vpack( cson_value **root_valuep, const char *fmt, va_list args );
2502
2503
/**
2504
Iterate over the given object or array and convert an arbitrary number of
2505
JSON values into their native C types or validates them according to the
2506
given format string fmt.
2507
2508
fmt is a format string, it must at least contain an array or object
2509
specifier as its root value. Format specifiers start with a percent sign '\%'
2510
followed by one or more modifiers and a type character. Object properties
2511
are specified as key-value pairs where the key is specified as a string and
2512
passed as an argument of const char *. Any space, tab, carriage return, line
2513
feed, colon and comma characters between format specifiers are ignored.
2514
2515
| Type | Description |
2516
| :--: | :---------- |
2517
| s | matches a either a property name or a string value, in case of the former the corresponding argument is a pointer to const char which is a sequence of bytes specifying the name of the property that is to be matched, in case of the latter the corresponding argument is a pointer to a pointer to const char unless the 'm' modifier is specified where the the corresponding argument is a pointer to a pointer to char |
2518
| d | matches an integer value and must be used in with the "ll" modifier, the corresponding argument is a pointer to cson_int_t |
2519
| i | ^ |
2520
| f | matches a floating point value, the corresponding argument is a pointer to double |
2521
| b | matches a boolean value, the corresponding argument is a pointer to int |
2522
| N | matches a null value |
2523
| [...] | matches an array, the corresponding argument is a pointer to a pointer to a cson_array |
2524
| {...} | matches an array, the corresponding argument is a pointer to a pointer to a cson_object |
2525
2526
| Modifier | Description |
2527
| :------: | :---------- |
2528
| ? | specifies that the property reffered to by the given property name is optional |
2529
| * | suppresses assignment, only check for the presence and type of the specified value |
2530
| m | allocates a memory buffer for the extracted string |
2531
| ll | specifies that the following d or i specifier applies to an argument which is a pointer to cson_int_t |
2532
2533
| Short Form | Expands to
2534
| :--------: | :--------- |
2535
| {...} | %*{...} |
2536
| [...] | %*[...] |
2537
| \%D | \%lld |
2538
2539
Returns 0 on success. The error conditions are:
2540
2541
- CSON_PACK_ARG_ERROR: fmt contains a syntax error
2542
2543
- CSON_PACK_ALLOC_ERROR: a memory allocation failed
2544
2545
- CSON_PACK_VALIDATION_ERROR: validation failed, the JSON document structure
2546
differs from that described by the format string
2547
2548
- CSON_PACK_INTERNAL_ERROR: an internal error has occurred, this
2549
indicates a bug in this library.
2550
2551
Example:
2552
@code
2553
cson_value * root_value;
2554
cson_int_t x = 0;
2555
cson_array * arr = NULL;
2556
const char *str = NULL;
2557
...
2558
rc = cson_unpack( root_value, "{%s: %d, %s: %[], %?s: %s}", "foo", &x, "bar", &arr, "baz", &str );
2559
if( rc < 3 && rc >= 0 ) {
2560
... optional property is missing ...
2561
} else if ( CSON_PACK_ALLOC_ERROR == rc ) {
2562
... out of memory error ...
2563
} else if ( CSON_PACK_VALIDATION_ERROR == rc ) {
2564
... unexpected JSON document structure ...
2565
} else if ( rc ) {
2566
... internal error ...
2567
}
2568
@endcode
2569
2570
*/
2571
int cson_unpack( cson_value *root_value, const char *fmt, ... );
2572
2573
/**
2574
Same as cson_unpack() except that it takes a va_list instead of a variable
2575
number of arguments.
2576
*/
2577
int cson_vunpack( cson_value *root_value, const char *fmt, va_list args );
2578
2579
/* LICENSE
2580
2581
This software's source code, including accompanying documentation and
2582
demonstration applications, are licensed under the following
2583
conditions...
2584
2585
Certain files are imported from external projects and have their own
2586
licensing terms. Namely, the JSON_parser.* files. See their files for
2587
their official licenses, but the summary is "do what you want [with
2588
them] but leave the license text and copyright in place."
2589
2590
The author (Stephan G. Beal [http://wanderinghorse.net/home/stephan/])
2591
explicitly disclaims copyright in all jurisdictions which recognize
2592
such a disclaimer. In such jurisdictions, this software is released
2593
into the Public Domain.
2594
2595
In jurisdictions which do not recognize Public Domain property
2596
(e.g. Germany as of 2011), this software is Copyright (c) 2011 by
2597
Stephan G. Beal, and is released under the terms of the MIT License
2598
(see below).
2599
2600
In jurisdictions which recognize Public Domain property, the user of
2601
this software may choose to accept it either as 1) Public Domain, 2)
2602
under the conditions of the MIT License (see below), or 3) under the
2603
terms of dual Public Domain/MIT License conditions described here, as
2604
they choose.
2605
2606
The MIT License is about as close to Public Domain as a license can
2607
get, and is described in clear, concise terms at:
2608
2609
http://en.wikipedia.org/wiki/MIT_License
2610
2611
The full text of the MIT License follows:
2612
2613
--
2614
Copyright (c) 2011 Stephan G. Beal (http://wanderinghorse.net/home/stephan/)
2615
2616
Permission is hereby granted, free of charge, to any person
2617
obtaining a copy of this software and associated documentation
2618
files (the "Software"), to deal in the Software without
2619
restriction, including without limitation the rights to use,
2620
copy, modify, merge, publish, distribute, sublicense, and/or sell
2621
copies of the Software, and to permit persons to whom the
2622
Software is furnished to do so, subject to the following
2623
conditions:
2624
2625
The above copyright notice and this permission notice shall be
2626
included in all copies or substantial portions of the Software.
2627
2628
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
2629
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
2630
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
2631
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
2632
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
2633
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
2634
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
2635
OTHER DEALINGS IN THE SOFTWARE.
2636
2637
--END OF MIT LICENSE--
2638
2639
For purposes of the above license, the term "Software" includes
2640
documentation and demonstration source code which accompanies
2641
this software. ("Accompanies" = is contained in the Software's
2642
primary public source code repository.)
2643
2644
*/
2645
2646
#if defined(__cplusplus)
2647
} /*extern "C"*/
2648
#endif
2649
2650
#endif /* WANDERINGHORSE_NET_CSON_H_INCLUDED */
2651
/* end file include/wh/cson/cson.h */
2652
/* begin file include/wh/cson/cson_sqlite3.h */
2653
/** @file cson_sqlite3.h
2654
2655
This file contains cson's public sqlite3-to-JSON API declarations
2656
and API documentation. If CSON_ENABLE_SQLITE3 is not defined,
2657
or is defined to 0, then including this file will have no side-effects
2658
other than defining CSON_ENABLE_SQLITE3 (if it was not defined) to 0
2659
and defining a few include guard macros. i.e. if CSON_ENABLE_SQLITE3
2660
is not set to a true value then the API is not visible.
2661
2662
This API requires that <sqlite3.h> be in the INCLUDES path and that
2663
the client eventually link to (or directly embed) the sqlite3 library.
2664
*/
2665
#if !defined(WANDERINGHORSE_NET_CSON_SQLITE3_H_INCLUDED)
2666
#define WANDERINGHORSE_NET_CSON_SQLITE3_H_INCLUDED 1
2667
#if !defined(CSON_ENABLE_SQLITE3)
2668
# if defined(DOXYGEN)
2669
#define CSON_ENABLE_SQLITE3 1
2670
# else
2671
#define CSON_ENABLE_SQLITE3 1
2672
# endif
2673
#endif
2674
2675
#if CSON_ENABLE_SQLITE3 /* we do this here for the sake of the amalgamation build */
2676
#include "sqlite3.h"
2677
2678
#if defined(__cplusplus)
2679
extern "C" {
2680
#endif
2681
2682
/**
2683
Converts a single value from a single 0-based column index to its JSON
2684
equivalent.
2685
2686
On success it returns a new JSON value, which will have a different concrete
2687
type depending on the field type reported by sqlite3_column_type(st,col):
2688
2689
Integer, double, null, or string (TEXT and BLOB data, though not
2690
all blob data is legal for a JSON string).
2691
2692
st must be a sqlite3_step()'d row and col must be a 0-based column
2693
index within that result row.
2694
*/
2695
cson_value * cson_sqlite3_column_to_value( sqlite3_stmt * st, int col );
2696
2697
/**
2698
Creates a JSON Array object containing the names of all columns
2699
of the given prepared statement handle.
2700
2701
Returns a new array value on success, which the caller owns. Its elements
2702
are in the same order as in the underlying query.
2703
2704
On error NULL is returned.
2705
2706
st is not traversed or freed by this function - only the column
2707
count and names are read.
2708
*/
2709
cson_value * cson_sqlite3_column_names( sqlite3_stmt * st );
2710
2711
/**
2712
Creates a JSON Object containing key/value pairs corresponding
2713
to the result columns in the current row of the given statement
2714
handle. st must be a sqlite3_step()'d row result.
2715
2716
On success a new Object is returned which is owned by the
2717
caller. On error NULL is returned.
2718
2719
cson_sqlite3_column_to_value() is used to convert each column to a
2720
JSON value, and the column names are taken from
2721
sqlite3_column_name().
2722
*/
2723
cson_value * cson_sqlite3_row_to_object( sqlite3_stmt * st );
2724
/**
2725
Functionally almost identical to cson_sqlite3_row_to_object(), the
2726
only difference being how the result objects gets its column names.
2727
st must be a freshly-step()'d handle holding a result row.
2728
colNames must be an Array with at least the same number of columns
2729
as st. If it has fewer, NULL is returned and this function has
2730
no side-effects.
2731
2732
For each column in the result set, the colNames entry at the same
2733
index is used for the column key. If a given entry is-not-a String
2734
then conversion will fail and NULL will be returned.
2735
2736
The one reason to prefer this over cson_sqlite3_row_to_object() is
2737
that this one can share the keys across multiple rows (or even
2738
other JSON containers), whereas the former makes fresh copies of
2739
the column names for each row.
2740
2741
*/
2742
cson_value * cson_sqlite3_row_to_object2( sqlite3_stmt * st,
2743
cson_array * colNames );
2744
2745
/**
2746
Similar to cson_sqlite3_row_to_object(), but creates an Array
2747
value which contains the JSON-form values of the given result
2748
set row.
2749
*/
2750
cson_value * cson_sqlite3_row_to_array( sqlite3_stmt * st );
2751
/**
2752
Converts the results of an sqlite3 SELECT statement to JSON,
2753
in the form of a cson_value object tree.
2754
2755
st must be a prepared, but not yet traversed, SELECT query.
2756
tgt must be a pointer to NULL (see the example below). If
2757
either of those arguments are NULL, cson_rc.ArgError is returned.
2758
2759
This walks the query results and returns a JSON object which
2760
has a different structure depending on the value of the 'fat'
2761
argument.
2762
2763
2764
If 'fat' is 0 then the structure is:
2765
2766
@code
2767
{
2768
"columns":["colName1",..."colNameN"],
2769
"rows":[
2770
[colVal0, ... colValN],
2771
[colVal0, ... colValN],
2772
...
2773
]
2774
}
2775
@endcode
2776
2777
In the "non-fat" format the order of the columns and row values is
2778
guaranteed to be the same as that of the underlying query.
2779
2780
If 'fat' is not 0 then the structure is:
2781
2782
@code
2783
{
2784
"columns":["colName1",..."colNameN"],
2785
"rows":[
2786
{"colName1":value1,..."colNameN":valueN},
2787
{"colName1":value1,..."colNameN":valueN},
2788
...
2789
]
2790
}
2791
@endcode
2792
2793
In the "fat" format, the order of the "columns" entries is guaranteed
2794
to be the same as the underlying query fields, but the order
2795
of the keys in the "rows" might be different and might in fact
2796
change when passed through different JSON implementations,
2797
depending on how they implement object key/value pairs.
2798
2799
On success it returns 0 and assigns *tgt to a newly-allocated
2800
JSON object tree (using the above structure), which the caller owns.
2801
If the query returns no rows, the "rows" value will be an empty
2802
array, as opposed to null.
2803
2804
On error non-0 is returned and *tgt is not modified.
2805
2806
The error code cson_rc.IOError is used to indicate a db-level
2807
error, and cson_rc.TypeError is returned if sqlite3_column_count(st)
2808
returns 0 or less (indicating an invalid or non-SELECT statement).
2809
2810
The JSON data types are determined by the column type as reported
2811
by sqlite3_column_type():
2812
2813
SQLITE_INTEGER: integer
2814
2815
SQLITE_FLOAT: double
2816
2817
SQLITE_TEXT or SQLITE_BLOB: string, and this will only work if
2818
the data is UTF8 compatible.
2819
2820
If the db returns a literal or SQL NULL for a value it is converted
2821
to a JSON null. If it somehow finds a column type it cannot handle,
2822
the value is also converted to a NULL in the output.
2823
2824
Example
2825
2826
@code
2827
cson_value * json = NULL;
2828
int rc = cson_sqlite3_stmt_to_json( myStatement, &json, 1 );
2829
if( 0 != rc ) { ... error ... }
2830
else {
2831
cson_output_FILE( json, stdout, NULL );
2832
cson_value_free( json );
2833
}
2834
@endcode
2835
*/
2836
int cson_sqlite3_stmt_to_json( sqlite3_stmt * st, cson_value ** tgt, char fat );
2837
2838
/**
2839
A convenience wrapper around cson_sqlite3_stmt_to_json(), which
2840
takes SQL instead of a sqlite3_stmt object. It has the same
2841
return value and argument semantics as that function.
2842
*/
2843
int cson_sqlite3_sql_to_json( sqlite3 * db, cson_value ** tgt, char const * sql, char fat );
2844
2845
/**
2846
Binds a JSON value to a 1-based parameter index in a prepared SQL
2847
statement. v must be NULL or one of one of the types (null, string,
2848
integer, double, boolean, array). Booleans are bound as integer 0
2849
or 1. NULL or null are bound as SQL NULL. Integers are bound as
2850
64-bit ints. Strings are bound using sqlite3_bind_text() (as
2851
opposed to text16), but we could/should arguably bind them as
2852
blobs.
2853
2854
If v is an Array then ndx is is used as a starting position
2855
(1-based) and each item in the array is bound to the next parameter
2856
position (starting and ndx, though the array uses 0-based offsets).
2857
2858
TODO: add Object support for named parameters.
2859
2860
Returns 0 on success, non-0 on error.
2861
*/
2862
int cson_sqlite3_bind_value( sqlite3_stmt * st, int ndx, cson_value const * v );
2863
2864
#if defined(__cplusplus)
2865
} /*extern "C"*/
2866
#endif
2867
2868
#endif /* CSON_ENABLE_SQLITE3 */
2869
#endif /* WANDERINGHORSE_NET_CSON_SQLITE3_H_INCLUDED */
2870
/* end file include/wh/cson/cson_sqlite3.h */
2871
#endif /* FOSSIL_ENABLE_JSON */
2872

Keyboard Shortcuts

Open search /
Next entry (timeline) j
Previous entry (timeline) k
Open focused entry Enter
Show this help ?
Toggle theme Top nav button