forked from python-rapidjson/python-rapidjson
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rapidjson.cpp
4095 lines (3475 loc) · 138 KB
/
rapidjson.cpp
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
// -*- coding: utf-8 -*-
// :Project: python-rapidjson -- Python extension module
// :Author: Ken Robbins <[email protected]>
// :License: MIT License
// :Copyright: © 2015 Ken Robbins
// :Copyright: © 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023 Lele Gaifax
//
#include <locale.h>
#include <Python.h>
#include <datetime.h>
#include <structmember.h>
#include <algorithm>
#include <cmath>
#include <string>
#include <vector>
#include "rapidjson/reader.h"
#include "rapidjson/schema.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/writer.h"
#include "rapidjson/prettywriter.h"
#include "rapidjson/error/en.h"
using namespace rapidjson;
/* On some MacOS combo, using Py_IS_XXX() macros does not work (see
https://github.com/python-rapidjson/python-rapidjson/issues/78).
OTOH, MSVC < 2015 does not have std::isxxx() (see
https://stackoverflow.com/questions/38441740/where-is-isnan-in-msvc-2010).
Oh well... */
#if defined (_MSC_VER) && (_MSC_VER < 1900)
#define IS_NAN(x) Py_IS_NAN(x)
#define IS_INF(x) Py_IS_INFINITY(x)
#else
#define IS_NAN(x) std::isnan(x)
#define IS_INF(x) std::isinf(x)
#endif
static PyObject* decimal_type = NULL;
static PyObject* timezone_type = NULL;
static PyObject* timezone_utc = NULL;
static PyObject* uuid_type = NULL;
static PyObject* validation_error = NULL;
static PyObject* decode_error = NULL;
/* These are the names of often used methods or literal values, interned in the module
initialization function, to avoid repeated creation/destruction of PyUnicode values
from plain C strings.
We cannot use _Py_IDENTIFIER() because that upsets the GNU C++ compiler in -pedantic
mode. */
static PyObject* astimezone_name = NULL;
static PyObject* hex_name = NULL;
static PyObject* timestamp_name = NULL;
static PyObject* total_seconds_name = NULL;
static PyObject* utcoffset_name = NULL;
static PyObject* is_infinite_name = NULL;
static PyObject* is_nan_name = NULL;
static PyObject* start_object_name = NULL;
static PyObject* end_object_name = NULL;
static PyObject* default_name = NULL;
static PyObject* end_array_name = NULL;
static PyObject* string_name = NULL;
static PyObject* read_name = NULL;
static PyObject* write_name = NULL;
static PyObject* encoding_name = NULL;
static PyObject* minus_inf_string_value = NULL;
static PyObject* nan_string_value = NULL;
static PyObject* plus_inf_string_value = NULL;
struct HandlerContext {
PyObject* object;
const char* key;
SizeType keyLength;
bool isObject;
bool keyValuePairs;
bool copiedKey;
};
enum DatetimeMode {
DM_NONE = 0,
// Formats
DM_ISO8601 = 1<<0, // Bidirectional ISO8601 for datetimes, dates and times
DM_UNIX_TIME = 1<<1, // Serialization only, "Unix epoch"-based number of seconds
// Options
DM_ONLY_SECONDS = 1<<4, // Truncate values to the whole second, ignoring micro seconds
DM_IGNORE_TZ = 1<<5, // Ignore timezones
DM_NAIVE_IS_UTC = 1<<6, // Assume naive datetime are in UTC timezone
DM_SHIFT_TO_UTC = 1<<7, // Shift to/from UTC
DM_MAX = 1<<8
};
#define DATETIME_MODE_FORMATS_MASK 0x0f // 0b00001111 in C++14
static inline int
datetime_mode_format(unsigned mode) {
return mode & DATETIME_MODE_FORMATS_MASK;
}
static inline bool
valid_datetime_mode(int mode) {
int format = datetime_mode_format(mode);
return (mode >= 0 && mode < DM_MAX
&& (format <= DM_UNIX_TIME)
&& (mode == 0 || format > 0));
}
static int
days_per_month(int year, int month) {
assert(month >= 1);
assert(month <= 12);
if (month == 1 || month == 3 || month == 5 || month == 7
|| month == 8 || month == 10 || month == 12) {
return 31;
} else if (month == 4 || month == 6 || month == 9 || month == 11) {
return 30;
} else if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) {
return 29;
} else {
return 28;
}
}
enum UuidMode {
UM_NONE = 0,
UM_CANONICAL = 1<<0, // 4-dashed 32 hex chars: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
UM_HEX = 1<<1, // canonical OR 32 hex chars in a row
UM_MAX = 1<<2
};
enum NumberMode {
NM_NONE = 0,
NM_NAN = 1<<0, // allow "not-a-number" values
NM_DECIMAL = 1<<1, // serialize Decimal instances, deserialize floats as Decimal
NM_NATIVE = 1<<2, // use faster native C library number handling
NM_MAX = 1<<3
};
enum BytesMode {
BM_NONE = 0,
BM_UTF8 = 1<<0, // try to convert to UTF-8
BM_MAX = 1<<1
};
enum ParseMode {
PM_NONE = 0,
PM_COMMENTS = 1<<0, // Allow one-line // ... and multi-line /* ... */ comments
PM_TRAILING_COMMAS = 1<<1, // allow trailing commas at the end of objects and arrays
PM_MAX = 1<<2
};
enum WriteMode {
WM_COMPACT = 0,
WM_PRETTY = 1<<0, // Use PrettyWriter
WM_SINGLE_LINE_ARRAY = 1<<1, // Format arrays on a single line
WM_MAX = 1<<2
};
enum IterableMode {
IM_ANY_ITERABLE = 0, // Default, any iterable is dumped as JSON array
IM_ONLY_LISTS = 1<<0, // Only list instances are dumped as JSON arrays
IM_MAX = 1<<1
};
enum MappingMode {
MM_ANY_MAPPING = 0, // Default, any mapping is dumped as JSON object
MM_ONLY_DICTS = 1<<0, // Only dict instances are dumped as JSON objects
MM_COERCE_KEYS_TO_STRINGS = 1<<1, // Convert keys to strings
MM_SKIP_NON_STRING_KEYS = 1<<2, // Ignore non-string keys
MM_SORT_KEYS = 1<<3, // Sort keys
MM_MAX = 1<<4
};
//////////////////////////
// Forward declarations //
//////////////////////////
static PyObject* do_decode(PyObject* decoder,
const char* jsonStr, Py_ssize_t jsonStrlen,
PyObject* jsonStream, size_t chunkSize,
PyObject* objectHook,
unsigned numberMode, unsigned datetimeMode,
unsigned uuidMode, unsigned parseMode);
static PyObject* decoder_call(PyObject* self, PyObject* args, PyObject* kwargs);
static PyObject* decoder_new(PyTypeObject* type, PyObject* args, PyObject* kwargs);
static PyObject* do_encode(PyObject* value, PyObject* defaultFn, bool ensureAscii,
unsigned writeMode, char indentChar, unsigned indentCount,
unsigned numberMode, unsigned datetimeMode,
unsigned uuidMode, unsigned bytesMode,
unsigned iterableMode, unsigned mappingMode);
static PyObject* do_stream_encode(PyObject* value, PyObject* stream, size_t chunkSize,
PyObject* defaultFn, bool ensureAscii,
unsigned writeMode, char indentChar,
unsigned indentCount, unsigned numberMode,
unsigned datetimeMode, unsigned uuidMode,
unsigned bytesMode, unsigned iterableMode,
unsigned mappingMode);
static PyObject* encoder_call(PyObject* self, PyObject* args, PyObject* kwargs);
static PyObject* encoder_new(PyTypeObject* type, PyObject* args, PyObject* kwargs);
static PyObject* validator_call(PyObject* self, PyObject* args, PyObject* kwargs);
static void validator_dealloc(PyObject* self);
static PyObject* validator_new(PyTypeObject* type, PyObject* args, PyObject* kwargs);
///////////////////////////////////////////////////
// Stream wrapper around Python file-like object //
///////////////////////////////////////////////////
class PyReadStreamWrapper {
public:
typedef char Ch;
PyReadStreamWrapper(PyObject* stream, size_t size)
: stream(stream) {
Py_INCREF(stream);
chunkSize = PyLong_FromUnsignedLong(size);
buffer = NULL;
chunk = NULL;
chunkLen = 0;
pos = 0;
offset = 0;
eof = false;
}
~PyReadStreamWrapper() {
Py_CLEAR(stream);
Py_CLEAR(chunkSize);
Py_CLEAR(chunk);
}
Ch Peek() {
if (!eof && pos == chunkLen) {
Read();
}
return eof ? '\0' : buffer[pos];
}
Ch Take() {
if (!eof && pos == chunkLen) {
Read();
}
return eof ? '\0' : buffer[pos++];
}
size_t Tell() const {
return offset + pos;
}
void Flush() {
assert(false);
}
void Put(Ch c) {
assert(false);
}
Ch* PutBegin() {
assert(false);
return 0;
}
size_t PutEnd(Ch* begin) {
assert(false);
return 0;
}
private:
void Read() {
Py_CLEAR(chunk);
chunk = PyObject_CallMethodObjArgs(stream, read_name, chunkSize, NULL);
if (chunk == NULL) {
eof = true;
} else {
Py_ssize_t len;
if (PyBytes_Check(chunk)) {
len = PyBytes_GET_SIZE(chunk);
buffer = PyBytes_AS_STRING(chunk);
} else {
buffer = PyUnicode_AsUTF8AndSize(chunk, &len);
if (buffer == NULL) {
len = 0;
}
}
if (len == 0) {
eof = true;
} else {
offset += chunkLen;
chunkLen = len;
pos = 0;
}
}
}
PyObject* stream;
PyObject* chunkSize;
PyObject* chunk;
const Ch* buffer;
size_t chunkLen;
size_t pos;
size_t offset;
bool eof;
};
class PyWriteStreamWrapper {
public:
typedef char Ch;
PyWriteStreamWrapper(PyObject* stream, size_t size)
: stream(stream) {
Py_INCREF(stream);
buffer = (char*) PyMem_Malloc(size);
assert(buffer);
bufferEnd = buffer + size;
cursor = buffer;
multiByteChar = NULL;
isBinary = !PyObject_HasAttr(stream, encoding_name);
}
~PyWriteStreamWrapper() {
Py_CLEAR(stream);
PyMem_Free(buffer);
}
Ch Peek() {
assert(false);
return 0;
}
Ch Take() {
assert(false);
return 0;
}
size_t Tell() const {
assert(false);
return 0;
}
void Flush() {
PyObject* c;
if (isBinary) {
c = PyBytes_FromStringAndSize(buffer, (size_t)(cursor - buffer));
cursor = buffer;
} else {
if (multiByteChar == NULL) {
c = PyUnicode_FromStringAndSize(buffer, (size_t)(cursor - buffer));
cursor = buffer;
} else {
size_t complete = (size_t)(multiByteChar - buffer);
c = PyUnicode_FromStringAndSize(buffer, complete);
size_t remaining = (size_t)(cursor - multiByteChar);
if (RAPIDJSON_LIKELY(remaining < complete))
memcpy(buffer, multiByteChar, remaining);
else
std::memmove(buffer, multiByteChar, remaining);
cursor = buffer + remaining;
multiByteChar = NULL;
}
}
if (c == NULL) {
// Propagate the error state, it will be caught by dumps_internal()
} else {
PyObject* res = PyObject_CallMethodObjArgs(stream, write_name, c, NULL);
if (res == NULL) {
// Likewise
} else {
Py_DECREF(res);
}
Py_DECREF(c);
}
}
void Put(Ch c) {
if (cursor == bufferEnd)
Flush();
if (!isBinary) {
if ((c & 0x80) == 0) {
multiByteChar = NULL;
} else if (c & 0x40) {
multiByteChar = cursor;
}
}
*cursor++ = c;
}
Ch* PutBegin() {
assert(false);
return 0;
}
size_t PutEnd(Ch* begin) {
assert(false);
return 0;
}
private:
PyObject* stream;
Ch* buffer;
Ch* bufferEnd;
Ch* cursor;
Ch* multiByteChar;
bool isBinary;
};
inline void PutUnsafe(PyWriteStreamWrapper& stream, char c) {
stream.Put(c);
}
/////////////
// RawJSON //
/////////////
typedef struct {
PyObject_HEAD
PyObject* value;
} RawJSON;
static void
RawJSON_dealloc(RawJSON* self)
{
Py_XDECREF(self->value);
Py_TYPE(self)->tp_free((PyObject*) self);
}
static PyObject*
RawJSON_new(PyTypeObject* type, PyObject* args, PyObject* kwds)
{
PyObject* self = type->tp_alloc(type, 0);
static char const* kwlist[] = {
"value",
NULL
};
PyObject* value = NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "U", (char**) kwlist, &value))
return NULL;
((RawJSON*) self)->value = value;
Py_INCREF(value);
return self;
}
static PyMemberDef RawJSON_members[] = {
{"value",
T_OBJECT_EX, offsetof(RawJSON, value), READONLY,
"string representing a serialized JSON object"},
{NULL} /* Sentinel */
};
PyDoc_STRVAR(rawjson_doc,
"Raw (preserialized) JSON object\n"
"\n"
"When rapidjson tries to serialize instances of this class, it will"
" use their literal `value`. For instance:\n"
">>> rapidjson.dumps(RawJSON('{\"already\": \"serialized\"}'))\n"
"'{\"already\": \"serialized\"}'");
static PyTypeObject RawJSON_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
"rapidjson.RawJSON", /* tp_name */
sizeof(RawJSON), /* tp_basicsize */
0, /* tp_itemsize */
(destructor) RawJSON_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
rawjson_doc, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
RawJSON_members, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
RawJSON_new, /* tp_new */
};
static bool
accept_indent_arg(PyObject* arg, unsigned &write_mode, unsigned &indent_count,
char &indent_char)
{
if (arg != NULL && arg != Py_None) {
write_mode = WM_PRETTY;
if (PyLong_Check(arg) && PyLong_AsLong(arg) >= 0) {
indent_count = PyLong_AsUnsignedLong(arg);
} else if (PyUnicode_Check(arg)) {
Py_ssize_t len;
const char* indentStr = PyUnicode_AsUTF8AndSize(arg, &len);
indent_count = len;
if (indent_count) {
indent_char = '\0';
while (len--) {
char ch = indentStr[len];
if (ch == '\n' || ch == ' ' || ch == '\t' || ch == '\r') {
if (indent_char == '\0') {
indent_char = ch;
} else if (indent_char != ch) {
PyErr_SetString(
PyExc_TypeError,
"indent string cannot contains different chars");
return false;
}
} else {
PyErr_SetString(PyExc_TypeError,
"non-whitespace char in indent string");
return false;
}
}
}
} else {
PyErr_SetString(PyExc_TypeError,
"indent must be a non-negative int or a string");
return false;
}
}
return true;
}
static bool
accept_write_mode_arg(PyObject* arg, unsigned &write_mode)
{
if (arg != NULL && arg != Py_None) {
if (PyLong_Check(arg)) {
long mode = PyLong_AsLong(arg);
if (mode < 0 || mode >= WM_MAX) {
PyErr_SetString(PyExc_ValueError, "Invalid write_mode");
return false;
}
write_mode = (unsigned) mode;
} else {
PyErr_SetString(PyExc_TypeError,
"write_mode must be a non-negative int");
return false;
}
}
return true;
}
static bool
accept_number_mode_arg(PyObject* arg, int allow_nan, unsigned &number_mode)
{
if (arg != NULL) {
if (arg == Py_None)
number_mode = NM_NONE;
else if (PyLong_Check(arg)) {
long mode = PyLong_AsLong(arg);
if (mode < 0 || mode >= NM_MAX) {
PyErr_SetString(PyExc_ValueError, "Invalid number_mode, out of range");
return false;
}
number_mode = (unsigned) mode;
} else {
PyErr_SetString(PyExc_TypeError,
"number_mode must be a non-negative int");
return false;
}
}
if (allow_nan != -1) {
if (allow_nan)
number_mode |= NM_NAN;
else
number_mode &= ~NM_NAN;
}
return true;
}
static bool
accept_datetime_mode_arg(PyObject* arg, unsigned &datetime_mode)
{
if (arg != NULL && arg != Py_None) {
if (PyLong_Check(arg)) {
long mode = PyLong_AsLong(arg);
if (!valid_datetime_mode(mode)) {
PyErr_SetString(PyExc_ValueError, "Invalid datetime_mode, out of range");
return false;
}
datetime_mode = (unsigned) mode;
} else {
PyErr_SetString(PyExc_TypeError,
"datetime_mode must be a non-negative int");
return false;
}
}
return true;
}
static bool
accept_uuid_mode_arg(PyObject* arg, unsigned &uuid_mode)
{
if (arg != NULL && arg != Py_None) {
if (PyLong_Check(arg)) {
long mode = PyLong_AsLong(arg);
if (mode < 0 || mode >= UM_MAX) {
PyErr_SetString(PyExc_ValueError, "Invalid uuid_mode, out of range");
return false;
}
uuid_mode = (unsigned) mode;
} else {
PyErr_SetString(PyExc_TypeError, "uuid_mode must be a non-negative int");
return false;
}
}
return true;
}
static bool
accept_bytes_mode_arg(PyObject* arg, unsigned &bytes_mode)
{
if (arg != NULL && arg != Py_None) {
if (PyLong_Check(arg)) {
long mode = PyLong_AsLong(arg);
if (mode < 0 || mode >= BM_MAX) {
PyErr_SetString(PyExc_ValueError, "Invalid bytes_mode, out of range");
return false;
}
bytes_mode = (unsigned) mode;
} else {
PyErr_SetString(PyExc_TypeError, "bytes_mode must be a non-negative int");
return false;
}
}
return true;
}
static bool
accept_iterable_mode_arg(PyObject* arg, unsigned &iterable_mode)
{
if (arg != NULL && arg != Py_None) {
if (PyLong_Check(arg)) {
long mode = PyLong_AsLong(arg);
if (mode < 0 || mode >= IM_MAX) {
PyErr_SetString(PyExc_ValueError, "Invalid iterable_mode, out of range");
return false;
}
iterable_mode = (unsigned) mode;
} else {
PyErr_SetString(PyExc_TypeError, "iterable_mode must be a non-negative int");
return false;
}
}
return true;
}
static bool
accept_mapping_mode_arg(PyObject* arg, unsigned &mapping_mode)
{
if (arg != NULL && arg != Py_None) {
if (PyLong_Check(arg)) {
long mode = PyLong_AsLong(arg);
if (mode < 0 || mode >= MM_MAX) {
PyErr_SetString(PyExc_ValueError, "Invalid mapping_mode, out of range");
return false;
}
mapping_mode = (unsigned) mode;
} else {
PyErr_SetString(PyExc_TypeError, "mapping_mode must be a non-negative int");
return false;
}
}
return true;
}
static bool
accept_chunk_size_arg(PyObject* arg, size_t &chunk_size)
{
if (arg != NULL && arg != Py_None) {
if (PyLong_Check(arg)) {
Py_ssize_t size = PyNumber_AsSsize_t(arg, PyExc_ValueError);
if (PyErr_Occurred() || size < 4 || size > UINT_MAX) {
PyErr_SetString(PyExc_ValueError, "Invalid chunk_size, out of range");
return false;
}
chunk_size = (size_t) size;
} else {
PyErr_SetString(PyExc_TypeError,
"chunk_size must be a non-negative int");
return false;
}
}
return true;
}
static bool
accept_parse_mode_arg(PyObject* arg, unsigned &parse_mode)
{
if (arg != NULL && arg != Py_None) {
if (PyLong_Check(arg)) {
long mode = PyLong_AsLong(arg);
if (mode < 0 || mode >= PM_MAX) {
PyErr_SetString(PyExc_ValueError, "Invalid parse_mode, out of range");
return false;
}
parse_mode = (unsigned) mode;
} else {
PyErr_SetString(PyExc_TypeError,
"parse_mode must be a non-negative int");
return false;
}
}
return true;
}
/////////////
// Decoder //
/////////////
/* Adapted from CPython's Objects/floatobject.c::float_from_string_inner() */
static PyObject*
float_from_string(const char* s, Py_ssize_t len)
{
double x;
const char* end;
/* We don't care about overflow or underflow. If the platform
* supports them, infinities and signed zeroes (on underflow) are
* fine. */
x = PyOS_string_to_double(s, (char **) &end, NULL);
if (end != s + len) {
return NULL;
} else if (x == -1.0 && PyErr_Occurred()) {
return NULL;
} else {
return PyFloat_FromDouble(x);
}
}
struct PyHandler {
PyObject* decoderStartObject;
PyObject* decoderEndObject;
PyObject* decoderEndArray;
PyObject* decoderString;
PyObject* sharedKeys;
PyObject* root;
PyObject* objectHook;
unsigned datetimeMode;
unsigned uuidMode;
unsigned numberMode;
std::vector<HandlerContext> stack;
PyHandler(PyObject* decoder,
PyObject* hook,
unsigned dm,
unsigned um,
unsigned nm)
: decoderStartObject(NULL),
decoderEndObject(NULL),
decoderEndArray(NULL),
decoderString(NULL),
root(NULL),
objectHook(hook),
datetimeMode(dm),
uuidMode(um),
numberMode(nm)
{
stack.reserve(128);
if (decoder != NULL) {
assert(!objectHook);
if (PyObject_HasAttr(decoder, start_object_name)) {
decoderStartObject = PyObject_GetAttr(decoder, start_object_name);
}
if (PyObject_HasAttr(decoder, end_object_name)) {
decoderEndObject = PyObject_GetAttr(decoder, end_object_name);
}
if (PyObject_HasAttr(decoder, end_array_name)) {
decoderEndArray = PyObject_GetAttr(decoder, end_array_name);
}
if (PyObject_HasAttr(decoder, string_name)) {
decoderString = PyObject_GetAttr(decoder, string_name);
}
}
sharedKeys = PyDict_New();
}
~PyHandler() {
while (!stack.empty()) {
const HandlerContext& ctx = stack.back();
if (ctx.copiedKey)
PyMem_Free((void*) ctx.key);
if (ctx.object != NULL)
Py_DECREF(ctx.object);
stack.pop_back();
}
Py_CLEAR(decoderStartObject);
Py_CLEAR(decoderEndObject);
Py_CLEAR(decoderEndArray);
Py_CLEAR(decoderString);
Py_CLEAR(sharedKeys);
}
bool Handle(PyObject* value) {
if (root) {
const HandlerContext& current = stack.back();
if (current.isObject) {
PyObject* key = PyUnicode_FromStringAndSize(current.key,
current.keyLength);
if (key == NULL) {
Py_DECREF(value);
return false;
}
PyObject* shared_key = PyDict_SetDefault(sharedKeys, key, key);
if (shared_key == NULL) {
Py_DECREF(key);
Py_DECREF(value);
return false;
}
Py_INCREF(shared_key);
Py_DECREF(key);
key = shared_key;
int rc;
if (current.keyValuePairs) {
PyObject* pair = PyTuple_Pack(2, key, value);
Py_DECREF(key);
Py_DECREF(value);
if (pair == NULL) {
return false;
}
rc = PyList_Append(current.object, pair);
Py_DECREF(pair);
} else {
if (PyDict_CheckExact(current.object))
// If it's a standard dictionary, this is +20% faster
rc = PyDict_SetItem(current.object, key, value);
else
rc = PyObject_SetItem(current.object, key, value);
Py_DECREF(key);
Py_DECREF(value);
}
if (rc == -1) {
return false;
}
} else {
PyList_Append(current.object, value);
Py_DECREF(value);
}
} else {
root = value;
}
return true;
}
bool Key(const char* str, SizeType length, bool copy) {
HandlerContext& current = stack.back();
// This happens when operating in stream mode and kParseInsituFlag is not set: we
// must copy the incoming string in the context, and destroy the duplicate when
// the context gets reused for the next dictionary key
if (current.key && current.copiedKey) {
PyMem_Free((void*) current.key);
current.key = NULL;
}
if (copy) {
char* copied_str = (char*) PyMem_Malloc(length+1);
if (copied_str == NULL)
return false;
memcpy(copied_str, str, length+1);
str = copied_str;
assert(!current.key);
}
current.key = str;
current.keyLength = length;
current.copiedKey = copy;
return true;
}
bool StartObject() {
PyObject* mapping;
bool key_value_pairs;
if (decoderStartObject != NULL) {
mapping = PyObject_CallFunctionObjArgs(decoderStartObject, NULL);
if (mapping == NULL)
return false;
key_value_pairs = PyList_Check(mapping);
if (!PyMapping_Check(mapping) && !key_value_pairs) {
Py_DECREF(mapping);
PyErr_SetString(PyExc_ValueError,
"start_object() must return a mapping or a list instance");
return false;
}
} else {
mapping = PyDict_New();
if (mapping == NULL) {
return false;
}
key_value_pairs = false;
}
if (!Handle(mapping)) {
return false;
}
HandlerContext ctx;
ctx.isObject = true;
ctx.keyValuePairs = key_value_pairs;
ctx.object = mapping;
ctx.key = NULL;
ctx.copiedKey = false;
Py_INCREF(mapping);
stack.push_back(ctx);
return true;
}
bool EndObject(SizeType member_count) {
const HandlerContext& ctx = stack.back();
if (ctx.copiedKey)
PyMem_Free((void*) ctx.key);
PyObject* mapping = ctx.object;
stack.pop_back();
if (objectHook == NULL && decoderEndObject == NULL) {
Py_DECREF(mapping);
return true;
}