Coverage Report

Created: 2026-12-01 06:09

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