From 6d121f168cca9df59fe4b3908cecbc346e185650 Mon Sep 17 00:00:00 2001
From: Raymond Hettinger <python@rcn.com>
Date: Thu, 8 Feb 2007 00:07:32 +0000
Subject: Do not let overflows in enumerate() and count() pass silently.

---
 Lib/test/test_itertools.py | 3 +--
 Modules/itertoolsmodule.c  | 5 +++++
 Objects/enumobject.c       | 6 ++++++
 3 files changed, 12 insertions(+), 2 deletions(-)

diff --git a/Lib/test/test_itertools.py b/Lib/test/test_itertools.py
index 5e375c9..c965d4c 100644
--- a/Lib/test/test_itertools.py
+++ b/Lib/test/test_itertools.py
@@ -52,8 +52,7 @@ class TestBasicOps(unittest.TestCase):
         self.assertEqual(take(2, zip('abc',count(3))), [('a', 3), ('b', 4)])
         self.assertRaises(TypeError, count, 2, 3)
         self.assertRaises(TypeError, count, 'a')
-        c = count(sys.maxint-2)   # verify that rollover doesn't crash
-        c.next(); c.next(); c.next(); c.next(); c.next()
+        self.assertRaises(OverflowError, list, islice(count(sys.maxint-5), 10))
         c = count(3)
         self.assertEqual(repr(c), 'count(3)')
         c.next()
diff --git a/Modules/itertoolsmodule.c b/Modules/itertoolsmodule.c
index 7896143..70f787f 100644
--- a/Modules/itertoolsmodule.c
+++ b/Modules/itertoolsmodule.c
@@ -2073,6 +2073,11 @@ count_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
 static PyObject *
 count_next(countobject *lz)
 {
+        if (lz->cnt == LONG_MAX) {
+                PyErr_SetString(PyExc_OverflowError,
+                        "cannot count beyond LONG_MAX");                
+                return NULL;         
+        }
 	return PyInt_FromSsize_t(lz->cnt++);
 }
 
diff --git a/Objects/enumobject.c b/Objects/enumobject.c
index a8f43e0..a456c9d 100644
--- a/Objects/enumobject.c
+++ b/Objects/enumobject.c
@@ -62,6 +62,12 @@ enum_next(enumobject *en)
 	PyObject *result = en->en_result;
 	PyObject *it = en->en_sit;
 
+	if (en->en_index == LONG_MAX) {
+		PyErr_SetString(PyExc_OverflowError,
+			"enumerate() is limited to LONG_MAX items");                
+		return NULL;         
+	}
+
 	next_item = (*it->ob_type->tp_iternext)(it);
 	if (next_item == NULL)
 		return NULL;
-- 
cgit v0.12

