]> sigrok.org Git - libsigrokdecode.git/blob - util.c
Factor out srd_decoder_apiver().
[libsigrokdecode.git] / util.c
1 /*
2  * This file is part of the libsigrokdecode project.
3  *
4  * Copyright (C) 2010 Uwe Hermann <uwe@hermann-uwe.de>
5  * Copyright (C) 2012 Bert Vermeulen <bert@biot.com>
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19  */
20
21 #include <config.h>
22 #include "libsigrokdecode-internal.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
23
24 /**
25  * Import a Python module by name.
26  *
27  * This function is implemented in terms of PyImport_Import() rather than
28  * PyImport_ImportModule(), so that the import hooks are not bypassed.
29  *
30  * @param[in] name The name of the module to load as UTF-8 string.
31  * @return The Python module object, or NULL if an exception occurred. The
32  *  caller is responsible for evaluating and clearing the Python error state.
33  *
34  * @private
35  */
36 SRD_PRIV PyObject *py_import_by_name(const char *name)
37 {
38         PyObject *py_mod, *py_modname;
39
40         py_modname = PyUnicode_FromString(name);
41         if (!py_modname)
42                 return NULL;
43
44         py_mod = PyImport_Import(py_modname);
45         Py_DECREF(py_modname);
46
47         return py_mod;
48 }
49
50 /**
51  * Get the value of a Python object's attribute, returned as a newly
52  * allocated char *.
53  *
54  * @param[in] py_obj The object to probe.
55  * @param[in] attr Name of the attribute to retrieve.
56  * @param[out] outstr ptr to char * storage to be filled in.
57  *
58  * @return SRD_OK upon success, a (negative) error code otherwise.
59  *         The 'outstr' argument points to a g_malloc()ed string upon success.
60  *
61  * @private
62  */
63 SRD_PRIV int py_attr_as_str(PyObject *py_obj, const char *attr, char **outstr)
64 {
65         PyObject *py_str;
66         int ret;
67
68         if (!PyObject_HasAttrString(py_obj, attr)) {
69                 srd_dbg("Object has no attribute '%s'.", attr);
70                 return SRD_ERR_PYTHON;
71         }
72
73         if (!(py_str = PyObject_GetAttrString(py_obj, attr))) {
74                 srd_exception_catch("Failed to get attribute '%s'", attr);
75                 return SRD_ERR_PYTHON;
76         }
77
78         ret = py_str_as_str(py_str, outstr);
79         Py_DECREF(py_str);
80
81         return ret;
82 }
83
84 /**
85  * Get the value of a Python dictionary item, returned as a newly
86  * allocated char *.
87  *
88  * @param[in] py_obj The dictionary to probe.
89  * @param[in] key Key of the item to retrieve.
90  * @param[out] outstr Pointer to char * storage to be filled in.
91  *
92  * @return SRD_OK upon success, a (negative) error code otherwise.
93  *         The 'outstr' argument points to a g_malloc()ed string upon success.
94  *
95  * @private
96  */
97 SRD_PRIV int py_dictitem_as_str(PyObject *py_obj, const char *key,
98                                 char **outstr)
99 {
100         PyObject *py_value;
101
102         if (!PyDict_Check(py_obj)) {
103                 srd_dbg("Object is not a dictionary.");
104                 return SRD_ERR_PYTHON;
105         }
106
107         if (!(py_value = PyDict_GetItemString(py_obj, key))) {
108                 srd_dbg("Dictionary has no attribute '%s'.", key);
109                 return SRD_ERR_PYTHON;
110         }
111
112         return py_str_as_str(py_value, outstr);
113 }
114
115 /**
116  * Get the value of a Python unicode string object, returned as a newly
117  * allocated char *.
118  *
119  * @param[in] py_str The unicode string object.
120  * @param[out] outstr ptr to char * storage to be filled in.
121  *
122  * @return SRD_OK upon success, a (negative) error code otherwise.
123  *         The 'outstr' argument points to a g_malloc()ed string upon success.
124  *
125  * @private
126  */
127 SRD_PRIV int py_str_as_str(PyObject *py_str, char **outstr)
128 {
129         PyObject *py_bytes;
130         char *str;
131
132         if (!PyUnicode_Check(py_str)) {
133                 srd_dbg("Object is not a string object.");
134                 return SRD_ERR_PYTHON;
135         }
136
137         py_bytes = PyUnicode_AsUTF8String(py_str);
138         if (py_bytes) {
139                 str = g_strdup(PyBytes_AsString(py_bytes));
140                 Py_DECREF(py_bytes);
141                 if (str) {
142                         *outstr = str;
143                         return SRD_OK;
144                 }
145         }
146         srd_exception_catch("Failed to extract string");
147
148         return SRD_ERR_PYTHON;
149 }
150
151 /**
152  * Convert a Python list of unicode strings to a C string vector.
153  * On success, a pointer to a newly allocated NULL-terminated array of
154  * allocated C strings is written to @a out_strv. The caller must g_free()
155  * each string and the array itself.
156  *
157  * @param[in] py_strseq The sequence object.
158  * @param[out] out_strv Address of string vector to be filled in.
159  *
160  * @return SRD_OK upon success, a (negative) error code otherwise.
161  *
162  * @private
163  */
164 SRD_PRIV int py_strseq_to_char(PyObject *py_strseq, char ***out_strv)
165 {
166         PyObject *py_item, *py_bytes;
167         char **strv, *str;
168         ssize_t seq_len, i;
169
170         if (!PySequence_Check(py_strseq)) {
171                 srd_err("Object does not provide sequence protocol.");
172                 return SRD_ERR_PYTHON;
173         }
174
175         seq_len = PySequence_Size(py_strseq);
176         if (seq_len < 0) {
177                 srd_exception_catch("Failed to obtain sequence size");
178                 return SRD_ERR_PYTHON;
179         }
180
181         strv = g_try_new0(char *, seq_len + 1);
182         if (!strv) {
183                 srd_err("Failed to allocate result string vector.");
184                 return SRD_ERR_MALLOC;
185         }
186
187         for (i = 0; i < seq_len; i++) {
188                 py_item = PySequence_GetItem(py_strseq, i);
189                 if (!py_item)
190                         goto err_out;
191
192                 if (!PyUnicode_Check(py_item)) {
193                         Py_DECREF(py_item);
194                         goto err_out;
195                 }
196                 py_bytes = PyUnicode_AsUTF8String(py_item);
197                 Py_DECREF(py_item);
198                 if (!py_bytes)
199                         goto err_out;
200
201                 str = g_strdup(PyBytes_AsString(py_bytes));
202                 Py_DECREF(py_bytes);
203                 if (!str)
204                         goto err_out;
205
206                 strv[i] = str;
207         }
208         *out_strv = strv;
209
210         return SRD_OK;
211
212 err_out:
213         g_strfreev(strv);
214         srd_exception_catch("Failed to obtain string item");
215
216         return SRD_ERR_PYTHON;
217 }
218
219 /**
220  * Convert a Python scalar object to a GLib variant.
221  * Supported variant types are string, int64 and double.
222  *
223  * @param[in] py_obj The Python object. Must not be NULL.
224  * @return A floating reference to a new variant, or NULL on failure.
225  *
226  * @private
227  */
228 SRD_PRIV GVariant *py_obj_to_variant(PyObject *py_obj)
229 {
230         GVariant *var = NULL;
231
232         if (PyUnicode_Check(py_obj)) { /* string */
233                 PyObject *py_bytes;
234                 const char *str;
235
236                 py_bytes = PyUnicode_AsUTF8String(py_obj);
237                 if (py_bytes) {
238                         str = PyBytes_AsString(py_bytes);
239                         if (str)
240                                 var = g_variant_new_string(str);
241                         Py_DECREF(py_bytes);
242                 }
243                 if (!var)
244                         srd_exception_catch("Failed to extract string value");
245
246         } else if (PyLong_Check(py_obj)) { /* integer */
247                 int64_t val;
248
249                 val = PyLong_AsLongLong(py_obj);
250                 if (!PyErr_Occurred())
251                         var = g_variant_new_int64(val);
252                 else
253                         srd_exception_catch("Failed to extract integer value");
254
255         } else if (PyFloat_Check(py_obj)) { /* float */
256                 double val;
257
258                 val = PyFloat_AsDouble(py_obj);
259                 if (!PyErr_Occurred())
260                         var = g_variant_new_double(val);
261                 else
262                         srd_exception_catch("Failed to extract float value");
263
264         } else {
265                 srd_err("Failed to extract value of unsupported type.");
266         }
267
268         return var;
269 }