Coverage Report

Created: 2026-10-31 06:21

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Objects/listobject.c
Line
Count
Source
1
/* List object implementation */
2
3
#include "Python.h"
4
#include "pycore_abstract.h"      // _PyIndex_Check()
5
#include "pycore_ceval.h"         // _PyEval_GetBuiltin()
6
#include "pycore_critical_section.h"  // _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED()
7
#include "pycore_dict.h"          // _PyDictViewObject
8
#include "pycore_freelist.h"      // _Py_FREELIST_FREE(), _Py_FREELIST_POP()
9
#include "pycore_interp.h"        // PyInterpreterState.list
10
#include "pycore_list.h"          // struct _Py_list_freelist, _PyListIterObject
11
#include "pycore_long.h"          // _PyLong_DigitCount
12
#include "pycore_modsupport.h"    // _PyArg_NoKwnames()
13
#include "pycore_object.h"        // _PyObject_GC_TRACK(), _PyDebugAllocatorStats()
14
#include "pycore_pyatomic_ft_wrappers.h"
15
#include "pycore_setobject.h"     // _PySet_NextEntry()
16
#include "pycore_stackref.h"      // _Py_TryIncrefCompareStackRef()
17
#include "pycore_tuple.h"         // _PyTuple_FromArraySteal()
18
#include "pycore_typeobject.h"    // _Py_TYPE_VERSION_LIST
19
#include <stddef.h>
20
21
/*[clinic input]
22
class list "PyListObject *" "&PyList_Type"
23
[clinic start generated code]*/
24
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=f9b222678f9f71e0]*/
25
26
#include "clinic/listobject.c.h"
27
28
_Py_DECLARE_STR(list_err, "list index out of range");
29
30
#ifdef Py_GIL_DISABLED
31
typedef struct {
32
    Py_ssize_t allocated;
33
    PyObject *ob_item[];
34
} _PyListArray;
35
36
static _PyListArray *
37
list_allocate_array(size_t capacity)
38
{
39
    if (capacity > PY_SSIZE_T_MAX/sizeof(PyObject*) - 1) {
40
        return NULL;
41
    }
42
    _PyListArray *array = PyMem_Malloc(sizeof(_PyListArray) + capacity * sizeof(PyObject *));
43
    if (array == NULL) {
44
        return NULL;
45
    }
46
    array->allocated = capacity;
47
    return array;
48
}
49
50
static Py_ssize_t
51
list_capacity(PyObject **items)
52
{
53
    _PyListArray *array = _Py_CONTAINER_OF(items, _PyListArray, ob_item);
54
    return array->allocated;
55
}
56
#endif
57
58
static void
59
free_list_items(PyObject** items, bool use_qsbr)
60
138M
{
61
#ifdef Py_GIL_DISABLED
62
    _PyListArray *array = _Py_CONTAINER_OF(items, _PyListArray, ob_item);
63
    if (use_qsbr) {
64
        size_t size = sizeof(_PyListArray) + array->allocated * sizeof(PyObject *);
65
        _PyMem_FreeDelayed(array, size);
66
    }
67
    else {
68
        PyMem_Free(array);
69
    }
70
#else
71
138M
    PyMem_Free(items);
72
138M
#endif
73
138M
}
74
75
static void
76
ensure_shared_on_resize(PyListObject *self)
77
84.8M
{
78
#ifdef Py_GIL_DISABLED
79
    // We can't use _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED here because
80
    // the `CALL_LIST_APPEND` bytecode handler may lock the list without
81
    // a critical section.
82
    assert(Py_REFCNT(self) == 1 || PyMutex_IsLocked(&_PyObject_CAST(self)->ob_mutex));
83
84
    // Ensure that the list array is freed using QSBR if we are not the
85
    // owning thread.
86
    if (!_Py_IsOwnedByCurrentThread((PyObject *)self) &&
87
        !_PyObject_GC_IS_SHARED(self))
88
    {
89
        _PyObject_GC_SET_SHARED(self);
90
    }
91
#endif
92
84.8M
}
93
94
12.3M
#define LIST_SMALL_ALLOCATED 32
95
96
static int py_list_resize(PyListObject *self, Py_ssize_t newsize);
97
98
/* Ensure ob_item has room for at least newsize elements, and set
99
 * ob_size to newsize.  If newsize > ob_size on entry, the content
100
 * of the new slots at exit is undefined heap trash; it's the caller's
101
 * responsibility to overwrite them with sane values.
102
 * The number of allocated elements may grow, shrink, or stay the same.
103
 * Failure is impossible if newsize <= self.allocated on entry.
104
 * Note that self->ob_item may change, and even if newsize is less
105
 * than ob_size on entry.
106
 *
107
 * Always inlining list_resize() makes the fast path a few instructions
108
 * in each caller instead of a function call.
109
 */
110
static inline Py_ALWAYS_INLINE int
111
list_resize(PyListObject *self, Py_ssize_t newsize)
112
106M
{
113
106M
    Py_ssize_t allocated = self->allocated;
114
115
    /* Bypass realloc() when a previous overallocation is large enough
116
       to accommodate the newsize.  If the newsize falls lower than half
117
       the allocated size, then proceed with the realloc() to shrink the list.
118
       gh-158592: do not shrink a small list, the realloc() cost is bigger
119
       than the memory we get back.
120
    */
121
106M
    if (allocated >= newsize
122
21.1M
        && (newsize >= (allocated >> 1) || allocated <= LIST_SMALL_ALLOCATED))
123
21.1M
    {
124
21.1M
        assert(self->ob_item != NULL || newsize == 0);
125
21.1M
        Py_SET_SIZE(self, newsize);
126
21.1M
        return 0;
127
21.1M
    }
128
84.8M
    return py_list_resize(self, newsize);
129
106M
}
130
131
/* Slow path of list_resize(): allocate or reallocate ob_item. */
132
static int
133
py_list_resize(PyListObject *self, Py_ssize_t newsize)
134
84.8M
{
135
84.8M
    size_t new_allocated, target_bytes;
136
84.8M
    Py_ssize_t allocated = self->allocated;
137
138
    /* This over-allocates proportional to the list size, making room
139
     * for additional growth.  The over-allocation is mild, but is
140
     * enough to give linear-time amortized behavior over a long
141
     * sequence of appends() in the presence of a poorly-performing
142
     * system realloc().
143
     * Add padding to make the allocated size multiple of 4.
144
     * The growth pattern is:  0, 4, 8, 16, 24, 32, 40, 52, 64, 76, ...
145
     * Note: new_allocated won't overflow because the largest possible value
146
     *       is PY_SSIZE_T_MAX * (9 / 8) + 6 which always fits in a size_t.
147
     */
148
84.8M
    new_allocated = ((size_t)newsize + (newsize >> 3) + 6) & ~(size_t)3;
149
    /* Do not overallocate if the new size is closer to overallocated size
150
     * than to the old size.
151
     */
152
84.8M
    if (newsize - Py_SIZE(self) > (Py_ssize_t)(new_allocated - newsize))
153
345k
        new_allocated = ((size_t)newsize + 3) & ~(size_t)3;
154
155
84.8M
    if (newsize == 0)
156
0
        new_allocated = 0;
157
158
84.8M
    assert(newsize > allocated || new_allocated < (size_t)allocated);
159
160
84.8M
    ensure_shared_on_resize(self);
161
162
#ifdef Py_GIL_DISABLED
163
    _PyListArray *array = list_allocate_array(new_allocated);
164
    if (array == NULL) {
165
        if (newsize < allocated) {
166
            // Never fail when shrinking allocations
167
            Py_SET_SIZE(self, newsize);
168
            return 0;
169
        }
170
        PyErr_NoMemory();
171
        return -1;
172
    }
173
    PyObject **old_items = self->ob_item;
174
    if (self->ob_item) {
175
        if (new_allocated < (size_t)allocated) {
176
            target_bytes = new_allocated * sizeof(PyObject*);
177
        }
178
        else {
179
            target_bytes = allocated * sizeof(PyObject*);
180
        }
181
        memcpy(array->ob_item, self->ob_item, target_bytes);
182
    }
183
    if (new_allocated > (size_t)allocated) {
184
        memset(array->ob_item + allocated, 0, sizeof(PyObject *) * (new_allocated - allocated));
185
    }
186
     _Py_atomic_store_ptr_release(&self->ob_item, &array->ob_item);
187
    self->allocated = new_allocated;
188
    Py_SET_SIZE(self, newsize);
189
    if (old_items != NULL) {
190
        free_list_items(old_items, _PyObject_GC_IS_SHARED(self));
191
    }
192
#else
193
84.8M
    PyObject **items;
194
84.8M
    if (new_allocated <= (size_t)PY_SSIZE_T_MAX / sizeof(PyObject *)) {
195
84.8M
        target_bytes = new_allocated * sizeof(PyObject *);
196
84.8M
        items = (PyObject **)PyMem_Realloc(self->ob_item, target_bytes);
197
84.8M
    }
198
0
    else {
199
        // integer overflow
200
0
        items = NULL;
201
0
    }
202
84.8M
    if (items == NULL) {
203
0
        if (newsize < allocated) {
204
            // Never fail when shrinking allocations
205
0
            Py_SET_SIZE(self, newsize);
206
0
            return 0;
207
0
        }
208
0
        PyErr_NoMemory();
209
0
        return -1;
210
0
    }
211
84.8M
    self->ob_item = items;
212
84.8M
    Py_SET_SIZE(self, newsize);
213
84.8M
    self->allocated = new_allocated;
214
84.8M
#endif
215
84.8M
    return 0;
216
84.8M
}
217
218
static int
219
list_preallocate_exact(PyListObject *self, Py_ssize_t size)
220
8.26M
{
221
8.26M
    PyObject **items;
222
8.26M
    assert(self->ob_item == NULL);
223
8.26M
    assert(size > 0);
224
225
    /* Since the Python memory allocator has granularity of 16 bytes on 64-bit
226
     * platforms (8 on 32-bit), there is no benefit of allocating space for
227
     * the odd number of items, and there is no drawback of rounding the
228
     * allocated size up to the nearest even number.
229
     */
230
8.26M
    size = (size + 1) & ~(size_t)1;
231
#ifdef Py_GIL_DISABLED
232
    _PyListArray *array = list_allocate_array(size);
233
    if (array == NULL) {
234
        PyErr_NoMemory();
235
        return -1;
236
    }
237
    items = array->ob_item;
238
    memset(items, 0, size * sizeof(PyObject *));
239
#else
240
8.26M
    items = PyMem_New(PyObject*, size);
241
8.26M
    if (items == NULL) {
242
0
        PyErr_NoMemory();
243
0
        return -1;
244
0
    }
245
8.26M
#endif
246
8.26M
    FT_ATOMIC_STORE_PTR_RELEASE(self->ob_item, items);
247
8.26M
    self->allocated = size;
248
8.26M
    return 0;
249
8.26M
}
250
251
/* Print summary info about the state of the optimized allocator */
252
void
253
_PyList_DebugMallocStats(FILE *out)
254
0
{
255
0
    _PyDebugAllocatorStats(out,
256
0
                           "free PyListObject",
257
0
                            _Py_FREELIST_SIZE(lists),
258
0
                           _PyType_PreHeaderSize(&PyList_Type) + sizeof(PyListObject));
259
0
}
260
261
PyObject *
262
PyList_New(Py_ssize_t size)
263
253M
{
264
253M
    if (size < 0) {
265
0
        PyErr_BadInternalCall();
266
0
        return NULL;
267
0
    }
268
269
253M
    PyListObject *op = _Py_FREELIST_POP(PyListObject, lists);
270
253M
    if (op == NULL) {
271
47.5M
        op = PyObject_GC_New(PyListObject, &PyList_Type);
272
47.5M
        if (op == NULL) {
273
0
            return NULL;
274
0
        }
275
47.5M
    }
276
253M
    if (size <= 0) {
277
208M
        op->ob_item = NULL;
278
208M
    }
279
45.4M
    else {
280
#ifdef Py_GIL_DISABLED
281
        _PyListArray *array = list_allocate_array(size);
282
        if (array == NULL) {
283
            Py_DECREF(op);
284
            return PyErr_NoMemory();
285
        }
286
        memset(&array->ob_item, 0, size * sizeof(PyObject *));
287
        op->ob_item = array->ob_item;
288
#else
289
45.4M
        op->ob_item = (PyObject **) PyMem_Calloc(size, sizeof(PyObject *));
290
45.4M
#endif
291
45.4M
        if (op->ob_item == NULL) {
292
0
            Py_DECREF(op);
293
0
            return PyErr_NoMemory();
294
0
        }
295
45.4M
    }
296
253M
    Py_SET_SIZE(op, size);
297
253M
    op->allocated = size;
298
253M
    _PyObject_GC_TRACK(op);
299
253M
    return (PyObject *) op;
300
253M
}
301
302
static PyObject *
303
list_new_prealloc(Py_ssize_t size)
304
16.9M
{
305
16.9M
    assert(size > 0);
306
16.9M
    PyListObject *op = (PyListObject *) PyList_New(0);
307
16.9M
    if (op == NULL) {
308
0
        return NULL;
309
0
    }
310
16.9M
    assert(op->ob_item == NULL);
311
#ifdef Py_GIL_DISABLED
312
    _PyListArray *array = list_allocate_array(size);
313
    if (array == NULL) {
314
        Py_DECREF(op);
315
        return PyErr_NoMemory();
316
    }
317
    op->ob_item = array->ob_item;
318
#else
319
16.9M
    op->ob_item = PyMem_New(PyObject *, size);
320
16.9M
    if (op->ob_item == NULL) {
321
0
        Py_DECREF(op);
322
0
        return PyErr_NoMemory();
323
0
    }
324
16.9M
#endif
325
16.9M
    op->allocated = size;
326
16.9M
    return (PyObject *) op;
327
16.9M
}
328
329
Py_ssize_t
330
PyList_Size(PyObject *op)
331
79.8k
{
332
79.8k
    if (!PyList_Check(op)) {
333
0
        PyErr_BadInternalCall();
334
0
        return -1;
335
0
    }
336
79.8k
    else {
337
79.8k
        return PyList_GET_SIZE(op);
338
79.8k
    }
339
79.8k
}
340
341
static inline int
342
valid_index(Py_ssize_t i, Py_ssize_t limit)
343
303M
{
344
    /* The cast to size_t lets us use just a single comparison
345
       to check whether i is in the range: 0 <= i < limit.
346
347
       See:  Section 14.2 "Bounds Checking" in the Agner Fog
348
       optimization manual found at:
349
       https://www.agner.org/optimize/optimizing_cpp.pdf
350
    */
351
303M
    return (size_t) i < (size_t) limit;
352
303M
}
353
354
#ifdef Py_GIL_DISABLED
355
356
static PyObject *
357
list_item_impl(PyListObject *self, Py_ssize_t idx)
358
{
359
    PyObject *item = NULL;
360
    Py_BEGIN_CRITICAL_SECTION(self);
361
    if (!_PyObject_GC_IS_SHARED(self)) {
362
        _PyObject_GC_SET_SHARED(self);
363
    }
364
    Py_ssize_t size = Py_SIZE(self);
365
    if (!valid_index(idx, size)) {
366
        goto exit;
367
    }
368
    item = _Py_NewRefWithLock(self->ob_item[idx]);
369
exit:
370
    Py_END_CRITICAL_SECTION();
371
    return item;
372
}
373
374
static inline PyObject*
375
list_get_item_ref(PyListObject *op, Py_ssize_t i)
376
{
377
    if (!_Py_IsOwnedByCurrentThread((PyObject *)op) && !_PyObject_GC_IS_SHARED(op)) {
378
        return list_item_impl(op, i);
379
    }
380
    // Need atomic operation for the getting size.
381
    Py_ssize_t size = PyList_GET_SIZE(op);
382
    if (!valid_index(i, size)) {
383
        return NULL;
384
    }
385
    PyObject **ob_item = _Py_atomic_load_ptr(&op->ob_item);
386
    if (ob_item == NULL) {
387
        return NULL;
388
    }
389
    Py_ssize_t cap = list_capacity(ob_item);
390
    assert(cap != -1);
391
    if (!valid_index(i, cap)) {
392
        return NULL;
393
    }
394
    PyObject *item = _Py_TryXGetRef(&ob_item[i]);
395
    if (item == NULL) {
396
        return list_item_impl(op, i);
397
    }
398
    return item;
399
}
400
#else
401
static inline PyObject*
402
list_get_item_ref(PyListObject *op, Py_ssize_t i)
403
229M
{
404
229M
    if (!valid_index(i, Py_SIZE(op))) {
405
37.6M
        return NULL;
406
37.6M
    }
407
191M
    return Py_NewRef(PyList_GET_ITEM(op, i));
408
229M
}
409
#endif
410
411
PyObject *
412
PyList_GetItem(PyObject *op, Py_ssize_t i)
413
80
{
414
80
    if (!PyList_Check(op)) {
415
0
        PyErr_BadInternalCall();
416
0
        return NULL;
417
0
    }
418
80
    if (!valid_index(i, Py_SIZE(op))) {
419
0
        _Py_DECLARE_STR(list_err, "list index out of range");
420
0
        PyErr_SetObject(PyExc_IndexError, &_Py_STR(list_err));
421
0
        return NULL;
422
0
    }
423
80
    return ((PyListObject *)op) -> ob_item[i];
424
80
}
425
426
PyObject *
427
PyList_GetItemRef(PyObject *op, Py_ssize_t i)
428
141k
{
429
141k
    if (!PyList_Check(op)) {
430
0
        PyErr_SetString(PyExc_TypeError, "expected a list");
431
0
        return NULL;
432
0
    }
433
141k
    PyObject *item = list_get_item_ref((PyListObject *)op, i);
434
141k
    if (item == NULL) {
435
0
        _Py_DECLARE_STR(list_err, "list index out of range");
436
0
        PyErr_SetObject(PyExc_IndexError, &_Py_STR(list_err));
437
0
        return NULL;
438
0
    }
439
141k
    return item;
440
141k
}
441
442
PyObject *
443
_PyList_GetItemRef(PyListObject *list, Py_ssize_t i)
444
0
{
445
0
    return list_get_item_ref(list, i);
446
0
}
447
448
#ifdef Py_GIL_DISABLED
449
int
450
_PyList_GetItemRefNoLock(PyListObject *list, Py_ssize_t i, _PyStackRef *result)
451
{
452
    assert(_Py_IsOwnedByCurrentThread((PyObject *)list) ||
453
           _PyObject_GC_IS_SHARED(list));
454
    if (!valid_index(i, PyList_GET_SIZE(list))) {
455
        return 0;
456
    }
457
    PyObject **ob_item = _Py_atomic_load_ptr(&list->ob_item);
458
    if (ob_item == NULL) {
459
        return 0;
460
    }
461
    Py_ssize_t cap = list_capacity(ob_item);
462
    assert(cap != -1);
463
    if (!valid_index(i, cap)) {
464
        return 0;
465
    }
466
    PyObject *obj = _Py_atomic_load_ptr(&ob_item[i]);
467
    if (obj == NULL || !_Py_TryIncrefCompareStackRef(&ob_item[i], obj, result)) {
468
        return -1;
469
    }
470
    return 1;
471
}
472
#endif
473
474
int
475
PyList_SetItem(PyObject *op, Py_ssize_t i,
476
               PyObject *newitem)
477
24.9M
{
478
24.9M
    if (!PyList_Check(op)) {
479
0
        Py_XDECREF(newitem);
480
0
        PyErr_BadInternalCall();
481
0
        return -1;
482
0
    }
483
24.9M
    int ret;
484
24.9M
    PyListObject *self = ((PyListObject *)op);
485
24.9M
    Py_BEGIN_CRITICAL_SECTION(self);
486
24.9M
    if (!valid_index(i, Py_SIZE(self))) {
487
0
        Py_XDECREF(newitem);
488
0
        PyErr_SetString(PyExc_IndexError,
489
0
                        "list assignment index out of range");
490
0
        ret = -1;
491
0
        goto end;
492
0
    }
493
24.9M
    PyObject *tmp = self->ob_item[i];
494
24.9M
    FT_ATOMIC_STORE_PTR_RELEASE(self->ob_item[i], newitem);
495
24.9M
    Py_XDECREF(tmp);
496
24.9M
    ret = 0;
497
24.9M
end:;
498
24.9M
    Py_END_CRITICAL_SECTION();
499
24.9M
    return ret;
500
24.9M
}
501
502
static void ptr_wise_atomic_memmove(PyListObject *a, PyObject **dest,
503
                                    PyObject **src, Py_ssize_t n);
504
505
static inline void
506
list_shift_items_right_lock_held(PyListObject *self, Py_ssize_t first,
507
                                 Py_ssize_t last)
508
111
{
509
#ifdef Py_GIL_DISABLED
510
    ptr_wise_atomic_memmove(self, &self->ob_item[first + 1],
511
                            &self->ob_item[first], last - first);
512
#else
513
111
    PyObject **items = self->ob_item;
514
338
    for (Py_ssize_t i = last; --i >= first; ) {
515
227
        items[i + 1] = items[i];
516
227
    }
517
111
#endif
518
111
}
519
520
static inline void
521
list_shift_items_left_lock_held(PyListObject *self, Py_ssize_t first,
522
                                Py_ssize_t last)
523
4.45k
{
524
#ifdef Py_GIL_DISABLED
525
    ptr_wise_atomic_memmove(self, &self->ob_item[first],
526
                            &self->ob_item[first + 1], last - first);
527
#else
528
4.45k
    PyObject **items = self->ob_item;
529
10.1M
    for (Py_ssize_t i = first; i < last; i++) {
530
10.1M
        items[i] = items[i + 1];
531
10.1M
    }
532
4.45k
#endif
533
4.45k
}
534
535
static int
536
ins1(PyListObject *self, Py_ssize_t where, PyObject *v)
537
123
{
538
123
    Py_ssize_t n = Py_SIZE(self);
539
123
    PyObject **items;
540
123
    if (v == NULL) {
541
0
        PyErr_BadInternalCall();
542
0
        return -1;
543
0
    }
544
545
123
    assert((size_t)n + 1 < PY_SSIZE_T_MAX);
546
123
    if (list_resize(self, n+1) < 0)
547
0
        return -1;
548
549
123
    if (where < 0) {
550
0
        where += n;
551
0
        if (where < 0)
552
0
            where = 0;
553
0
    }
554
123
    if (where > n)
555
0
        where = n;
556
123
    items = self->ob_item;
557
123
    if (where < n) {
558
111
        list_shift_items_right_lock_held(self, where, n);
559
111
    }
560
123
    FT_ATOMIC_STORE_PTR_RELEASE(items[where], Py_NewRef(v));
561
123
    return 0;
562
123
}
563
564
int
565
PyList_Insert(PyObject *op, Py_ssize_t where, PyObject *newitem)
566
47
{
567
47
    if (!PyList_Check(op)) {
568
0
        PyErr_BadInternalCall();
569
0
        return -1;
570
0
    }
571
47
    PyListObject *self = (PyListObject *)op;
572
47
    int err;
573
47
    Py_BEGIN_CRITICAL_SECTION(self);
574
47
    err = ins1(self, where, newitem);
575
47
    Py_END_CRITICAL_SECTION();
576
47
    return err;
577
47
}
578
579
/* internal, used by _PyList_AppendTakeRef */
580
int
581
_PyList_AppendTakeRefListResize(PyListObject *self, PyObject *newitem)
582
76.6M
{
583
76.6M
    Py_ssize_t len = Py_SIZE(self);
584
76.6M
    assert(self->allocated == -1 || self->allocated == len);
585
76.6M
    if (list_resize(self, len + 1) < 0) {
586
0
        Py_DECREF(newitem);
587
0
        return -1;
588
0
    }
589
76.6M
    FT_ATOMIC_STORE_PTR_RELEASE(self->ob_item[len], newitem);
590
76.6M
    return 0;
591
76.6M
}
592
593
int
594
PyList_Append(PyObject *op, PyObject *newitem)
595
51.0M
{
596
51.0M
    if (PyList_Check(op) && (newitem != NULL)) {
597
51.0M
        int ret;
598
51.0M
        Py_BEGIN_CRITICAL_SECTION(op);
599
51.0M
        ret = _PyList_AppendTakeRef((PyListObject *)op, Py_NewRef(newitem));
600
51.0M
        Py_END_CRITICAL_SECTION();
601
51.0M
        return ret;
602
51.0M
    }
603
0
    PyErr_BadInternalCall();
604
0
    return -1;
605
51.0M
}
606
607
/* Methods */
608
609
static void
610
list_dealloc(PyObject *self)
611
266M
{
612
266M
    PyListObject *op = (PyListObject *)self;
613
266M
    Py_ssize_t i;
614
266M
    PyObject_GC_UnTrack(op);
615
266M
    if (op->ob_item != NULL) {
616
        /* Do it backwards, for Christian Tismer.
617
           There's a simple test case where somehow this reduces
618
           thrashing when a *very* large list is created and
619
           immediately deleted. */
620
131M
        i = Py_SIZE(op);
621
2.70G
        while (--i >= 0) {
622
2.57G
            Py_XDECREF(op->ob_item[i]);
623
2.57G
        }
624
131M
        free_list_items(op->ob_item, false);
625
131M
        op->ob_item = NULL;
626
131M
    }
627
266M
    if (PyList_CheckExact(op)) {
628
253M
        _Py_FREELIST_FREE(lists, op, PyObject_GC_Del);
629
253M
    }
630
12.3M
    else {
631
12.3M
        PyObject_GC_Del(op);
632
12.3M
    }
633
266M
}
634
635
/*[clinic input]
636
@critical_section
637
list.__repr__
638
639
    v: self(type="PyListObject *")
640
[clinic start generated code]*/
641
642
static PyObject *
643
list_repr_impl(PyListObject *v)
644
/*[clinic end generated code: output=c5ffe3b9cfee36ce input=f4b85c550d11de32]*/
645
4.07M
{
646
4.07M
    if (PyList_GET_SIZE(v) == 0) {
647
82.0k
        return PyUnicode_FromString("[]");
648
82.0k
    }
649
650
3.99M
    int res = Py_ReprEnter((PyObject*)v);
651
3.99M
    if (res != 0) {
652
0
        return (res > 0 ? PyUnicode_FromString("[...]") : NULL);
653
0
    }
654
655
    /* "[" + "1" + ", 2" * (len - 1) + "]" */
656
3.99M
    Py_ssize_t prealloc = 1 + 1 + (2 + 1) * (Py_SIZE(v) - 1) + 1;
657
3.99M
    PyUnicodeWriter *writer = PyUnicodeWriter_Create(prealloc);
658
3.99M
    PyObject *item = NULL;
659
3.99M
    if (writer == NULL) {
660
0
        goto error;
661
0
    }
662
663
3.99M
    if (PyUnicodeWriter_WriteChar(writer, '[') < 0) {
664
0
        goto error;
665
0
    }
666
667
    /* Do repr() on each element.  Note that this may mutate the list,
668
       so must refetch the list size on each iteration. */
669
11.6M
    for (Py_ssize_t i = 0; i < Py_SIZE(v); ++i) {
670
        /* Hold a strong reference since repr(item) can mutate the list */
671
7.64M
        item = Py_XNewRef(v->ob_item[i]);
672
673
7.64M
        if (i > 0) {
674
3.65M
            if (PyUnicodeWriter_WriteChar(writer, ',') < 0) {
675
0
                goto error;
676
0
            }
677
3.65M
            if (PyUnicodeWriter_WriteChar(writer, ' ') < 0) {
678
0
                goto error;
679
0
            }
680
3.65M
        }
681
682
7.64M
        if (PyUnicodeWriter_WriteRepr(writer, item) < 0) {
683
0
            goto error;
684
0
        }
685
7.64M
        Py_CLEAR(item);
686
7.64M
    }
687
688
3.99M
    if (PyUnicodeWriter_WriteChar(writer, ']') < 0) {
689
0
        goto error;
690
0
    }
691
692
3.99M
    Py_ReprLeave((PyObject *)v);
693
3.99M
    return PyUnicodeWriter_Finish(writer);
694
695
0
error:
696
0
    Py_XDECREF(item);
697
0
    PyUnicodeWriter_Discard(writer);
698
0
    Py_ReprLeave((PyObject *)v);
699
0
    return NULL;
700
3.99M
}
701
702
static Py_ssize_t
703
list_length(PyObject *a)
704
43.3M
{
705
43.3M
    return PyList_GET_SIZE(a);
706
43.3M
}
707
708
static int
709
list_contains(PyObject *aa, PyObject *el)
710
5.68k
{
711
712
36.3k
    for (Py_ssize_t i = 0; ; i++) {
713
36.3k
        PyObject *item = list_get_item_ref((PyListObject *)aa, i);
714
36.3k
        if (item == NULL) {
715
            // out-of-bounds
716
3.89k
            return 0;
717
3.89k
        }
718
32.4k
        int cmp = PyObject_RichCompareBool(item, el, Py_EQ);
719
32.4k
        Py_DECREF(item);
720
32.4k
        if (cmp != 0) {
721
1.79k
            return cmp;
722
1.79k
        }
723
32.4k
    }
724
0
    return 0;
725
5.68k
}
726
727
static PyObject *
728
list_item(PyObject *aa, Py_ssize_t i)
729
26.8M
{
730
26.8M
    PyListObject *a = (PyListObject *)aa;
731
26.8M
    if (!valid_index(i, PyList_GET_SIZE(a))) {
732
1.72M
        PyErr_SetObject(PyExc_IndexError, &_Py_STR(list_err));
733
1.72M
        return NULL;
734
1.72M
    }
735
25.1M
    PyObject *item;
736
#ifdef Py_GIL_DISABLED
737
    item = list_get_item_ref(a, i);
738
    if (item == NULL) {
739
        PyErr_SetObject(PyExc_IndexError, &_Py_STR(list_err));
740
        return NULL;
741
    }
742
#else
743
25.1M
    item = Py_NewRef(a->ob_item[i]);
744
25.1M
#endif
745
25.1M
    return item;
746
26.8M
}
747
748
static PyObject *
749
list_slice_lock_held(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
750
2.49M
{
751
2.49M
    PyListObject *np;
752
2.49M
    PyObject **src, **dest;
753
2.49M
    Py_ssize_t i, len;
754
2.49M
    len = ihigh - ilow;
755
2.49M
    if (len <= 0) {
756
1.58k
        return PyList_New(0);
757
1.58k
    }
758
2.49M
    np = (PyListObject *) list_new_prealloc(len);
759
2.49M
    if (np == NULL)
760
0
        return NULL;
761
762
2.49M
    src = a->ob_item + ilow;
763
2.49M
    dest = np->ob_item;
764
29.3M
    for (i = 0; i < len; i++) {
765
26.8M
        PyObject *v = src[i];
766
26.8M
        dest[i] = Py_NewRef(v);
767
26.8M
    }
768
2.49M
    Py_SET_SIZE(np, len);
769
2.49M
    return (PyObject *)np;
770
2.49M
}
771
772
PyObject *
773
_PyList_BinarySlice(PyObject *container, PyObject *start, PyObject *stop)
774
96.2k
{
775
96.2k
    assert(PyList_CheckExact(container));
776
96.2k
    Py_ssize_t istart = 0;
777
96.2k
    Py_ssize_t istop = PY_SSIZE_T_MAX;
778
    /* Unpack the index values before acquiring the lock, since
779
     * _PyEval_SliceIndex may call __index__ which could execute
780
     * arbitrary Python code. */
781
96.2k
    if (!_PyEval_SliceIndex(start, &istart)) {
782
0
        return NULL;
783
0
    }
784
96.2k
    if (!_PyEval_SliceIndex(stop, &istop)) {
785
0
        return NULL;
786
0
    }
787
96.2k
    PyObject *ret;
788
96.2k
    Py_BEGIN_CRITICAL_SECTION(container);
789
96.2k
    Py_ssize_t len = Py_SIZE(container);
790
96.2k
    PySlice_AdjustIndices(len, &istart, &istop, 1);
791
96.2k
    ret = list_slice_lock_held((PyListObject *)container, istart, istop);
792
96.2k
    Py_END_CRITICAL_SECTION();
793
96.2k
    return ret;
794
96.2k
}
795
796
PyObject *
797
PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
798
0
{
799
0
    if (!PyList_Check(a)) {
800
0
        PyErr_BadInternalCall();
801
0
        return NULL;
802
0
    }
803
0
    PyObject *ret;
804
0
    Py_BEGIN_CRITICAL_SECTION(a);
805
0
    if (ilow < 0) {
806
0
        ilow = 0;
807
0
    }
808
0
    else if (ilow > Py_SIZE(a)) {
809
0
        ilow = Py_SIZE(a);
810
0
    }
811
0
    if (ihigh < ilow) {
812
0
        ihigh = ilow;
813
0
    }
814
0
    else if (ihigh > Py_SIZE(a)) {
815
0
        ihigh = Py_SIZE(a);
816
0
    }
817
0
    ret = list_slice_lock_held((PyListObject *)a, ilow, ihigh);
818
0
    Py_END_CRITICAL_SECTION();
819
0
    return ret;
820
0
}
821
822
static PyObject *
823
list_concat_lock_held(PyListObject *a, PyListObject *b)
824
22.5M
{
825
22.5M
    Py_ssize_t size;
826
22.5M
    Py_ssize_t i;
827
22.5M
    PyObject **src, **dest;
828
22.5M
    PyListObject *np;
829
22.5M
    assert((size_t)Py_SIZE(a) + (size_t)Py_SIZE(b) < PY_SSIZE_T_MAX);
830
22.5M
    size = Py_SIZE(a) + Py_SIZE(b);
831
22.5M
    if (size == 0) {
832
8.09M
        return PyList_New(0);
833
8.09M
    }
834
14.4M
    np = (PyListObject *) list_new_prealloc(size);
835
14.4M
    if (np == NULL) {
836
0
        return NULL;
837
0
    }
838
14.4M
    src = a->ob_item;
839
14.4M
    dest = np->ob_item;
840
989M
    for (i = 0; i < Py_SIZE(a); i++) {
841
975M
        PyObject *v = src[i];
842
975M
        dest[i] = Py_NewRef(v);
843
975M
    }
844
14.4M
    src = b->ob_item;
845
14.4M
    dest = np->ob_item + Py_SIZE(a);
846
423M
    for (i = 0; i < Py_SIZE(b); i++) {
847
408M
        PyObject *v = src[i];
848
408M
        dest[i] = Py_NewRef(v);
849
408M
    }
850
14.4M
    Py_SET_SIZE(np, size);
851
14.4M
    return (PyObject *)np;
852
14.4M
}
853
854
PyObject *
855
_PyList_Concat(PyObject *aa, PyObject *bb)
856
22.5M
{
857
22.5M
    if (!PyList_Check(bb)) {
858
0
        PyErr_Format(PyExc_TypeError,
859
0
                  "can only concatenate list (not \"%.200s\") to list",
860
0
                  Py_TYPE(bb)->tp_name);
861
0
        return NULL;
862
0
    }
863
22.5M
    PyListObject *a = (PyListObject *)aa;
864
22.5M
    PyListObject *b = (PyListObject *)bb;
865
22.5M
    PyObject *ret;
866
22.5M
    Py_BEGIN_CRITICAL_SECTION2(a, b);
867
22.5M
    ret = list_concat_lock_held(a, b);
868
22.5M
    Py_END_CRITICAL_SECTION2();
869
22.5M
    return ret;
870
22.5M
}
871
872
/*[clinic input]
873
@critical_section
874
list.__mul__ as list_repeat
875
876
    a: self(type="PyListObject *")
877
    n: Py_ssize_t
878
    /
879
[clinic start generated code]*/
880
881
static PyObject *
882
list_repeat_impl(PyListObject *a, Py_ssize_t n)
883
/*[clinic end generated code: output=65bb40ed76d3e733 input=dfef16e067b2abb6]*/
884
23.3k
{
885
23.3k
    const Py_ssize_t input_size = Py_SIZE(a);
886
23.3k
    if (input_size == 0 || n <= 0)
887
2.88k
        return PyList_New(0);
888
23.3k
    assert(n > 0);
889
890
20.4k
    if (input_size > PY_SSIZE_T_MAX / n)
891
0
        return PyErr_NoMemory();
892
20.4k
    Py_ssize_t output_size = input_size * n;
893
894
20.4k
    PyListObject *np = (PyListObject *) list_new_prealloc(output_size);
895
20.4k
    if (np == NULL)
896
0
        return NULL;
897
898
20.4k
    PyObject **dest = np->ob_item;
899
20.4k
    if (input_size == 1) {
900
20.4k
        PyObject *elem = a->ob_item[0];
901
20.4k
        _Py_RefcntAdd(elem, n);
902
20.4k
        PyObject **dest_end = dest + output_size;
903
5.70M
        while (dest < dest_end) {
904
5.68M
            *dest++ = elem;
905
5.68M
        }
906
20.4k
    }
907
0
    else {
908
0
        PyObject **src = a->ob_item;
909
0
        PyObject **src_end = src + input_size;
910
0
        while (src < src_end) {
911
0
            _Py_RefcntAdd(*src, n);
912
0
            *dest++ = *src++;
913
0
        }
914
        // This list is not yet visible to other threads, so atomic repeat
915
        // is not necessary even in Py_GIL_DISABLED builds.
916
0
        _Py_memory_repeat((char *)np->ob_item, sizeof(PyObject *)*output_size,
917
0
                                        sizeof(PyObject *)*input_size);
918
0
    }
919
920
20.4k
    Py_SET_SIZE(np, output_size);
921
20.4k
    return (PyObject *) np;
922
20.4k
}
923
924
static void
925
list_clear_impl(PyListObject *a, bool is_resize)
926
8.44M
{
927
8.44M
    PyObject **items = a->ob_item;
928
8.44M
    if (items == NULL) {
929
708k
        return;
930
708k
    }
931
932
    /* Because XDECREF can recursively invoke operations on
933
       this list, we make it empty first. */
934
7.74M
    Py_ssize_t i = Py_SIZE(a);
935
7.74M
    Py_SET_SIZE(a, 0);
936
7.74M
    FT_ATOMIC_STORE_PTR_RELEASE(a->ob_item, NULL);
937
7.74M
    a->allocated = 0;
938
15.5M
    while (--i >= 0) {
939
7.80M
        Py_XDECREF(items[i]);
940
7.80M
    }
941
#ifdef Py_GIL_DISABLED
942
    if (is_resize) {
943
        ensure_shared_on_resize(a);
944
    }
945
    bool use_qsbr = is_resize && _PyObject_GC_IS_SHARED(a);
946
#else
947
7.74M
    bool use_qsbr = false;
948
7.74M
#endif
949
7.74M
    free_list_items(items, use_qsbr);
950
    // Note that there is no guarantee that the list is actually empty
951
    // at this point, because XDECREF may have populated it indirectly again!
952
7.74M
}
953
954
static void
955
list_clear(PyListObject *a)
956
8.44M
{
957
8.44M
    list_clear_impl(a, true);
958
8.44M
}
959
960
static int
961
list_clear_slot(PyObject *self)
962
0
{
963
0
    list_clear_impl((PyListObject *)self, false);
964
0
    return 0;
965
0
}
966
967
// Pointer-by-pointer memmove for PyObject** arrays that is safe
968
// for shared lists in Py_GIL_DISABLED builds.
969
static void
970
ptr_wise_atomic_memmove(PyListObject *a, PyObject **dest, PyObject **src, Py_ssize_t n)
971
5.28M
{
972
5.28M
#ifndef Py_GIL_DISABLED
973
5.28M
    memmove(dest, src, n * sizeof(PyObject *));
974
#else
975
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(a);
976
    if (_Py_IsOwnedByCurrentThread((PyObject *)a) && !_PyObject_GC_IS_SHARED(a)) {
977
        // No other threads can read this list concurrently
978
        memmove(dest, src, n * sizeof(PyObject *));
979
        return;
980
    }
981
    if (dest < src) {
982
        for (Py_ssize_t i = 0; i != n; i++) {
983
            _Py_atomic_store_ptr_release(&dest[i], src[i]);
984
        }
985
    }
986
    else {
987
        // copy backwards to avoid overwriting src before it's read
988
        for (Py_ssize_t i = n; i != 0; i--) {
989
            _Py_atomic_store_ptr_release(&dest[i - 1], src[i - 1]);
990
        }
991
    }
992
#endif
993
5.28M
}
994
995
/* a[ilow:ihigh] = v if v != NULL.
996
 * del a[ilow:ihigh] if v == NULL.
997
 *
998
 * Special speed gimmick:  when v is NULL and ihigh - ilow <= 8, it's
999
 * guaranteed the call cannot fail.
1000
 */
1001
static int
1002
list_ass_slice_lock_held(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
1003
6.53M
{
1004
    /* Because [X]DECREF can recursively invoke list operations on
1005
       this list, we must postpone all [X]DECREF activity until
1006
       after the list is back in its canonical shape.  Therefore
1007
       we must allocate an additional array, 'recycle', into which
1008
       we temporarily copy the items that are deleted from the
1009
       list. :-( */
1010
6.53M
    PyObject *recycle_on_stack[8];
1011
6.53M
    PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
1012
6.53M
    PyObject **item;
1013
6.53M
    PyObject **vitem = NULL;
1014
6.53M
    PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
1015
6.53M
    Py_ssize_t n; /* # of elements in replacement list */
1016
6.53M
    Py_ssize_t norig; /* # of elements in list getting replaced */
1017
6.53M
    Py_ssize_t d; /* Change in size */
1018
6.53M
    Py_ssize_t k;
1019
6.53M
    size_t s;
1020
6.53M
    int result = -1;            /* guilty until proved innocent */
1021
6.53M
#define b ((PyListObject *)v)
1022
6.53M
    if (v == NULL)
1023
4.06M
        n = 0;
1024
2.47M
    else {
1025
2.47M
        v_as_SF = PySequence_Fast(v, "can only assign an iterable");
1026
2.47M
        if(v_as_SF == NULL)
1027
0
            goto Error;
1028
2.47M
        n = PySequence_Fast_GET_SIZE(v_as_SF);
1029
2.47M
        vitem = PySequence_Fast_ITEMS(v_as_SF);
1030
2.47M
    }
1031
6.53M
    if (ilow < 0)
1032
0
        ilow = 0;
1033
6.53M
    else if (ilow > Py_SIZE(a))
1034
408k
        ilow = Py_SIZE(a);
1035
1036
6.53M
    if (ihigh < ilow)
1037
0
        ihigh = ilow;
1038
6.53M
    else if (ihigh > Py_SIZE(a))
1039
408k
        ihigh = Py_SIZE(a);
1040
1041
6.53M
    norig = ihigh - ilow;
1042
6.53M
    assert(norig >= 0);
1043
6.53M
    d = n - norig;
1044
6.53M
    if (Py_SIZE(a) + d == 0) {
1045
1.33M
        Py_XDECREF(v_as_SF);
1046
1.33M
        list_clear(a);
1047
1.33M
        return 0;
1048
1.33M
    }
1049
5.19M
    item = a->ob_item;
1050
    /* recycle the items that we are about to remove */
1051
5.19M
    s = norig * sizeof(PyObject *);
1052
    /* If norig == 0, item might be NULL, in which case we may not memcpy from it. */
1053
5.19M
    if (s) {
1054
4.50M
        if (s > sizeof(recycle_on_stack)) {
1055
24.7k
            recycle = (PyObject **)PyMem_Malloc(s);
1056
24.7k
            if (recycle == NULL) {
1057
0
                PyErr_NoMemory();
1058
0
                goto Error;
1059
0
            }
1060
24.7k
        }
1061
4.50M
        memcpy(recycle, &item[ilow], s);
1062
4.50M
    }
1063
1064
5.19M
    if (d < 0) { /* Delete -d items */
1065
3.45M
        Py_ssize_t tail = Py_SIZE(a) - ihigh;
1066
3.45M
        ptr_wise_atomic_memmove(a, &item[ihigh+d], &item[ihigh], tail);
1067
3.45M
        (void)list_resize(a, Py_SIZE(a) + d); // NB: shrinking a list can't fail
1068
3.45M
        item = a->ob_item;
1069
3.45M
    }
1070
1.74M
    else if (d > 0) { /* Insert d items */
1071
695k
        k = Py_SIZE(a);
1072
695k
        if (list_resize(a, k+d) < 0)
1073
0
            goto Error;
1074
695k
        item = a->ob_item;
1075
695k
        ptr_wise_atomic_memmove(a, &item[ihigh+d], &item[ihigh], k - ihigh);
1076
695k
    }
1077
235M
    for (k = 0; k < n; k++, ilow++) {
1078
230M
        PyObject *w = vitem[k];
1079
230M
        FT_ATOMIC_STORE_PTR_RELEASE(item[ilow], Py_XNewRef(w));
1080
230M
    }
1081
26.9M
    for (k = norig - 1; k >= 0; --k)
1082
21.7M
        Py_XDECREF(recycle[k]);
1083
5.19M
    result = 0;
1084
5.19M
 Error:
1085
5.19M
    if (recycle != recycle_on_stack)
1086
24.7k
        PyMem_Free(recycle);
1087
5.19M
    Py_XDECREF(v_as_SF);
1088
5.19M
    return result;
1089
5.19M
#undef b
1090
5.19M
}
1091
1092
static int
1093
list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
1094
4.46M
{
1095
4.46M
    int ret;
1096
4.46M
    if (a == (PyListObject *)v) {
1097
0
        Py_BEGIN_CRITICAL_SECTION(a);
1098
0
        Py_ssize_t n = PyList_GET_SIZE(a);
1099
0
        PyObject *copy = list_slice_lock_held(a, 0, n);
1100
0
        if (copy == NULL) {
1101
0
            ret = -1;
1102
0
        }
1103
0
        else {
1104
0
            ret = list_ass_slice_lock_held(a, ilow, ihigh, copy);
1105
0
            Py_DECREF(copy);
1106
0
        }
1107
0
        Py_END_CRITICAL_SECTION();
1108
0
    }
1109
4.46M
    else if (v != NULL && PyList_CheckExact(v)) {
1110
189k
        Py_BEGIN_CRITICAL_SECTION2(a, v);
1111
189k
        ret = list_ass_slice_lock_held(a, ilow, ihigh, v);
1112
189k
        Py_END_CRITICAL_SECTION2();
1113
189k
    }
1114
4.27M
    else {
1115
4.27M
        Py_BEGIN_CRITICAL_SECTION(a);
1116
4.27M
        ret = list_ass_slice_lock_held(a, ilow, ihigh, v);
1117
4.27M
        Py_END_CRITICAL_SECTION();
1118
4.27M
    }
1119
4.46M
    return ret;
1120
4.46M
}
1121
1122
int
1123
PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
1124
4.46M
{
1125
4.46M
    if (!PyList_Check(a)) {
1126
0
        PyErr_BadInternalCall();
1127
0
        return -1;
1128
0
    }
1129
4.46M
    return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
1130
4.46M
}
1131
1132
static int
1133
list_inplace_repeat_lock_held(PyListObject *self, Py_ssize_t n)
1134
0
{
1135
0
    Py_ssize_t input_size = PyList_GET_SIZE(self);
1136
0
    if (input_size == 0 || n == 1) {
1137
0
        return 0;
1138
0
    }
1139
1140
0
    if (n < 1) {
1141
0
        list_clear(self);
1142
0
        return 0;
1143
0
    }
1144
1145
0
    if (input_size > PY_SSIZE_T_MAX / n) {
1146
0
        PyErr_NoMemory();
1147
0
        return -1;
1148
0
    }
1149
0
    Py_ssize_t output_size = input_size * n;
1150
1151
0
    if (list_resize(self, output_size) < 0) {
1152
0
        return -1;
1153
0
    }
1154
1155
0
    PyObject **items = self->ob_item;
1156
0
    for (Py_ssize_t j = 0; j < input_size; j++) {
1157
0
        _Py_RefcntAdd(items[j], n-1);
1158
0
    }
1159
0
#ifndef Py_GIL_DISABLED
1160
0
    _Py_memory_repeat((char *)items, sizeof(PyObject *)*output_size,
1161
0
                      sizeof(PyObject *)*input_size);
1162
#else
1163
    Py_ssize_t copied = input_size;
1164
    while (copied < output_size) {
1165
        Py_ssize_t items_to_copy = Py_MIN(copied, output_size - copied);
1166
        ptr_wise_atomic_memmove(self, items + copied, items, items_to_copy);
1167
        copied += items_to_copy;
1168
    }
1169
#endif
1170
0
    return 0;
1171
0
}
1172
1173
/*[clinic input]
1174
@critical_section
1175
list.__imul__ as list_inplace_repeat
1176
1177
    n: Py_ssize_t
1178
    /
1179
[clinic start generated code]*/
1180
1181
static PyObject *
1182
list_inplace_repeat_impl(PyListObject *self, Py_ssize_t n)
1183
/*[clinic end generated code: output=d318a9f047b4fcaf input=530d74de0e4a61f0]*/
1184
0
{
1185
0
    if (list_inplace_repeat_lock_held(self, n) < 0) {
1186
0
        return NULL;
1187
0
    }
1188
0
    return Py_NewRef(self);
1189
0
}
1190
1191
/*[clinic input]
1192
@critical_section
1193
list.__setitem__ as list_ass_item
1194
1195
    a: self(type="PyListObject *")
1196
    i: Py_ssize_t
1197
    v: object
1198
    /
1199
[clinic start generated code]*/
1200
1201
static int
1202
list_ass_item_impl(PyListObject *a, Py_ssize_t i, PyObject *v)
1203
/*[clinic end generated code: output=51d8b4f1790b67db input=0ba2adeaf8b3d5a0]*/
1204
3.61M
{
1205
3.61M
    if (!valid_index(i, Py_SIZE(a))) {
1206
0
        PyErr_SetString(PyExc_IndexError,
1207
0
                        "list assignment index out of range");
1208
0
        return -1;
1209
0
    }
1210
3.61M
    PyObject *tmp = a->ob_item[i];
1211
3.61M
    if (v == NULL) {
1212
8.48k
        Py_ssize_t size = Py_SIZE(a);
1213
8.48k
        if (i < size - 1) {
1214
4.45k
            list_shift_items_left_lock_held(a, i, size - 1);
1215
4.45k
        }
1216
8.48k
        list_resize(a, size - 1);  // NB: shrinking a list can't fail
1217
8.48k
    }
1218
3.60M
    else {
1219
3.60M
        FT_ATOMIC_STORE_PTR_RELEASE(a->ob_item[i], Py_NewRef(v));
1220
3.60M
    }
1221
3.61M
    Py_DECREF(tmp);
1222
3.61M
    return 0;
1223
3.61M
}
1224
1225
/*[clinic input]
1226
@critical_section
1227
list.insert
1228
1229
    index: Py_ssize_t
1230
    object: object
1231
    /
1232
1233
Insert object before index.
1234
[clinic start generated code]*/
1235
1236
static PyObject *
1237
list_insert_impl(PyListObject *self, Py_ssize_t index, PyObject *object)
1238
/*[clinic end generated code: output=7f35e32f60c8cb78 input=b1987ca998a4ae2d]*/
1239
76
{
1240
76
    if (ins1(self, index, object) == 0) {
1241
76
        Py_RETURN_NONE;
1242
76
    }
1243
0
    return NULL;
1244
76
}
1245
1246
/*[clinic input]
1247
@critical_section
1248
list.clear as py_list_clear
1249
1250
Remove all items from list.
1251
[clinic start generated code]*/
1252
1253
static PyObject *
1254
py_list_clear_impl(PyListObject *self)
1255
/*[clinic end generated code: output=83726743807e3518 input=e285b7f09051a9ba]*/
1256
158
{
1257
158
    list_clear(self);
1258
158
    Py_RETURN_NONE;
1259
158
}
1260
1261
/*[clinic input]
1262
@critical_section
1263
list.copy
1264
1265
Return a shallow copy of the list.
1266
[clinic start generated code]*/
1267
1268
static PyObject *
1269
list_copy_impl(PyListObject *self)
1270
/*[clinic end generated code: output=ec6b72d6209d418e input=81c54b0c7bb4f73d]*/
1271
0
{
1272
0
    return list_slice_lock_held(self, 0, Py_SIZE(self));
1273
0
}
1274
1275
/*[clinic input]
1276
@critical_section
1277
list.append
1278
1279
     object: object
1280
     /
1281
1282
Append object to the end of the list.
1283
[clinic start generated code]*/
1284
1285
static PyObject *
1286
list_append_impl(PyListObject *self, PyObject *object)
1287
/*[clinic end generated code: output=78423561d92ed405 input=122b0853de54004f]*/
1288
97.3M
{
1289
97.3M
    if (_PyList_AppendTakeRef(self, Py_NewRef(object)) < 0) {
1290
0
        return NULL;
1291
0
    }
1292
97.3M
    Py_RETURN_NONE;
1293
97.3M
}
1294
1295
static int
1296
list_extend_fast(PyListObject *self, PyObject *iterable)
1297
16.7M
{
1298
16.7M
    Py_ssize_t n = PySequence_Fast_GET_SIZE(iterable);
1299
16.7M
    if (n == 0) {
1300
        /* short circuit when iterable is empty */
1301
9.76M
        return 0;
1302
9.76M
    }
1303
1304
7.00M
    Py_ssize_t m = Py_SIZE(self);
1305
    // It should not be possible to allocate a list large enough to cause
1306
    // an overflow on any relevant platform.
1307
7.00M
    assert(m < PY_SSIZE_T_MAX - n);
1308
7.00M
    if (self->ob_item == NULL) {
1309
1.45M
        if (list_preallocate_exact(self, n) < 0) {
1310
0
            return -1;
1311
0
        }
1312
1.45M
        Py_SET_SIZE(self, n);
1313
1.45M
    }
1314
5.55M
    else if (list_resize(self, m + n) < 0) {
1315
0
        return -1;
1316
0
    }
1317
1318
    // note that we may still have self == iterable here for the
1319
    // situation a.extend(a), but the following code works
1320
    // in that case too.  Just make sure to resize self
1321
    // before calling PySequence_Fast_ITEMS.
1322
    //
1323
    // populate the end of self with iterable's items.
1324
7.00M
    PyObject **src = PySequence_Fast_ITEMS(iterable);
1325
7.00M
    PyObject **dest = self->ob_item + m;
1326
37.7M
    for (Py_ssize_t i = 0; i < n; i++) {
1327
30.7M
        PyObject *o = src[i];
1328
30.7M
        FT_ATOMIC_STORE_PTR_RELEASE(dest[i], Py_NewRef(o));
1329
30.7M
    }
1330
7.00M
    return 0;
1331
7.00M
}
1332
1333
static int
1334
list_extend_iter_lock_held(PyListObject *self, PyObject *iterable)
1335
7.39M
{
1336
7.39M
    PyObject *it = PyObject_GetIter(iterable);
1337
7.39M
    if (it == NULL) {
1338
0
        return -1;
1339
0
    }
1340
7.39M
    PyObject *(*iternext)(PyObject *) = *Py_TYPE(it)->tp_iternext;
1341
1342
    /* Guess a result list size. */
1343
7.39M
    Py_ssize_t n = PyObject_LengthHint(iterable, 8);
1344
7.39M
    if (n < 0) {
1345
0
        Py_DECREF(it);
1346
0
        return -1;
1347
0
    }
1348
1349
7.39M
    Py_ssize_t m = Py_SIZE(self);
1350
7.39M
    if (m > PY_SSIZE_T_MAX - n) {
1351
        /* m + n overflowed; on the chance that n lied, and there really
1352
         * is enough room, ignore it.  If n was telling the truth, we'll
1353
         * eventually run out of memory during the loop.
1354
         */
1355
0
    }
1356
7.39M
    else if (self->ob_item == NULL) {
1357
7.06M
        if (n && list_preallocate_exact(self, n) < 0)
1358
0
            goto error;
1359
7.06M
    }
1360
324k
    else {
1361
        /* Make room. */
1362
324k
        if (list_resize(self, m + n) < 0) {
1363
0
            goto error;
1364
0
        }
1365
1366
        /* Make the list sane again. */
1367
324k
        Py_SET_SIZE(self, m);
1368
324k
    }
1369
1370
    /* Run iterator to exhaustion. */
1371
246M
    for (;;) {
1372
246M
        PyObject *item = iternext(it);
1373
246M
        if (item == NULL) {
1374
7.39M
            if (PyErr_Occurred()) {
1375
664
                if (PyErr_ExceptionMatches(PyExc_StopIteration))
1376
0
                    PyErr_Clear();
1377
664
                else
1378
664
                    goto error;
1379
664
            }
1380
7.39M
            break;
1381
7.39M
        }
1382
1383
239M
        if (Py_SIZE(self) < self->allocated) {
1384
238M
            Py_ssize_t len = Py_SIZE(self);
1385
238M
            FT_ATOMIC_STORE_PTR_RELEASE(self->ob_item[len], item);  // steals item ref
1386
238M
            Py_SET_SIZE(self, len + 1);
1387
238M
        }
1388
809k
        else {
1389
809k
            if (_PyList_AppendTakeRef(self, item) < 0)
1390
0
                goto error;
1391
809k
        }
1392
239M
    }
1393
1394
    /* Cut back result list if initial guess was too large. */
1395
7.39M
    if (Py_SIZE(self) < self->allocated) {
1396
4.64M
        if (list_resize(self, Py_SIZE(self)) < 0)
1397
0
            goto error;
1398
4.64M
    }
1399
1400
7.39M
    Py_DECREF(it);
1401
7.39M
    return 0;
1402
1403
664
  error:
1404
664
    Py_DECREF(it);
1405
664
    return -1;
1406
7.39M
}
1407
1408
static int
1409
list_extend_lock_held(PyListObject *self, PyObject *iterable)
1410
16.7M
{
1411
16.7M
    PyObject *seq = PySequence_Fast(iterable, "argument must be iterable");
1412
16.7M
    if (!seq) {
1413
0
        return -1;
1414
0
    }
1415
1416
16.7M
    int res = list_extend_fast(self, seq);
1417
16.7M
    Py_DECREF(seq);
1418
16.7M
    return res;
1419
16.7M
}
1420
1421
static int
1422
list_extend_set(PyListObject *self, PySetObject *other)
1423
1.38M
{
1424
1.38M
    Py_ssize_t m = Py_SIZE(self);
1425
1.38M
    Py_ssize_t n = PySet_GET_SIZE(other);
1426
1.38M
    Py_ssize_t r = m + n;
1427
1.38M
    if (r == 0) {
1428
4.34k
        return 0;
1429
4.34k
    }
1430
1.38M
    if (list_resize(self, r) < 0) {
1431
0
        return -1;
1432
0
    }
1433
1434
1.38M
    assert(self->ob_item != NULL);
1435
    /* populate the end of self with iterable's items */
1436
1.38M
    Py_ssize_t setpos = 0;
1437
1.38M
    Py_hash_t hash;
1438
1.38M
    PyObject *key;
1439
1.38M
    PyObject **dest = self->ob_item + m;
1440
5.09M
    while (_PySet_NextEntryRef((PyObject *)other, &setpos, &key, &hash)) {
1441
3.71M
        FT_ATOMIC_STORE_PTR_RELEASE(*dest, key);
1442
3.71M
        dest++;
1443
3.71M
    }
1444
1.38M
    Py_SET_SIZE(self, r);
1445
1.38M
    return 0;
1446
1.38M
}
1447
1448
static int
1449
list_extend_dict(PyListObject *self, PyDictObject *dict, int which_item)
1450
1.42M
{
1451
    // which_item: 0 for keys and 1 for values
1452
1.42M
    Py_ssize_t m = Py_SIZE(self);
1453
1.42M
    Py_ssize_t n = PyDict_GET_SIZE(dict);
1454
1.42M
    Py_ssize_t r = m + n;
1455
1.42M
    if (r == 0) {
1456
0
        return 0;
1457
0
    }
1458
1.42M
    if (list_resize(self, r) < 0) {
1459
0
        return -1;
1460
0
    }
1461
1462
1.42M
    assert(self->ob_item != NULL);
1463
1.42M
    PyObject **dest = self->ob_item + m;
1464
1.42M
    Py_ssize_t pos = 0;
1465
1.42M
    PyObject *keyvalue[2];
1466
4.49M
    while (_PyDict_Next((PyObject *)dict, &pos, &keyvalue[0], &keyvalue[1], NULL)) {
1467
3.07M
        PyObject *obj = keyvalue[which_item];
1468
3.07M
        Py_INCREF(obj);
1469
3.07M
        FT_ATOMIC_STORE_PTR_RELEASE(*dest, obj);
1470
3.07M
        dest++;
1471
3.07M
    }
1472
1473
1.42M
    Py_SET_SIZE(self, r);
1474
1.42M
    return 0;
1475
1.42M
}
1476
1477
static int
1478
list_extend_dictitems(PyListObject *self, PyDictObject *dict)
1479
44.5k
{
1480
44.5k
    Py_ssize_t m = Py_SIZE(self);
1481
44.5k
    Py_ssize_t n = PyDict_GET_SIZE(dict);
1482
44.5k
    Py_ssize_t r = m + n;
1483
44.5k
    if (r == 0) {
1484
0
        return 0;
1485
0
    }
1486
44.5k
    if (list_resize(self, r) < 0) {
1487
0
        return -1;
1488
0
    }
1489
1490
44.5k
    assert(self->ob_item != NULL);
1491
44.5k
    PyObject **dest = self->ob_item + m;
1492
44.5k
    Py_ssize_t pos = 0;
1493
44.5k
    Py_ssize_t i = 0;
1494
44.5k
    PyObject *key, *value;
1495
223k
    while (_PyDict_Next((PyObject *)dict, &pos, &key, &value, NULL)) {
1496
178k
        PyObject *item = _PyTuple_FromPair(key, value);
1497
178k
        if (item == NULL) {
1498
0
            Py_SET_SIZE(self, m + i);
1499
0
            return -1;
1500
0
        }
1501
178k
        FT_ATOMIC_STORE_PTR_RELEASE(*dest, item);
1502
178k
        dest++;
1503
178k
        i++;
1504
178k
    }
1505
1506
44.5k
    Py_SET_SIZE(self, r);
1507
44.5k
    return 0;
1508
44.5k
}
1509
1510
static int
1511
_list_extend(PyListObject *self, PyObject *iterable)
1512
27.0M
{
1513
    // Special case:
1514
    // lists and tuples which can use PySequence_Fast ops
1515
27.0M
    int res = -1;
1516
27.0M
    if ((PyObject *)self == iterable) {
1517
0
        Py_BEGIN_CRITICAL_SECTION(self);
1518
0
        res = list_inplace_repeat_lock_held(self, 2);
1519
0
        Py_END_CRITICAL_SECTION();
1520
0
    }
1521
27.0M
    else if (PyList_CheckExact(iterable)) {
1522
11.2M
        Py_BEGIN_CRITICAL_SECTION2(self, iterable);
1523
11.2M
        res = list_extend_lock_held(self, iterable);
1524
11.2M
        Py_END_CRITICAL_SECTION2();
1525
11.2M
    }
1526
15.7M
    else if (PyTuple_CheckExact(iterable)) {
1527
5.55M
        Py_BEGIN_CRITICAL_SECTION(self);
1528
5.55M
        res = list_extend_lock_held(self, iterable);
1529
5.55M
        Py_END_CRITICAL_SECTION();
1530
5.55M
    }
1531
10.2M
    else if (PyAnySet_CheckExact(iterable)) {
1532
1.38M
        Py_BEGIN_CRITICAL_SECTION2(self, iterable);
1533
1.38M
        res = list_extend_set(self, (PySetObject *)iterable);
1534
1.38M
        Py_END_CRITICAL_SECTION2();
1535
1.38M
    }
1536
8.85M
    else if (PyDict_CheckExact(iterable)) {
1537
1.42M
        Py_BEGIN_CRITICAL_SECTION2(self, iterable);
1538
1.42M
        res = list_extend_dict(self, (PyDictObject *)iterable, 0 /*keys*/);
1539
1.42M
        Py_END_CRITICAL_SECTION2();
1540
1.42M
    }
1541
7.43M
    else if (Py_IS_TYPE(iterable, &PyDictKeys_Type)) {
1542
4
        PyDictObject *dict = ((_PyDictViewObject *)iterable)->dv_dict;
1543
4
        Py_BEGIN_CRITICAL_SECTION2(self, dict);
1544
4
        res = list_extend_dict(self, dict, 0 /*keys*/);
1545
4
        Py_END_CRITICAL_SECTION2();
1546
4
    }
1547
7.43M
    else if (Py_IS_TYPE(iterable, &PyDictValues_Type)) {
1548
9
        PyDictObject *dict = ((_PyDictViewObject *)iterable)->dv_dict;
1549
9
        Py_BEGIN_CRITICAL_SECTION2(self, dict);
1550
9
        res = list_extend_dict(self, dict, 1 /*values*/);
1551
9
        Py_END_CRITICAL_SECTION2();
1552
9
    }
1553
7.43M
    else if (Py_IS_TYPE(iterable, &PyDictItems_Type)) {
1554
44.5k
        PyDictObject *dict = ((_PyDictViewObject *)iterable)->dv_dict;
1555
44.5k
        Py_BEGIN_CRITICAL_SECTION2(self, dict);
1556
44.5k
        res = list_extend_dictitems(self, dict);
1557
44.5k
        Py_END_CRITICAL_SECTION2();
1558
44.5k
    }
1559
7.39M
    else {
1560
7.39M
        Py_BEGIN_CRITICAL_SECTION(self);
1561
7.39M
        res = list_extend_iter_lock_held(self, iterable);
1562
7.39M
        Py_END_CRITICAL_SECTION();
1563
7.39M
    }
1564
27.0M
    return res;
1565
27.0M
}
1566
1567
/*[clinic input]
1568
list.extend as list_extend
1569
1570
     iterable: object
1571
     /
1572
1573
Extend list by appending elements from the iterable.
1574
[clinic start generated code]*/
1575
1576
static PyObject *
1577
list_extend_impl(PyListObject *self, PyObject *iterable)
1578
/*[clinic end generated code: output=b0eba9e0b186d5ce input=979da7597a515791]*/
1579
15.4M
{
1580
15.4M
    if (_list_extend(self, iterable) < 0) {
1581
664
        return NULL;
1582
664
    }
1583
15.4M
    Py_RETURN_NONE;
1584
15.4M
}
1585
1586
PyObject *
1587
_PyList_Extend(PyListObject *self, PyObject *iterable)
1588
14.1M
{
1589
14.1M
    return list_extend((PyObject*)self, iterable);
1590
14.1M
}
1591
1592
int
1593
PyList_Extend(PyObject *self, PyObject *iterable)
1594
0
{
1595
0
    if (!PyList_Check(self)) {
1596
0
        PyErr_BadInternalCall();
1597
0
        return -1;
1598
0
    }
1599
0
    return _list_extend((PyListObject*)self, iterable);
1600
0
}
1601
1602
1603
int
1604
PyList_Clear(PyObject *self)
1605
0
{
1606
0
    if (!PyList_Check(self)) {
1607
0
        PyErr_BadInternalCall();
1608
0
        return -1;
1609
0
    }
1610
0
    Py_BEGIN_CRITICAL_SECTION(self);
1611
0
    list_clear((PyListObject*)self);
1612
0
    Py_END_CRITICAL_SECTION();
1613
0
    return 0;
1614
0
}
1615
1616
1617
static PyObject *
1618
list_inplace_concat(PyObject *_self, PyObject *other)
1619
102k
{
1620
102k
    PyListObject *self = (PyListObject *)_self;
1621
102k
    if (_list_extend(self, other) < 0) {
1622
0
        return NULL;
1623
0
    }
1624
102k
    return Py_NewRef(self);
1625
102k
}
1626
1627
/*[clinic input]
1628
@critical_section
1629
list.pop
1630
1631
    index: Py_ssize_t = -1
1632
    /
1633
1634
Remove and return item at index (default last).
1635
1636
Raises IndexError if list is empty or index is out of range.
1637
[clinic start generated code]*/
1638
1639
static PyObject *
1640
list_pop_impl(PyListObject *self, Py_ssize_t index)
1641
/*[clinic end generated code: output=6bd69dcb3f17eca8 input=c269141068ae4b8f]*/
1642
18.9M
{
1643
18.9M
    PyObject *v;
1644
1645
18.9M
    if (Py_SIZE(self) == 0) {
1646
        /* Special-case most common failure cause */
1647
0
        PyErr_SetString(PyExc_IndexError, "pop from empty list");
1648
0
        return NULL;
1649
0
    }
1650
18.9M
    if (index < 0)
1651
17.8M
        index += Py_SIZE(self);
1652
18.9M
    if (!valid_index(index, Py_SIZE(self))) {
1653
0
        PyErr_SetString(PyExc_IndexError, "pop index out of range");
1654
0
        return NULL;
1655
0
    }
1656
1657
18.9M
    PyObject **items = self->ob_item;
1658
18.9M
    v = items[index];
1659
18.9M
    if (Py_SIZE(self) == 1) {
1660
7.10M
        Py_INCREF(v);
1661
7.10M
        list_clear(self);
1662
7.10M
        return v;
1663
7.10M
    }
1664
11.8M
    Py_ssize_t size_after_pop = Py_SIZE(self) - 1;
1665
11.8M
    if (index < size_after_pop) {
1666
1.13M
        ptr_wise_atomic_memmove(self, &items[index], &items[index+1],
1667
1.13M
                                size_after_pop - index);
1668
1.13M
    }
1669
11.8M
    list_resize(self, size_after_pop);  // NB: shrinking a list can't fail
1670
11.8M
    return v;
1671
18.9M
}
1672
1673
/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
1674
static void
1675
reverse_slice(PyObject **lo, PyObject **hi)
1676
265k
{
1677
265k
    assert(lo && hi);
1678
1679
265k
    --hi;
1680
4.11M
    while (lo < hi) {
1681
3.85M
        PyObject *t = *lo;
1682
3.85M
        FT_ATOMIC_STORE_PTR_RELEASE(*lo, *hi);
1683
3.85M
        FT_ATOMIC_STORE_PTR_RELEASE(*hi, t);
1684
3.85M
        ++lo;
1685
3.85M
        --hi;
1686
3.85M
    }
1687
265k
}
1688
1689
/* Lots of code for an adaptive, stable, natural mergesort.  There are many
1690
 * pieces to this algorithm; read listsort.txt for overviews and details.
1691
 */
1692
1693
/* A sortslice contains a pointer to an array of keys and a pointer to
1694
 * an array of corresponding values.  In other words, keys[i]
1695
 * corresponds with values[i].  If values == NULL, then the keys are
1696
 * also the values.
1697
 *
1698
 * Several convenience routines are provided here, so that keys and
1699
 * values are always moved in sync.
1700
 */
1701
1702
typedef struct {
1703
    PyObject **keys;
1704
    PyObject **values;
1705
} sortslice;
1706
1707
Py_LOCAL_INLINE(void)
1708
sortslice_copy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j)
1709
38.5k
{
1710
38.5k
    s1->keys[i] = s2->keys[j];
1711
38.5k
    if (s1->values != NULL)
1712
32.1k
        s1->values[i] = s2->values[j];
1713
38.5k
}
1714
1715
Py_LOCAL_INLINE(void)
1716
sortslice_copy_incr(sortslice *dst, sortslice *src)
1717
1.20M
{
1718
1.20M
    *dst->keys++ = *src->keys++;
1719
1.20M
    if (dst->values != NULL)
1720
618k
        *dst->values++ = *src->values++;
1721
1.20M
}
1722
1723
Py_LOCAL_INLINE(void)
1724
sortslice_copy_decr(sortslice *dst, sortslice *src)
1725
2.77M
{
1726
2.77M
    *dst->keys-- = *src->keys--;
1727
2.77M
    if (dst->values != NULL)
1728
516k
        *dst->values-- = *src->values--;
1729
2.77M
}
1730
1731
1732
Py_LOCAL_INLINE(void)
1733
sortslice_memcpy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
1734
                 Py_ssize_t n)
1735
187k
{
1736
187k
    memcpy(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
1737
187k
    if (s1->values != NULL)
1738
166k
        memcpy(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
1739
187k
}
1740
1741
Py_LOCAL_INLINE(void)
1742
sortslice_memmove(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
1743
                  Py_ssize_t n)
1744
134k
{
1745
134k
    memmove(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
1746
134k
    if (s1->values != NULL)
1747
114k
        memmove(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
1748
134k
}
1749
1750
Py_LOCAL_INLINE(void)
1751
sortslice_advance(sortslice *slice, Py_ssize_t n)
1752
1.44M
{
1753
1.44M
    slice->keys += n;
1754
1.44M
    if (slice->values != NULL)
1755
643k
        slice->values += n;
1756
1.44M
}
1757
1758
/* Comparison function: ms->key_compare, which is set at run-time in
1759
 * listsort_impl to optimize for various special cases.
1760
 * Returns -1 on error, 1 if x < y, 0 if x >= y.
1761
 */
1762
1763
26.4M
#define ISLT(X, Y) (*(ms->key_compare))(X, Y, ms)
1764
1765
/* Compare X to Y via "<".  Goto "fail" if the comparison raises an
1766
   error.  Else "k" is set to true iff X<Y, and an "if (k)" block is
1767
   started.  It makes more sense in context <wink>.  X and Y are PyObject*s.
1768
*/
1769
22.7M
#define IFLT(X, Y) if ((k = ISLT(X, Y)) < 0) goto fail;  \
1770
22.7M
           if (k)
1771
1772
/* The maximum number of entries in a MergeState's pending-runs stack.
1773
 * For a list with n elements, this needs at most floor(log2(n)) + 1 entries
1774
 * even if we didn't force runs to a minimal length.  So the number of bits
1775
 * in a Py_ssize_t is plenty large enough for all cases.
1776
 */
1777
#define MAX_MERGE_PENDING (SIZEOF_SIZE_T * 8)
1778
1779
/* When we get into galloping mode, we stay there until both runs win less
1780
 * often than MIN_GALLOP consecutive times.  See listsort.txt for more info.
1781
 */
1782
2.54M
#define MIN_GALLOP 7
1783
1784
/* Avoid malloc for small temp arrays. */
1785
3.71M
#define MERGESTATE_TEMP_SIZE 256
1786
1787
/* The largest value of minrun. This must be a power of 2, and >= 1 */
1788
2.31M
#define MAX_MINRUN 64
1789
#if ((MAX_MINRUN) < 1) || ((MAX_MINRUN) & ((MAX_MINRUN) - 1))
1790
#error "MAX_MINRUN must be a power of 2, and >= 1"
1791
#endif
1792
1793
/* One MergeState exists on the stack per invocation of mergesort.  It's just
1794
 * a convenient way to pass state around among the helper functions.
1795
 */
1796
struct s_slice {
1797
    sortslice base;
1798
    Py_ssize_t len;   /* length of run */
1799
    int power; /* node "level" for powersort merge strategy */
1800
};
1801
1802
typedef struct s_MergeState MergeState;
1803
struct s_MergeState {
1804
    /* This controls when we get *into* galloping mode.  It's initialized
1805
     * to MIN_GALLOP.  merge_lo and merge_hi tend to nudge it higher for
1806
     * random data, and lower for highly structured data.
1807
     */
1808
    Py_ssize_t min_gallop;
1809
1810
    Py_ssize_t listlen;     /* len(input_list) - read only */
1811
    PyObject **basekeys;    /* base address of keys array - read only */
1812
1813
    /* 'a' is temp storage to help with merges.  It contains room for
1814
     * alloced entries.
1815
     */
1816
    sortslice a;        /* may point to temparray below */
1817
    Py_ssize_t alloced;
1818
1819
    /* A stack of n pending runs yet to be merged.  Run #i starts at
1820
     * address base[i] and extends for len[i] elements.  It's always
1821
     * true (so long as the indices are in bounds) that
1822
     *
1823
     *     pending[i].base + pending[i].len == pending[i+1].base
1824
     *
1825
     * so we could cut the storage for this, but it's a minor amount,
1826
     * and keeping all the info explicit simplifies the code.
1827
     */
1828
    int n;
1829
    struct s_slice pending[MAX_MERGE_PENDING];
1830
1831
    /* 'a' points to this when possible, rather than muck with malloc. */
1832
    PyObject *temparray[MERGESTATE_TEMP_SIZE];
1833
1834
    /* This is the function we will use to compare two keys,
1835
     * even when none of our special cases apply and we have to use
1836
     * safe_object_compare. */
1837
    int (*key_compare)(PyObject *, PyObject *, MergeState *);
1838
1839
    /* This function is used by unsafe_object_compare to optimize comparisons
1840
     * when we know our list is type-homogeneous but we can't assume anything else.
1841
     * In the pre-sort check it is set equal to Py_TYPE(key)->tp_richcompare */
1842
    PyObject *(*key_richcompare)(PyObject *, PyObject *, int);
1843
1844
    /* This function is used by unsafe_tuple_compare to compare the first elements
1845
     * of tuples. It may be set to safe_object_compare, but the idea is that hopefully
1846
     * we can assume more, and use one of the special-case compares. */
1847
    int (*tuple_elem_compare)(PyObject *, PyObject *, MergeState *);
1848
1849
    /* Varisbles used for minrun computation. The "ideal" minrun length is
1850
     * the infinite precision listlen / 2**e. See listsort.txt.
1851
     */
1852
     Py_ssize_t mr_current, mr_e, mr_mask;
1853
};
1854
1855
/* binarysort is the best method for sorting small arrays: it does few
1856
   compares, but can do data movement quadratic in the number of elements.
1857
   ss->keys is viewed as an array of n kays, a[:n]. a[:ok] is already sorted.
1858
   Pass ok = 0 (or 1) if you don't know.
1859
   It's sorted in-place, by a stable binary insertion sort. If ss->values
1860
   isn't NULL, it's permuted in lockstap with ss->keys.
1861
   On entry, must have n >= 1, and 0 <= ok <= n <= MAX_MINRUN.
1862
   Return -1 if comparison raises an exception, else 0.
1863
   Even in case of error, the output slice will be some permutation of
1864
   the input (nothing is lost or duplicated).
1865
*/
1866
static int
1867
binarysort(MergeState *ms, const sortslice *ss, Py_ssize_t n, Py_ssize_t ok)
1868
442k
{
1869
442k
    Py_ssize_t k; /* for IFLT macro expansion */
1870
442k
    PyObject ** const a = ss->keys;
1871
442k
    PyObject ** const v = ss->values;
1872
442k
    const bool has_values = v != NULL;
1873
442k
    PyObject *pivot;
1874
442k
    Py_ssize_t M;
1875
1876
442k
    assert(0 <= ok && ok <= n && 1 <= n && n <= MAX_MINRUN);
1877
    /* assert a[:ok] is sorted */
1878
442k
    if (! ok)
1879
0
        ++ok;
1880
    /* Regular insertion sort has average- and worst-case O(n**2) cost
1881
       for both # of comparisons and number of bytes moved. But its branches
1882
       are highly predictable, and it loves sorted input (n-1 compares and no
1883
       data movement). This is significant in cases like sortperf.py's %sort,
1884
       where an out-of-order element near the start of a run is moved into
1885
       place slowly but then the remaining elements up to length minrun are
1886
       generally at worst one slot away from their correct position (so only
1887
       need 1 or 2 commpares to resolve). If comparisons are very fast (such
1888
       as for a list of Python floats), the simple inner loop leaves it
1889
       very competitive with binary insertion, despite that it does
1890
       significantly more compares overall on random data.
1891
1892
       Binary insertion sort has worst, average, and best case O(n log n)
1893
       cost for # of comparisons, but worst and average case O(n**2) cost
1894
       for data movement. The more expensive comparisons, the more important
1895
       the comparison advantage. But its branches are less predictable the
1896
       more "randomish" the data, and that's so significant its worst case
1897
       in real life is random input rather than reverse-ordered (which does
1898
       about twice the data movement than random input does).
1899
1900
       Note that the number of bytes moved doesn't seem to matter. MAX_MINRUN
1901
       of 64 is so small that the key and value pointers all fit in a corner
1902
       of L1 cache, and moving things around in that is very fast. */
1903
#if 0 // ordinary insertion sort.
1904
    PyObject * vpivot = NULL;
1905
    for (; ok < n; ++ok) {
1906
        pivot = a[ok];
1907
        if (has_values)
1908
            vpivot = v[ok];
1909
        for (M = ok - 1; M >= 0; --M) {
1910
            k = ISLT(pivot, a[M]);
1911
            if (k < 0) {
1912
                a[M + 1] = pivot;
1913
                if (has_values)
1914
                    v[M + 1] = vpivot;
1915
                goto fail;
1916
            }
1917
            else if (k) {
1918
                a[M + 1] = a[M];
1919
                if (has_values)
1920
                    v[M + 1] = v[M];
1921
            }
1922
            else
1923
                break;
1924
        }
1925
        a[M + 1] = pivot;
1926
        if (has_values)
1927
            v[M + 1] = vpivot;
1928
    }
1929
#else // binary insertion sort
1930
442k
    Py_ssize_t L, R;
1931
4.20M
    for (; ok < n; ++ok) {
1932
        /* set L to where a[ok] belongs */
1933
3.76M
        L = 0;
1934
3.76M
        R = ok;
1935
3.76M
        pivot = a[ok];
1936
        /* Slice invariants. vacuously true at the start:
1937
         * all a[0:L]  <= pivot
1938
         * all a[L:R]     unknown
1939
         * all a[R:ok]  > pivot
1940
         */
1941
3.76M
        assert(L < R);
1942
13.6M
        do {
1943
            /* don't do silly ;-) things to prevent overflow when finding
1944
               the midpoint; L and R are very far from filling a Py_ssize_t */
1945
13.6M
            M = (L + R) >> 1;
1946
13.6M
#if 1 // straightforward, but highly unpredictable branch on random data
1947
13.6M
            IFLT(pivot, a[M])
1948
6.16M
                R = M;
1949
7.49M
            else
1950
7.49M
                L = M + 1;
1951
#else
1952
            /* Try to get compiler to generate conditional move instructions
1953
               instead. Works fine, but leaving it disabled for now because
1954
               it's not yielding consistently faster sorts. Needs more
1955
               investigation. More computation in the inner loop adds its own
1956
               costs, which can be significant when compares are fast. */
1957
            k = ISLT(pivot, a[M]);
1958
            if (k < 0)
1959
                goto fail;
1960
            Py_ssize_t Mp1 = M + 1;
1961
            R = k ? M : R;
1962
            L = k ? L : Mp1;
1963
#endif
1964
13.6M
        } while (L < R);
1965
3.76M
        assert(L == R);
1966
        /* a[:L] holds all elements from a[:ok] <= pivot now, so pivot belongs
1967
           at index L. Slide a[L:ok] to the right a slot to make room for it.
1968
           Caution: using memmove is much slower under MSVC 5; we're not
1969
           usually moving many slots. Years later: under Visual Studio 2022,
1970
           memmove seems just slightly slower than doing it "by hand". */
1971
23.1M
        for (M = ok; M > L; --M)
1972
19.3M
            a[M] = a[M - 1];
1973
3.76M
        a[L] = pivot;
1974
3.76M
        if (has_values) {
1975
1.61M
            pivot = v[ok];
1976
8.67M
            for (M = ok; M > L; --M)
1977
7.05M
                v[M] = v[M - 1];
1978
1.61M
            v[L] = pivot;
1979
1.61M
        }
1980
3.76M
    }
1981
442k
#endif // pick binary or regular insertion sort
1982
442k
    return 0;
1983
1984
0
 fail:
1985
0
    return -1;
1986
442k
}
1987
1988
static void
1989
sortslice_reverse(sortslice *s, Py_ssize_t n)
1990
219k
{
1991
219k
    reverse_slice(s->keys, &s->keys[n]);
1992
219k
    if (s->values != NULL)
1993
45.5k
        reverse_slice(s->values, &s->values[n]);
1994
219k
}
1995
1996
/*
1997
Return the length of the run beginning at slo->keys, spanning no more than
1998
nremaining elements. The run beginning there may be ascending or descending,
1999
but the function permutes it in place, if needed, so that it's always ascending
2000
upon return.
2001
2002
Returns -1 in case of error.
2003
*/
2004
static Py_ssize_t
2005
count_run(MergeState *ms, sortslice *slo, Py_ssize_t nremaining)
2006
924k
{
2007
924k
    Py_ssize_t k; /* used by IFLT macro expansion */
2008
924k
    Py_ssize_t n;
2009
924k
    PyObject ** const lo = slo->keys;
2010
2011
    /* In general, as things go on we've established that the slice starts
2012
       with a monotone run of n elements, starting at lo. */
2013
2014
    /* We're n elements into the slice, and the most recent neq+1 elements are
2015
     * all equal. This reverses them in-place, and resets neq for reuse.
2016
     */
2017
924k
#define REVERSE_LAST_NEQ                        \
2018
2.57M
    if (neq) {                                  \
2019
9.62k
        sortslice slice = *slo;                 \
2020
9.62k
        ++neq;                                  \
2021
9.62k
        sortslice_advance(&slice, n - neq);     \
2022
9.62k
        sortslice_reverse(&slice, neq);         \
2023
9.62k
        neq = 0;                                \
2024
9.62k
    }
2025
2026
    /* Sticking to only __lt__ compares is confusing and error-prone. But in
2027
     * this routine, almost all uses of IFLT can be captured by tiny macros
2028
     * giving mnemonic names to the intent. Note that inline functions don't
2029
     * work for this (IFLT expands to code including `goto fail`).
2030
     */
2031
924k
#define IF_NEXT_LARGER  IFLT(lo[n-1], lo[n])
2032
6.49M
#define IF_NEXT_SMALLER IFLT(lo[n], lo[n-1])
2033
2034
924k
    assert(nremaining);
2035
    /* try ascending run first */
2036
3.82M
    for (n = 1; n < nremaining; ++n) {
2037
3.48M
        IF_NEXT_SMALLER
2038
582k
            break;
2039
3.48M
    }
2040
924k
    if (n == nremaining)
2041
342k
        return n;
2042
    /* lo[n] is strictly less */
2043
    /* If n is 1 now, then the first compare established it's a descending
2044
     * run, so fall through to the descending case. But if n > 1, there are
2045
     * n elements in an ascending run terminated by the strictly less lo[n].
2046
     * If the first key < lo[n-1], *somewhere* along the way the sequence
2047
     * increased, so we're done (there is no descending run).
2048
     * Else first key >= lo[n-1], which implies that the entire ascending run
2049
     * consists of equal elements. In that case, this is a descending run,
2050
     * and we reverse the all-equal prefix in-place.
2051
     */
2052
582k
    if (n > 1) {
2053
382k
        IFLT(lo[0], lo[n-1])
2054
377k
            return n;
2055
4.97k
        sortslice_reverse(slo, n);
2056
4.97k
    }
2057
205k
    ++n; /* in all cases it's been established that lo[n] has been resolved */
2058
2059
    /* Finish descending run. All-squal subruns are reversed in-place on the
2060
     * fly. Their original order will be restored at the end by the whole-slice
2061
     * reversal.
2062
     */
2063
205k
    Py_ssize_t neq = 0;
2064
2.61M
    for ( ; n < nremaining; ++n) {
2065
2.56M
        IF_NEXT_SMALLER {
2066
            /* This ends the most recent run of equal elements, but still in
2067
             * the "descending" direction.
2068
             */
2069
2.37M
            REVERSE_LAST_NEQ
2070
2.37M
        }
2071
194k
        else {
2072
194k
            IF_NEXT_LARGER /* descending run is over */
2073
162k
                break;
2074
32.1k
            else /* not x < y and not y < x implies x == y */
2075
32.1k
                ++neq;
2076
194k
        }
2077
2.56M
    }
2078
205k
    REVERSE_LAST_NEQ
2079
205k
    sortslice_reverse(slo, n); /* transform to ascending run */
2080
2081
    /* And after reversing, it's possible this can be extended by a
2082
     * naturally increasing suffix; e.g., [3, 2, 3, 4, 1] makes an
2083
     * ascending run from the first 4 elements.
2084
     */
2085
570k
    for ( ; n < nremaining; ++n) {
2086
442k
        IF_NEXT_SMALLER
2087
77.5k
            break;
2088
442k
    }
2089
2090
205k
    return n;
2091
0
fail:
2092
0
    return -1;
2093
2094
205k
#undef REVERSE_LAST_NEQ
2095
205k
#undef IF_NEXT_SMALLER
2096
205k
#undef IF_NEXT_LARGER
2097
205k
}
2098
2099
/*
2100
Locate the proper position of key in a sorted vector; if the vector contains
2101
an element equal to key, return the position immediately to the left of
2102
the leftmost equal element.  [gallop_right() does the same except returns
2103
the position to the right of the rightmost equal element (if any).]
2104
2105
"a" is a sorted vector with n elements, starting at a[0].  n must be > 0.
2106
2107
"hint" is an index at which to begin the search, 0 <= hint < n.  The closer
2108
hint is to the final result, the faster this runs.
2109
2110
The return value is the int k in 0..n such that
2111
2112
    a[k-1] < key <= a[k]
2113
2114
pretending that *(a-1) is minus infinity and a[n] is plus infinity.  IOW,
2115
key belongs at index k; or, IOW, the first k elements of a should precede
2116
key, and the last n-k should follow key.
2117
2118
Returns -1 on error.  See listsort.txt for info on the method.
2119
*/
2120
static Py_ssize_t
2121
gallop_left(MergeState *ms, PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
2122
189k
{
2123
189k
    Py_ssize_t ofs;
2124
189k
    Py_ssize_t lastofs;
2125
189k
    Py_ssize_t k;
2126
2127
189k
    assert(key && a && n > 0 && hint >= 0 && hint < n);
2128
2129
189k
    a += hint;
2130
189k
    lastofs = 0;
2131
189k
    ofs = 1;
2132
189k
    IFLT(*a, key) {
2133
        /* a[hint] < key -- gallop right, until
2134
         * a[hint + lastofs] < key <= a[hint + ofs]
2135
         */
2136
96.0k
        const Py_ssize_t maxofs = n - hint;             /* &a[n-1] is highest */
2137
287k
        while (ofs < maxofs) {
2138
221k
            IFLT(a[ofs], key) {
2139
191k
                lastofs = ofs;
2140
191k
                assert(ofs <= (PY_SSIZE_T_MAX - 1) / 2);
2141
191k
                ofs = (ofs << 1) + 1;
2142
191k
            }
2143
29.4k
            else                /* key <= a[hint + ofs] */
2144
29.4k
                break;
2145
221k
        }
2146
96.0k
        if (ofs > maxofs)
2147
26.0k
            ofs = maxofs;
2148
        /* Translate back to offsets relative to &a[0]. */
2149
96.0k
        lastofs += hint;
2150
96.0k
        ofs += hint;
2151
96.0k
    }
2152
93.4k
    else {
2153
        /* key <= a[hint] -- gallop left, until
2154
         * a[hint - ofs] < key <= a[hint - lastofs]
2155
         */
2156
93.4k
        const Py_ssize_t maxofs = hint + 1;             /* &a[0] is lowest */
2157
288k
        while (ofs < maxofs) {
2158
256k
            IFLT(*(a-ofs), key)
2159
60.6k
                break;
2160
            /* key <= a[hint - ofs] */
2161
195k
            lastofs = ofs;
2162
195k
            assert(ofs <= (PY_SSIZE_T_MAX - 1) / 2);
2163
195k
            ofs = (ofs << 1) + 1;
2164
195k
        }
2165
93.4k
        if (ofs > maxofs)
2166
18.3k
            ofs = maxofs;
2167
        /* Translate back to positive offsets relative to &a[0]. */
2168
93.4k
        k = lastofs;
2169
93.4k
        lastofs = hint - ofs;
2170
93.4k
        ofs = hint - k;
2171
93.4k
    }
2172
189k
    a -= hint;
2173
2174
189k
    assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
2175
    /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
2176
     * right of lastofs but no farther right than ofs.  Do a binary
2177
     * search, with invariant a[lastofs-1] < key <= a[ofs].
2178
     */
2179
189k
    ++lastofs;
2180
525k
    while (lastofs < ofs) {
2181
335k
        Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
2182
2183
335k
        IFLT(a[m], key)
2184
170k
            lastofs = m+1;              /* a[m] < key */
2185
165k
        else
2186
165k
            ofs = m;                    /* key <= a[m] */
2187
335k
    }
2188
189k
    assert(lastofs == ofs);             /* so a[ofs-1] < key <= a[ofs] */
2189
189k
    return ofs;
2190
2191
0
fail:
2192
0
    return -1;
2193
189k
}
2194
2195
/*
2196
Exactly like gallop_left(), except that if key already exists in a[0:n],
2197
finds the position immediately to the right of the rightmost equal value.
2198
2199
The return value is the int k in 0..n such that
2200
2201
    a[k-1] <= key < a[k]
2202
2203
or -1 if error.
2204
2205
The code duplication is massive, but this is enough different given that
2206
we're sticking to "<" comparisons that it's much harder to follow if
2207
written as one routine with yet another "left or right?" flag.
2208
*/
2209
static Py_ssize_t
2210
gallop_right(MergeState *ms, PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
2211
209k
{
2212
209k
    Py_ssize_t ofs;
2213
209k
    Py_ssize_t lastofs;
2214
209k
    Py_ssize_t k;
2215
2216
209k
    assert(key && a && n > 0 && hint >= 0 && hint < n);
2217
2218
209k
    a += hint;
2219
209k
    lastofs = 0;
2220
209k
    ofs = 1;
2221
209k
    IFLT(key, *a) {
2222
        /* key < a[hint] -- gallop left, until
2223
         * a[hint - ofs] <= key < a[hint - lastofs]
2224
         */
2225
81.1k
        const Py_ssize_t maxofs = hint + 1;             /* &a[0] is lowest */
2226
198k
        while (ofs < maxofs) {
2227
140k
            IFLT(key, *(a-ofs)) {
2228
117k
                lastofs = ofs;
2229
117k
                assert(ofs <= (PY_SSIZE_T_MAX - 1) / 2);
2230
117k
                ofs = (ofs << 1) + 1;
2231
117k
            }
2232
22.5k
            else                /* a[hint - ofs] <= key */
2233
22.5k
                break;
2234
140k
        }
2235
81.1k
        if (ofs > maxofs)
2236
11.4k
            ofs = maxofs;
2237
        /* Translate back to positive offsets relative to &a[0]. */
2238
81.1k
        k = lastofs;
2239
81.1k
        lastofs = hint - ofs;
2240
81.1k
        ofs = hint - k;
2241
81.1k
    }
2242
128k
    else {
2243
        /* a[hint] <= key -- gallop right, until
2244
         * a[hint + lastofs] <= key < a[hint + ofs]
2245
        */
2246
128k
        const Py_ssize_t maxofs = n - hint;             /* &a[n-1] is highest */
2247
409k
        while (ofs < maxofs) {
2248
357k
            IFLT(key, a[ofs])
2249
76.5k
                break;
2250
            /* a[hint + ofs] <= key */
2251
280k
            lastofs = ofs;
2252
280k
            assert(ofs <= (PY_SSIZE_T_MAX - 1) / 2);
2253
280k
            ofs = (ofs << 1) + 1;
2254
280k
        }
2255
128k
        if (ofs > maxofs)
2256
27.6k
            ofs = maxofs;
2257
        /* Translate back to offsets relative to &a[0]. */
2258
128k
        lastofs += hint;
2259
128k
        ofs += hint;
2260
128k
    }
2261
209k
    a -= hint;
2262
2263
209k
    assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
2264
    /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
2265
     * right of lastofs but no farther right than ofs.  Do a binary
2266
     * search, with invariant a[lastofs-1] <= key < a[ofs].
2267
     */
2268
209k
    ++lastofs;
2269
558k
    while (lastofs < ofs) {
2270
348k
        Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
2271
2272
348k
        IFLT(key, a[m])
2273
179k
            ofs = m;                    /* key < a[m] */
2274
169k
        else
2275
169k
            lastofs = m+1;              /* a[m] <= key */
2276
348k
    }
2277
209k
    assert(lastofs == ofs);             /* so a[ofs-1] <= key < a[ofs] */
2278
209k
    return ofs;
2279
2280
0
fail:
2281
0
    return -1;
2282
209k
}
2283
2284
/* Conceptually a MergeState's constructor. */
2285
static void
2286
merge_init(MergeState *ms, Py_ssize_t list_size, int has_keyfunc,
2287
           sortslice *lo)
2288
2.28M
{
2289
2.28M
    assert(ms != NULL);
2290
2.28M
    if (has_keyfunc) {
2291
        /* The temporary space for merging will need at most half the list
2292
         * size rounded up.  Use the minimum possible space so we can use the
2293
         * rest of temparray for other things.  In particular, if there is
2294
         * enough extra space, listsort() will use it to store the keys.
2295
         */
2296
713k
        ms->alloced = (list_size + 1) / 2;
2297
2298
        /* ms->alloced describes how many keys will be stored at
2299
           ms->temparray, but we also need to store the values.  Hence,
2300
           ms->alloced is capped at half of MERGESTATE_TEMP_SIZE. */
2301
713k
        if (MERGESTATE_TEMP_SIZE / 2 < ms->alloced)
2302
2.40k
            ms->alloced = MERGESTATE_TEMP_SIZE / 2;
2303
713k
        ms->a.values = &ms->temparray[ms->alloced];
2304
713k
    }
2305
1.57M
    else {
2306
1.57M
        ms->alloced = MERGESTATE_TEMP_SIZE;
2307
1.57M
        ms->a.values = NULL;
2308
1.57M
    }
2309
2.28M
    ms->a.keys = ms->temparray;
2310
2.28M
    ms->n = 0;
2311
2.28M
    ms->min_gallop = MIN_GALLOP;
2312
2.28M
    ms->listlen = list_size;
2313
2.28M
    ms->basekeys = lo->keys;
2314
2315
    /* State for generating minrun values. See listsort.txt. */
2316
2.28M
    ms->mr_e = 0;
2317
2.31M
    while (list_size >> ms->mr_e >= MAX_MINRUN) {
2318
30.7k
        ++ms->mr_e;
2319
30.7k
    }
2320
2.28M
    ms->mr_mask = ((Py_ssize_t)1 << ms->mr_e) - 1;
2321
2.28M
    ms->mr_current = 0;
2322
2.28M
}
2323
2324
/* Free all the temp memory owned by the MergeState.  This must be called
2325
 * when you're done with a MergeState, and may be called before then if
2326
 * you want to free the temp memory early.
2327
 */
2328
static void
2329
merge_freemem(MergeState *ms)
2330
2.29M
{
2331
2.29M
    assert(ms != NULL);
2332
2.29M
    if (ms->a.keys != ms->temparray) {
2333
4.70k
        PyMem_Free(ms->a.keys);
2334
4.70k
        ms->a.keys = NULL;
2335
4.70k
    }
2336
2.29M
}
2337
2338
/* Ensure enough temp memory for 'need' array slots is available.
2339
 * Returns 0 on success and -1 if the memory can't be gotten.
2340
 */
2341
static int
2342
merge_getmem(MergeState *ms, Py_ssize_t need)
2343
4.70k
{
2344
4.70k
    int multiplier;
2345
2346
4.70k
    assert(ms != NULL);
2347
4.70k
    if (need <= ms->alloced)
2348
0
        return 0;
2349
2350
4.70k
    multiplier = ms->a.values != NULL ? 2 : 1;
2351
2352
    /* Don't realloc!  That can cost cycles to copy the old data, but
2353
     * we don't care what's in the block.
2354
     */
2355
4.70k
    merge_freemem(ms);
2356
4.70k
    if ((size_t)need > PY_SSIZE_T_MAX / sizeof(PyObject *) / multiplier) {
2357
0
        PyErr_NoMemory();
2358
0
        return -1;
2359
0
    }
2360
4.70k
    ms->a.keys = (PyObject **)PyMem_Malloc(multiplier * need
2361
4.70k
                                          * sizeof(PyObject *));
2362
4.70k
    if (ms->a.keys != NULL) {
2363
4.70k
        ms->alloced = need;
2364
4.70k
        if (ms->a.values != NULL)
2365
4.63k
            ms->a.values = &ms->a.keys[need];
2366
4.70k
        return 0;
2367
4.70k
    }
2368
0
    PyErr_NoMemory();
2369
0
    return -1;
2370
4.70k
}
2371
68.0k
#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 :   \
2372
68.0k
                                merge_getmem(MS, NEED))
2373
2374
/* Merge the na elements starting at ssa with the nb elements starting at
2375
 * ssb.keys = ssa.keys + na in a stable way, in-place.  na and nb must be > 0.
2376
 * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
2377
 * should have na <= nb.  See listsort.txt for more info.  Return 0 if
2378
 * successful, -1 if error.
2379
 */
2380
static Py_ssize_t
2381
merge_lo(MergeState *ms, sortslice ssa, Py_ssize_t na,
2382
         sortslice ssb, Py_ssize_t nb)
2383
44.4k
{
2384
44.4k
    Py_ssize_t k;
2385
44.4k
    sortslice dest;
2386
44.4k
    int result = -1;            /* guilty until proved innocent */
2387
44.4k
    Py_ssize_t min_gallop;
2388
2389
44.4k
    assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
2390
44.4k
    assert(ssa.keys + na == ssb.keys);
2391
44.4k
    if (MERGE_GETMEM(ms, na) < 0)
2392
0
        return -1;
2393
44.4k
    sortslice_memcpy(&ms->a, 0, &ssa, 0, na);
2394
44.4k
    dest = ssa;
2395
44.4k
    ssa = ms->a;
2396
2397
44.4k
    sortslice_copy_incr(&dest, &ssb);
2398
44.4k
    --nb;
2399
44.4k
    if (nb == 0)
2400
2.02k
        goto Succeed;
2401
42.4k
    if (na == 1)
2402
6.31k
        goto CopyB;
2403
2404
36.1k
    min_gallop = ms->min_gallop;
2405
64.4k
    for (;;) {
2406
64.4k
        Py_ssize_t acount = 0;          /* # of times A won in a row */
2407
64.4k
        Py_ssize_t bcount = 0;          /* # of times B won in a row */
2408
2409
        /* Do the straightforward thing until (if ever) one run
2410
         * appears to win consistently.
2411
         */
2412
1.02M
        for (;;) {
2413
1.02M
            assert(na > 1 && nb > 0);
2414
1.02M
            k = ISLT(ssb.keys[0], ssa.keys[0]);
2415
1.02M
            if (k) {
2416
524k
                if (k < 0)
2417
0
                    goto Fail;
2418
524k
                sortslice_copy_incr(&dest, &ssb);
2419
524k
                ++bcount;
2420
524k
                acount = 0;
2421
524k
                --nb;
2422
524k
                if (nb == 0)
2423
3.15k
                    goto Succeed;
2424
520k
                if (bcount >= min_gallop)
2425
26.2k
                    break;
2426
520k
            }
2427
498k
            else {
2428
498k
                sortslice_copy_incr(&dest, &ssa);
2429
498k
                ++acount;
2430
498k
                bcount = 0;
2431
498k
                --na;
2432
498k
                if (na == 1)
2433
8.42k
                    goto CopyB;
2434
489k
                if (acount >= min_gallop)
2435
26.6k
                    break;
2436
489k
            }
2437
1.02M
        }
2438
2439
        /* One run is winning so consistently that galloping may
2440
         * be a huge win.  So try that, and continue galloping until
2441
         * (if ever) neither run appears to be winning consistently
2442
         * anymore.
2443
         */
2444
52.8k
        ++min_gallop;
2445
83.8k
        do {
2446
83.8k
            assert(na > 1 && nb > 0);
2447
83.8k
            min_gallop -= min_gallop > 1;
2448
83.8k
            ms->min_gallop = min_gallop;
2449
83.8k
            k = gallop_right(ms, ssb.keys[0], ssa.keys, na, 0);
2450
83.8k
            acount = k;
2451
83.8k
            if (k) {
2452
50.7k
                if (k < 0)
2453
0
                    goto Fail;
2454
50.7k
                sortslice_memcpy(&dest, 0, &ssa, 0, k);
2455
50.7k
                sortslice_advance(&dest, k);
2456
50.7k
                sortslice_advance(&ssa, k);
2457
50.7k
                na -= k;
2458
50.7k
                if (na == 1)
2459
7.55k
                    goto CopyB;
2460
                /* na==0 is impossible now if the comparison
2461
                 * function is consistent, but we can't assume
2462
                 * that it is.
2463
                 */
2464
43.1k
                if (na == 0)
2465
0
                    goto Succeed;
2466
43.1k
            }
2467
76.2k
            sortslice_copy_incr(&dest, &ssb);
2468
76.2k
            --nb;
2469
76.2k
            if (nb == 0)
2470
2.19k
                goto Succeed;
2471
2472
74.0k
            k = gallop_left(ms, ssa.keys[0], ssb.keys, nb, 0);
2473
74.0k
            bcount = k;
2474
74.0k
            if (k) {
2475
60.5k
                if (k < 0)
2476
0
                    goto Fail;
2477
60.5k
                sortslice_memmove(&dest, 0, &ssb, 0, k);
2478
60.5k
                sortslice_advance(&dest, k);
2479
60.5k
                sortslice_advance(&ssb, k);
2480
60.5k
                nb -= k;
2481
60.5k
                if (nb == 0)
2482
10.9k
                    goto Succeed;
2483
60.5k
            }
2484
63.1k
            sortslice_copy_incr(&dest, &ssa);
2485
63.1k
            --na;
2486
63.1k
            if (na == 1)
2487
3.86k
                goto CopyB;
2488
63.1k
        } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
2489
28.3k
        ++min_gallop;           /* penalize it for leaving galloping mode */
2490
28.3k
        ms->min_gallop = min_gallop;
2491
28.3k
    }
2492
18.3k
Succeed:
2493
18.3k
    result = 0;
2494
18.3k
Fail:
2495
18.3k
    if (na)
2496
18.3k
        sortslice_memcpy(&dest, 0, &ssa, 0, na);
2497
18.3k
    return result;
2498
26.1k
CopyB:
2499
26.1k
    assert(na == 1 && nb > 0);
2500
    /* The last element of ssa belongs at the end of the merge. */
2501
26.1k
    sortslice_memmove(&dest, 0, &ssb, 0, nb);
2502
26.1k
    sortslice_copy(&dest, nb, &ssa, 0);
2503
26.1k
    return 0;
2504
18.3k
}
2505
2506
/* Merge the na elements starting at pa with the nb elements starting at
2507
 * ssb.keys = ssa.keys + na in a stable way, in-place.  na and nb must be > 0.
2508
 * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
2509
 * should have na >= nb.  See listsort.txt for more info.  Return 0 if
2510
 * successful, -1 if error.
2511
 */
2512
static Py_ssize_t
2513
merge_hi(MergeState *ms, sortslice ssa, Py_ssize_t na,
2514
         sortslice ssb, Py_ssize_t nb)
2515
23.5k
{
2516
23.5k
    Py_ssize_t k;
2517
23.5k
    sortslice dest, basea, baseb;
2518
23.5k
    int result = -1;            /* guilty until proved innocent */
2519
23.5k
    Py_ssize_t min_gallop;
2520
2521
23.5k
    assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
2522
23.5k
    assert(ssa.keys + na == ssb.keys);
2523
23.5k
    if (MERGE_GETMEM(ms, nb) < 0)
2524
0
        return -1;
2525
23.5k
    dest = ssb;
2526
23.5k
    sortslice_advance(&dest, nb-1);
2527
23.5k
    sortslice_memcpy(&ms->a, 0, &ssb, 0, nb);
2528
23.5k
    basea = ssa;
2529
23.5k
    baseb = ms->a;
2530
23.5k
    ssb.keys = ms->a.keys + nb - 1;
2531
23.5k
    if (ssb.values != NULL)
2532
22.6k
        ssb.values = ms->a.values + nb - 1;
2533
23.5k
    sortslice_advance(&ssa, na - 1);
2534
2535
23.5k
    sortslice_copy_decr(&dest, &ssa);
2536
23.5k
    --na;
2537
23.5k
    if (na == 0)
2538
0
        goto Succeed;
2539
23.5k
    if (nb == 1)
2540
796
        goto CopyA;
2541
2542
22.7k
    min_gallop = ms->min_gallop;
2543
35.4k
    for (;;) {
2544
35.4k
        Py_ssize_t acount = 0;          /* # of times A won in a row */
2545
35.4k
        Py_ssize_t bcount = 0;          /* # of times B won in a row */
2546
2547
        /* Do the straightforward thing until (if ever) one run
2548
         * appears to win consistently.
2549
         */
2550
2.66M
        for (;;) {
2551
2.66M
            assert(na > 0 && nb > 1);
2552
2.66M
            k = ISLT(ssb.keys[0], ssa.keys[0]);
2553
2.66M
            if (k) {
2554
1.33M
                if (k < 0)
2555
0
                    goto Fail;
2556
1.33M
                sortslice_copy_decr(&dest, &ssa);
2557
1.33M
                ++acount;
2558
1.33M
                bcount = 0;
2559
1.33M
                --na;
2560
1.33M
                if (na == 0)
2561
1.00k
                    goto Succeed;
2562
1.33M
                if (acount >= min_gallop)
2563
16.1k
                    break;
2564
1.33M
            }
2565
1.32M
            else {
2566
1.32M
                sortslice_copy_decr(&dest, &ssb);
2567
1.32M
                ++bcount;
2568
1.32M
                acount = 0;
2569
1.32M
                --nb;
2570
1.32M
                if (nb == 1)
2571
600
                    goto CopyA;
2572
1.32M
                if (bcount >= min_gallop)
2573
17.7k
                    break;
2574
1.32M
            }
2575
2.66M
        }
2576
2577
        /* One run is winning so consistently that galloping may
2578
         * be a huge win.  So try that, and continue galloping until
2579
         * (if ever) neither run appears to be winning consistently
2580
         * anymore.
2581
         */
2582
33.8k
        ++min_gallop;
2583
57.6k
        do {
2584
57.6k
            assert(na > 0 && nb > 1);
2585
57.6k
            min_gallop -= min_gallop > 1;
2586
57.6k
            ms->min_gallop = min_gallop;
2587
57.6k
            k = gallop_right(ms, ssb.keys[0], basea.keys, na, na-1);
2588
57.6k
            if (k < 0)
2589
0
                goto Fail;
2590
57.6k
            k = na - k;
2591
57.6k
            acount = k;
2592
57.6k
            if (k) {
2593
35.1k
                sortslice_advance(&dest, -k);
2594
35.1k
                sortslice_advance(&ssa, -k);
2595
35.1k
                sortslice_memmove(&dest, 1, &ssa, 1, k);
2596
35.1k
                na -= k;
2597
35.1k
                if (na == 0)
2598
9.37k
                    goto Succeed;
2599
35.1k
            }
2600
48.2k
            sortslice_copy_decr(&dest, &ssb);
2601
48.2k
            --nb;
2602
48.2k
            if (nb == 1)
2603
954
                goto CopyA;
2604
2605
47.3k
            k = gallop_left(ms, ssa.keys[0], baseb.keys, nb, nb-1);
2606
47.3k
            if (k < 0)
2607
0
                goto Fail;
2608
47.3k
            k = nb - k;
2609
47.3k
            bcount = k;
2610
47.3k
            if (k) {
2611
39.4k
                sortslice_advance(&dest, -k);
2612
39.4k
                sortslice_advance(&ssb, -k);
2613
39.4k
                sortslice_memcpy(&dest, 1, &ssb, 1, k);
2614
39.4k
                nb -= k;
2615
39.4k
                if (nb == 1)
2616
9.99k
                    goto CopyA;
2617
                /* nb==0 is impossible now if the comparison
2618
                 * function is consistent, but we can't assume
2619
                 * that it is.
2620
                 */
2621
29.4k
                if (nb == 0)
2622
0
                    goto Succeed;
2623
29.4k
            }
2624
37.3k
            sortslice_copy_decr(&dest, &ssa);
2625
37.3k
            --na;
2626
37.3k
            if (na == 0)
2627
825
                goto Succeed;
2628
37.3k
        } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
2629
12.6k
        ++min_gallop;           /* penalize it for leaving galloping mode */
2630
12.6k
        ms->min_gallop = min_gallop;
2631
12.6k
    }
2632
11.2k
Succeed:
2633
11.2k
    result = 0;
2634
11.2k
Fail:
2635
11.2k
    if (nb)
2636
11.2k
        sortslice_memcpy(&dest, -(nb-1), &baseb, 0, nb);
2637
11.2k
    return result;
2638
12.3k
CopyA:
2639
12.3k
    assert(nb == 1 && na > 0);
2640
    /* The first element of ssb belongs at the front of the merge. */
2641
12.3k
    sortslice_memmove(&dest, 1-na, &ssa, 1-na, na);
2642
12.3k
    sortslice_advance(&dest, -na);
2643
12.3k
    sortslice_advance(&ssa, -na);
2644
12.3k
    sortslice_copy(&dest, 0, &ssb, 0);
2645
12.3k
    return 0;
2646
11.2k
}
2647
2648
/* Merge the two runs at stack indices i and i+1.
2649
 * Returns 0 on success, -1 on error.
2650
 */
2651
static Py_ssize_t
2652
merge_at(MergeState *ms, Py_ssize_t i)
2653
68.4k
{
2654
68.4k
    sortslice ssa, ssb;
2655
68.4k
    Py_ssize_t na, nb;
2656
68.4k
    Py_ssize_t k;
2657
2658
68.4k
    assert(ms != NULL);
2659
68.4k
    assert(ms->n >= 2);
2660
68.4k
    assert(i >= 0);
2661
68.4k
    assert(i == ms->n - 2 || i == ms->n - 3);
2662
2663
68.4k
    ssa = ms->pending[i].base;
2664
68.4k
    na = ms->pending[i].len;
2665
68.4k
    ssb = ms->pending[i+1].base;
2666
68.4k
    nb = ms->pending[i+1].len;
2667
68.4k
    assert(na > 0 && nb > 0);
2668
68.4k
    assert(ssa.keys + na == ssb.keys);
2669
2670
    /* Record the length of the combined runs; if i is the 3rd-last
2671
     * run now, also slide over the last run (which isn't involved
2672
     * in this merge).  The current run i+1 goes away in any case.
2673
     */
2674
68.4k
    ms->pending[i].len = na + nb;
2675
68.4k
    if (i == ms->n - 3)
2676
407
        ms->pending[i+1] = ms->pending[i+2];
2677
68.4k
    --ms->n;
2678
2679
    /* Where does b start in a?  Elements in a before that can be
2680
     * ignored (already in place).
2681
     */
2682
68.4k
    k = gallop_right(ms, *ssb.keys, ssa.keys, na, 0);
2683
68.4k
    if (k < 0)
2684
0
        return -1;
2685
68.4k
    sortslice_advance(&ssa, k);
2686
68.4k
    na -= k;
2687
68.4k
    if (na == 0)
2688
434
        return 0;
2689
2690
    /* Where does a end in b?  Elements in b after that can be
2691
     * ignored (already in place).
2692
     */
2693
68.0k
    nb = gallop_left(ms, ssa.keys[na-1], ssb.keys, nb, nb-1);
2694
68.0k
    if (nb <= 0)
2695
0
        return nb;
2696
2697
    /* Merge what remains of the runs, using a temp array with
2698
     * min(na, nb) elements.
2699
     */
2700
68.0k
    if (na <= nb)
2701
44.4k
        return merge_lo(ms, ssa, na, ssb, nb);
2702
23.5k
    else
2703
23.5k
        return merge_hi(ms, ssa, na, ssb, nb);
2704
68.0k
}
2705
2706
/* Two adjacent runs begin at index s1. The first run has length n1, and
2707
 * the second run (starting at index s1+n1) has length n2. The list has total
2708
 * length n.
2709
 * Compute the "power" of the first run. See listsort.txt for details.
2710
 */
2711
static int
2712
powerloop(Py_ssize_t s1, Py_ssize_t n1, Py_ssize_t n2, Py_ssize_t n)
2713
68.4k
{
2714
68.4k
    int result = 0;
2715
68.4k
    assert(s1 >= 0);
2716
68.4k
    assert(n1 > 0 && n2 > 0);
2717
68.4k
    assert(s1 + n1 + n2 <= n);
2718
    /* midpoints a and b:
2719
     * a = s1 + n1/2
2720
     * b = s1 + n1 + n2/2 = a + (n1 + n2)/2
2721
     *
2722
     * Those may not be integers, though, because of the "/2". So we work with
2723
     * 2*a and 2*b instead, which are necessarily integers. It makes no
2724
     * difference to the outcome, since the bits in the expansion of (2*i)/n
2725
     * are merely shifted one position from those of i/n.
2726
     */
2727
68.4k
    Py_ssize_t a = 2 * s1 + n1;  /* 2*a */
2728
68.4k
    Py_ssize_t b = a + n1 + n2;  /* 2*b */
2729
    /* Emulate a/n and b/n one bit a time, until bits differ. */
2730
249k
    for (;;) {
2731
249k
        ++result;
2732
249k
        if (a >= n) {  /* both quotient bits are 1 */
2733
93.5k
            assert(b >= a);
2734
93.5k
            a -= n;
2735
93.5k
            b -= n;
2736
93.5k
        }
2737
156k
        else if (b >= n) {  /* a/n bit is 0, b/n bit is 1 */
2738
68.4k
            break;
2739
68.4k
        } /* else both quotient bits are 0 */
2740
249k
        assert(a < b && b < n);
2741
181k
        a <<= 1;
2742
181k
        b <<= 1;
2743
181k
    }
2744
68.4k
    return result;
2745
68.4k
}
2746
2747
/* The next run has been identified, of length n2.
2748
 * If there's already a run on the stack, apply the "powersort" merge strategy:
2749
 * compute the topmost run's "power" (depth in a conceptual binary merge tree)
2750
 * and merge adjacent runs on the stack with greater power. See listsort.txt
2751
 * for more info.
2752
 *
2753
 * It's the caller's responsibility to push the new run on the stack when this
2754
 * returns.
2755
 *
2756
 * Returns 0 on success, -1 on error.
2757
 */
2758
static int
2759
found_new_run(MergeState *ms, Py_ssize_t n2)
2760
924k
{
2761
924k
    assert(ms);
2762
924k
    if (ms->n) {
2763
68.4k
        assert(ms->n > 0);
2764
68.4k
        struct s_slice *p = ms->pending;
2765
68.4k
        Py_ssize_t s1 = p[ms->n - 1].base.keys - ms->basekeys; /* start index */
2766
68.4k
        Py_ssize_t n1 = p[ms->n - 1].len;
2767
68.4k
        int power = powerloop(s1, n1, n2, ms->listlen);
2768
109k
        while (ms->n > 1 && p[ms->n - 2].power > power) {
2769
40.8k
            if (merge_at(ms, ms->n - 2) < 0)
2770
0
                return -1;
2771
40.8k
        }
2772
68.4k
        assert(ms->n < 2 || p[ms->n - 2].power < power);
2773
68.4k
        p[ms->n - 1].power = power;
2774
68.4k
    }
2775
924k
    return 0;
2776
924k
}
2777
2778
/* Regardless of invariants, merge all runs on the stack until only one
2779
 * remains.  This is used at the end of the mergesort.
2780
 *
2781
 * Returns 0 on success, -1 on error.
2782
 */
2783
static int
2784
merge_force_collapse(MergeState *ms)
2785
855k
{
2786
855k
    struct s_slice *p = ms->pending;
2787
2788
855k
    assert(ms);
2789
883k
    while (ms->n > 1) {
2790
27.6k
        Py_ssize_t n = ms->n - 2;
2791
27.6k
        if (n > 0 && p[n-1].len < p[n+1].len)
2792
407
            --n;
2793
27.6k
        if (merge_at(ms, n) < 0)
2794
0
            return -1;
2795
27.6k
    }
2796
855k
    return 0;
2797
855k
}
2798
2799
/* Return the next minrun value to use. See listsort.txt. */
2800
Py_LOCAL_INLINE(Py_ssize_t)
2801
minrun_next(MergeState *ms)
2802
924k
{
2803
924k
    ms->mr_current += ms->listlen;
2804
924k
    assert(ms->mr_current >= 0); /* no overflow */
2805
924k
    Py_ssize_t result = ms->mr_current >> ms->mr_e;
2806
924k
    ms->mr_current &= ms->mr_mask;
2807
924k
    return result;
2808
924k
}
2809
2810
/* Here we define custom comparison functions to optimize for the cases one commonly
2811
 * encounters in practice: homogeneous lists, often of one of the basic types. */
2812
2813
/* This struct holds the comparison function and helper functions
2814
 * selected in the pre-sort check. */
2815
2816
/* These are the special case compare functions.
2817
 * ms->key_compare will always point to one of these: */
2818
2819
/* Heterogeneous compare: default, always safe to fall back on. */
2820
static int
2821
safe_object_compare(PyObject *v, PyObject *w, MergeState *ms)
2822
8.31k
{
2823
    /* No assumptions necessary! */
2824
8.31k
    return PyObject_RichCompareBool(v, w, Py_LT);
2825
8.31k
}
2826
2827
/* Homogeneous compare: safe for any two comparable objects of the same type.
2828
 * (ms->key_richcompare is set to ob_type->tp_richcompare in the
2829
 *  pre-sort check.)
2830
 */
2831
static int
2832
unsafe_object_compare(PyObject *v, PyObject *w, MergeState *ms)
2833
12.3M
{
2834
12.3M
    PyObject *res_obj; int res;
2835
2836
    /* No assumptions, because we check first: */
2837
12.3M
    if (Py_TYPE(v)->tp_richcompare != ms->key_richcompare)
2838
0
        return PyObject_RichCompareBool(v, w, Py_LT);
2839
2840
12.3M
    assert(ms->key_richcompare != NULL);
2841
12.3M
    res_obj = (*(ms->key_richcompare))(v, w, Py_LT);
2842
2843
12.3M
    if (res_obj == Py_NotImplemented) {
2844
0
        Py_DECREF(res_obj);
2845
0
        return PyObject_RichCompareBool(v, w, Py_LT);
2846
0
    }
2847
12.3M
    if (res_obj == NULL)
2848
0
        return -1;
2849
2850
12.3M
    if (PyBool_Check(res_obj)) {
2851
12.3M
        res = (res_obj == Py_True);
2852
12.3M
        assert(_Py_IsImmortal(res_obj));
2853
12.3M
    }
2854
0
    else {
2855
0
        res = PyObject_IsTrue(res_obj);
2856
0
        Py_DECREF(res_obj);
2857
0
    }
2858
2859
    /* Note that we can't assert
2860
     *     res == PyObject_RichCompareBool(v, w, Py_LT);
2861
     * because of evil compare functions like this:
2862
     *     lambda a, b:  int(random.random() * 3) - 1)
2863
     * (which is actually in test_sort.py) */
2864
12.3M
    return res;
2865
12.3M
}
2866
2867
#ifndef NDEBUG
2868
static void
2869
assert_compare_consistent(PyObject *v, PyObject *w, int res)
2870
{
2871
    int cmp = PyObject_RichCompareBool(v, w, Py_LT);
2872
    if (cmp < 0) {
2873
        /* This debug-only cross-check can hit the C stack guard even when
2874
         * the specialized comparison itself is safe. Keep the optimized path
2875
         * side-effect free by discarding that exception.
2876
         */
2877
        assert(PyErr_ExceptionMatches(PyExc_RecursionError));
2878
        PyErr_Clear();
2879
        return;
2880
    }
2881
    assert(res == cmp);
2882
}
2883
#else
2884
12.9M
#  define assert_compare_consistent(v, w, res) ((void)0)
2885
#endif
2886
2887
/* Latin string compare: safe for any two latin (one byte per char) strings. */
2888
static int
2889
unsafe_latin_compare(PyObject *v, PyObject *w, MergeState *ms)
2890
3.39M
{
2891
3.39M
    Py_ssize_t len;
2892
3.39M
    int res;
2893
2894
    /* Modified from Objects/unicodeobject.c:unicode_compare, assuming: */
2895
3.39M
    assert(Py_IS_TYPE(v, &PyUnicode_Type));
2896
3.39M
    assert(Py_IS_TYPE(w, &PyUnicode_Type));
2897
3.39M
    assert(PyUnicode_KIND(v) == PyUnicode_KIND(w));
2898
3.39M
    assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
2899
2900
3.39M
    len = Py_MIN(PyUnicode_GET_LENGTH(v), PyUnicode_GET_LENGTH(w));
2901
3.39M
    res = memcmp(PyUnicode_DATA(v), PyUnicode_DATA(w), len);
2902
2903
3.39M
    res = (res != 0 ?
2904
3.33M
           res < 0 :
2905
3.39M
           PyUnicode_GET_LENGTH(v) < PyUnicode_GET_LENGTH(w));
2906
2907
3.39M
    assert_compare_consistent(v, w, res);
2908
3.39M
    return res;
2909
3.39M
}
2910
2911
/* Bounded int compare: compare any two longs that fit in a single machine word. */
2912
static int
2913
unsafe_long_compare(PyObject *v, PyObject *w, MergeState *ms)
2914
9.58M
{
2915
9.58M
    PyLongObject *vl, *wl;
2916
9.58M
    intptr_t v0, w0;
2917
9.58M
    int res;
2918
2919
    /* Modified from Objects/longobject.c:long_compare, assuming: */
2920
9.58M
    assert(Py_IS_TYPE(v, &PyLong_Type));
2921
9.58M
    assert(Py_IS_TYPE(w, &PyLong_Type));
2922
9.58M
    assert(_PyLong_IsCompact((PyLongObject *)v));
2923
9.58M
    assert(_PyLong_IsCompact((PyLongObject *)w));
2924
2925
9.58M
    vl = (PyLongObject*)v;
2926
9.58M
    wl = (PyLongObject*)w;
2927
2928
9.58M
    v0 = _PyLong_CompactValue(vl);
2929
9.58M
    w0 = _PyLong_CompactValue(wl);
2930
2931
9.58M
    res = v0 < w0;
2932
9.58M
    assert_compare_consistent(v, w, res);
2933
9.58M
    return res;
2934
9.58M
}
2935
2936
/* Float compare: compare any two floats. */
2937
static int
2938
unsafe_float_compare(PyObject *v, PyObject *w, MergeState *ms)
2939
0
{
2940
0
    int res;
2941
2942
    /* Modified from Objects/floatobject.c:float_richcompare, assuming: */
2943
0
    assert(Py_IS_TYPE(v, &PyFloat_Type));
2944
0
    assert(Py_IS_TYPE(w, &PyFloat_Type));
2945
2946
0
    res = PyFloat_AS_DOUBLE(v) < PyFloat_AS_DOUBLE(w);
2947
0
    assert_compare_consistent(v, w, res);
2948
0
    return res;
2949
0
}
2950
2951
/* Tuple compare: compare *any* two tuples, using
2952
 * ms->tuple_elem_compare to compare the first elements, which is set
2953
 * using the same pre-sort check as we use for ms->key_compare,
2954
 * but run on the list [x[0] for x in L]. This allows us to optimize compares
2955
 * on two levels (as long as [x[0] for x in L] is type-homogeneous.) The idea is
2956
 * that most tuple compares don't involve x[1:]. */
2957
static int
2958
unsafe_tuple_compare(PyObject *v, PyObject *w, MergeState *ms)
2959
4.68M
{
2960
4.68M
    PyTupleObject *vt, *wt;
2961
4.68M
    Py_ssize_t i, vlen, wlen;
2962
4.68M
    int k;
2963
2964
    /* Modified from Objects/tupleobject.c:tuplerichcompare, assuming: */
2965
4.68M
    assert(Py_IS_TYPE(v, &PyTuple_Type));
2966
4.68M
    assert(Py_IS_TYPE(w, &PyTuple_Type));
2967
4.68M
    assert(Py_SIZE(v) > 0);
2968
4.68M
    assert(Py_SIZE(w) > 0);
2969
2970
4.68M
    vt = (PyTupleObject *)v;
2971
4.68M
    wt = (PyTupleObject *)w;
2972
2973
4.68M
    vlen = Py_SIZE(vt);
2974
4.68M
    wlen = Py_SIZE(wt);
2975
2976
6.91M
    for (i = 0; i < vlen && i < wlen; i++) {
2977
5.80M
        k = PyObject_RichCompareBool(vt->ob_item[i], wt->ob_item[i], Py_EQ);
2978
5.80M
        if (k < 0)
2979
0
            return -1;
2980
5.80M
        if (!k)
2981
3.57M
            break;
2982
5.80M
    }
2983
2984
4.68M
    if (i >= vlen || i >= wlen)
2985
1.11M
        return vlen < wlen;
2986
2987
3.57M
    if (i == 0)
2988
3.57M
        return ms->tuple_elem_compare(vt->ob_item[i], wt->ob_item[i], ms);
2989
1.02k
    else
2990
1.02k
        return PyObject_RichCompareBool(vt->ob_item[i], wt->ob_item[i], Py_LT);
2991
3.57M
}
2992
2993
/* An adaptive, stable, natural mergesort.  See listsort.txt.
2994
 * Returns Py_None on success, NULL on error.  Even in case of error, the
2995
 * list will be some permutation of its input state (nothing is lost or
2996
 * duplicated).
2997
 */
2998
/*[clinic input]
2999
@critical_section
3000
list.sort
3001
3002
    *
3003
    key as keyfunc: object = None
3004
    reverse: bool = False
3005
3006
Sort the list in ascending order and return None.
3007
3008
The sort is in-place (i.e. the list itself is modified) and stable
3009
(i.e. the order of two equal elements is maintained).
3010
3011
If a key function is given, apply it once to each list item and sort
3012
them, ascending or descending, according to their function values.
3013
3014
The reverse flag can be set to sort in descending order.
3015
[clinic start generated code]*/
3016
3017
static PyObject *
3018
list_sort_impl(PyListObject *self, PyObject *keyfunc, int reverse)
3019
/*[clinic end generated code: output=57b9f9c5e23fbe42 input=c145526281e1fb9f]*/
3020
2.28M
{
3021
2.28M
    MergeState ms;
3022
2.28M
    Py_ssize_t nremaining;
3023
2.28M
    Py_ssize_t minrun;
3024
2.28M
    sortslice lo;
3025
2.28M
    Py_ssize_t saved_ob_size, saved_allocated;
3026
2.28M
    PyObject **saved_ob_item;
3027
2.28M
    PyObject **final_ob_item;
3028
2.28M
    PyObject *result = NULL;            /* guilty until proved innocent */
3029
2.28M
    Py_ssize_t i;
3030
2.28M
    PyObject **keys;
3031
3032
2.28M
    assert(self != NULL);
3033
2.28M
    assert(PyList_Check(self));
3034
2.28M
    if (keyfunc == Py_None)
3035
1.55M
        keyfunc = NULL;
3036
3037
    /* The list is temporarily made empty, so that mutations performed
3038
     * by comparison functions can't affect the slice of memory we're
3039
     * sorting (allowing mutations during sorting is a core-dump
3040
     * factory, since ob_item may change).
3041
     */
3042
2.28M
    saved_ob_size = Py_SIZE(self);
3043
2.28M
    saved_ob_item = self->ob_item;
3044
2.28M
    saved_allocated = self->allocated;
3045
2.28M
    Py_SET_SIZE(self, 0);
3046
2.28M
    FT_ATOMIC_STORE_PTR_RELEASE(self->ob_item, NULL);
3047
2.28M
    self->allocated = -1; /* any operation will reset it to >= 0 */
3048
3049
2.28M
    if (keyfunc == NULL) {
3050
1.57M
        keys = NULL;
3051
1.57M
        lo.keys = saved_ob_item;
3052
1.57M
        lo.values = NULL;
3053
1.57M
    }
3054
713k
    else {
3055
713k
        if (saved_ob_size < MERGESTATE_TEMP_SIZE/2)
3056
            /* Leverage stack space we allocated but won't otherwise use */
3057
709k
            keys = &ms.temparray[saved_ob_size+1];
3058
4.22k
        else {
3059
4.22k
            keys = PyMem_Malloc(sizeof(PyObject *) * saved_ob_size);
3060
4.22k
            if (keys == NULL) {
3061
0
                PyErr_NoMemory();
3062
0
                goto keyfunc_fail;
3063
0
            }
3064
4.22k
        }
3065
3066
5.49M
        for (i = 0; i < saved_ob_size ; i++) {
3067
4.78M
            keys[i] = PyObject_CallOneArg(keyfunc, saved_ob_item[i]);
3068
4.78M
            if (keys[i] == NULL) {
3069
0
                for (i=i-1 ; i>=0 ; i--)
3070
0
                    Py_DECREF(keys[i]);
3071
0
                if (saved_ob_size >= MERGESTATE_TEMP_SIZE/2)
3072
0
                    PyMem_Free(keys);
3073
0
                goto keyfunc_fail;
3074
0
            }
3075
4.78M
        }
3076
3077
713k
        lo.keys = keys;
3078
713k
        lo.values = saved_ob_item;
3079
713k
    }
3080
3081
3082
    /* The pre-sort check: here's where we decide which compare function to use.
3083
     * How much optimization is safe? We test for homogeneity with respect to
3084
     * several properties that are expensive to check at compare-time, and
3085
     * set ms appropriately. */
3086
2.28M
    if (saved_ob_size > 1) {
3087
        /* Assume the first element is representative of the whole list. */
3088
855k
        int keys_are_in_tuples = (Py_IS_TYPE(lo.keys[0], &PyTuple_Type) &&
3089
45.7k
                                  Py_SIZE(lo.keys[0]) > 0);
3090
3091
855k
        PyTypeObject* key_type = (keys_are_in_tuples ?
3092
45.7k
                                  Py_TYPE(PyTuple_GET_ITEM(lo.keys[0], 0)) :
3093
855k
                                  Py_TYPE(lo.keys[0]));
3094
3095
855k
        int keys_are_all_same_type = 1;
3096
855k
        int strings_are_latin = 1;
3097
855k
        int ints_are_bounded = 1;
3098
3099
        /* Prove that assumption by checking every key. */
3100
11.4M
        for (i=0; i < saved_ob_size; i++) {
3101
3102
10.5M
            if (keys_are_in_tuples &&
3103
2.45M
                !(Py_IS_TYPE(lo.keys[i], &PyTuple_Type) && Py_SIZE(lo.keys[i]) != 0)) {
3104
0
                keys_are_in_tuples = 0;
3105
0
                keys_are_all_same_type = 0;
3106
0
                break;
3107
0
            }
3108
3109
            /* Note: for lists of tuples, key is the first element of the tuple
3110
             * lo.keys[i], not lo.keys[i] itself! We verify type-homogeneity
3111
             * for lists of tuples in the if-statement directly above. */
3112
10.5M
            PyObject *key = (keys_are_in_tuples ?
3113
2.45M
                             PyTuple_GET_ITEM(lo.keys[i], 0) :
3114
10.5M
                             lo.keys[i]);
3115
3116
10.5M
            if (!Py_IS_TYPE(key, key_type)) {
3117
4
                keys_are_all_same_type = 0;
3118
                /* If keys are in tuple we must loop over the whole list to make
3119
                   sure all items are tuples */
3120
4
                if (!keys_are_in_tuples) {
3121
4
                    break;
3122
4
                }
3123
4
            }
3124
3125
10.5M
            if (keys_are_all_same_type) {
3126
10.5M
                if (key_type == &PyLong_Type &&
3127
6.62M
                    ints_are_bounded &&
3128
4.91M
                    !_PyLong_IsCompact((PyLongObject *)key)) {
3129
3130
23.4k
                    ints_are_bounded = 0;
3131
23.4k
                }
3132
10.5M
                else if (key_type == &PyUnicode_Type &&
3133
3.68M
                         strings_are_latin &&
3134
1.40M
                         PyUnicode_KIND(key) != PyUnicode_1BYTE_KIND) {
3135
3136
582k
                        strings_are_latin = 0;
3137
582k
                    }
3138
10.5M
                }
3139
10.5M
            }
3140
3141
        /* Choose the best compare, given what we now know about the keys. */
3142
855k
        if (keys_are_all_same_type) {
3143
3144
855k
            if (key_type == &PyUnicode_Type && strings_are_latin) {
3145
98.7k
                ms.key_compare = unsafe_latin_compare;
3146
98.7k
            }
3147
757k
            else if (key_type == &PyLong_Type && ints_are_bounded) {
3148
125k
                ms.key_compare = unsafe_long_compare;
3149
125k
            }
3150
631k
            else if (key_type == &PyFloat_Type) {
3151
0
                ms.key_compare = unsafe_float_compare;
3152
0
            }
3153
631k
            else if ((ms.key_richcompare = key_type->tp_richcompare) != NULL) {
3154
631k
                ms.key_compare = unsafe_object_compare;
3155
631k
            }
3156
0
            else {
3157
0
                ms.key_compare = safe_object_compare;
3158
0
            }
3159
855k
        }
3160
4
        else {
3161
4
            ms.key_compare = safe_object_compare;
3162
4
        }
3163
3164
855k
        if (keys_are_in_tuples) {
3165
            /* Make sure we're not dealing with tuples of tuples
3166
             * (remember: here, key_type refers list [key[0] for key in keys]) */
3167
45.7k
            if (key_type == &PyTuple_Type) {
3168
0
                ms.tuple_elem_compare = safe_object_compare;
3169
0
            }
3170
45.7k
            else {
3171
45.7k
                ms.tuple_elem_compare = ms.key_compare;
3172
45.7k
            }
3173
3174
45.7k
            ms.key_compare = unsafe_tuple_compare;
3175
45.7k
        }
3176
855k
    }
3177
    /* End of pre-sort check: ms is now set properly! */
3178
3179
2.28M
    merge_init(&ms, saved_ob_size, keys != NULL, &lo);
3180
3181
2.28M
    nremaining = saved_ob_size;
3182
2.28M
    if (nremaining < 2)
3183
1.43M
        goto succeed;
3184
3185
    /* Reverse sort stability achieved by initially reversing the list,
3186
    applying a stable forward sort, then reversing the final result. */
3187
855k
    if (reverse) {
3188
122
        if (keys != NULL)
3189
0
            reverse_slice(&keys[0], &keys[saved_ob_size]);
3190
122
        reverse_slice(&saved_ob_item[0], &saved_ob_item[saved_ob_size]);
3191
122
    }
3192
3193
    /* March over the array once, left to right, finding natural runs,
3194
     * and extending short natural runs to minrun elements.
3195
     */
3196
924k
    do {
3197
924k
        Py_ssize_t n;
3198
3199
        /* Identify next run. */
3200
924k
        n = count_run(&ms, &lo, nremaining);
3201
924k
        if (n < 0)
3202
0
            goto fail;
3203
        /* If short, extend to min(minrun, nremaining). */
3204
924k
        minrun = minrun_next(&ms);
3205
924k
        if (n < minrun) {
3206
442k
            const Py_ssize_t force = nremaining <= minrun ?
3207
389k
                              nremaining : minrun;
3208
442k
            if (binarysort(&ms, &lo, force, n) < 0)
3209
0
                goto fail;
3210
442k
            n = force;
3211
442k
        }
3212
        /* Maybe merge pending runs. */
3213
924k
        assert(ms.n == 0 || ms.pending[ms.n -1].base.keys +
3214
924k
                            ms.pending[ms.n-1].len == lo.keys);
3215
924k
        if (found_new_run(&ms, n) < 0)
3216
0
            goto fail;
3217
        /* Push new run on stack. */
3218
924k
        assert(ms.n < MAX_MERGE_PENDING);
3219
924k
        ms.pending[ms.n].base = lo;
3220
924k
        ms.pending[ms.n].len = n;
3221
924k
        ++ms.n;
3222
        /* Advance to find next run. */
3223
924k
        sortslice_advance(&lo, n);
3224
924k
        nremaining -= n;
3225
924k
    } while (nremaining);
3226
3227
855k
    if (merge_force_collapse(&ms) < 0)
3228
0
        goto fail;
3229
855k
    assert(ms.n == 1);
3230
855k
    assert(keys == NULL
3231
855k
           ? ms.pending[0].base.keys == saved_ob_item
3232
855k
           : ms.pending[0].base.keys == &keys[0]);
3233
855k
    assert(ms.pending[0].len == saved_ob_size);
3234
855k
    lo = ms.pending[0].base;
3235
3236
2.28M
succeed:
3237
2.28M
    result = Py_None;
3238
2.28M
fail:
3239
2.28M
    if (keys != NULL) {
3240
5.49M
        for (i = 0; i < saved_ob_size; i++)
3241
4.78M
            Py_DECREF(keys[i]);
3242
713k
        if (saved_ob_size >= MERGESTATE_TEMP_SIZE/2)
3243
4.22k
            PyMem_Free(keys);
3244
713k
    }
3245
3246
2.28M
    if (self->allocated != -1 && result != NULL) {
3247
        /* The user mucked with the list during the sort,
3248
         * and we don't already have another error to report.
3249
         */
3250
0
        PyErr_SetString(PyExc_ValueError, "list modified during sort");
3251
0
        result = NULL;
3252
0
    }
3253
3254
2.28M
    if (reverse && saved_ob_size > 1)
3255
122
        reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
3256
3257
2.28M
    merge_freemem(&ms);
3258
3259
2.28M
keyfunc_fail:
3260
2.28M
    final_ob_item = self->ob_item;
3261
2.28M
    i = Py_SIZE(self);
3262
2.28M
    Py_SET_SIZE(self, saved_ob_size);
3263
2.28M
    FT_ATOMIC_STORE_PTR_RELEASE(self->ob_item, saved_ob_item);
3264
2.28M
    FT_ATOMIC_STORE_SSIZE_RELAXED(self->allocated, saved_allocated);
3265
2.28M
    if (final_ob_item != NULL) {
3266
        /* we cannot use list_clear() for this because it does not
3267
           guarantee that the list is really empty when it returns */
3268
0
        while (--i >= 0) {
3269
0
            Py_XDECREF(final_ob_item[i]);
3270
0
        }
3271
#ifdef Py_GIL_DISABLED
3272
        ensure_shared_on_resize(self);
3273
        bool use_qsbr = _PyObject_GC_IS_SHARED(self);
3274
#else
3275
0
        bool use_qsbr = false;
3276
0
#endif
3277
0
        free_list_items(final_ob_item, use_qsbr);
3278
0
    }
3279
2.28M
    return Py_XNewRef(result);
3280
2.28M
}
3281
#undef IFLT
3282
#undef ISLT
3283
3284
int
3285
PyList_Sort(PyObject *v)
3286
16.8k
{
3287
16.8k
    if (v == NULL || !PyList_Check(v)) {
3288
0
        PyErr_BadInternalCall();
3289
0
        return -1;
3290
0
    }
3291
16.8k
    Py_BEGIN_CRITICAL_SECTION(v);
3292
16.8k
    v = list_sort_impl((PyListObject *)v, NULL, 0);
3293
16.8k
    Py_END_CRITICAL_SECTION();
3294
16.8k
    if (v == NULL)
3295
0
        return -1;
3296
16.8k
    Py_DECREF(v);
3297
16.8k
    return 0;
3298
16.8k
}
3299
3300
/*[clinic input]
3301
@critical_section
3302
list.reverse
3303
3304
Reverse *IN PLACE*.
3305
[clinic start generated code]*/
3306
3307
static PyObject *
3308
list_reverse_impl(PyListObject *self)
3309
/*[clinic end generated code: output=482544fc451abea9 input=04ac8e0c6a66e4d9]*/
3310
0
{
3311
0
    if (Py_SIZE(self) > 1)
3312
0
        reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
3313
0
    Py_RETURN_NONE;
3314
0
}
3315
3316
int
3317
PyList_Reverse(PyObject *v)
3318
42
{
3319
42
    PyListObject *self = (PyListObject *)v;
3320
3321
42
    if (v == NULL || !PyList_Check(v)) {
3322
0
        PyErr_BadInternalCall();
3323
0
        return -1;
3324
0
    }
3325
42
    Py_BEGIN_CRITICAL_SECTION(self);
3326
42
    if (Py_SIZE(self) > 1) {
3327
42
        reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
3328
42
    }
3329
42
    Py_END_CRITICAL_SECTION()
3330
42
    return 0;
3331
42
}
3332
3333
PyObject *
3334
PyList_AsTuple(PyObject *v)
3335
340k
{
3336
340k
    if (v == NULL || !PyList_Check(v)) {
3337
0
        PyErr_BadInternalCall();
3338
0
        return NULL;
3339
0
    }
3340
340k
    PyObject *ret;
3341
340k
    PyListObject *self = (PyListObject *)v;
3342
340k
    Py_BEGIN_CRITICAL_SECTION(self);
3343
340k
    ret = PyTuple_FromArray(self->ob_item, Py_SIZE(v));
3344
340k
    Py_END_CRITICAL_SECTION();
3345
340k
    return ret;
3346
340k
}
3347
3348
PyObject *
3349
_PyList_AsTupleAndClear(PyListObject *self)
3350
5.63M
{
3351
5.63M
    assert(self != NULL);
3352
5.63M
    PyObject *ret;
3353
5.63M
    if (self->ob_item == NULL) {
3354
53.4k
        return PyTuple_New(0);
3355
53.4k
    }
3356
5.57M
    Py_BEGIN_CRITICAL_SECTION(self);
3357
5.57M
    PyObject **items = self->ob_item;
3358
5.57M
    Py_ssize_t size = Py_SIZE(self);
3359
5.57M
    Py_SET_SIZE(self, 0);
3360
5.57M
    ret = _PyTuple_FromArraySteal(items, size);
3361
5.57M
    Py_END_CRITICAL_SECTION();
3362
5.57M
    return ret;
3363
5.63M
}
3364
3365
PyObject *
3366
_PyList_FromStackRefStealOnSuccess(const _PyStackRef *src, Py_ssize_t n)
3367
117M
{
3368
117M
    if (n == 0) {
3369
101M
        return PyList_New(0);
3370
101M
    }
3371
3372
15.8M
    PyListObject *list = (PyListObject *)PyList_New(n);
3373
15.8M
    if (list == NULL) {
3374
0
        return NULL;
3375
0
    }
3376
3377
15.8M
    PyObject **dst = list->ob_item;
3378
35.8M
    for (Py_ssize_t i = 0; i < n; i++) {
3379
19.9M
        dst[i] = PyStackRef_AsPyObjectSteal(src[i]);
3380
19.9M
    }
3381
3382
15.8M
    return (PyObject *)list;
3383
15.8M
}
3384
3385
/*[clinic input]
3386
list.index
3387
3388
    value: object
3389
    start: slice_index(accept={int}) = 0
3390
    stop: slice_index(accept={int}, c_default="PY_SSIZE_T_MAX") = sys.maxsize
3391
    /
3392
3393
Return first index of value.
3394
3395
Raises ValueError if the value is not present.
3396
[clinic start generated code]*/
3397
3398
static PyObject *
3399
list_index_impl(PyListObject *self, PyObject *value, Py_ssize_t start,
3400
                Py_ssize_t stop)
3401
/*[clinic end generated code: output=ec51b88787e4e481 input=40ec5826303a0eb1]*/
3402
0
{
3403
0
    if (start < 0) {
3404
0
        start += Py_SIZE(self);
3405
0
        if (start < 0)
3406
0
            start = 0;
3407
0
    }
3408
0
    if (stop < 0) {
3409
0
        stop += Py_SIZE(self);
3410
0
        if (stop < 0)
3411
0
            stop = 0;
3412
0
    }
3413
0
    for (Py_ssize_t i = start; i < stop; i++) {
3414
0
        PyObject *obj = list_get_item_ref(self, i);
3415
0
        if (obj == NULL) {
3416
            // out-of-bounds
3417
0
            break;
3418
0
        }
3419
0
        int cmp = PyObject_RichCompareBool(obj, value, Py_EQ);
3420
0
        Py_DECREF(obj);
3421
0
        if (cmp > 0)
3422
0
            return PyLong_FromSsize_t(i);
3423
0
        else if (cmp < 0)
3424
0
            return NULL;
3425
0
    }
3426
0
    PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
3427
0
    return NULL;
3428
0
}
3429
3430
/*[clinic input]
3431
list.count
3432
3433
     value: object
3434
     /
3435
3436
Return number of occurrences of value.
3437
[clinic start generated code]*/
3438
3439
static PyObject *
3440
list_count_impl(PyListObject *self, PyObject *value)
3441
/*[clinic end generated code: output=eff66f14aef2df86 input=3bdc3a5e6f749565]*/
3442
0
{
3443
0
    Py_ssize_t count = 0;
3444
0
    for (Py_ssize_t i = 0; ; i++) {
3445
0
        PyObject *obj = list_get_item_ref(self, i);
3446
0
        if (obj == NULL) {
3447
            // out-of-bounds
3448
0
            break;
3449
0
        }
3450
0
        if (obj == value) {
3451
0
           count++;
3452
0
           Py_DECREF(obj);
3453
0
           continue;
3454
0
        }
3455
0
        int cmp = PyObject_RichCompareBool(obj, value, Py_EQ);
3456
0
        Py_DECREF(obj);
3457
0
        if (cmp > 0)
3458
0
            count++;
3459
0
        else if (cmp < 0)
3460
0
            return NULL;
3461
0
    }
3462
0
    return PyLong_FromSsize_t(count);
3463
0
}
3464
3465
/*[clinic input]
3466
@critical_section
3467
list.remove
3468
3469
     value: object
3470
     /
3471
3472
Remove first occurrence of value.
3473
3474
Raises ValueError if the value is not present.
3475
[clinic start generated code]*/
3476
3477
static PyObject *
3478
list_remove_impl(PyListObject *self, PyObject *value)
3479
/*[clinic end generated code: output=b9b76a6633b18778 input=26c813dbb95aa93b]*/
3480
13.7k
{
3481
13.7k
    Py_ssize_t i;
3482
3483
13.8k
    for (i = 0; i < Py_SIZE(self); i++) {
3484
13.8k
        PyObject *obj = self->ob_item[i];
3485
13.8k
        Py_INCREF(obj);
3486
13.8k
        int cmp = PyObject_RichCompareBool(obj, value, Py_EQ);
3487
13.8k
        Py_DECREF(obj);
3488
13.8k
        if (cmp > 0) {
3489
13.7k
            if (list_ass_slice_lock_held(self, i, i+1, NULL) == 0)
3490
13.7k
                Py_RETURN_NONE;
3491
0
            return NULL;
3492
13.7k
        }
3493
24
        else if (cmp < 0)
3494
0
            return NULL;
3495
13.8k
    }
3496
2
    PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
3497
2
    return NULL;
3498
13.7k
}
3499
3500
static int
3501
list_traverse(PyObject *self, visitproc visit, void *arg)
3502
148M
{
3503
148M
    PyListObject *o = (PyListObject *)self;
3504
148M
    Py_ssize_t i;
3505
3506
498M
    for (i = Py_SIZE(o); --i >= 0; )
3507
350M
        Py_VISIT(o->ob_item[i]);
3508
148M
    return 0;
3509
148M
}
3510
3511
static PyObject *
3512
list_richcompare_impl(PyObject *v, PyObject *w, int op)
3513
93.8k
{
3514
93.8k
    PyListObject *vl, *wl;
3515
93.8k
    Py_ssize_t i;
3516
3517
93.8k
    if (!PyList_Check(v) || !PyList_Check(w))
3518
1.85k
        Py_RETURN_NOTIMPLEMENTED;
3519
3520
92.0k
    vl = (PyListObject *)v;
3521
92.0k
    wl = (PyListObject *)w;
3522
3523
92.0k
    if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) {
3524
        /* Shortcut: if the lengths differ, the lists differ */
3525
13.3k
        if (op == Py_EQ)
3526
13.3k
            Py_RETURN_FALSE;
3527
0
        else
3528
0
            Py_RETURN_TRUE;
3529
13.3k
    }
3530
3531
    /* Search for the first index where items are different.
3532
     * We incref vitem/witem before calling PyObject_RichCompareBool, which may
3533
     * release the GIL and allow the list to be mutated in the meantime.
3534
     */
3535
114k
    for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
3536
100k
        PyObject *vitem = vl->ob_item[i];
3537
100k
        PyObject *witem = wl->ob_item[i];
3538
100k
        if (vitem == witem) {
3539
34.3k
            continue;
3540
34.3k
        }
3541
3542
66.4k
        Py_INCREF(vitem);
3543
66.4k
        Py_INCREF(witem);
3544
66.4k
        int k = PyObject_RichCompareBool(vitem, witem, Py_EQ);
3545
66.4k
        if (k < 0) {
3546
0
            Py_DECREF(vitem);
3547
0
            Py_DECREF(witem);
3548
0
            return NULL;
3549
0
        }
3550
66.4k
        if (!k) {
3551
            /* We have a differing item -- shortcuts for EQ/NE */
3552
65.4k
            if (op == Py_EQ) {
3553
65.4k
                Py_DECREF(vitem);
3554
65.4k
                Py_DECREF(witem);
3555
65.4k
                Py_RETURN_FALSE;
3556
65.4k
            }
3557
27
            if (op == Py_NE) {
3558
27
                Py_DECREF(vitem);
3559
27
                Py_DECREF(witem);
3560
27
                Py_RETURN_TRUE;
3561
27
            }
3562
            /* Compare the differing items using the proper operator */
3563
0
            PyObject *result = PyObject_RichCompare(vitem, witem, op);
3564
0
            Py_DECREF(vitem);
3565
0
            Py_DECREF(witem);
3566
0
            return result;
3567
27
        }
3568
3569
1.00k
        Py_DECREF(vitem);
3570
1.00k
        Py_DECREF(witem);
3571
1.00k
    }
3572
3573
    /* All compared elements were equal -- compare sizes */
3574
13.1k
    Py_RETURN_RICHCOMPARE(Py_SIZE(vl), Py_SIZE(wl), op);
3575
13.1k
}
3576
3577
static PyObject *
3578
list_richcompare(PyObject *v, PyObject *w, int op)
3579
93.8k
{
3580
93.8k
    PyObject *ret;
3581
93.8k
    Py_BEGIN_CRITICAL_SECTION2(v, w);
3582
93.8k
    ret = list_richcompare_impl(v, w, op);
3583
93.8k
    Py_END_CRITICAL_SECTION2()
3584
93.8k
    return ret;
3585
93.8k
}
3586
3587
/*[clinic input]
3588
list.__init__
3589
3590
    iterable: object(c_default="NULL") = ()
3591
    /
3592
3593
Built-in mutable sequence.
3594
3595
If no argument is given, the constructor creates a new empty list.
3596
The argument must be an iterable if specified.
3597
[clinic start generated code]*/
3598
3599
static int
3600
list___init___impl(PyListObject *self, PyObject *iterable)
3601
/*[clinic end generated code: output=0f3c21379d01de48 input=b3f3fe7206af8f6b]*/
3602
23.8M
{
3603
    /* Verify list invariants */
3604
23.8M
    assert(0 <= Py_SIZE(self));
3605
23.8M
    assert(Py_SIZE(self) <= self->allocated || self->allocated == -1);
3606
23.8M
    assert(self->ob_item != NULL ||
3607
23.8M
           self->allocated == 0 || self->allocated == -1);
3608
3609
    /* Empty previous contents */
3610
23.8M
    if (self->ob_item != NULL) {
3611
0
        Py_BEGIN_CRITICAL_SECTION(self);
3612
0
        list_clear(self);
3613
0
        Py_END_CRITICAL_SECTION();
3614
0
    }
3615
23.8M
    if (iterable != NULL) {
3616
11.4M
        if (_list_extend(self, iterable) < 0) {
3617
0
            return -1;
3618
0
        }
3619
11.4M
    }
3620
23.8M
    return 0;
3621
23.8M
}
3622
3623
static PyObject *
3624
list_vectorcall(PyObject *type, PyObject * const*args,
3625
                size_t nargsf, PyObject *kwnames)
3626
11.4M
{
3627
11.4M
    if (!_PyArg_NoKwnames("list", kwnames)) {
3628
0
        return NULL;
3629
0
    }
3630
11.4M
    Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
3631
11.4M
    if (!_PyArg_CheckPositional("list", nargs, 0, 1)) {
3632
0
        return NULL;
3633
0
    }
3634
3635
    /* use PyList_New() to make exact lists from the freelist. */
3636
11.4M
    PyObject *list = (type == (PyObject *)&PyList_Type
3637
11.4M
                      ? PyList_New(0)
3638
11.4M
                      : PyType_GenericAlloc(_PyType_CAST(type), 0));
3639
11.4M
    if (list == NULL) {
3640
0
        return NULL;
3641
0
    }
3642
11.4M
    if (nargs) {
3643
11.4M
        if (list___init___impl((PyListObject *)list, args[0])) {
3644
0
            Py_DECREF(list);
3645
0
            return NULL;
3646
0
        }
3647
11.4M
    }
3648
11.4M
    return list;
3649
11.4M
}
3650
3651
3652
/*[clinic input]
3653
list.__sizeof__
3654
3655
Return the size of the list in memory, in bytes.
3656
[clinic start generated code]*/
3657
3658
static PyObject *
3659
list___sizeof___impl(PyListObject *self)
3660
/*[clinic end generated code: output=3417541f95f9a53e input=b8030a5d5ce8a187]*/
3661
0
{
3662
0
    size_t res = _PyObject_SIZE(Py_TYPE(self));
3663
#ifdef Py_GIL_DISABLED
3664
    Py_BEGIN_CRITICAL_SECTION(self);
3665
    PyObject **ob_item = self->ob_item;
3666
    if (ob_item != NULL) {
3667
        res += list_capacity(ob_item) * sizeof(PyObject *);
3668
    }
3669
    Py_END_CRITICAL_SECTION();
3670
#else
3671
0
    res += (size_t)self->allocated * sizeof(PyObject *);
3672
0
#endif
3673
0
    return PyLong_FromSize_t(res);
3674
0
}
3675
3676
static PyObject *list_iter(PyObject *seq);
3677
static PyObject *list_subscript(PyObject*, PyObject*);
3678
3679
static PyMethodDef list_methods[] = {
3680
    {"__getitem__", list_subscript, METH_O|METH_COEXIST,
3681
     PyDoc_STR("__getitem__($self, index, /)\n--\n\nReturn self[index].")},
3682
    LIST___REVERSED___METHODDEF
3683
    LIST___SIZEOF___METHODDEF
3684
    PY_LIST_CLEAR_METHODDEF
3685
    LIST_COPY_METHODDEF
3686
    LIST_APPEND_METHODDEF
3687
    LIST_INSERT_METHODDEF
3688
    LIST_EXTEND_METHODDEF
3689
    LIST_POP_METHODDEF
3690
    LIST_REMOVE_METHODDEF
3691
    LIST_INDEX_METHODDEF
3692
    LIST_COUNT_METHODDEF
3693
    LIST_REVERSE_METHODDEF
3694
    LIST_SORT_METHODDEF
3695
    {"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS,
3696
     PyDoc_STR("lists are generic over the type of their contents")},
3697
    {NULL,              NULL}           /* sentinel */
3698
};
3699
3700
static PySequenceMethods list_as_sequence = {
3701
    list_length,                                /* sq_length */
3702
    _PyList_Concat,                             /* sq_concat */
3703
    list_repeat,                                /* sq_repeat */
3704
    list_item,                                  /* sq_item */
3705
    0,                                          /* sq_slice */
3706
    list_ass_item,                              /* sq_ass_item */
3707
    0,                                          /* sq_ass_slice */
3708
    list_contains,                              /* sq_contains */
3709
    list_inplace_concat,                        /* sq_inplace_concat */
3710
    list_inplace_repeat,                        /* sq_inplace_repeat */
3711
};
3712
3713
static inline PyObject *
3714
list_slice_step_lock_held(PyListObject *a, Py_ssize_t start, Py_ssize_t step, Py_ssize_t len)
3715
316
{
3716
316
    PyListObject *np = (PyListObject *)list_new_prealloc(len);
3717
316
    if (np == NULL) {
3718
0
        return NULL;
3719
0
    }
3720
316
    size_t cur;
3721
316
    Py_ssize_t i;
3722
316
    PyObject **src = a->ob_item;
3723
316
    PyObject **dest = np->ob_item;
3724
5.59k
    for (cur = start, i = 0; i < len;
3725
5.27k
            cur += (size_t)step, i++) {
3726
5.27k
        PyObject *v = src[cur];
3727
5.27k
        dest[i] = Py_NewRef(v);
3728
5.27k
    }
3729
316
    Py_SET_SIZE(np, len);
3730
316
    return (PyObject *)np;
3731
316
}
3732
3733
static PyObject *
3734
list_slice_wrap(PyListObject *aa, Py_ssize_t start, Py_ssize_t stop, Py_ssize_t step)
3735
2.86M
{
3736
2.86M
    PyObject *res = NULL;
3737
2.86M
    Py_BEGIN_CRITICAL_SECTION(aa);
3738
2.86M
    Py_ssize_t len = PySlice_AdjustIndices(Py_SIZE(aa), &start, &stop, step);
3739
2.86M
    if (len <= 0) {
3740
464k
        res = PyList_New(0);
3741
464k
    }
3742
2.39M
    else if (step == 1) {
3743
2.39M
        res = list_slice_lock_held(aa, start, stop);
3744
2.39M
    }
3745
316
    else {
3746
316
        res = list_slice_step_lock_held(aa, start, step, len);
3747
316
    }
3748
2.86M
    Py_END_CRITICAL_SECTION();
3749
2.86M
    return res;
3750
2.86M
}
3751
3752
static inline PyObject*
3753
list_slice_subscript(PyObject* self, PyObject* item)
3754
2.86M
{
3755
2.86M
    assert(PyList_Check(self));
3756
2.86M
    assert(PySlice_Check(item));
3757
2.86M
    Py_ssize_t start, stop, step;
3758
2.86M
    if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
3759
0
        return NULL;
3760
0
    }
3761
2.86M
    return list_slice_wrap((PyListObject *)self, start, stop, step);
3762
2.86M
}
3763
3764
PyObject *
3765
_PyList_SliceSubscript(PyObject* _self, PyObject* item)
3766
2.86M
{
3767
2.86M
    return list_slice_subscript(_self, item);
3768
2.86M
}
3769
3770
static PyObject *
3771
list_subscript(PyObject* _self, PyObject* item)
3772
26.7M
{
3773
26.7M
    PyListObject* self = (PyListObject*)_self;
3774
26.7M
    if (_PyIndex_Check(item)) {
3775
26.7M
        Py_ssize_t i;
3776
26.7M
        i = PyNumber_AsSsize_t(item, PyExc_IndexError);
3777
26.7M
        if (i == -1 && PyErr_Occurred())
3778
31
            return NULL;
3779
26.7M
        if (i < 0)
3780
21.0M
            i += PyList_GET_SIZE(self);
3781
26.7M
        return list_item((PyObject *)self, i);
3782
26.7M
    }
3783
265
    else if (PySlice_Check(item)) {
3784
265
        return list_slice_subscript(_self, item);
3785
265
    }
3786
0
    else {
3787
0
        PyErr_Format(PyExc_TypeError,
3788
0
                     "list indices must be integers or slices, not %.200s",
3789
0
                     Py_TYPE(item)->tp_name);
3790
0
        return NULL;
3791
0
    }
3792
26.7M
}
3793
3794
static Py_ssize_t
3795
adjust_slice_indexes(PyListObject *lst,
3796
                     Py_ssize_t *start, Py_ssize_t *stop,
3797
                     Py_ssize_t step)
3798
2.06M
{
3799
2.06M
    Py_ssize_t slicelength = PySlice_AdjustIndices(Py_SIZE(lst), start, stop,
3800
2.06M
                                                   step);
3801
3802
    /* Make sure s[5:2] = [..] inserts at the right place:
3803
        before 5, not before 2. */
3804
2.06M
    if ((step < 0 && *start < *stop) ||
3805
2.06M
        (step > 0 && *start > *stop))
3806
0
        *stop = *start;
3807
3808
2.06M
    return slicelength;
3809
2.06M
}
3810
3811
static int
3812
list_ass_subscript_lock_held(PyObject *_self, PyObject *item, PyObject *value)
3813
5.67M
{
3814
5.67M
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(_self);
3815
3816
5.67M
    PyListObject *self = (PyListObject *)_self;
3817
5.67M
    if (_PyIndex_Check(item)) {
3818
3.61M
        Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
3819
3.61M
        if (i == -1 && PyErr_Occurred())
3820
0
            return -1;
3821
3.61M
        if (i < 0)
3822
3.60M
            i += PyList_GET_SIZE(self);
3823
3.61M
        return list_ass_item_impl(self, i, value);
3824
3.61M
    }
3825
2.06M
    else if (PySlice_Check(item)) {
3826
2.06M
        Py_ssize_t start, stop, step;
3827
3828
2.06M
        if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
3829
0
            return -1;
3830
0
        }
3831
3832
2.06M
        if (value == NULL) {
3833
            /* delete slice */
3834
127
            PyObject **garbage;
3835
127
            size_t cur;
3836
127
            Py_ssize_t i;
3837
127
            int res;
3838
3839
127
            Py_ssize_t slicelength = adjust_slice_indexes(self, &start, &stop,
3840
127
                                                          step);
3841
3842
127
            if (step == 1)
3843
127
                return list_ass_slice_lock_held(self, start, stop, value);
3844
3845
0
            if (slicelength <= 0)
3846
0
                return 0;
3847
3848
0
            if (step < 0) {
3849
0
                stop = start + 1;
3850
0
                start = stop + step*(slicelength - 1) - 1;
3851
0
                step = -step;
3852
0
            }
3853
3854
0
            garbage = (PyObject**)
3855
0
                PyMem_Malloc(slicelength*sizeof(PyObject*));
3856
0
            if (!garbage) {
3857
0
                PyErr_NoMemory();
3858
0
                return -1;
3859
0
            }
3860
3861
            /* drawing pictures might help understand these for
3862
               loops. Basically, we memmove the parts of the
3863
               list that are *not* part of the slice: step-1
3864
               items for each item that is part of the slice,
3865
               and then tail end of the list that was not
3866
               covered by the slice */
3867
0
            for (cur = start, i = 0;
3868
0
                 cur < (size_t)stop;
3869
0
                 cur += step, i++) {
3870
0
                Py_ssize_t lim = step - 1;
3871
3872
0
                garbage[i] = PyList_GET_ITEM(self, cur);
3873
3874
0
                if (cur + step >= (size_t)Py_SIZE(self)) {
3875
0
                    lim = Py_SIZE(self) - cur - 1;
3876
0
                }
3877
3878
0
                ptr_wise_atomic_memmove(self, self->ob_item + cur - i,
3879
0
                    self->ob_item + cur + 1, lim);
3880
0
            }
3881
0
            cur = start + (size_t)slicelength * step;
3882
0
            if (cur < (size_t)Py_SIZE(self)) {
3883
0
                ptr_wise_atomic_memmove(self, self->ob_item + cur - slicelength,
3884
0
                    self->ob_item + cur, Py_SIZE(self) - cur);
3885
0
            }
3886
3887
0
            Py_SET_SIZE(self, Py_SIZE(self) - slicelength);
3888
0
            res = list_resize(self, Py_SIZE(self));
3889
3890
0
            for (i = 0; i < slicelength; i++) {
3891
0
                Py_DECREF(garbage[i]);
3892
0
            }
3893
0
            PyMem_Free(garbage);
3894
3895
0
            return res;
3896
0
        }
3897
2.06M
        else {
3898
            /* assign slice */
3899
2.06M
            PyObject *ins, *seq;
3900
2.06M
            PyObject **garbage, **seqitems, **selfitems;
3901
2.06M
            Py_ssize_t i;
3902
2.06M
            size_t cur;
3903
3904
            /* protect against a[::-1] = a */
3905
2.06M
            if (self == (PyListObject*)value) {
3906
0
                seq = list_slice_lock_held((PyListObject *)value, 0,
3907
0
                                            Py_SIZE(value));
3908
0
            }
3909
2.06M
            else {
3910
2.06M
                seq = PySequence_Fast(value,
3911
2.06M
                                      "must assign iterable "
3912
2.06M
                                      "to extended slice");
3913
2.06M
            }
3914
2.06M
            if (!seq)
3915
0
                return -1;
3916
3917
2.06M
            Py_ssize_t slicelength = adjust_slice_indexes(self, &start, &stop,
3918
2.06M
                                                          step);
3919
3920
2.06M
            if (step == 1) {
3921
2.06M
                int res = list_ass_slice_lock_held(self, start, stop, seq);
3922
2.06M
                Py_DECREF(seq);
3923
2.06M
                return res;
3924
2.06M
            }
3925
3926
0
            if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
3927
0
                PyErr_Format(PyExc_ValueError,
3928
0
                    "attempt to assign sequence of "
3929
0
                    "size %zd to extended slice of "
3930
0
                    "size %zd",
3931
0
                         PySequence_Fast_GET_SIZE(seq),
3932
0
                         slicelength);
3933
0
                Py_DECREF(seq);
3934
0
                return -1;
3935
0
            }
3936
3937
0
            if (!slicelength) {
3938
0
                Py_DECREF(seq);
3939
0
                return 0;
3940
0
            }
3941
3942
0
            garbage = (PyObject**)
3943
0
                PyMem_Malloc(slicelength*sizeof(PyObject*));
3944
0
            if (!garbage) {
3945
0
                Py_DECREF(seq);
3946
0
                PyErr_NoMemory();
3947
0
                return -1;
3948
0
            }
3949
3950
0
            selfitems = self->ob_item;
3951
0
            seqitems = PySequence_Fast_ITEMS(seq);
3952
0
            for (cur = start, i = 0; i < slicelength;
3953
0
                 cur += (size_t)step, i++) {
3954
0
                garbage[i] = selfitems[cur];
3955
0
                ins = Py_NewRef(seqitems[i]);
3956
0
                FT_ATOMIC_STORE_PTR_RELEASE(selfitems[cur], ins);
3957
0
            }
3958
3959
0
            for (i = 0; i < slicelength; i++) {
3960
0
                Py_DECREF(garbage[i]);
3961
0
            }
3962
3963
0
            PyMem_Free(garbage);
3964
0
            Py_DECREF(seq);
3965
3966
0
            return 0;
3967
0
        }
3968
2.06M
    }
3969
0
    else {
3970
0
        PyErr_Format(PyExc_TypeError,
3971
0
                     "list indices must be integers or slices, not %.200s",
3972
0
                     Py_TYPE(item)->tp_name);
3973
0
        return -1;
3974
0
    }
3975
5.67M
}
3976
3977
static int
3978
list_ass_subscript(PyObject *self, PyObject *item, PyObject *value)
3979
5.67M
{
3980
5.67M
    int res;
3981
#ifdef Py_GIL_DISABLED
3982
    if (PySlice_Check(item) && value != NULL && PyList_CheckExact(value)) {
3983
        Py_BEGIN_CRITICAL_SECTION2(self, value);
3984
        res = list_ass_subscript_lock_held(self, item, value);
3985
        Py_END_CRITICAL_SECTION2();
3986
        return res;
3987
    }
3988
#endif
3989
5.67M
    Py_BEGIN_CRITICAL_SECTION(self);
3990
5.67M
    res = list_ass_subscript_lock_held(self, item, value);
3991
5.67M
    Py_END_CRITICAL_SECTION();
3992
5.67M
    return res;
3993
5.67M
}
3994
3995
static _PyObjectIndexPair
3996
list_iteritem(PyObject *obj, Py_ssize_t index)
3997
1.88M
{
3998
1.88M
    PyObject *result = list_get_item_ref((PyListObject *)obj, index);
3999
1.88M
    return (_PyObjectIndexPair) { .object = result, .index = index + 1 };
4000
1.88M
}
4001
4002
static PyMappingMethods list_as_mapping = {
4003
    list_length,
4004
    list_subscript,
4005
    list_ass_subscript
4006
};
4007
4008
PyTypeObject PyList_Type = {
4009
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
4010
    "list",
4011
    sizeof(PyListObject),
4012
    0,
4013
    list_dealloc,                               /* tp_dealloc */
4014
    0,                                          /* tp_vectorcall_offset */
4015
    0,                                          /* tp_getattr */
4016
    0,                                          /* tp_setattr */
4017
    0,                                          /* tp_as_async */
4018
    list_repr,                                  /* tp_repr */
4019
    0,                                          /* tp_as_number */
4020
    &list_as_sequence,                          /* tp_as_sequence */
4021
    &list_as_mapping,                           /* tp_as_mapping */
4022
    PyObject_HashNotImplemented,                /* tp_hash */
4023
    0,                                          /* tp_call */
4024
    0,                                          /* tp_str */
4025
    PyObject_GenericGetAttr,                    /* tp_getattro */
4026
    0,                                          /* tp_setattro */
4027
    0,                                          /* tp_as_buffer */
4028
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
4029
        Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS |
4030
        _Py_TPFLAGS_MATCH_SELF | Py_TPFLAGS_SEQUENCE,  /* tp_flags */
4031
    list___init____doc__,                       /* tp_doc */
4032
    list_traverse,                              /* tp_traverse */
4033
    list_clear_slot,                            /* tp_clear */
4034
    list_richcompare,                           /* tp_richcompare */
4035
    0,                                          /* tp_weaklistoffset */
4036
    list_iter,                                  /* tp_iter */
4037
    0,                                          /* tp_iternext */
4038
    list_methods,                               /* tp_methods */
4039
    0,                                          /* tp_members */
4040
    0,                                          /* tp_getset */
4041
    0,                                          /* tp_base */
4042
    0,                                          /* tp_dict */
4043
    0,                                          /* tp_descr_get */
4044
    0,                                          /* tp_descr_set */
4045
    0,                                          /* tp_dictoffset */
4046
    list___init__,                              /* tp_init */
4047
    PyType_GenericAlloc,                        /* tp_alloc */
4048
    PyType_GenericNew,                          /* tp_new */
4049
    PyObject_GC_Del,                            /* tp_free */
4050
    .tp_vectorcall = list_vectorcall,
4051
    .tp_version_tag = _Py_TYPE_VERSION_LIST,
4052
    ._tp_iteritem = list_iteritem,
4053
};
4054
4055
/*********************** List Iterator **************************/
4056
4057
static void listiter_dealloc(PyObject *);
4058
static int listiter_traverse(PyObject *, visitproc, void *);
4059
static PyObject *listiter_next(PyObject *);
4060
static PyObject *listiter_len(PyObject *, PyObject *);
4061
static PyObject *listiter_reduce_general(void *_it, int forward);
4062
static PyObject *listiter_reduce(PyObject *, PyObject *);
4063
static PyObject *listiter_setstate(PyObject *, PyObject *state);
4064
4065
PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
4066
PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
4067
PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
4068
4069
static PyMethodDef listiter_methods[] = {
4070
    {"__length_hint__", listiter_len, METH_NOARGS, length_hint_doc},
4071
    {"__reduce__", listiter_reduce, METH_NOARGS, reduce_doc},
4072
    {"__setstate__", listiter_setstate, METH_O, setstate_doc},
4073
    {NULL,              NULL}           /* sentinel */
4074
};
4075
4076
PyTypeObject PyListIter_Type = {
4077
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
4078
    "list_iterator",                            /* tp_name */
4079
    sizeof(_PyListIterObject),                  /* tp_basicsize */
4080
    0,                                          /* tp_itemsize */
4081
    /* methods */
4082
    listiter_dealloc,               /* tp_dealloc */
4083
    0,                                          /* tp_vectorcall_offset */
4084
    0,                                          /* tp_getattr */
4085
    0,                                          /* tp_setattr */
4086
    0,                                          /* tp_as_async */
4087
    0,                                          /* tp_repr */
4088
    0,                                          /* tp_as_number */
4089
    0,                                          /* tp_as_sequence */
4090
    0,                                          /* tp_as_mapping */
4091
    0,                                          /* tp_hash */
4092
    0,                                          /* tp_call */
4093
    0,                                          /* tp_str */
4094
    PyObject_GenericGetAttr,                    /* tp_getattro */
4095
    0,                                          /* tp_setattro */
4096
    0,                                          /* tp_as_buffer */
4097
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
4098
    0,                                          /* tp_doc */
4099
    listiter_traverse,                          /* tp_traverse */
4100
    0,                                          /* tp_clear */
4101
    0,                                          /* tp_richcompare */
4102
    0,                                          /* tp_weaklistoffset */
4103
    PyObject_SelfIter,                          /* tp_iter */
4104
    listiter_next,                              /* tp_iternext */
4105
    listiter_methods,                           /* tp_methods */
4106
    0,                                          /* tp_members */
4107
};
4108
4109
4110
static PyObject *
4111
list_iter(PyObject *seq)
4112
38.0M
{
4113
38.0M
    if (!PyList_Check(seq)) {
4114
0
        PyErr_BadInternalCall();
4115
0
        return NULL;
4116
0
    }
4117
38.0M
    _PyListIterObject *it = _Py_FREELIST_POP(_PyListIterObject, list_iters);
4118
38.0M
    if (it == NULL) {
4119
2.70M
        it = PyObject_GC_New(_PyListIterObject, &PyListIter_Type);
4120
2.70M
        if (it == NULL) {
4121
0
            return NULL;
4122
0
        }
4123
2.70M
    }
4124
38.0M
    it->it_index = 0;
4125
38.0M
    it->it_seq = (PyListObject *)Py_NewRef(seq);
4126
38.0M
    _PyObject_GC_TRACK(it);
4127
38.0M
    return (PyObject *)it;
4128
38.0M
}
4129
4130
static void
4131
listiter_dealloc(PyObject *self)
4132
38.0M
{
4133
38.0M
    _PyListIterObject *it = (_PyListIterObject *)self;
4134
38.0M
    _PyObject_GC_UNTRACK(it);
4135
38.0M
    Py_XDECREF(it->it_seq);
4136
38.0M
    assert(Py_IS_TYPE(self, &PyListIter_Type));
4137
38.0M
    _Py_FREELIST_FREE(list_iters, it, PyObject_GC_Del);
4138
38.0M
}
4139
4140
static int
4141
listiter_traverse(PyObject *it, visitproc visit, void *arg)
4142
955k
{
4143
955k
    Py_VISIT(((_PyListIterObject *)it)->it_seq);
4144
955k
    return 0;
4145
955k
}
4146
4147
static PyObject *
4148
listiter_next(PyObject *self)
4149
202M
{
4150
202M
    _PyListIterObject *it = (_PyListIterObject *)self;
4151
202M
    Py_ssize_t index = FT_ATOMIC_LOAD_SSIZE_RELAXED(it->it_index);
4152
202M
    if (index < 0) {
4153
173
        return NULL;
4154
173
    }
4155
4156
202M
    PyObject *item = list_get_item_ref(it->it_seq, index);
4157
202M
    if (item == NULL) {
4158
        // out-of-bounds
4159
37.5M
        FT_ATOMIC_STORE_SSIZE_RELAXED(it->it_index, -1);
4160
37.5M
#ifndef Py_GIL_DISABLED
4161
37.5M
        PyListObject *seq = it->it_seq;
4162
37.5M
        it->it_seq = NULL;
4163
37.5M
        Py_DECREF(seq);
4164
37.5M
#endif
4165
37.5M
        return NULL;
4166
37.5M
    }
4167
165M
    FT_ATOMIC_STORE_SSIZE_RELAXED(it->it_index, index + 1);
4168
165M
    return item;
4169
202M
}
4170
4171
static PyObject *
4172
listiter_len(PyObject *self, PyObject *Py_UNUSED(ignored))
4173
1.36M
{
4174
1.36M
    assert(self != NULL);
4175
1.36M
    _PyListIterObject *it = (_PyListIterObject *)self;
4176
1.36M
    Py_ssize_t index = FT_ATOMIC_LOAD_SSIZE_RELAXED(it->it_index);
4177
1.36M
    if (index >= 0) {
4178
1.36M
        Py_ssize_t len = PyList_GET_SIZE(it->it_seq) - index;
4179
1.36M
        if (len >= 0)
4180
1.36M
            return PyLong_FromSsize_t(len);
4181
1.36M
    }
4182
0
    return PyLong_FromLong(0);
4183
1.36M
}
4184
4185
static PyObject *
4186
listiter_reduce(PyObject *it, PyObject *Py_UNUSED(ignored))
4187
0
{
4188
0
    return listiter_reduce_general(it, 1);
4189
0
}
4190
4191
static PyObject *
4192
listiter_setstate(PyObject *self, PyObject *state)
4193
0
{
4194
0
    _PyListIterObject *it = (_PyListIterObject *)self;
4195
0
    Py_ssize_t index = PyLong_AsSsize_t(state);
4196
0
    if (index == -1 && PyErr_Occurred())
4197
0
        return NULL;
4198
0
    if (it->it_seq != NULL) {
4199
0
        if (index < -1)
4200
0
            index = -1;
4201
0
        else if (index > PyList_GET_SIZE(it->it_seq))
4202
0
            index = PyList_GET_SIZE(it->it_seq); /* iterator exhausted */
4203
0
        FT_ATOMIC_STORE_SSIZE_RELAXED(it->it_index, index);
4204
0
    }
4205
0
    Py_RETURN_NONE;
4206
0
}
4207
4208
/*********************** List Reverse Iterator **************************/
4209
4210
typedef struct {
4211
    PyObject_HEAD
4212
    Py_ssize_t it_index;
4213
    PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
4214
} listreviterobject;
4215
4216
static void listreviter_dealloc(PyObject *);
4217
static int listreviter_traverse(PyObject *, visitproc, void *);
4218
static PyObject *listreviter_next(PyObject *);
4219
static PyObject *listreviter_len(PyObject *, PyObject *);
4220
static PyObject *listreviter_reduce(PyObject *, PyObject *);
4221
static PyObject *listreviter_setstate(PyObject *, PyObject *);
4222
4223
static PyMethodDef listreviter_methods[] = {
4224
    {"__length_hint__", listreviter_len, METH_NOARGS, length_hint_doc},
4225
    {"__reduce__", listreviter_reduce, METH_NOARGS, reduce_doc},
4226
    {"__setstate__", listreviter_setstate, METH_O, setstate_doc},
4227
    {NULL,              NULL}           /* sentinel */
4228
};
4229
4230
PyTypeObject PyListRevIter_Type = {
4231
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
4232
    "list_reverseiterator",                     /* tp_name */
4233
    sizeof(listreviterobject),                  /* tp_basicsize */
4234
    0,                                          /* tp_itemsize */
4235
    /* methods */
4236
    listreviter_dealloc,                        /* tp_dealloc */
4237
    0,                                          /* tp_vectorcall_offset */
4238
    0,                                          /* tp_getattr */
4239
    0,                                          /* tp_setattr */
4240
    0,                                          /* tp_as_async */
4241
    0,                                          /* tp_repr */
4242
    0,                                          /* tp_as_number */
4243
    0,                                          /* tp_as_sequence */
4244
    0,                                          /* tp_as_mapping */
4245
    0,                                          /* tp_hash */
4246
    0,                                          /* tp_call */
4247
    0,                                          /* tp_str */
4248
    PyObject_GenericGetAttr,                    /* tp_getattro */
4249
    0,                                          /* tp_setattro */
4250
    0,                                          /* tp_as_buffer */
4251
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
4252
    0,                                          /* tp_doc */
4253
    listreviter_traverse,                       /* tp_traverse */
4254
    0,                                          /* tp_clear */
4255
    0,                                          /* tp_richcompare */
4256
    0,                                          /* tp_weaklistoffset */
4257
    PyObject_SelfIter,                          /* tp_iter */
4258
    listreviter_next,                           /* tp_iternext */
4259
    listreviter_methods,                /* tp_methods */
4260
    0,
4261
};
4262
4263
/*[clinic input]
4264
list.__reversed__
4265
4266
Return a reverse iterator over the list.
4267
[clinic start generated code]*/
4268
4269
static PyObject *
4270
list___reversed___impl(PyListObject *self)
4271
/*[clinic end generated code: output=b166f073208c888c input=eadb6e17f8a6a280]*/
4272
41.7M
{
4273
41.7M
    listreviterobject *it;
4274
4275
41.7M
    it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
4276
41.7M
    if (it == NULL)
4277
0
        return NULL;
4278
41.7M
    assert(PyList_Check(self));
4279
41.7M
    it->it_index = PyList_GET_SIZE(self) - 1;
4280
41.7M
    it->it_seq = (PyListObject*)Py_NewRef(self);
4281
41.7M
    PyObject_GC_Track(it);
4282
41.7M
    return (PyObject *)it;
4283
41.7M
}
4284
4285
static void
4286
listreviter_dealloc(PyObject *self)
4287
41.7M
{
4288
41.7M
    listreviterobject *it = (listreviterobject *)self;
4289
41.7M
    PyObject_GC_UnTrack(it);
4290
41.7M
    Py_XDECREF(it->it_seq);
4291
41.7M
    PyObject_GC_Del(it);
4292
41.7M
}
4293
4294
static int
4295
listreviter_traverse(PyObject *it, visitproc visit, void *arg)
4296
11.8k
{
4297
11.8k
    Py_VISIT(((listreviterobject *)it)->it_seq);
4298
11.8k
    return 0;
4299
11.8k
}
4300
4301
static PyObject *
4302
listreviter_next(PyObject *self)
4303
51.5M
{
4304
51.5M
    listreviterobject *it = (listreviterobject *)self;
4305
51.5M
    assert(it != NULL);
4306
51.5M
    Py_ssize_t index = FT_ATOMIC_LOAD_SSIZE_RELAXED(it->it_index);
4307
51.5M
    if (index < 0) {
4308
27.3M
        return NULL;
4309
27.3M
    }
4310
4311
24.2M
    PyListObject *seq = it->it_seq;
4312
24.2M
    assert(PyList_Check(seq));
4313
24.2M
    PyObject *item = list_get_item_ref(seq, index);
4314
24.2M
    if (item != NULL) {
4315
24.2M
        FT_ATOMIC_STORE_SSIZE_RELAXED(it->it_index, index - 1);
4316
24.2M
        return item;
4317
24.2M
    }
4318
0
    FT_ATOMIC_STORE_SSIZE_RELAXED(it->it_index, -1);
4319
0
#ifndef Py_GIL_DISABLED
4320
0
    it->it_seq = NULL;
4321
0
    Py_DECREF(seq);
4322
0
#endif
4323
0
    return NULL;
4324
24.2M
}
4325
4326
static PyObject *
4327
listreviter_len(PyObject *self, PyObject *Py_UNUSED(ignored))
4328
0
{
4329
0
    listreviterobject *it = (listreviterobject *)self;
4330
0
    Py_ssize_t index = FT_ATOMIC_LOAD_SSIZE_RELAXED(it->it_index);
4331
0
    Py_ssize_t len = index + 1;
4332
0
    if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
4333
0
        len = 0;
4334
0
    return PyLong_FromSsize_t(len);
4335
0
}
4336
4337
static PyObject *
4338
listreviter_reduce(PyObject *it, PyObject *Py_UNUSED(ignored))
4339
0
{
4340
0
    return listiter_reduce_general(it, 0);
4341
0
}
4342
4343
static PyObject *
4344
listreviter_setstate(PyObject *self, PyObject *state)
4345
0
{
4346
0
    listreviterobject *it = (listreviterobject *)self;
4347
0
    Py_ssize_t index = PyLong_AsSsize_t(state);
4348
0
    if (index == -1 && PyErr_Occurred())
4349
0
        return NULL;
4350
0
    if (it->it_seq != NULL) {
4351
0
        if (index < -1)
4352
0
            index = -1;
4353
0
        else if (index > PyList_GET_SIZE(it->it_seq) - 1)
4354
0
            index = PyList_GET_SIZE(it->it_seq) - 1;
4355
0
        FT_ATOMIC_STORE_SSIZE_RELAXED(it->it_index, index);
4356
0
    }
4357
0
    Py_RETURN_NONE;
4358
0
}
4359
4360
/* common pickling support */
4361
4362
static PyObject *
4363
listiter_reduce_general(void *_it, int forward)
4364
0
{
4365
0
    PyObject *list;
4366
0
    PyObject *iter;
4367
4368
    /* _PyEval_GetBuiltin can invoke arbitrary code,
4369
     * call must be before access of iterator pointers.
4370
     * see issue #101765 */
4371
4372
0
    if (forward) {
4373
0
        iter = _PyEval_GetBuiltin(&_Py_ID(iter));
4374
0
        _PyListIterObject *it = (_PyListIterObject *)_it;
4375
0
        Py_ssize_t idx = FT_ATOMIC_LOAD_SSIZE_RELAXED(it->it_index);
4376
0
        if (idx >= 0) {
4377
0
            return Py_BuildValue("N(O)n", iter, it->it_seq, idx);
4378
0
        }
4379
0
    } else {
4380
0
        iter = _PyEval_GetBuiltin(&_Py_ID(reversed));
4381
0
        listreviterobject *it = (listreviterobject *)_it;
4382
0
        Py_ssize_t idx = FT_ATOMIC_LOAD_SSIZE_RELAXED(it->it_index);
4383
0
        if (idx >= 0) {
4384
0
            return Py_BuildValue("N(O)n", iter, it->it_seq, idx);
4385
0
        }
4386
0
    }
4387
    /* empty iterator, create an empty list */
4388
0
    list = PyList_New(0);
4389
0
    if (list == NULL) {
4390
0
        Py_DECREF(iter);
4391
0
        return NULL;
4392
0
    }
4393
0
    return Py_BuildValue("N(N)", iter, list);
4394
0
}