forked from pandas-dev/pandas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathobjToJSON.c
2331 lines (2000 loc) · 68.7 KB
/
objToJSON.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (c) 2011-2013, ESN Social Software AB and Jonas Tarnstrom
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the ESN Social Software AB nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL ESN SOCIAL SOFTWARE AB OR JONAS TARNSTROM BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Portions of code from MODP_ASCII - Ascii transformations (upper/lower, etc)
https://github.com/client9/stringencoders
Copyright (c) 2007 Nick Galbreath -- nickg [at] modp [dot] com. All rights
reserved.
Numeric decoder derived from from TCL library
https://www.opensource.apple.com/source/tcl/tcl-14/tcl/license.terms
* Copyright (c) 1988-1993 The Regents of the University of California.
* Copyright (c) 1994 Sun Microsystems, Inc.
*/
#define PY_ARRAY_UNIQUE_SYMBOL UJSON_NUMPY
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <math.h>
#include <numpy/arrayobject.h>
#include <numpy/arrayscalars.h>
#include <numpy/ndarraytypes.h>
#include <numpy/npy_math.h>
#include <ultrajson.h>
#include "date_conversions.h"
#include "datetime.h"
static PyTypeObject *type_decimal;
static PyTypeObject *cls_dataframe;
static PyTypeObject *cls_series;
static PyTypeObject *cls_index;
static PyTypeObject *cls_nat;
static PyTypeObject *cls_na;
PyObject *cls_timedelta;
npy_int64 get_nat(void) { return NPY_MIN_INT64; }
typedef char *(*PFN_PyTypeToUTF8)(JSOBJ obj, JSONTypeContext *ti,
size_t *_outLen);
typedef struct __NpyArrContext {
PyObject *array;
char *dataptr;
int curdim; // current dimension in array's order
int stridedim; // dimension we are striding over
int inc; // stride dimension increment (+/- 1)
npy_intp dim;
npy_intp stride;
npy_intp ndim;
npy_intp index[NPY_MAXDIMS];
int type_num;
PyArray_GetItemFunc *getitem;
char **rowLabels;
char **columnLabels;
} NpyArrContext;
typedef struct __PdBlockContext {
int colIdx;
int ncols;
int transpose;
int *cindices; // frame column -> block column map
NpyArrContext **npyCtxts; // NpyArrContext for each column
} PdBlockContext;
typedef struct __TypeContext {
JSPFN_ITERBEGIN iterBegin;
JSPFN_ITEREND iterEnd;
JSPFN_ITERNEXT iterNext;
JSPFN_ITERGETNAME iterGetName;
JSPFN_ITERGETVALUE iterGetValue;
PFN_PyTypeToUTF8 PyTypeToUTF8;
PyObject *newObj;
PyObject *dictObj;
Py_ssize_t index;
Py_ssize_t size;
PyObject *itemValue;
PyObject *itemName;
PyObject *attrList;
PyObject *iterator;
double doubleValue;
JSINT64 longValue;
char *cStr;
NpyArrContext *npyarr;
PdBlockContext *pdblock;
int transpose;
char **rowLabels;
char **columnLabels;
npy_intp rowLabelsLen;
npy_intp columnLabelsLen;
} TypeContext;
typedef struct __PyObjectEncoder {
JSONObjectEncoder enc;
// pass through the NpyArrContext when encoding multi-dimensional arrays
NpyArrContext *npyCtxtPassthru;
// pass through the PdBlockContext when encoding blocks
PdBlockContext *blkCtxtPassthru;
// pass-through to encode numpy data directly
int npyType;
void *npyValue;
int datetimeIso;
NPY_DATETIMEUNIT datetimeUnit;
// output format style for pandas data types
int outputFormat;
int originalOutputFormat;
PyObject *defaultHandler;
} PyObjectEncoder;
#define GET_TC(__ptrtc) ((TypeContext *)((__ptrtc)->prv))
enum PANDAS_FORMAT { SPLIT, RECORDS, INDEX, COLUMNS, VALUES };
#define PRINTMARK()
int PdBlock_iterNext(JSOBJ, JSONTypeContext *);
void *initObjToJSON(void) {
PyObject *mod_pandas;
PyObject *mod_nattype;
PyObject *mod_natype;
PyObject *mod_decimal = PyImport_ImportModule("decimal");
type_decimal =
(PyTypeObject *)PyObject_GetAttrString(mod_decimal, "Decimal");
Py_DECREF(mod_decimal);
PyDateTime_IMPORT;
mod_pandas = PyImport_ImportModule("pandas");
if (mod_pandas) {
cls_dataframe =
(PyTypeObject *)PyObject_GetAttrString(mod_pandas, "DataFrame");
cls_index = (PyTypeObject *)PyObject_GetAttrString(mod_pandas, "Index");
cls_series =
(PyTypeObject *)PyObject_GetAttrString(mod_pandas, "Series");
cls_timedelta = PyObject_GetAttrString(mod_pandas, "Timedelta");
Py_DECREF(mod_pandas);
}
mod_nattype = PyImport_ImportModule("pandas._libs.tslibs.nattype");
if (mod_nattype) {
cls_nat =
(PyTypeObject *)PyObject_GetAttrString(mod_nattype, "NaTType");
Py_DECREF(mod_nattype);
}
mod_natype = PyImport_ImportModule("pandas._libs.missing");
if (mod_natype) {
cls_na = (PyTypeObject *)PyObject_GetAttrString(mod_natype, "NAType");
Py_DECREF(mod_natype);
}
/* Initialise numpy API */
import_array();
// GH 31463
return NULL;
}
static TypeContext *createTypeContext(void) {
TypeContext *pc;
pc = PyObject_Malloc(sizeof(TypeContext));
if (!pc) {
PyErr_NoMemory();
return NULL;
}
pc->newObj = NULL;
pc->dictObj = NULL;
pc->itemValue = NULL;
pc->itemName = NULL;
pc->attrList = NULL;
pc->index = 0;
pc->size = 0;
pc->longValue = 0;
pc->doubleValue = 0.0;
pc->cStr = NULL;
pc->npyarr = NULL;
pc->pdblock = NULL;
pc->rowLabels = NULL;
pc->columnLabels = NULL;
pc->transpose = 0;
pc->rowLabelsLen = 0;
pc->columnLabelsLen = 0;
return pc;
}
static PyObject *get_values(PyObject *obj) {
PyObject *values = NULL;
PRINTMARK();
if (PyObject_HasAttrString(obj, "_internal_get_values")) {
PRINTMARK();
values = PyObject_CallMethod(obj, "_internal_get_values", NULL);
if (values == NULL) {
// Clear so we can subsequently try another method
PyErr_Clear();
} else if (!PyArray_CheckExact(values)) {
// Didn't get a numpy array, so keep trying
PRINTMARK();
Py_DECREF(values);
values = NULL;
}
}
if ((values == NULL) && PyObject_HasAttrString(obj, "get_block_values")) {
PRINTMARK();
values = PyObject_CallMethod(obj, "get_block_values", NULL);
if (values == NULL) {
// Clear so we can subsequently try another method
PyErr_Clear();
} else if (!PyArray_CheckExact(values)) {
// Didn't get a numpy array, so keep trying
PRINTMARK();
Py_DECREF(values);
values = NULL;
}
}
if (values == NULL) {
PyObject *typeRepr = PyObject_Repr((PyObject *)Py_TYPE(obj));
PyObject *repr;
PRINTMARK();
if (PyObject_HasAttrString(obj, "dtype")) {
PyObject *dtype = PyObject_GetAttrString(obj, "dtype");
repr = PyObject_Repr(dtype);
Py_DECREF(dtype);
} else {
repr = PyUnicode_FromString("<unknown dtype>");
}
PyErr_Format(PyExc_ValueError, "%R or %R are not JSON serializable yet",
repr, typeRepr);
Py_DECREF(repr);
Py_DECREF(typeRepr);
return NULL;
}
return values;
}
static PyObject *get_sub_attr(PyObject *obj, char *attr, char *subAttr) {
PyObject *tmp = PyObject_GetAttrString(obj, attr);
PyObject *ret;
if (tmp == 0) {
return 0;
}
ret = PyObject_GetAttrString(tmp, subAttr);
Py_DECREF(tmp);
return ret;
}
static int is_simple_frame(PyObject *obj) {
PyObject *check = get_sub_attr(obj, "_data", "is_mixed_type");
int ret = (check == Py_False);
if (!check) {
return 0;
}
Py_DECREF(check);
return ret;
}
static Py_ssize_t get_attr_length(PyObject *obj, char *attr) {
PyObject *tmp = PyObject_GetAttrString(obj, attr);
Py_ssize_t ret;
if (tmp == 0) {
return 0;
}
ret = PyObject_Length(tmp);
Py_DECREF(tmp);
if (ret == -1) {
return 0;
}
return ret;
}
static npy_int64 get_long_attr(PyObject *o, const char *attr) {
npy_int64 long_val;
PyObject *value = PyObject_GetAttrString(o, attr);
long_val =
(PyLong_Check(value) ? PyLong_AsLongLong(value) : PyLong_AsLong(value));
Py_DECREF(value);
return long_val;
}
static npy_float64 total_seconds(PyObject *td) {
npy_float64 double_val;
PyObject *value = PyObject_CallMethod(td, "total_seconds", NULL);
double_val = PyFloat_AS_DOUBLE(value);
Py_DECREF(value);
return double_val;
}
static PyObject *get_item(PyObject *obj, Py_ssize_t i) {
PyObject *tmp = PyLong_FromSsize_t(i);
PyObject *ret;
if (tmp == 0) {
return 0;
}
ret = PyObject_GetItem(obj, tmp);
Py_DECREF(tmp);
return ret;
}
static char *PyBytesToUTF8(JSOBJ _obj, JSONTypeContext *Py_UNUSED(tc),
size_t *_outLen) {
PyObject *obj = (PyObject *)_obj;
*_outLen = PyBytes_GET_SIZE(obj);
return PyBytes_AS_STRING(obj);
}
static char *PyUnicodeToUTF8(JSOBJ _obj, JSONTypeContext *Py_UNUSED(tc),
size_t *_outLen) {
return (char *)PyUnicode_AsUTF8AndSize(_obj, (Py_ssize_t *)_outLen);
}
/* JSON callback. returns a char* and mutates the pointer to *len */
static char *NpyDateTimeToIsoCallback(JSOBJ Py_UNUSED(unused),
JSONTypeContext *tc, size_t *len) {
NPY_DATETIMEUNIT base = ((PyObjectEncoder *)tc->encoder)->datetimeUnit;
return int64ToIso(GET_TC(tc)->longValue, base, len);
}
/* JSON callback */
static char *PyDateTimeToIsoCallback(JSOBJ obj, JSONTypeContext *tc,
size_t *len) {
if (!PyDate_Check(obj)) {
PyErr_SetString(PyExc_TypeError, "Expected date object");
return NULL;
}
NPY_DATETIMEUNIT base = ((PyObjectEncoder *)tc->encoder)->datetimeUnit;
return PyDateTimeToIso(obj, base, len);
}
static char *PyTimeToJSON(JSOBJ _obj, JSONTypeContext *tc, size_t *outLen) {
PyObject *obj = (PyObject *)_obj;
PyObject *str;
PyObject *tmp;
str = PyObject_CallMethod(obj, "isoformat", NULL);
if (str == NULL) {
PRINTMARK();
*outLen = 0;
if (!PyErr_Occurred()) {
PyErr_SetString(PyExc_ValueError, "Failed to convert time");
}
((JSONObjectEncoder *)tc->encoder)->errorMsg = "";
return NULL;
}
if (PyUnicode_Check(str)) {
tmp = str;
str = PyUnicode_AsUTF8String(str);
Py_DECREF(tmp);
}
GET_TC(tc)->newObj = str;
*outLen = PyBytes_GET_SIZE(str);
char *outValue = PyBytes_AS_STRING(str);
return outValue;
}
//=============================================================================
// Numpy array iteration functions
//=============================================================================
static void NpyArr_freeItemValue(JSOBJ Py_UNUSED(_obj), JSONTypeContext *tc) {
if (GET_TC(tc)->npyarr &&
GET_TC(tc)->itemValue != GET_TC(tc)->npyarr->array) {
PRINTMARK();
Py_XDECREF(GET_TC(tc)->itemValue);
GET_TC(tc)->itemValue = NULL;
}
}
int NpyArr_iterNextNone(JSOBJ Py_UNUSED(_obj), JSONTypeContext *Py_UNUSED(tc)) {
return 0;
}
void NpyArr_iterBegin(JSOBJ _obj, JSONTypeContext *tc) {
PyArrayObject *obj;
NpyArrContext *npyarr;
if (GET_TC(tc)->newObj) {
obj = (PyArrayObject *)GET_TC(tc)->newObj;
} else {
obj = (PyArrayObject *)_obj;
}
PRINTMARK();
npyarr = PyObject_Malloc(sizeof(NpyArrContext));
GET_TC(tc)->npyarr = npyarr;
if (!npyarr) {
PyErr_NoMemory();
GET_TC(tc)->iterNext = NpyArr_iterNextNone;
return;
}
npyarr->array = (PyObject *)obj;
npyarr->getitem = (PyArray_GetItemFunc *)PyArray_DESCR(obj)->f->getitem;
npyarr->dataptr = PyArray_DATA(obj);
npyarr->ndim = PyArray_NDIM(obj) - 1;
npyarr->curdim = 0;
npyarr->type_num = PyArray_DESCR(obj)->type_num;
if (GET_TC(tc)->transpose) {
npyarr->dim = PyArray_DIM(obj, npyarr->ndim);
npyarr->stride = PyArray_STRIDE(obj, npyarr->ndim);
npyarr->stridedim = npyarr->ndim;
npyarr->index[npyarr->ndim] = 0;
npyarr->inc = -1;
} else {
npyarr->dim = PyArray_DIM(obj, 0);
npyarr->stride = PyArray_STRIDE(obj, 0);
npyarr->stridedim = 0;
npyarr->index[0] = 0;
npyarr->inc = 1;
}
npyarr->columnLabels = GET_TC(tc)->columnLabels;
npyarr->rowLabels = GET_TC(tc)->rowLabels;
}
void NpyArr_iterEnd(JSOBJ obj, JSONTypeContext *tc) {
NpyArrContext *npyarr = GET_TC(tc)->npyarr;
PRINTMARK();
if (npyarr) {
NpyArr_freeItemValue(obj, tc);
PyObject_Free(npyarr);
}
}
void NpyArrPassThru_iterBegin(JSOBJ Py_UNUSED(obj),
JSONTypeContext *Py_UNUSED(tc)) {
PRINTMARK();
}
void NpyArrPassThru_iterEnd(JSOBJ obj, JSONTypeContext *tc) {
NpyArrContext *npyarr = GET_TC(tc)->npyarr;
PRINTMARK();
// finished this dimension, reset the data pointer
npyarr->curdim--;
npyarr->dataptr -= npyarr->stride * npyarr->index[npyarr->stridedim];
npyarr->stridedim -= npyarr->inc;
npyarr->dim = PyArray_DIM(npyarr->array, npyarr->stridedim);
npyarr->stride = PyArray_STRIDE(npyarr->array, npyarr->stridedim);
npyarr->dataptr += npyarr->stride;
NpyArr_freeItemValue(obj, tc);
}
int NpyArr_iterNextItem(JSOBJ obj, JSONTypeContext *tc) {
NpyArrContext *npyarr = GET_TC(tc)->npyarr;
PRINTMARK();
if (PyErr_Occurred()) {
return 0;
}
if (npyarr->index[npyarr->stridedim] >= npyarr->dim) {
PRINTMARK();
return 0;
}
NpyArr_freeItemValue(obj, tc);
if (PyArray_ISDATETIME(npyarr->array)) {
PRINTMARK();
GET_TC(tc)->itemValue = obj;
Py_INCREF(obj);
((PyObjectEncoder *)tc->encoder)->npyType = PyArray_TYPE(npyarr->array);
((PyObjectEncoder *)tc->encoder)->npyValue = npyarr->dataptr;
((PyObjectEncoder *)tc->encoder)->npyCtxtPassthru = npyarr;
} else {
PRINTMARK();
GET_TC(tc)->itemValue = npyarr->getitem(npyarr->dataptr, npyarr->array);
}
npyarr->dataptr += npyarr->stride;
npyarr->index[npyarr->stridedim]++;
return 1;
}
int NpyArr_iterNext(JSOBJ _obj, JSONTypeContext *tc) {
NpyArrContext *npyarr = GET_TC(tc)->npyarr;
PRINTMARK();
if (PyErr_Occurred()) {
PRINTMARK();
return 0;
}
if (npyarr->curdim >= npyarr->ndim ||
npyarr->index[npyarr->stridedim] >= npyarr->dim) {
PRINTMARK();
// innermost dimension, start retrieving item values
GET_TC(tc)->iterNext = NpyArr_iterNextItem;
return NpyArr_iterNextItem(_obj, tc);
}
// dig a dimension deeper
npyarr->index[npyarr->stridedim]++;
npyarr->curdim++;
npyarr->stridedim += npyarr->inc;
npyarr->dim = PyArray_DIM(npyarr->array, npyarr->stridedim);
npyarr->stride = PyArray_STRIDE(npyarr->array, npyarr->stridedim);
npyarr->index[npyarr->stridedim] = 0;
((PyObjectEncoder *)tc->encoder)->npyCtxtPassthru = npyarr;
GET_TC(tc)->itemValue = npyarr->array;
return 1;
}
JSOBJ NpyArr_iterGetValue(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) {
PRINTMARK();
return GET_TC(tc)->itemValue;
}
char *NpyArr_iterGetName(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc,
size_t *outLen) {
NpyArrContext *npyarr = GET_TC(tc)->npyarr;
npy_intp idx;
PRINTMARK();
char *cStr;
if (GET_TC(tc)->iterNext == NpyArr_iterNextItem) {
idx = npyarr->index[npyarr->stridedim] - 1;
cStr = npyarr->columnLabels[idx];
} else {
idx = npyarr->index[npyarr->stridedim - npyarr->inc] - 1;
cStr = npyarr->rowLabels[idx];
}
*outLen = strlen(cStr);
return cStr;
}
//=============================================================================
// Pandas block iteration functions
//
// Serialises a DataFrame column by column to avoid unnecessary data copies and
// more representative serialisation when dealing with mixed dtypes.
//
// Uses a dedicated NpyArrContext for each column.
//=============================================================================
void PdBlockPassThru_iterEnd(JSOBJ obj, JSONTypeContext *tc) {
PdBlockContext *blkCtxt = GET_TC(tc)->pdblock;
PRINTMARK();
if (blkCtxt->transpose) {
blkCtxt->colIdx++;
} else {
blkCtxt->colIdx = 0;
}
NpyArr_freeItemValue(obj, tc);
}
int PdBlock_iterNextItem(JSOBJ obj, JSONTypeContext *tc) {
PdBlockContext *blkCtxt = GET_TC(tc)->pdblock;
PRINTMARK();
if (blkCtxt->colIdx >= blkCtxt->ncols) {
return 0;
}
GET_TC(tc)->npyarr = blkCtxt->npyCtxts[blkCtxt->colIdx];
blkCtxt->colIdx++;
return NpyArr_iterNextItem(obj, tc);
}
char *PdBlock_iterGetName(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc,
size_t *outLen) {
PdBlockContext *blkCtxt = GET_TC(tc)->pdblock;
NpyArrContext *npyarr = blkCtxt->npyCtxts[0];
npy_intp idx;
char *cStr;
PRINTMARK();
if (GET_TC(tc)->iterNext == PdBlock_iterNextItem) {
idx = blkCtxt->colIdx - 1;
cStr = npyarr->columnLabels[idx];
} else {
idx = GET_TC(tc)->iterNext != PdBlock_iterNext
? npyarr->index[npyarr->stridedim - npyarr->inc] - 1
: npyarr->index[npyarr->stridedim];
cStr = npyarr->rowLabels[idx];
}
*outLen = strlen(cStr);
return cStr;
}
char *PdBlock_iterGetName_Transpose(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc,
size_t *outLen) {
PdBlockContext *blkCtxt = GET_TC(tc)->pdblock;
NpyArrContext *npyarr = blkCtxt->npyCtxts[blkCtxt->colIdx];
npy_intp idx;
char *cStr;
PRINTMARK();
if (GET_TC(tc)->iterNext == NpyArr_iterNextItem) {
idx = npyarr->index[npyarr->stridedim] - 1;
cStr = npyarr->columnLabels[idx];
} else {
idx = blkCtxt->colIdx;
cStr = npyarr->rowLabels[idx];
}
*outLen = strlen(cStr);
return cStr;
}
int PdBlock_iterNext(JSOBJ obj, JSONTypeContext *tc) {
PdBlockContext *blkCtxt = GET_TC(tc)->pdblock;
NpyArrContext *npyarr;
PRINTMARK();
if (PyErr_Occurred() || ((JSONObjectEncoder *)tc->encoder)->errorMsg) {
return 0;
}
if (blkCtxt->transpose) {
if (blkCtxt->colIdx >= blkCtxt->ncols) {
return 0;
}
} else {
npyarr = blkCtxt->npyCtxts[0];
if (npyarr->index[npyarr->stridedim] >= npyarr->dim) {
return 0;
}
}
((PyObjectEncoder *)tc->encoder)->blkCtxtPassthru = blkCtxt;
GET_TC(tc)->itemValue = obj;
return 1;
}
void PdBlockPassThru_iterBegin(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) {
PdBlockContext *blkCtxt = GET_TC(tc)->pdblock;
PRINTMARK();
if (blkCtxt->transpose) {
// if transposed we exhaust each column before moving to the next
GET_TC(tc)->iterNext = NpyArr_iterNextItem;
GET_TC(tc)->iterGetName = PdBlock_iterGetName_Transpose;
GET_TC(tc)->npyarr = blkCtxt->npyCtxts[blkCtxt->colIdx];
}
}
void PdBlock_iterBegin(JSOBJ _obj, JSONTypeContext *tc) {
PyObject *obj, *blocks, *block, *values, *tmp;
PyArrayObject *locs;
PdBlockContext *blkCtxt;
NpyArrContext *npyarr;
Py_ssize_t i;
PyArray_Descr *dtype;
NpyIter *iter;
NpyIter_IterNextFunc *iternext;
npy_int64 **dataptr;
npy_int64 colIdx;
npy_intp idx;
PRINTMARK();
i = 0;
blocks = NULL;
dtype = PyArray_DescrFromType(NPY_INT64);
obj = (PyObject *)_obj;
GET_TC(tc)->iterGetName = GET_TC(tc)->transpose
? PdBlock_iterGetName_Transpose
: PdBlock_iterGetName;
blkCtxt = PyObject_Malloc(sizeof(PdBlockContext));
if (!blkCtxt) {
PyErr_NoMemory();
GET_TC(tc)->iterNext = NpyArr_iterNextNone;
goto BLKRET;
}
GET_TC(tc)->pdblock = blkCtxt;
blkCtxt->colIdx = 0;
blkCtxt->transpose = GET_TC(tc)->transpose;
blkCtxt->ncols = get_attr_length(obj, "columns");
if (blkCtxt->ncols == 0) {
blkCtxt->npyCtxts = NULL;
blkCtxt->cindices = NULL;
GET_TC(tc)->iterNext = NpyArr_iterNextNone;
goto BLKRET;
}
blkCtxt->npyCtxts =
PyObject_Malloc(sizeof(NpyArrContext *) * blkCtxt->ncols);
if (!blkCtxt->npyCtxts) {
PyErr_NoMemory();
GET_TC(tc)->iterNext = NpyArr_iterNextNone;
goto BLKRET;
}
for (i = 0; i < blkCtxt->ncols; i++) {
blkCtxt->npyCtxts[i] = NULL;
}
blkCtxt->cindices = PyObject_Malloc(sizeof(int) * blkCtxt->ncols);
if (!blkCtxt->cindices) {
PyErr_NoMemory();
GET_TC(tc)->iterNext = NpyArr_iterNextNone;
goto BLKRET;
}
blocks = get_sub_attr(obj, "_data", "blocks");
if (!blocks) {
GET_TC(tc)->iterNext = NpyArr_iterNextNone;
goto BLKRET;
}
// force transpose so each NpyArrContext strides down its column
GET_TC(tc)->transpose = 1;
for (i = 0; i < PyObject_Length(blocks); i++) {
block = get_item(blocks, i);
if (!block) {
GET_TC(tc)->iterNext = NpyArr_iterNextNone;
goto BLKRET;
}
tmp = get_values(block);
if (!tmp) {
((JSONObjectEncoder *)tc->encoder)->errorMsg = "";
Py_DECREF(block);
GET_TC(tc)->iterNext = NpyArr_iterNextNone;
goto BLKRET;
}
values = PyArray_Transpose((PyArrayObject *)tmp, NULL);
Py_DECREF(tmp);
if (!values) {
Py_DECREF(block);
GET_TC(tc)->iterNext = NpyArr_iterNextNone;
goto BLKRET;
}
locs = (PyArrayObject *)get_sub_attr(block, "mgr_locs", "as_array");
if (!locs) {
Py_DECREF(block);
Py_DECREF(values);
GET_TC(tc)->iterNext = NpyArr_iterNextNone;
goto BLKRET;
}
iter = NpyIter_New(locs, NPY_ITER_READONLY, NPY_KEEPORDER,
NPY_NO_CASTING, dtype);
if (!iter) {
Py_DECREF(block);
Py_DECREF(values);
Py_DECREF(locs);
GET_TC(tc)->iterNext = NpyArr_iterNextNone;
goto BLKRET;
}
iternext = NpyIter_GetIterNext(iter, NULL);
if (!iternext) {
NpyIter_Deallocate(iter);
Py_DECREF(block);
Py_DECREF(values);
Py_DECREF(locs);
GET_TC(tc)->iterNext = NpyArr_iterNextNone;
goto BLKRET;
}
dataptr = (npy_int64 **)NpyIter_GetDataPtrArray(iter);
do {
colIdx = **dataptr;
idx = NpyIter_GetIterIndex(iter);
blkCtxt->cindices[colIdx] = idx;
// Reference freed in Pdblock_iterend
Py_INCREF(values);
GET_TC(tc)->newObj = values;
// init a dedicated context for this column
NpyArr_iterBegin(obj, tc);
npyarr = GET_TC(tc)->npyarr;
// set the dataptr to our desired column and initialise
if (npyarr != NULL) {
npyarr->dataptr += npyarr->stride * idx;
NpyArr_iterNext(obj, tc);
}
GET_TC(tc)->itemValue = NULL;
((PyObjectEncoder *)tc->encoder)->npyCtxtPassthru = NULL;
blkCtxt->npyCtxts[colIdx] = npyarr;
GET_TC(tc)->newObj = NULL;
} while (iternext(iter));
NpyIter_Deallocate(iter);
Py_DECREF(block);
Py_DECREF(values);
Py_DECREF(locs);
}
GET_TC(tc)->npyarr = blkCtxt->npyCtxts[0];
BLKRET:
Py_XDECREF(dtype);
Py_XDECREF(blocks);
}
void PdBlock_iterEnd(JSOBJ obj, JSONTypeContext *tc) {
PdBlockContext *blkCtxt;
NpyArrContext *npyarr;
int i;
PRINTMARK();
GET_TC(tc)->itemValue = NULL;
npyarr = GET_TC(tc)->npyarr;
blkCtxt = GET_TC(tc)->pdblock;
if (blkCtxt) {
for (i = 0; i < blkCtxt->ncols; i++) {
npyarr = blkCtxt->npyCtxts[i];
if (npyarr) {
if (npyarr->array) {
Py_DECREF(npyarr->array);
npyarr->array = NULL;
}
GET_TC(tc)->npyarr = npyarr;
NpyArr_iterEnd(obj, tc);
blkCtxt->npyCtxts[i] = NULL;
}
}
if (blkCtxt->npyCtxts) {
PyObject_Free(blkCtxt->npyCtxts);
}
if (blkCtxt->cindices) {
PyObject_Free(blkCtxt->cindices);
}
PyObject_Free(blkCtxt);
}
}
//=============================================================================
// Tuple iteration functions
// itemValue is borrowed reference, no ref counting
//=============================================================================
void Tuple_iterBegin(JSOBJ obj, JSONTypeContext *tc) {
GET_TC(tc)->index = 0;
GET_TC(tc)->size = PyTuple_GET_SIZE((PyObject *)obj);
GET_TC(tc)->itemValue = NULL;
}
int Tuple_iterNext(JSOBJ obj, JSONTypeContext *tc) {
PyObject *item;
if (GET_TC(tc)->index >= GET_TC(tc)->size) {
return 0;
}
item = PyTuple_GET_ITEM(obj, GET_TC(tc)->index);
GET_TC(tc)->itemValue = item;
GET_TC(tc)->index++;
return 1;
}
void Tuple_iterEnd(JSOBJ Py_UNUSED(obj), JSONTypeContext *Py_UNUSED(tc)) {}
JSOBJ Tuple_iterGetValue(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) {
return GET_TC(tc)->itemValue;
}
char *Tuple_iterGetName(JSOBJ Py_UNUSED(obj), JSONTypeContext *Py_UNUSED(tc),
size_t *Py_UNUSED(outLen)) {
return NULL;
}
//=============================================================================
// Set iteration functions
// itemValue is borrowed reference, no ref counting
//=============================================================================
void Set_iterBegin(JSOBJ obj, JSONTypeContext *tc) {
GET_TC(tc)->itemValue = NULL;
GET_TC(tc)->iterator = PyObject_GetIter(obj);
}
int Set_iterNext(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) {
PyObject *item;
if (GET_TC(tc)->itemValue) {
Py_DECREF(GET_TC(tc)->itemValue);
GET_TC(tc)->itemValue = NULL;
}
item = PyIter_Next(GET_TC(tc)->iterator);
if (item == NULL) {
return 0;
}
GET_TC(tc)->itemValue = item;
return 1;
}
void Set_iterEnd(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) {
if (GET_TC(tc)->itemValue) {
Py_DECREF(GET_TC(tc)->itemValue);
GET_TC(tc)->itemValue = NULL;
}
if (GET_TC(tc)->iterator) {
Py_DECREF(GET_TC(tc)->iterator);
GET_TC(tc)->iterator = NULL;
}
}
JSOBJ Set_iterGetValue(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) {
return GET_TC(tc)->itemValue;
}
char *Set_iterGetName(JSOBJ Py_UNUSED(obj), JSONTypeContext *Py_UNUSED(tc),
size_t *Py_UNUSED(outLen)) {
return NULL;
}
//=============================================================================
// Dir iteration functions
// itemName ref is borrowed from PyObject_Dir (attrList). No refcount
// itemValue ref is from PyObject_GetAttr. Ref counted
//=============================================================================
void Dir_iterBegin(JSOBJ obj, JSONTypeContext *tc) {
GET_TC(tc)->attrList = PyObject_Dir(obj);
GET_TC(tc)->index = 0;
GET_TC(tc)->size = PyList_GET_SIZE(GET_TC(tc)->attrList);
PRINTMARK();
}
void Dir_iterEnd(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) {
if (GET_TC(tc)->itemValue) {
Py_DECREF(GET_TC(tc)->itemValue);
GET_TC(tc)->itemValue = NULL;
}