summaryrefslogtreecommitdiff
path: root/json.c
blob: ade21362b92de22f27ddde7a6e3d6b4fcf2095c8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
/*-------------------------------------------------------------------------
 *
 * json.c
 *	  Core JSON manipulation routines used by JSON data type support.
 *
 * Copyright (c) 2010, PostgreSQL Global Development Group
 * Written by Joey Adams <[email protected]>.
 *
 *-------------------------------------------------------------------------
 */

#include "json.h"
#include "util.h"

#include <ctype.h>

#include "mb/pg_wchar.h"

#define is_internal(node) ((node)->type == JSON_ARRAY || (node)->type == JSON_OBJECT)

/* We can't use isspace() because it also accepts \v and \f, which
   aren't legal whitespace characters in strict JSON. */
#define is_whitespace(c) ((c)==' ' || (c)=='\t' || (c)=='\n' || (c)=='\r')

static void
skip_whitespace(const char **sp)
{
	const char *s = *sp;

	while (is_whitespace(*s))
		s++;
	*sp = s;
}

static char
end_parenthesis(JSON * node)
{
	Assert(node != NULL);

	switch (node->type)
	{
		case JSON_ARRAY:
			return ']';
		case JSON_OBJECT:
			return '}';
		default:
			Assert(false);
			return '\0';
	}
}

/*
 * Reads exactly 4 hex characters (capital or lowercase).
 * Writes the result to *out .
 * Returns true on success, false if any input chars are not [0-9A-Fa-f] .
 */
static bool
read_hex16(const char *in, unsigned int *out)
{
	unsigned int i;
	unsigned int tmp;
	char		c;

	*out = 0;

	for (i = 0; i < 4; i++)
	{
		c = *in++;
		if (c >= '0' && c <= '9')
			tmp = c - '0';
		else if (c >= 'A' && c <= 'F')
			tmp = c - 'A' + 10;
		else if (c >= 'a' && c <= 'f')
			tmp = c - 'a' + 10;
		else
			return false;

		*out <<= 4;
		*out += tmp;
	}

	return true;
}

/*
 * Encodes a 16-bit number into hexadecimal,
 * writing exactly 4 hex chars.
 */
static void
write_hex16(char *out, unsigned int val)
{
	const char *hex = "0123456789ABCDEF";

	*out++ = hex[(val >> 12) & 0xF];
	*out++ = hex[(val >> 8) & 0xF];
	*out++ = hex[(val >> 4) & 0xF];
	*out++ = hex[val & 0xF];
}


/*********** JSON creation, manipulation, and deletion **********/

JSON *
json_mknode(json_type type)
{
	JSON	   *node = palloc(sizeof(*node));

	memset(node, 0, sizeof(*node));
	node->type = type;
	return node;
}

JSON *
json_mkbool(bool v_bool)
{
	JSON	   *node = json_mknode(JSON_BOOL);

	node->v.v_bool = v_bool;
	return node;
}

JSON *
json_mkstring(const char *str, size_t length)
{
	JSON	   *node = json_mknode(JSON_STRING);

	if (str)
	{
		node->v.string.str = pnstrdup(str, length);
		node->v.string.length = length;
	}
	return node;
}

JSON *
json_mknumber(const char *number, size_t length)
{
	JSON	   *node = json_mknode(JSON_NUMBER);

	if (number)
		node->v.number = pnstrdup(number, length);
	return node;
}

/*
 * Indicate that the node's value has changed,
 * marking ancestors as necessary.
 *
 * Call json_touch_value so that json_encode(..., JSONOPT_ORIG)
 * will encode the new value rather than using original text.
 */
void
json_touch_value(JSON * node)
{
	while (node && node->orig.value.start)
	{
		node->orig.value.start = NULL;
		node = node->parent;
	}
}

/*
 * Add child to parent, but don't clear orig pointers of ancestors.
 *
 * This is used by json_decode to ensure that original text segments
 * are preserved while building the JSON tree.
 */
static void
json_append_notouch(JSON * parent, JSON * child)
{
	Assert(parent->type == JSON_ARRAY || parent->type == JSON_OBJECT);
	Assert(child->parent == NULL);

	parent->v.children.count++;
	child->parent = parent;
	child->prev = parent->v.children.tail;
	child->next = NULL;

	if (parent->v.children.tail)
	{
		parent->v.children.tail->next = child;
		parent->v.children.tail = child;
	}
	else
	{
		parent->v.children.head = parent->v.children.tail = child;
	}
}

/*
 * json_append
 *	  Add child to parent, putting it at the end of its child list.
 *
 *	  Child must not already have another parent.
 */
void
json_append(JSON * parent, JSON * child)
{
	json_append_notouch(parent, child);
	json_touch_value(parent);
}

/*
 * json_remove
 *	  Remove node from its parent, but do not delete it.
 */
void
json_remove(JSON * node)
{
	JSON	   *parent = node->parent;

	if (parent == NULL)
		return;
	Assert(parent->type == JSON_ARRAY || parent->type == JSON_OBJECT);
	Assert(parent->v.children.count > 0);

	if (node->prev)
		node->prev->next = node->next;
	else
		parent->v.children.head = node->next;
	if (node->next)
		node->next->prev = node->prev;
	else
		parent->v.children.tail = node->prev;

	parent->v.children.count--;
	node->parent = NULL;
	node->prev = NULL;
	node->next = NULL;

	json_touch_value(parent);
}

/*
 * Update the value of a node, preserving position and key information.
 *
 * Note well: If replacement is an array or object with children, the parent
 *			  pointers of those children will be incorrect
 *			  (they'll still refer to their original parent).
 *
 *			  Untrustworthy parent pointers is the price to pay for
 *			  being able to copy JSON values by reference.
 */
void
json_replace_value(JSON * node, JSON * replacement)
{
	node->type = replacement->type;
	node->v = replacement->v;
	node->orig.value = replacement->orig.value;

	if (node->parent)
		json_touch_value(node->parent);
}

const char *
json_get_string(JSON * node, size_t *length_out)
{
	Assert(node->type == JSON_STRING);
	if (length_out)
		*length_out = node->v.string.length;
	return node->v.string.str;
}

void
json_set_string(JSON * node, const char *str, size_t length)
{
	Assert(node->type == JSON_STRING);
	if (node->v.string.str)
		pfree(node->v.string.str);
	if (str)
	{
		node->v.string.str = pnstrdup(str, length);
		node->v.string.length = length;
	}
	else
	{
		node->v.string.str = NULL;
		node->v.string.length = 0;
	}
	json_touch_value(node);
}

const char *
json_get_number(JSON * node)
{
	Assert(node->type == JSON_NUMBER);
	return node->v.number;
}

void
json_set_number(JSON * node, const char *number, size_t length)
{
	Assert(node->type == JSON_NUMBER);
	if (node->v.number)
		pfree(node->v.number);
	if (number)
		node->v.number = pnstrdup(number, length);
	else
		node->v.number = NULL;
	json_touch_value(node);
}

/* Non-recursively free a node */
static void
free_node(JSON * node)
{
	if (node->type == JSON_STRING)
	{
		if (node->v.string.str)
			pfree(node->v.string.str);
	}
	else if (node->type == JSON_NUMBER)
	{
		if (node->v.number)
			pfree(node->v.number);
	}

	if (node->key)
		pfree(node->key);

	pfree(node);
}

/*
 * Free a JSON node and all its descendants.
 *
 * Do not use this function if you have performed json_replace_value on
 * a descendant, as this function relies on each node's ->parent field
 * being trustworthy.
 */
static void
json_delete(JSON * node)
{
	JSON	   *parent,
			   *next;

	if (node == NULL)
		return;

	/* Remove node from parent (if it has one). */
	json_remove(node);

descend:
	while (is_internal(node) && node->v.children.head)
		node = node->v.children.head;

advance:
	parent = node->parent;
	next = node->next;
	free_node(node);
	node = next;

	if (node != NULL)
	{
		goto descend;
	}
	else
	{
		node = parent;
		if (node != NULL)
			goto advance;
		else
			return;
	}
}


/*********************** Parsing and validation **********************/

static JSON *decode_leaf(const char **sp);
static JSON *decode_number(const char **sp);

/*
 * json_decode_string has a different signature than its friends
 * because it's also used to parse object member keys.
 * It's also useful outside of json.c, such as in jsonpath.c .
 */
char	   *json_decode_string(const char **sp, size_t *length, bool strict);

/*
 * json_validate
 *	  Make sure the given UTF-8 string is valid JSON.
 *
 * TODO: Consider making a dedicated function for this so we don't have to
 *		 convert to UTF-8, build a JSON node, then free both
 *		 whenever we need to validate (such as in json_in and json_recv).
 */
bool
json_validate(const char *str)
{
	JSON	   *node = json_decode(str);

	if (node == NULL)
		return false;
	json_delete(node);
	return true;
}

/*
 * json_validate_server_encoded
 *	  Variant of json_validate that takes a server-encoded string
 *	  rather than a UTF-8 string.
 *
 *	  Note that a dedicated json_validate (described in the TODO above)
 *	  would be able to handle both encodings natively, since both are
 *	  ASCII-compatible.
 */
bool
json_validate_server_encoded(const char *str)
{
	char	   *str_utf8 = server_to_utf8(str, strlen(str));
	bool		result = json_validate(str_utf8);

	if (str_utf8 != str)
		pfree(str_utf8);

	return result;
}

/*
 * json_decode
 *	  Convert a JSON-encoded string to a JSON node.
 *	  @str must be valid UTF-8.
 */
JSON *
json_decode(const char *str)
{
	JSON	   *root = NULL,
			   *parent = NULL,
			   *node = NULL;
	const char *s = str;
	char	   *key;
	size_t		key_length;
	struct json_orig orig;
	bool		expect_endp;

	if (str == NULL)
		return NULL;

	Assert(utf8_validate(str, strlen(str)));

	expect_endp = false;
	goto item;

item:							/* Expect a value (set expect_endp before goto
								 * item; ) */
	key = NULL;
	key_length = 0;
	memset(&orig, 0, sizeof(orig));

	orig.key_left_space.start = s;
	orig.left_space.start = s;

	skip_whitespace(&s);

	if (expect_endp)
	{
		if (*s == ']' || *s == '}')
			goto endp;
	}

	if (parent != NULL && parent->type == JSON_OBJECT)
	{
		/* Parse member key string. */
		orig.key_left_space.end = s;
		orig.key.start = s;

		key = json_decode_string(&s, &key_length, true);
		if (key == NULL)
			goto failed;

		orig.key.end = s;
		orig.key_right_space.start = s;

		/* Eat the " : " */
		skip_whitespace(&s);
		if (*s != ':')
			goto failed;

		orig.key_right_space.end = s;
		s++;
		orig.left_space.start = s;

		skip_whitespace(&s);
	}

	/*
	 * The way orig.value and company are initialized is a bit funky. If this
	 * node has children, we have to finish parsing the node's children before
	 * we know where it ends.  Hence, initialization of orig.value_end and
	 * after will be deferred if this node has children.
	 */

	orig.left_space.end = s;
	orig.value.start = s;

	node = decode_leaf(&s);
	if (node == NULL)
	{
		if (*s == '[')
			node = json_mknode(JSON_ARRAY);
		else if (*s == '{')
			node = json_mknode(JSON_OBJECT);
		else
			goto failed;
		s++;

		/*
		 * orig.value.end and later are dangling (actually NULL) for now, but
		 * will be initialized when we get to state 'endp' .
		 */
	}
	else
	{
		orig.value.end = s;
		orig.right_space.start = s;

		skip_whitespace(&s);

		orig.right_space.end = s;
	}

	node->key = key;
	node->key_length = key_length;

	/*
	 * The key now belongs to the node.  This prevents a double free on
	 * failure (see the failed: label).
	 */
	key = NULL;

	node->orig = orig;

	if (parent != NULL)
		json_append_notouch(parent, node);
	else
		root = node;

	if (is_internal(node))
	{
		/*
		 * "push" node onto the "stack".  Nodes point up to their parents,
		 * which is why this function doesn't need a "stack" per se.
		 */
		parent = node;

		expect_endp = true;
		goto item;
	}

	if (parent != NULL)
		goto comma_endp;
	else
		goto end;

comma_endp:						/* Expect a comma or end bracket/brace */
	if (*s == ',')
	{
		s++;

		expect_endp = false;
		goto item;
	}
	if (*s == ']' || *s == '}')
		goto endp;

	goto failed;

endp:							/* Handle an end bracket/brace */
	if (*s != end_parenthesis(parent))
		goto failed;
	s++;

	/* "pop" a node from the "stack" */
	node = parent;
	parent = parent->parent;

	/*
	 * The other pointers were set when we started parsing this node in the
	 * 'item' state.
	 */
	node->orig.value.end = s;
	node->orig.right_space.start = s;

	skip_whitespace(&s);

	node->orig.right_space.end = s;

	if (parent != NULL)
		goto comma_endp;
	else
		goto end;

end:							/* Expect end of text */
	if (*s != '\0')
		goto failed;
	return node;

failed:					/* Handle failure */
	if (key != NULL)
		pfree(key);
	json_delete(root);
	return NULL;
}

/*
 * Decode and skip a node that does not have children.
 * Whitespace is not skipped first (it is done in the primary decode loop).
 *
 * Returns NULL if next character is '[', '{', or invalid.
 */
static JSON *
decode_leaf(const char **sp)
{
	char		c = **sp;

	if (c == '"')
	{
		size_t		length;
		char	   *str = json_decode_string(sp, &length, true);

		if (str != NULL)
		{
			JSON	   *node = json_mknode(JSON_STRING);

			node->v.string.str = str;
			node->v.string.length = length;
			return node;
		}

		return NULL;
	}
	if ((c >= '0' && c <= '9') || c == '-')
		return decode_number(sp);
	if (strncmp(*sp, "true", 4) == 0)
	{
		(*sp) += 4;
		return json_mkbool(true);
	}
	if (strncmp(*sp, "false", 5) == 0)
	{
		(*sp) += 5;
		return json_mkbool(false);
	}
	if (strncmp(*sp, "null", 4) == 0)
	{
		(*sp) += 4;
		return json_mknode(JSON_NULL);
	}

	return NULL;
}

/*
 * The JSON spec says that a number shall follow this precise pattern
 * (spaces and quotes added for readability):
 *	 '-'? (0 | [1-9][0-9]*) ('.' [0-9]+)? ([Ee] [+-]? [0-9]+)?
 *
 * However, some JSON parsers are more liberal.  For instance, PHP accepts
 * '.5' and '1.'.  JSON.parse accepts '+3'.
 *
 * This function takes the strict approach.
 */
static bool
validate_number(const char **sp)
{
	const char *s = *sp;

	/* '-'? */
	if (*s == '-')
		s++;

	/* (0 | [1-9][0-9]*) */
	if (*s == '0')
	{
		s++;
	}
	else
	{
		if (!isdigit(*s))
			return false;
		do
			s++;
		while (isdigit(*s));
	}

	/* ('.' [0-9]+)? */
	if (*s == '.')
	{
		s++;
		if (!isdigit(*s))
			return false;
		do
			s++;
		while (isdigit(*s));
	}

	/* ([Ee] [+-]? [0-9]+)? */
	if (*s == 'E' || *s == 'e')
	{
		s++;
		if (*s == '+' || *s == '-')
			s++;
		if (!isdigit(*s))
			return false;
		do
			s++;
		while (isdigit(*s));
	}

	*sp = s;
	return true;
}

static JSON *
decode_number(const char **sp)
{
	const char *start,
			   *end;

	start = *sp;
	if (!validate_number(sp))
		return NULL;
	end = *sp;

	return json_mknumber(start, end - start);
}

/*
 * json_decode_string
 *	  If you're interested in the decoding JSON in general, see json_decode.
 *
 *	  Decodes a JSON string literal (e.g. "\"hello\"").
 *
 *	  If strict is true, string must be double-quoted,
 *	  as is required by the JSON RFC.
 *	  Otherwise (e.g. if parsing something JSON-like, such as JSONPath),
 *	  the string may be single- or double-quoted.
 *
 *	  Also, no whitespace skipping is done, so the caller should only
 *	  call this function when it expects **sp to be either " or '
 *
 *	  On success, returns the decoded string, passes the decoded string's
 *	  length through *length (which must not be NULL), and advances *sp to point
 *	  to the end of string literal (after the closing quote character).
 *
 *	  On failure (parse error), returns NULL and
 *	  leaves *length and *sp untouched.
 */
char *
json_decode_string(const char **sp, size_t *length, bool strict)
{
	const char *s = *sp;
	StringInfoData ret;
	char		buf[4];
	int			len;
	char		quote;

	Assert(length != NULL);

	initStringInfo(&ret);

	quote = *s++;
	if (strict)
	{
		if (quote != '"')
			return NULL;
	}
	else
	{
		if (quote != '"' && quote != '\'')
			return NULL;
	}

	while (*s != '\0' && *s != quote)
	{
		unsigned char c = *s++;
		unsigned int uc;
		unsigned int lc;

		if (c == '\\')
		{
			c = *s++;
			switch (c)
			{
				case '\\':
				case '/':
					break;
				case 'b':
					c = '\b';
					break;
				case 'f':
					c = '\f';
					break;
				case 'n':
					c = '\n';
					break;
				case 'r':
					c = '\r';
					break;
				case 't':
					c = '\t';
					break;
				case 'u':
					if (!read_hex16(s, &uc))
						goto failed;
					s += 4;

					if (uc >= 0xD800 && uc <= 0xDFFF)
					{
						/* Handle UTF-16 surrogate pair. */

						if (uc >= 0xDC00)
							goto failed;		/* Second surrogate not
												 * preceded by first
												 * surrogate. */

						if (s[0] != '\\' || s[1] != 'u'
							|| !read_hex16(s + 2, &lc)
							|| !(lc >= 0xDC00 && lc <= 0xDFFF))
							goto failed;		/* First surrogate not
												 * followed by second
												 * surrogate. */

						s += 6;

						uc = 0x10000 + (((uc & 0x3FF) << 10) | (lc & 0x3FF));
					}

					unicode_to_utf8(uc, (unsigned char *) buf);
					len = pg_utf_mblen((unsigned char *) buf);

					Assert(len > 0);

					appendBinaryStringInfo(&ret, buf, len);

					continue;	/* Continue the enclosing while loop to skip
								 * the str_append below. */
				default:		/* Invalid escape */
					if (c == quote)
						break;
					if (!strict && (c == '"' || c == '\''))
						break;
					goto failed;	/* Invalid escape */
			}
		}
		else if (c <= 0x1F)
		{
			/* Control characters not allowed in string literals. */
			goto failed;
		}
		appendStringInfoChar(&ret, c);
	}

	if (*s++ != quote)
		goto failed;

	*length = ret.len;
	*sp = s;
	return ret.data;

failed:
	pfree(ret.data);
	return NULL;
}

/*
 * json_text_type
 *	  Determines the type of a JSON string without fully decoding it.
 *	  Expects the given string to be valid JSON.
 *	  Might return JSON_INVALID if something is wrong with the input.
 */
json_type
json_text_type(const char *str, size_t nbytes)
{
	const char *s = str;
	const char *e = str + nbytes;
	char		c;

	/* Skip whitespace characters. */
	while (s < e && is_whitespace(*s))
		s++;

	/* Get first non-white character, making sure it's in bounds. */
	if (s >= e)
		return JSON_INVALID;
	c = *s;

	switch (c)
	{
		case 'n':
			return JSON_NULL;
		case '"':
			return JSON_STRING;
		case 't':
		case 'f':
			return JSON_BOOL;
		case '{':
			return JSON_OBJECT;
		case '[':
			return JSON_ARRAY;
		default:
			if (c == '-' || (c >= '0' && c <= '9'))
				return JSON_NUMBER;
			return JSON_INVALID;
	}
}


/****************************** Encoding *****************************/

/*
 * encode_string
 *	  Variant of json_encode_string that writes its output to a StringInfo.
 */
static void
encode_string(StringInfo out, const char *string, size_t length, char quote,
			  bool escape_unicode)
{
	const char *s = string;
	const char *e = s + length;

	Assert(quote != '\\');
	if (escape_unicode)
		Assert(utf8_validate(string, length));

	appendStringInfoChar(out, quote);

	while (s < e)
	{
		unsigned char c = *s++;
		unsigned char endchar;

		switch (c)
		{
			case '\\':
				endchar = '\\';
				break;
			case '\b':
				endchar = 'b';
				break;
			case '\f':
				endchar = 'f';
				break;
			case '\n':
				endchar = 'n';
				break;
			case '\r':
				endchar = 'r';
				break;
			case '\t':
				endchar = 't';
				break;
			default:
				{
					if (c == quote)
					{
						endchar = quote;
						break;
					}
					if (c < 0x1F || (c >= 0x80 && escape_unicode))
					{
						/* Encode using \u.... */
						pg_wchar	uc;
						unsigned int lc;
						char		txt[13];

						s--;
						uc = utf8_decode_char(&s);

						txt[0] = '\\';
						txt[1] = 'u';
						txt[6] = '\\';
						txt[7] = 'u';
						if (uc <= 0xFFFF)
						{
							write_hex16(txt + 2, uc);
							txt[6] = '\0';
						}
						else
						{
							uc -= 0x10000;
							lc = uc & 0x3FF;
							uc = uc >> 10;
							uc |= 0xD800;
							lc |= 0xDC00;
							write_hex16(txt + 2, uc);
							write_hex16(txt + 8, lc);
							txt[12] = '\0';
						}

						appendStringInfoString(out, txt);
						continue;		/* Skip backslash-encoding code below. */
					}
					endchar = '\0';
				}
		}

		appendStringInfoChar(out, endchar ? '\\' : c);
		if (endchar != '\0')
			appendStringInfoChar(out, endchar);
	}

	appendStringInfoChar(out, quote);
}

static bool
encode_number(StringInfo out, const char *string)
{
	const char *s = string;
	const char *start,
			   *end;

	if (string == NULL)
		return false;

	/* Validate number, trimming whitespace. */
	skip_whitespace(&s);
	start = s;
	if (!validate_number(&s))
		return false;
	end = s;
	skip_whitespace(&s);
	if (*s != '\0')
		return false;

	/* Append number to out */
	appendBinaryStringInfo(out, start, end - start);

	return true;
}

typedef struct
{
	StringInfoData str;
	bool		use_orig;
	bool		escape_unicode;
	bool		trim;
}	json_encode_ctx;

static bool json_encode_recurse(JSON * node, json_encode_ctx * ctx);

/*
 * json_encode
 *	  Encode a JSON node.
 *
 *	  The JSONOPT_ESCAPE_UNICODE option may only be used
 *	  if the strings in the JSON tree are UTF-8-encoded.
 */
char *
json_encode(JSON * node, int options)
{
	json_encode_ctx ctx;

	initStringInfo(&ctx.str);
	ctx.use_orig = !!(options & JSONOPT_USE_ORIG);
	ctx.escape_unicode = !!(options & JSONOPT_ESCAPE_UNICODE);
	ctx.trim = !(options & JSONOPT_NO_TRIM);

	if (!json_encode_recurse(node, &ctx))
	{
		pfree(ctx.str.data);
		return NULL;
	}

	return ctx.str.data;
}

static bool
json_encode_recurse(JSON * node, json_encode_ctx * ctx)
{
#define has_orig(field) \
		(use_orig && node->orig.field.start)
#define push_orig(field) \
		appendBinaryStringInfo(&ctx->str, node->orig.field.start, \
							node->orig.field.end - node->orig.field.start)

	bool		use_orig = ctx->use_orig;
	bool		trim = ctx->trim;

	ctx->trim = false;			/* Don't trim internal nodes, just the root
								 * node. */

	if (!trim && has_orig(left_space))
		push_orig(left_space);

	if (has_orig(value))
	{
		push_orig(value);
	}
	else
	{
		const char *txt = NULL;
		JSON	   *child;

		switch (node->type)
		{
			case JSON_NULL:
				txt = "null";
				break;
			case JSON_BOOL:
				if (node->v.v_bool)
					txt = "true";
				else
					txt = "false";
				break;
			case JSON_STRING:
				encode_string(&ctx->str,
							  node->v.string.str, node->v.string.length,
							  '"', ctx->escape_unicode);
				break;
			case JSON_NUMBER:
				if (!encode_number(&ctx->str, node->v.number))
					return false;
				break;
			case JSON_ARRAY:
				appendStringInfoChar(&ctx->str, '[');

				json_foreach(child, node)
				{
					json_encode_recurse(child, ctx);
					if (child->next != NULL)
						appendStringInfoChar(&ctx->str, ',');
				}

				appendStringInfoChar(&ctx->str, ']');
				break;
			case JSON_OBJECT:
				appendStringInfoChar(&ctx->str, '{');

				json_foreach(child, node)
				{
					/*
					 * Shadows the parent node (assigned to the variable
					 * @node) so we can use our macros on the child node
					 * instead. Hurray for lexical scoping!
					 */
					JSON	   *node = child;

					if (has_orig(key_left_space))
						push_orig(key_left_space);

					if (has_orig(key))
						push_orig(key);
					else
						encode_string(&ctx->str, node->key, node->key_length,
									  '"', ctx->escape_unicode);

					if (has_orig(key_right_space))
						push_orig(key_right_space);

					appendStringInfoChar(&ctx->str, ':');

					json_encode_recurse(node, ctx);

					if (node->next != NULL)
						appendStringInfoChar(&ctx->str, ',');
				}

				appendStringInfoChar(&ctx->str, '}');
				break;
			default:
				return false;
		}

		if (txt != NULL)
			appendStringInfoString(&ctx->str, txt);
	}

	if (!trim && has_orig(right_space))
		push_orig(right_space);

	return true;

#undef has_orig
#undef push_orig
}

/*
 * json_encode_string
 *	  If you're interested in encoding JSON in general, see json_encode .
 *
 *	  Encodes a string literal JSON-style using the given quote character.
 *	  Note that using anything but '"' as the quote character will result
 *	  in invalid JSON.
 *
 *	  If escape_unicode is true, str must be valid UTF-8.
 *	  In any case, str may contain null characters (hence the length argument).
 *
 *	  quote must not be a backslash.
 */
char *
json_encode_string(const char *str, size_t length, char quote,
				   bool escape_unicode)
{
	StringInfoData ret;

	initStringInfo(&ret);
	encode_string(&ret, str, length, quote, escape_unicode);

	return ret.data;
}