From: Kent Gibson Date: Sun, 1 Dec 2019 03:23:58 +0000 (+0800) Subject: bindings: python: move tuple to int array conversion into helper function X-Git-Url: http://git.maquefel.me/?a=commitdiff_plain;h=587fd129610f28e10cf872a7802c8d88171e9369;p=qemu-gpiodev%2Flibgpiod.git bindings: python: move tuple to int array conversion into helper function Restructured gpiod_LineBulk_set_values to move the conversion of values from Python tuple to int array into a helper function as it is useful for similar functions. Signed-off-by: Kent Gibson Signed-off-by: Bartosz Golaszewski --- diff --git a/bindings/python/gpiodmodule.c b/bindings/python/gpiodmodule.c index 4723771..8369ff0 100644 --- a/bindings/python/gpiodmodule.c +++ b/bindings/python/gpiodmodule.c @@ -1216,6 +1216,42 @@ static PyObject *gpiod_LineBulk_get_values(gpiod_LineBulkObject *self, return val_list; } +static int gpiod_TupleToIntArray(PyObject *src, int *dst, Py_ssize_t nv) +{ + Py_ssize_t num_vals, i; + PyObject *iter, *next; + int val; + + num_vals = PyObject_Size(src); + if (num_vals != nv) { + PyErr_SetString(PyExc_TypeError, + "Number of values must correspond to the number of lines"); + return -1; + } + + iter = PyObject_GetIter(src); + if (!iter) + return -1; + + for (i = 0;; i++) { + next = PyIter_Next(iter); + if (!next) { + Py_DECREF(iter); + break; + } + + val = PyLong_AsLong(next); + Py_DECREF(next); + if (PyErr_Occurred()) { + Py_DECREF(iter); + return -1; + } + dst[i] = (int)val; + } + + return 0; +} + PyDoc_STRVAR(gpiod_LineBulk_set_values_doc, "set_values(values) -> None\n" "\n" @@ -1231,10 +1267,9 @@ PyDoc_STRVAR(gpiod_LineBulk_set_values_doc, static PyObject *gpiod_LineBulk_set_values(gpiod_LineBulkObject *self, PyObject *args) { - int rv, vals[GPIOD_LINE_BULK_MAX_LINES], val; - PyObject *val_list, *iter, *next; + int rv, vals[GPIOD_LINE_BULK_MAX_LINES]; struct gpiod_line_bulk bulk; - Py_ssize_t num_vals, i; + PyObject *val_list; if (gpiod_LineBulkOwnerIsClosed(self)) return NULL; @@ -1246,34 +1281,10 @@ static PyObject *gpiod_LineBulk_set_values(gpiod_LineBulkObject *self, if (!rv) return NULL; - num_vals = PyObject_Size(val_list); - if (self->num_lines != num_vals) { - PyErr_SetString(PyExc_TypeError, - "Number of values must correspond to the number of lines"); - return NULL; - } - - iter = PyObject_GetIter(val_list); - if (!iter) + rv = gpiod_TupleToIntArray(val_list, vals, self->num_lines); + if (rv) return NULL; - for (i = 0;; i++) { - next = PyIter_Next(iter); - if (!next) { - Py_DECREF(iter); - break; - } - - val = PyLong_AsLong(next); - Py_DECREF(next); - if (PyErr_Occurred()) { - Py_DECREF(iter); - return NULL; - } - - vals[i] = (int)val; - } - Py_BEGIN_ALLOW_THREADS; rv = gpiod_line_set_value_bulk(&bulk, vals); Py_END_ALLOW_THREADS;