Skip to content

Commit 5bbcce1

Browse files
committed
gh-162784: Add list fast path for STORE_SLICE and slice helpers
STORE_SLICE list fast path Skip the temporary slice for exact lists. Stage displaced references for equal-length replacements of up to 32 items and release them after all writes. Preserve bound finalization order and iterable conversion errors. Slice helpers Unpack compact integer bounds directly and use a difference to count unit-step slices after normalization.
1 parent d88a6b9 commit 5bbcce1

10 files changed

Lines changed: 377 additions & 67 deletions

File tree

‎Include/internal/pycore_list.h‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@ extern "C" {
1515
PyAPI_FUNC(PyObject*) _PyList_Extend(PyListObject *, PyObject *);
1616
PyAPI_FUNC(PyObject) *_PyList_SliceSubscript(PyObject*, PyObject*);
1717
PyAPI_FUNC(PyObject *) _PyList_BinarySlice(PyObject *, PyObject *, PyObject *);
18+
PyAPI_FUNC(int) _PyList_StoreSlice(PyObject *container, PyObject *start,
19+
PyObject *stop, PyObject *value);
1820
PyAPI_FUNC(PyObject *) _PyList_Concat(PyObject *, PyObject *);
1921
extern void _PyList_DebugMallocStats(FILE *out);
2022
// _PyList_GetItemRef should be used only when the object is known as a list

‎Lib/test/test_capi/test_slice.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import itertools
12
import sys
23
import unittest
34
from test.support import import_helper
@@ -180,6 +181,16 @@ def test_adjustindices(self):
180181
# CRASHES adjust(10, 0, 10, 0)
181182
# CRASHES adjust(10, 0, 10, SSIZE_MIN)
182183

184+
def test_adjustindices_unit_step(self):
185+
adjust = _testlimitedcapi.slice_adjustindices
186+
bounds = range(-12, 12)
187+
for start, stop, end in itertools.product(bounds, repeat=3):
188+
length = end - bounds.start # sequence lengths from 0 to 23
189+
for step in (-1, 1):
190+
lo, hi, _ = slice(start, stop, step).indices(length)
191+
self.assertEqual(adjust(length, start, stop, step),
192+
(len(range(lo, hi, step)), lo, hi))
193+
183194

184195
class GetIndicesExMacroTest(unittest.TestCase):
185196
# PySlice_GetIndicesEx() is a macro using PySlice_Unpack() and

‎Lib/test/test_list.py‎

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -429,5 +429,119 @@ def foo(x):
429429
self.assertEqual(foo(list(range(10))), 45)
430430

431431

432+
class ListStoreSliceTests(unittest.TestCase):
433+
def test_equal_length(self):
434+
for n in (0, 1, 8, 16, 32, 33, 40):
435+
for rhs in (list, tuple):
436+
with self.subTest(n=n, rhs=rhs):
437+
a = list(range(n + 2))
438+
a[1:1+n] = rhs(a[n:0:-1])
439+
self.assertEqual(a, [0, *range(n, 0, -1), n + 1])
440+
441+
def test_self_assignment(self):
442+
a = [1, 2, 3, 4]
443+
a[:] = a
444+
self.assertEqual(a, [1, 2, 3, 4])
445+
a[1:3] = a
446+
self.assertEqual(a, [1, 1, 2, 3, 4, 4])
447+
448+
def test_index_protocol(self):
449+
class Idx:
450+
def __index__(self):
451+
return -2
452+
453+
a = [0, 1, 2]
454+
a[True:2] = [7]
455+
self.assertEqual(a, [0, 7, 2])
456+
a[Idx():2] = (8,)
457+
self.assertEqual(a, [0, 8, 2])
458+
459+
def test_bad_index(self):
460+
a = [1, 2, 3]
461+
msg = "slice indices must be integers or have an __index__ method"
462+
for start, stop in ((object(), 2), (1, object())):
463+
with self.assertRaises(TypeError) as cm:
464+
a[start:stop] = None
465+
self.assertEqual(str(cm.exception), msg)
466+
self.assertEqual(a, [1, 2, 3])
467+
468+
def test_non_iterable(self):
469+
a = [1, 2, 3]
470+
with self.assertRaises(TypeError) as cm:
471+
a[:2] = None
472+
self.assertEqual(str(cm.exception),
473+
"must assign iterable to extended slice")
474+
self.assertEqual(a, [1, 2, 3])
475+
476+
def test_resize_and_insert(self):
477+
a = list(range(6))
478+
a[5:2] = [99]
479+
self.assertEqual(a, [0, 1, 2, 3, 4, 99, 5])
480+
a[1:2] = (7, 8)
481+
self.assertEqual(a, [0, 7, 8, 2, 3, 4, 99, 5])
482+
a[1:4] = (9,)
483+
self.assertEqual(a, [0, 9, 3, 4, 99, 5])
484+
485+
def test_iterator_mutates_target(self):
486+
a = list(range(10))
487+
488+
def gen():
489+
yield 100
490+
a.clear()
491+
yield 200
492+
493+
a[2:8] = gen()
494+
self.assertEqual(a, [100, 200])
495+
496+
@cpython_only
497+
def test_finalizers_see_replacement(self):
498+
seen = []
499+
500+
class D:
501+
def __init__(self, i):
502+
self.i = i
503+
504+
def __del__(self):
505+
seen.append((self.i, tuple(a[:3])))
506+
a.append(self.i)
507+
508+
a = [D(i) for i in range(3)]
509+
a[:3] = [5, 6, 7]
510+
self.assertEqual(seen, [(i, (5, 6, 7)) for i in (2, 1, 0)])
511+
self.assertEqual(a, [5, 6, 7, 2, 1, 0])
512+
513+
@cpython_only
514+
def test_bound_finalizer_order(self):
515+
seen = []
516+
517+
class Idx:
518+
def __init__(self, i):
519+
self.i = i
520+
521+
def __index__(self):
522+
return self.i
523+
524+
def __del__(self):
525+
seen.append(self.i)
526+
527+
a = [0, 1, 2]
528+
a[Idx(0):Idx(1)] = [8]
529+
self.assertEqual(a, [8, 1, 2])
530+
self.assertEqual(seen, [0, 1])
531+
532+
def test_list_subclass(self):
533+
seen = []
534+
535+
class MyList(list):
536+
def __setitem__(self, key, value):
537+
seen.append(key)
538+
super().__setitem__(key, value)
539+
540+
a = MyList([1, 2, 3, 4])
541+
a[1:3] = [8, 9]
542+
self.assertEqual(a, [1, 8, 9, 4])
543+
self.assertEqual(seen, [slice(1, 3)])
544+
545+
432546
if __name__ == "__main__":
433547
unittest.main()
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Speed up slice assignment on lists and index adjustment for unit-step slices.

‎Modules/_testinternalcapi/test_cases.c.h‎

Lines changed: 37 additions & 17 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Objects/listobject.c‎

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3975,6 +3975,98 @@ list_ass_subscript_lock_held(PyObject *_self, PyObject *item, PyObject *value)
39753975
}
39763976
}
39773977

3978+
#define LIST_SMALL_SLICE_INPLACE_MAX 32
3979+
3980+
static inline void
3981+
list_replace_small_slice_inplace(PyListObject *self, Py_ssize_t start,
3982+
Py_ssize_t len, PyObject *const *src)
3983+
{
3984+
PyObject *garbage[LIST_SMALL_SLICE_INPLACE_MAX];
3985+
PyObject **dst = self->ob_item + start;
3986+
for (Py_ssize_t i = 0; i < len; i++) {
3987+
garbage[i] = dst[i];
3988+
FT_ATOMIC_STORE_PTR_RELEASE(dst[i], Py_NewRef(src[i]));
3989+
}
3990+
/* A finalizer can inspect or resize the list. */
3991+
for (Py_ssize_t i = len - 1; i >= 0; i--) {
3992+
Py_DECREF(garbage[i]);
3993+
}
3994+
}
3995+
3996+
static inline int
3997+
list_slice_index_fast(PyObject *obj, Py_ssize_t defval, Py_ssize_t *out)
3998+
{
3999+
if (Py_IsNone(obj)) {
4000+
*out = defval;
4001+
return 1;
4002+
}
4003+
if (PyLong_CheckExact(obj) && _PyLong_IsCompact((PyLongObject *)obj)) {
4004+
*out = _PyLong_CompactValue((PyLongObject *)obj);
4005+
return 1;
4006+
}
4007+
return _PyEval_SliceIndex(obj, out);
4008+
}
4009+
4010+
static int
4011+
list_store_slice_lock_held(PyListObject *self, Py_ssize_t start,
4012+
Py_ssize_t stop, PyObject *value)
4013+
{
4014+
assert(value != NULL);
4015+
if ((PyObject *)self != value &&
4016+
(PyList_CheckExact(value) || PyTuple_CheckExact(value)))
4017+
{
4018+
Py_ssize_t len = adjust_slice_indexes(self, &start, &stop, 1);
4019+
if (len > 0 && len <= LIST_SMALL_SLICE_INPLACE_MAX &&
4020+
len == Py_SIZE(value))
4021+
{
4022+
list_replace_small_slice_inplace(self, start, len,
4023+
PySequence_Fast_ITEMS(value));
4024+
return 0;
4025+
}
4026+
return list_ass_slice_lock_held(self, start, stop, value);
4027+
}
4028+
4029+
PyObject *seq = ((PyObject *)self == value)
4030+
? list_slice_lock_held(self, 0, Py_SIZE(self))
4031+
: PySequence_Fast(value, "must assign iterable to extended slice");
4032+
if (seq == NULL) {
4033+
return -1;
4034+
}
4035+
/* The iterator may have changed the list length. */
4036+
adjust_slice_indexes(self, &start, &stop, 1);
4037+
int res = list_ass_slice_lock_held(self, start, stop, seq);
4038+
Py_DECREF(seq);
4039+
return res;
4040+
}
4041+
4042+
int
4043+
_PyList_StoreSlice(PyObject *container, PyObject *start, PyObject *stop,
4044+
PyObject *value)
4045+
{
4046+
assert(value != NULL);
4047+
assert(PyList_CheckExact(container));
4048+
Py_ssize_t istart, istop;
4049+
if (!list_slice_index_fast(start, 0, &istart) ||
4050+
!list_slice_index_fast(stop, PY_SSIZE_T_MAX, &istop))
4051+
{
4052+
return -1;
4053+
}
4054+
PyListObject *self = (PyListObject *)container;
4055+
int res;
4056+
#ifdef Py_GIL_DISABLED
4057+
if (PyList_CheckExact(value)) {
4058+
Py_BEGIN_CRITICAL_SECTION2(container, value);
4059+
res = list_store_slice_lock_held(self, istart, istop, value);
4060+
Py_END_CRITICAL_SECTION2();
4061+
return res;
4062+
}
4063+
#endif
4064+
Py_BEGIN_CRITICAL_SECTION(container);
4065+
res = list_store_slice_lock_held(self, istart, istop, value);
4066+
Py_END_CRITICAL_SECTION();
4067+
return res;
4068+
}
4069+
39784070
static int
39794071
list_ass_subscript(PyObject *self, PyObject *item, PyObject *value)
39804072
{

‎Objects/sliceobject.c‎

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -214,6 +214,16 @@ PySlice_GetIndices(PyObject *_r, Py_ssize_t length,
214214
return 0;
215215
}
216216

217+
static inline int
218+
slice_index_fast(PyObject *v, Py_ssize_t *pi)
219+
{
220+
if (PyLong_CheckExact(v) && _PyLong_IsCompact((PyLongObject *)v)) {
221+
*pi = _PyLong_CompactValue((PyLongObject *)v);
222+
return 1;
223+
}
224+
return _PyEval_SliceIndex(v, pi);
225+
}
226+
217227
int
218228
PySlice_Unpack(PyObject *_r,
219229
Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step)
@@ -228,7 +238,9 @@ PySlice_Unpack(PyObject *_r,
228238
*step = 1;
229239
}
230240
else {
231-
if (!_PyEval_SliceIndex(r->step, step)) return -1;
241+
if (!slice_index_fast(r->step, step)) {
242+
return -1;
243+
}
232244
if (*step == 0) {
233245
PyErr_SetString(PyExc_ValueError,
234246
"slice step cannot be zero");
@@ -247,14 +259,18 @@ PySlice_Unpack(PyObject *_r,
247259
*start = *step < 0 ? PY_SSIZE_T_MAX : 0;
248260
}
249261
else {
250-
if (!_PyEval_SliceIndex(r->start, start)) return -1;
262+
if (!slice_index_fast(r->start, start)) {
263+
return -1;
264+
}
251265
}
252266

253267
if (r->stop == Py_None) {
254268
*stop = *step < 0 ? PY_SSIZE_T_MIN : PY_SSIZE_T_MAX;
255269
}
256270
else {
257-
if (!_PyEval_SliceIndex(r->stop, stop)) return -1;
271+
if (!slice_index_fast(r->stop, stop)) {
272+
return -1;
273+
}
258274
}
259275

260276
return 0;
@@ -289,6 +305,13 @@ PySlice_AdjustIndices(Py_ssize_t length,
289305
*stop = (step < 0) ? length - 1 : length;
290306
}
291307

308+
/* For unit steps the general formula reduces to a difference. */
309+
if (step == 1) {
310+
return *start < *stop ? *stop - *start : 0;
311+
}
312+
if (step == -1) {
313+
return *stop < *start ? *start - *stop : 0;
314+
}
292315
if (step < 0) {
293316
if (*stop < *start) {
294317
return (*start - *stop - 1) / (-step) + 1;

0 commit comments

Comments
 (0)