[Python-checkins] cpython: Beautify and better document the use of the size_t cast for bounds checking.

raymond.hettinger python-checkins at python.org
Tue Mar 3 06:45:11 CET 2015


https://hg.python.org/cpython/rev/8c1d4ab76db0
changeset: 94837:8c1d4ab76db0
user: Raymond Hettinger <python at rcn.com>
date: Mon Mar 02 21:45:02 2015 -0800
summary:
 Beautify and better document the use of the size_t cast for bounds checking.
files:
 Modules/_collectionsmodule.c | 18 ++++++++++++------
 1 files changed, 12 insertions(+), 6 deletions(-)
diff --git a/Modules/_collectionsmodule.c b/Modules/_collectionsmodule.c
--- a/Modules/_collectionsmodule.c
+++ b/Modules/_collectionsmodule.c
@@ -765,6 +765,14 @@
 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 @@
 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 @@
 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)
-- 
Repository URL: https://hg.python.org/cpython


More information about the Python-checkins mailing list

AltStyle によって変換されたページ (->オリジナル) /