[libgpiod,v4,11/20] bindings: python: move tuple to int array conversion into helper function
diff mbox series

Message ID 20191201032407.23589-12-warthog618@gmail.com
State New
Headers show
Series
  • Add support for bias flags and SET_CONFIG
Related show

Commit Message

Kent Gibson Dec. 1, 2019, 3:23 a.m. UTC
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 <warthog618@gmail.com>
---
 bindings/python/gpiodmodule.c | 65 +++++++++++++++++++----------------
 1 file changed, 36 insertions(+), 29 deletions(-)

Patch
diff mbox series

diff --git a/bindings/python/gpiodmodule.c b/bindings/python/gpiodmodule.c
index 4723771..d87edb7 100644
--- a/bindings/python/gpiodmodule.c
+++ b/bindings/python/gpiodmodule.c
@@ -1216,6 +1216,38 @@  static PyObject *gpiod_LineBulk_get_values(gpiod_LineBulkObject *self,
 	return val_list;
 }
 
+static int gpiod_TupleToIntArray(PyObject *src, int *dst, Py_ssize_t n)
+{
+	int val;
+	Py_ssize_t num_vals, i;
+	PyObject *iter, *next;
+
+	num_vals = PyObject_Size(src);
+	if (num_vals != n) {
+		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 +1263,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];
+	PyObject *val_list;
 	struct gpiod_line_bulk bulk;
-	Py_ssize_t num_vals, i;
 
 	if (gpiod_LineBulkOwnerIsClosed(self))
 		return NULL;
@@ -1246,34 +1277,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;