From: Gerhard Sittig Date: Sun, 17 Dec 2017 17:50:25 +0000 (+0100) Subject: decoder: rephrase .has_channel() argument parse logic X-Git-Url: https://sigrok.org/gitaction?a=commitdiff_plain;h=cd8d918846a00847f2e8e15ba1642882c34a1ff3;p=libsigrokdecode.git decoder: rephrase .has_channel() argument parse logic Have the Python C API check the argument type and do the type conversion already. Raise an IndexError exception when the range check fails. --- diff --git a/type_decoder.c b/type_decoder.c index 0d21951..7c71132 100644 --- a/type_decoder.c +++ b/type_decoder.c @@ -855,9 +855,8 @@ err: */ static PyObject *Decoder_has_channel(PyObject *self, PyObject *args) { - int idx, max_idx; + int idx, count; struct srd_decoder_inst *di; - PyObject *py_channel; PyGILState_STATE gstate; if (!self || !args) @@ -870,24 +869,20 @@ static PyObject *Decoder_has_channel(PyObject *self, PyObject *args) goto err; } - /* Parse the argument of self.has_channel() into 'py_channel'. */ - if (!PyArg_ParseTuple(args, "O", &py_channel)) { + /* + * Get the integer argument of self.has_channel(). Check for + * the range of supported PD input channel numbers. + */ + if (!PyArg_ParseTuple(args, "i", &idx)) { /* Let Python raise this exception. */ goto err; } - if (!PyLong_Check(py_channel)) { - PyErr_SetString(PyExc_Exception, "channel index not a number"); - goto err; - } - - idx = PyLong_AsLong(py_channel); - max_idx = g_slist_length(di->decoder->channels) - + g_slist_length(di->decoder->opt_channels) - 1; - - if (idx < 0 || idx > max_idx) { - srd_err("Invalid channel index %d/%d.", idx, max_idx); - PyErr_SetString(PyExc_Exception, "invalid channel"); + count = g_slist_length(di->decoder->channels) + + g_slist_length(di->decoder->opt_channels); + if (idx < 0 || idx >= count) { + srd_err("Invalid index %d, PD channel count %d.", idx, count); + PyErr_SetString(PyExc_IndexError, "invalid channel index"); goto err; }