Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Include/internal/pycore_list.h
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ extern "C" {
PyAPI_FUNC(PyObject*) _PyList_Extend(PyListObject *, PyObject *);
PyAPI_FUNC(PyObject) *_PyList_SliceSubscript(PyObject*, PyObject*);
PyAPI_FUNC(PyObject *) _PyList_BinarySlice(PyObject *, PyObject *, PyObject *);
PyAPI_FUNC(int) _PyList_StoreSlice(PyObject *container, PyObject *start,
PyObject *stop, PyObject *value);
PyAPI_FUNC(PyObject *) _PyList_Concat(PyObject *, PyObject *);
extern void _PyList_DebugMallocStats(FILE *out);
// _PyList_GetItemRef should be used only when the object is known as a list
Expand Down
11 changes: 11 additions & 0 deletions Lib/test/test_capi/test_slice.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import itertools
import sys
import unittest
from test.support import import_helper
Expand Down Expand Up @@ -180,6 +181,16 @@ def test_adjustindices(self):
# CRASHES adjust(10, 0, 10, 0)
# CRASHES adjust(10, 0, 10, SSIZE_MIN)

def test_adjustindices_unit_step(self):
adjust = _testlimitedcapi.slice_adjustindices
bounds = range(-12, 12)
for start, stop, end in itertools.product(bounds, repeat=3):
length = end - bounds.start # sequence lengths from 0 to 23
for step in (-1, 1):
lo, hi, _ = slice(start, stop, step).indices(length)
self.assertEqual(adjust(length, start, stop, step),
(len(range(lo, hi, step)), lo, hi))


class GetIndicesExMacroTest(unittest.TestCase):
# PySlice_GetIndicesEx() is a macro using PySlice_Unpack() and
Expand Down
114 changes: 114 additions & 0 deletions Lib/test/test_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -429,5 +429,119 @@ def foo(x):
self.assertEqual(foo(list(range(10))), 45)


class ListStoreSliceTests(unittest.TestCase):
def test_equal_length(self):
for n in (0, 1, 8, 16, 32, 33, 40):
for rhs in (list, tuple):
with self.subTest(n=n, rhs=rhs):
a = list(range(n + 2))
a[1:1+n] = rhs(a[n:0:-1])
self.assertEqual(a, [0, *range(n, 0, -1), n + 1])

def test_self_assignment(self):
a = [1, 2, 3, 4]
a[:] = a
self.assertEqual(a, [1, 2, 3, 4])
a[1:3] = a
self.assertEqual(a, [1, 1, 2, 3, 4, 4])

def test_index_protocol(self):
class Idx:
def __index__(self):
return -2

a = [0, 1, 2]
a[True:2] = [7]
self.assertEqual(a, [0, 7, 2])
a[Idx():2] = (8,)
self.assertEqual(a, [0, 8, 2])

def test_bad_index(self):
a = [1, 2, 3]
msg = "slice indices must be integers or have an __index__ method"
for start, stop in ((object(), 2), (1, object())):
with self.assertRaises(TypeError) as cm:
a[start:stop] = None
self.assertEqual(str(cm.exception), msg)
self.assertEqual(a, [1, 2, 3])

def test_non_iterable(self):
a = [1, 2, 3]
with self.assertRaises(TypeError) as cm:
a[:2] = None
self.assertEqual(str(cm.exception),
"must assign iterable to extended slice")
self.assertEqual(a, [1, 2, 3])

def test_resize_and_insert(self):
a = list(range(6))
a[5:2] = [99]
self.assertEqual(a, [0, 1, 2, 3, 4, 99, 5])
a[1:2] = (7, 8)
self.assertEqual(a, [0, 7, 8, 2, 3, 4, 99, 5])
a[1:4] = (9,)
self.assertEqual(a, [0, 9, 3, 4, 99, 5])

def test_iterator_mutates_target(self):
a = list(range(10))

def gen():
yield 100
a.clear()
yield 200

a[2:8] = gen()
self.assertEqual(a, [100, 200])

@cpython_only
def test_finalizers_see_replacement(self):
seen = []

class D:
def __init__(self, i):
self.i = i

def __del__(self):
seen.append((self.i, tuple(a[:3])))
a.append(self.i)

a = [D(i) for i in range(3)]
a[:3] = [5, 6, 7]
self.assertEqual(seen, [(i, (5, 6, 7)) for i in (2, 1, 0)])
self.assertEqual(a, [5, 6, 7, 2, 1, 0])

@cpython_only
def test_bound_finalizer_order(self):
seen = []

class Idx:
def __init__(self, i):
self.i = i

def __index__(self):
return self.i

def __del__(self):
seen.append(self.i)

a = [0, 1, 2]
a[Idx(0):Idx(1)] = [8]
self.assertEqual(a, [8, 1, 2])
self.assertEqual(seen, [0, 1])

def test_list_subclass(self):
seen = []

class MyList(list):
def __setitem__(self, key, value):
seen.append(key)
super().__setitem__(key, value)

a = MyList([1, 2, 3, 4])
a[1:3] = [8, 9]
self.assertEqual(a, [1, 8, 9, 4])
self.assertEqual(seen, [slice(1, 3)])


if __name__ == "__main__":
unittest.main()
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Speed up slice assignment on lists and index adjustment for unit-step slices.
54 changes: 37 additions & 17 deletions Modules/_testinternalcapi/test_cases.c.h

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

92 changes: 92 additions & 0 deletions Objects/listobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -3975,6 +3975,98 @@ list_ass_subscript_lock_held(PyObject *_self, PyObject *item, PyObject *value)
}
}

#define LIST_SMALL_SLICE_INPLACE_MAX 32

static inline void
list_replace_small_slice_inplace(PyListObject *self, Py_ssize_t start,
Py_ssize_t len, PyObject *const *src)
{
PyObject *garbage[LIST_SMALL_SLICE_INPLACE_MAX];
PyObject **dst = self->ob_item + start;
for (Py_ssize_t i = 0; i < len; i++) {
garbage[i] = dst[i];
FT_ATOMIC_STORE_PTR_RELEASE(dst[i], Py_NewRef(src[i]));
}
/* A finalizer can inspect or resize the list. */
for (Py_ssize_t i = len - 1; i >= 0; i--) {
Py_DECREF(garbage[i]);
}
}

static inline int
list_slice_index_fast(PyObject *obj, Py_ssize_t defval, Py_ssize_t *out)
{
if (Py_IsNone(obj)) {
*out = defval;
return 1;
}
if (PyLong_CheckExact(obj) && _PyLong_IsCompact((PyLongObject *)obj)) {
*out = _PyLong_CompactValue((PyLongObject *)obj);
return 1;
}
return _PyEval_SliceIndex(obj, out);
}

static int
list_store_slice_lock_held(PyListObject *self, Py_ssize_t start,
Py_ssize_t stop, PyObject *value)
{
assert(value != NULL);
if ((PyObject *)self != value &&
(PyList_CheckExact(value) || PyTuple_CheckExact(value)))
{
Py_ssize_t len = adjust_slice_indexes(self, &start, &stop, 1);
if (len > 0 && len <= LIST_SMALL_SLICE_INPLACE_MAX &&
len == Py_SIZE(value))
{
list_replace_small_slice_inplace(self, start, len,
PySequence_Fast_ITEMS(value));
return 0;
}
return list_ass_slice_lock_held(self, start, stop, value);
}

PyObject *seq = ((PyObject *)self == value)
? list_slice_lock_held(self, 0, Py_SIZE(self))
: PySequence_Fast(value, "must assign iterable to extended slice");
if (seq == NULL) {
return -1;
}
/* The iterator may have changed the list length. */
adjust_slice_indexes(self, &start, &stop, 1);
int res = list_ass_slice_lock_held(self, start, stop, seq);
Py_DECREF(seq);
return res;
}

int
_PyList_StoreSlice(PyObject *container, PyObject *start, PyObject *stop,
PyObject *value)
{
assert(value != NULL);
assert(PyList_CheckExact(container));
Py_ssize_t istart, istop;
if (!list_slice_index_fast(start, 0, &istart) ||
!list_slice_index_fast(stop, PY_SSIZE_T_MAX, &istop))
{
return -1;
}
PyListObject *self = (PyListObject *)container;
int res;
#ifdef Py_GIL_DISABLED
if (PyList_CheckExact(value)) {
Py_BEGIN_CRITICAL_SECTION2(container, value);
res = list_store_slice_lock_held(self, istart, istop, value);
Py_END_CRITICAL_SECTION2();
return res;
}
#endif
Py_BEGIN_CRITICAL_SECTION(container);
res = list_store_slice_lock_held(self, istart, istop, value);
Py_END_CRITICAL_SECTION();
return res;
}

static int
list_ass_subscript(PyObject *self, PyObject *item, PyObject *value)
{
Expand Down
29 changes: 26 additions & 3 deletions Objects/sliceobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,16 @@ PySlice_GetIndices(PyObject *_r, Py_ssize_t length,
return 0;
}

static inline int
slice_index_fast(PyObject *v, Py_ssize_t *pi)
{
if (PyLong_CheckExact(v) && _PyLong_IsCompact((PyLongObject *)v)) {
*pi = _PyLong_CompactValue((PyLongObject *)v);
return 1;
}
return _PyEval_SliceIndex(v, pi);
}

int
PySlice_Unpack(PyObject *_r,
Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step)
Expand All @@ -228,7 +238,9 @@ PySlice_Unpack(PyObject *_r,
*step = 1;
}
else {
if (!_PyEval_SliceIndex(r->step, step)) return -1;
if (!slice_index_fast(r->step, step)) {
return -1;
}
if (*step == 0) {
PyErr_SetString(PyExc_ValueError,
"slice step cannot be zero");
Expand All @@ -247,14 +259,18 @@ PySlice_Unpack(PyObject *_r,
*start = *step < 0 ? PY_SSIZE_T_MAX : 0;
}
else {
if (!_PyEval_SliceIndex(r->start, start)) return -1;
if (!slice_index_fast(r->start, start)) {
return -1;
}
}

if (r->stop == Py_None) {
*stop = *step < 0 ? PY_SSIZE_T_MIN : PY_SSIZE_T_MAX;
}
else {
if (!_PyEval_SliceIndex(r->stop, stop)) return -1;
if (!slice_index_fast(r->stop, stop)) {
return -1;
}
}

return 0;
Expand Down Expand Up @@ -289,6 +305,13 @@ PySlice_AdjustIndices(Py_ssize_t length,
*stop = (step < 0) ? length - 1 : length;
}

/* For unit steps the general formula reduces to a difference. */
if (step == 1) {
return *start < *stop ? *stop - *start : 0;
}
if (step == -1) {
return *stop < *start ? *start - *stop : 0;
}
if (step < 0) {
if (*stop < *start) {
return (*start - *stop - 1) / (-step) + 1;
Expand Down
Loading
Loading