summaryrefslogtreecommitdiffstats
path: root/Modules/_collectionsmodule.c
diff options
context:
space:
mode:
authorRaymond Hettinger <python@rcn.com>2015-03-03 05:45:02 (GMT)
committerRaymond Hettinger <python@rcn.com>2015-03-03 05:45:02 (GMT)
commit3c186ba4412c043a36eb63c0b524d76223497ffd (patch)
tree7f466bba0de08d0df97f915fc95112c4947bbe2c /Modules/_collectionsmodule.c
parent738f8050747ea616d0708ce0a74322ba47dd15e6 (diff)
downloadcpython-3c186ba4412c043a36eb63c0b524d76223497ffd.zip
cpython-3c186ba4412c043a36eb63c0b524d76223497ffd.tar.gz
cpython-3c186ba4412c043a36eb63c0b524d76223497ffd.tar.bz2
Beautify and better document the use of the size_t cast for bounds checking.
Diffstat (limited to 'Modules/_collectionsmodule.c')
-rw-r--r--Modules/_collectionsmodule.c18
1 files changed, 12 insertions, 6 deletions
diff --git a/Modules/_collectionsmodule.c b/Modules/_collectionsmodule.c
index 69814bb..579c37c 100644
--- a/Modules/_collectionsmodule.c
+++ b/Modules/_collectionsmodule.c
@@ -765,6 +765,14 @@ deque_clear(dequeobject *deque)
Py_SIZE(deque) == 0);
}
+static int
+valid_index(Py_ssize_t i, Py_ssize_t limit)
+{
+ /* The cast to size_t let us use just a single comparison
+ to check whether i is in the range: 0 <= i < limit */
+ return (size_t) i < (size_t) limit;
+}
+
static PyObject *
deque_item(dequeobject *deque, Py_ssize_t i)
{
@@ -772,9 +780,8 @@ deque_item(dequeobject *deque, Py_ssize_t i)
PyObject *item;
Py_ssize_t n, index=i;
- if ((size_t)i >= (size_t)Py_SIZE(deque)) {
- PyErr_SetString(PyExc_IndexError,
- "deque index out of range");
+ if (!valid_index(i, Py_SIZE(deque))) {
+ PyErr_SetString(PyExc_IndexError, "deque index out of range");
return NULL;
}
@@ -836,9 +843,8 @@ deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
block *b;
Py_ssize_t n, len=Py_SIZE(deque), halflen=(len+1)>>1, index=i;
- if ((size_t)i >= (size_t)len) {
- PyErr_SetString(PyExc_IndexError,
- "deque index out of range");
+ if (!valid_index(i, len)) {
+ PyErr_SetString(PyExc_IndexError, "deque index out of range");
return -1;
}
if (v == NULL)