Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 92709a2

Browse files
sir-sigurdYhg1s
authored andcommitted
bpo-37840: Fix handling of negative indices in bytearray_getitem() (GH-15250)
1 parent 915cd3f commit 92709a2

File tree

4 files changed

+24
-2
lines changed

4 files changed

+24
-2
lines changed

Lib/test/test_bytes.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -962,6 +962,15 @@ def test_translate(self):
962962
c = b.translate(None, delete=b'e')
963963
self.assertEqual(c, b'hllo')
964964

965+
def test_sq_item(self):
966+
_testcapi = test.support.import_module('_testcapi')
967+
obj = self.type2test((42,))
968+
with self.assertRaises(IndexError):
969+
_testcapi.sequence_getitem(obj, -2)
970+
with self.assertRaises(IndexError):
971+
_testcapi.sequence_getitem(obj, 1)
972+
self.assertEqual(_testcapi.sequence_getitem(obj, 0), 42)
973+
965974

966975
class BytesTest(BaseBytesTest, unittest.TestCase):
967976
type2test = bytes
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix handling of negative indices in :c:member:`~PySequenceMethods.sq_item`
2+
of :class:`bytearray`. Patch by Sergey Fedoseev.

Modules/_testcapimodule.c

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5164,6 +5164,18 @@ test_write_unraisable_exc(PyObject *self, PyObject *args)
51645164
}
51655165

51665166

5167+
static PyObject *
5168+
sequence_getitem(PyObject *self, PyObject *args)
5169+
{
5170+
PyObject *seq;
5171+
Py_ssize_t i;
5172+
if (!PyArg_ParseTuple(args, "On", &seq, &i)) {
5173+
return NULL;
5174+
}
5175+
return PySequence_GetItem(seq, i);
5176+
}
5177+
5178+
51675179
static PyMethodDef TestMethods[] = {
51685180
{"raise_exception", raise_exception, METH_VARARGS},
51695181
{"raise_memoryerror", raise_memoryerror, METH_NOARGS},
@@ -5413,6 +5425,7 @@ static PyMethodDef TestMethods[] = {
54135425
{"negative_refcount", negative_refcount, METH_NOARGS},
54145426
#endif
54155427
{"write_unraisable_exc", test_write_unraisable_exc, METH_VARARGS},
5428+
{"sequence_getitem", sequence_getitem, METH_VARARGS},
54165429
{NULL, NULL} /* sentinel */
54175430
};
54185431

Objects/bytearrayobject.c

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -381,8 +381,6 @@ bytearray_irepeat(PyByteArrayObject *self, Py_ssize_t count)
381381
static PyObject *
382382
bytearray_getitem(PyByteArrayObject *self, Py_ssize_t i)
383383
{
384-
if (i < 0)
385-
i += Py_SIZE(self);
386384
if (i < 0 || i >= Py_SIZE(self)) {
387385
PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
388386
return NULL;

0 commit comments

Comments
 (0)