Commit 92709a26 authored by Sergey Fedoseev's avatar Sergey Fedoseev Committed by T. Wouters

bpo-37840: Fix handling of negative indices in bytearray_getitem() (GH-15250)

parent 915cd3f0
...@@ -962,6 +962,15 @@ class BaseBytesTest: ...@@ -962,6 +962,15 @@ class BaseBytesTest:
c = b.translate(None, delete=b'e') c = b.translate(None, delete=b'e')
self.assertEqual(c, b'hllo') self.assertEqual(c, b'hllo')
def test_sq_item(self):
_testcapi = test.support.import_module('_testcapi')
obj = self.type2test((42,))
with self.assertRaises(IndexError):
_testcapi.sequence_getitem(obj, -2)
with self.assertRaises(IndexError):
_testcapi.sequence_getitem(obj, 1)
self.assertEqual(_testcapi.sequence_getitem(obj, 0), 42)
class BytesTest(BaseBytesTest, unittest.TestCase): class BytesTest(BaseBytesTest, unittest.TestCase):
type2test = bytes type2test = bytes
......
Fix handling of negative indices in :c:member:`~PySequenceMethods.sq_item`
of :class:`bytearray`. Patch by Sergey Fedoseev.
...@@ -5164,6 +5164,18 @@ test_write_unraisable_exc(PyObject *self, PyObject *args) ...@@ -5164,6 +5164,18 @@ test_write_unraisable_exc(PyObject *self, PyObject *args)
} }
static PyObject *
sequence_getitem(PyObject *self, PyObject *args)
{
PyObject *seq;
Py_ssize_t i;
if (!PyArg_ParseTuple(args, "On", &seq, &i)) {
return NULL;
}
return PySequence_GetItem(seq, i);
}
static PyMethodDef TestMethods[] = { static PyMethodDef TestMethods[] = {
{"raise_exception", raise_exception, METH_VARARGS}, {"raise_exception", raise_exception, METH_VARARGS},
{"raise_memoryerror", raise_memoryerror, METH_NOARGS}, {"raise_memoryerror", raise_memoryerror, METH_NOARGS},
...@@ -5413,6 +5425,7 @@ static PyMethodDef TestMethods[] = { ...@@ -5413,6 +5425,7 @@ static PyMethodDef TestMethods[] = {
{"negative_refcount", negative_refcount, METH_NOARGS}, {"negative_refcount", negative_refcount, METH_NOARGS},
#endif #endif
{"write_unraisable_exc", test_write_unraisable_exc, METH_VARARGS}, {"write_unraisable_exc", test_write_unraisable_exc, METH_VARARGS},
{"sequence_getitem", sequence_getitem, METH_VARARGS},
{NULL, NULL} /* sentinel */ {NULL, NULL} /* sentinel */
}; };
......
...@@ -381,8 +381,6 @@ bytearray_irepeat(PyByteArrayObject *self, Py_ssize_t count) ...@@ -381,8 +381,6 @@ bytearray_irepeat(PyByteArrayObject *self, Py_ssize_t count)
static PyObject * static PyObject *
bytearray_getitem(PyByteArrayObject *self, Py_ssize_t i) bytearray_getitem(PyByteArrayObject *self, Py_ssize_t i)
{ {
if (i < 0)
i += Py_SIZE(self);
if (i < 0 || i >= Py_SIZE(self)) { if (i < 0 || i >= Py_SIZE(self)) {
PyErr_SetString(PyExc_IndexError, "bytearray index out of range"); PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
return NULL; return NULL;
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment