blob: 5c5ec22095f0e840ebb4dd409614e1ab67bd0f1e [file] [log] [blame]
Ed Tanouscd9b1c52025-04-22 08:59:45 -07001#if LIBCPER_PYTHON
2#define PY_SSIZE_T_CLEAN
3#include <Python.h>
4#include <libcper/cper-parse-str.h>
5#include <libcper/cper-parse.h>
6
7PyObject *convert_to_pydict(json_object *jso)
8{
9 PyObject *ret = Py_None;
10 enum json_type type = json_object_get_type(jso);
11 //printf("type: %d ", type);
12 switch (type) {
13 case json_type_null:
14 //printf("json_type_null\n");
15 ret = Py_None;
16 break;
17 case json_type_boolean: {
18 //printf("json_type_boolean\n");
19 int b = json_object_get_boolean(jso);
20 ret = PyBool_FromLong(b);
21 } break;
22 case json_type_double: {
23 //printf("json_type_double\n");
24 double d = json_object_get_double(jso);
25 ret = PyFloat_FromDouble(d);
26 } break;
27
28 case json_type_int: {
29 //printf("json_type_int\n");
30 int64_t i = json_object_get_int64(jso);
31 ret = PyLong_FromLong(i);
32 } break;
33 case json_type_object: {
34 //printf("json_type_object\n");
35 ret = PyDict_New();
36
37 json_object_object_foreach(jso, key1, val)
38 {
39 PyObject *pyobj = convert_to_pydict(val);
40 if (key1 != NULL) {
41 //printf("Parsing %s\n", key1);
42 if (pyobj == NULL) {
43 pyobj = Py_None;
44 }
45 PyDict_SetItemString(ret, key1, pyobj);
46 }
47 }
48 } break;
49 case json_type_array: {
50 //printf("json_type_array\n");
51 ret = PyList_New(0);
52 int arraylen = json_object_array_length(jso);
53
54 for (int i = 0; i < arraylen; i++) {
55 //printf("Parsing %d\n", i);
56 json_object *val = json_object_array_get_idx(jso, i);
57 PyObject *pyobj = convert_to_pydict(val);
58 if (pyobj == NULL) {
59 pyobj = Py_None;
60 }
61 PyList_Append(ret, pyobj);
62 }
63 } break;
64 case json_type_string: {
65 //printf("json_type_string\n");
66 const char *strval = json_object_get_string(jso);
67 ret = PyUnicode_FromString(strval);
68 } break;
69 }
70 return ret;
71}
72
73static PyObject *parse(PyObject *self, PyObject *args)
74{
75 (void)self;
76 PyObject *ret;
77 const unsigned char *data;
78 Py_ssize_t count;
79
80 if (!PyArg_ParseTuple(args, "y#", &data, &count)) {
81 return NULL;
82 }
83
84 char *jstrout = cperbuf_to_str_ir(data, count);
85 if (jstrout == NULL) {
86 free(jstrout);
87 return NULL;
88 }
89 json_object *jout = cper_buf_to_ir(data, count);
90 if (jout == NULL) {
91 free(jstrout);
92 free(jout);
93 return NULL;
94 }
95
96 ret = convert_to_pydict(jout);
97
98 //ret = PyUnicode_FromString(jstrout);
99 free(jout);
100 free(jstrout);
101 return ret;
102}
103
104static PyMethodDef methods[] = {
105 { "parse", (PyCFunction)parse, METH_VARARGS, NULL },
106 { NULL, NULL, 0, NULL },
107};
108
109static struct PyModuleDef module = {
110 PyModuleDef_HEAD_INIT,
111 "cper",
112 NULL,
113 -1,
114 methods,
115 NULL,
116 NULL,
117 NULL,
118 NULL,
119};
120
121PyMODINIT_FUNC PyInit_cper(void)
122{
123 return PyModule_Create(&module);
124}
125#endif