In Python 3, return all our string data as surrogate-escaped utf-8 strings
[platform/upstream/rpm.git] / python / rpmtd-py.c
1 /** \ingroup py_c
2  * \file python/rpmtd-py.c
3  */
4
5 #include "rpmsystem-py.h"
6 #include <rpm/rpmtd.h>
7 #include <rpm/header.h>
8 #include "rpmtd-py.h"
9 #include "header-py.h"
10
11 /*
12  * Convert single tag data item to python object of suitable type
13  */
14 PyObject * rpmtd_ItemAsPyobj(rpmtd td, rpmTagClass tclass)
15 {
16     PyObject *res = NULL;
17
18     switch (tclass) {
19     case RPM_STRING_CLASS:
20         res = utf8FromString(rpmtdGetString(td));
21         break;
22     case RPM_NUMERIC_CLASS:
23         res = PyLong_FromLongLong(rpmtdGetNumber(td));
24         break;
25     case RPM_BINARY_CLASS:
26         res = PyBytes_FromStringAndSize(td->data, td->count);
27         break;
28     default:
29         PyErr_SetString(PyExc_KeyError, "unknown data type");
30         break;
31     }
32     return res;
33 }
34
35 PyObject *rpmtd_AsPyobj(rpmtd td)
36 {
37     PyObject *res = NULL;
38     int array = (rpmTagGetReturnType(td->tag) == RPM_ARRAY_RETURN_TYPE);
39     rpmTagClass tclass = rpmtdClass(td);
40
41     if (!array && rpmtdCount(td) < 1) {
42         Py_RETURN_NONE;
43     }
44     
45     if (array) {
46         int ix;
47         res = PyList_New(rpmtdCount(td));
48         if (!res) {
49             return NULL;
50         }
51         while ((ix = rpmtdNext(td)) >= 0) {
52             PyObject *item = rpmtd_ItemAsPyobj(td, tclass);
53             if (!item) {
54                 Py_DECREF(res);
55                 return NULL;
56             }
57             PyList_SET_ITEM(res, ix, item);
58         }
59     } else {
60         res = rpmtd_ItemAsPyobj(td, tclass);
61     }
62     return res;
63 }