Coverage Report

Created: 2026-10-17 06:15

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
136M
{
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
136M
    PyMem_Free(items);
72
136M
#endif
73
136M
}
74
75
static void
76
ensure_shared_on_resize(PyListObject *self)
77
86.1M
{
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
86.1M
}
93
94
11.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
106M
{
113
106M
    Py_ssize_t allocated = self->allocated;
114
115
    /* Bypass realloc() when a previous overallocation is large enough
116
       to accommodate the newsize.  If the newsize falls lower than half
117
       the allocated size, then proceed with the realloc() to shrink the list.
118
       gh-158592: do not shrink a small list, the realloc() cost is bigger
119
       than the memory we get back.
120
    */
121
106M
    if (allocated >= newsize
122
20.7M
        && (newsize >= (allocated >> 1) || allocated <= LIST_SMALL_ALLOCATED))
123
20.7M
    {
124
20.7M
        assert(self->ob_item != NULL || newsize == 0);
125
20.7M
        Py_SET_SIZE(self, newsize);
126
20.7M
        return 0;
127
20.7M
    }
128
86.1M
    return py_list_resize(self, newsize);
129
106M
}
130
131
/* Slow path of list_resize(): allocate or reallocate ob_item. */
132
static int
133
py_list_resize(PyListObject *self, Py_ssize_t newsize)
134
86.1M
{
135
86.1M
    size_t new_allocated, target_bytes;
136
86.1M
    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
86.1M
    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
86.1M
    if (newsize - Py_SIZE(self) > (Py_ssize_t)(new_allocated - newsize))
153
345k
        new_allocated = ((size_t)newsize + 3) & ~(size_t)3;
154
155
86.1M
    if (newsize == 0)
156
0
        new_allocated = 0;
157
158
86.1M
    assert(newsize > allocated || new_allocated < (size_t)allocated);
159
160
86.1M
    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
86.1M
    PyObject **items;
194
86.1M
    if (new_allocated <= (size_t)PY_SSIZE_T_MAX / sizeof(PyObject *)) {
195
86.1M
        target_bytes = new_allocated * sizeof(PyObject *);
196
86.1M
        items = (PyObject **)PyMem_Realloc(self->ob_item, target_bytes);
197
86.1M
    }
198
0
    else {
199
        // integer overflow
200
0
        items = NULL;
201
0
    }
202
86.1M
    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
86.1M
    self->ob_item = items;
212
86.1M
    Py_SET_SIZE(self, newsize);
213
86.1M
    self->allocated = new_allocated;
214
86.1M
#endif
215
86.1M
    return 0;
216
86.1M
}
217
218
static int
219
list_preallocate_exact(PyListObject *self, Py_ssize_t size)
220
7.11M
{
221
7.11M
    PyObject **items;
222
7.11M
    assert(self->ob_item == NULL);
223
7.11M
    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
7.11M
    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
7.11M
    items = PyMem_New(PyObject*, size);
241
7.11M
    if (items == NULL) {
242
0
        PyErr_NoMemory();
243
0
        return -1;
244
0
    }
245
7.11M
#endif
246
7.11M
    FT_ATOMIC_STORE_PTR_RELEASE(self->ob_item, items);
247
7.11M
    self->allocated = size;
248
7.11M
    return 0;
249
7.11M
}
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
238M
{
264
238M
    if (size < 0) {
265
0
        PyErr_BadInternalCall();
266
0
        return NULL;
267
0
    }
268
269
238M
    PyListObject *op = _Py_FREELIST_POP(PyListObject, lists);
270
238M
    if (op == NULL) {
271
44.8M
        op = PyObject_GC_New(PyListObject, &PyList_Type);
272
44.8M
        if (op == NULL) {
273
0
            return NULL;
274
0
        }
275
44.8M
    }
276
238M
    if (size <= 0) {
277
195M
        op->ob_item = NULL;
278
195M
    }
279
43.5M
    else {
280
#ifdef Py_GIL_DISABLED
281
        _PyListArray *array = list_allocate_array(size);
282
        if (array == NULL) {
283
            Py_DECREF(op);
284
            return PyErr_NoMemory();
285
        }
286
        memset(&array->ob_item, 0, size * sizeof(PyObject *));
287
        op->ob_item = array->ob_item;
288
#else
289
43.5M
        op->ob_item = (PyObject **) PyMem_Calloc(size, sizeof(PyObject *));
290
43.5M
#endif
291
43.5M
        if (op->ob_item == NULL) {
292
0
            Py_DECREF(op);
293
0
            return PyErr_NoMemory();
294
0
        }
295
43.5M
    }
296
238M
    Py_SET_SIZE(op, size);
297
238M
    op->allocated = size;
298
238M
    _PyObject_GC_TRACK(op);
299
238M
    return (PyObject *) op;
300
238M
}
301
302
static PyObject *
303
list_new_prealloc(Py_ssize_t size)
304
15.8M
{
305
15.8M
    assert(size > 0);
306
15.8M
    PyListObject *op = (PyListObject *) PyList_New(0);
307
15.8M
    if (op == NULL) {
308
0
        return NULL;
309
0
    }
310
15.8M
    assert(op->ob_item == NULL);
311
#ifdef Py_GIL_DISABLED
312
    _PyListArray *array = list_allocate_array(size);
313
    if (array == NULL) {
314
        Py_DECREF(op);
315
        return PyErr_NoMemory();
316
    }
317
    op->ob_item = array->ob_item;
318
#else
319
15.8M
    op->ob_item = PyMem_New(PyObject *, size);
320
15.8M
    if (op->ob_item == NULL) {
321
0
        Py_DECREF(op);
322
0
        return PyErr_NoMemory();
323
0
    }
324
15.8M
#endif
325
15.8M
    op->allocated = size;
326
15.8M
    return (PyObject *) op;
327
15.8M
}
328
329
Py_ssize_t
330
PyList_Size(PyObject *op)
331
76.0k
{
332
76.0k
    if (!PyList_Check(op)) {
333
0
        PyErr_BadInternalCall();
334
0
        return -1;
335
0
    }
336
76.0k
    else {
337
76.0k
        return PyList_GET_SIZE(op);
338
76.0k
    }
339
76.0k
}
340
341
static inline int
342
valid_index(Py_ssize_t i, Py_ssize_t limit)
343
291M
{
344
    /* The cast to size_t lets us use just a single comparison
345
       to check whether i is in the range: 0 <= i < limit.
346
347
       See:  Section 14.2 "Bounds Checking" in the Agner Fog
348
       optimization manual found at:
349
       https://www.agner.org/optimize/optimizing_cpp.pdf
350
    */
351
291M
    return (size_t) i < (size_t) limit;
352
291M
}
353
354
#ifdef Py_GIL_DISABLED
355
356
static PyObject *
357
list_item_impl(PyListObject *self, Py_ssize_t idx)
358
{
359
    PyObject *item = NULL;
360
    Py_BEGIN_CRITICAL_SECTION(self);
361
    if (!_PyObject_GC_IS_SHARED(self)) {
362
        _PyObject_GC_SET_SHARED(self);
363
    }
364
    Py_ssize_t size = Py_SIZE(self);
365
    if (!valid_index(idx, size)) {
366
        goto exit;
367
    }
368
    item = _Py_NewRefWithLock(self->ob_item[idx]);
369
exit:
370
    Py_END_CRITICAL_SECTION();
371
    return item;
372
}
373
374
static inline PyObject*
375
list_get_item_ref(PyListObject *op, Py_ssize_t i)
376
{
377
    if (!_Py_IsOwnedByCurrentThread((PyObject *)op) && !_PyObject_GC_IS_SHARED(op)) {
378
        return list_item_impl(op, i);
379
    }
380
    // Need atomic operation for the getting size.
381
    Py_ssize_t size = PyList_GET_SIZE(op);
382
    if (!valid_index(i, size)) {
383
        return NULL;
384
    }
385
    PyObject **ob_item = _Py_atomic_load_ptr(&op->ob_item);
386
    if (ob_item == NULL) {
387
        return NULL;
388
    }
389
    Py_ssize_t cap = list_capacity(ob_item);
390
    assert(cap != -1);
391
    if (!valid_index(i, cap)) {
392
        return NULL;
393
    }
394
    PyObject *item = _Py_TryXGetRef(&ob_item[i]);
395
    if (item == NULL) {
396
        return list_item_impl(op, i);
397
    }
398
    return item;
399
}
400
#else
401
static inline PyObject*
402
list_get_item_ref(PyListObject *op, Py_ssize_t i)
403
220M
{
404
220M
    if (!valid_index(i, Py_SIZE(op))) {
405
34.9M
        return NULL;
406
34.9M
    }
407
185M
    return Py_NewRef(PyList_GET_ITEM(op, i));
408
220M
}
409
#endif
410
411
PyObject *
412
PyList_GetItem(PyObject *op, Py_ssize_t i)
413
124
{
414
124
    if (!PyList_Check(op)) {
415
0
        PyErr_BadInternalCall();
416
0
        return NULL;
417
0
    }
418
124
    if (!valid_index(i, Py_SIZE(op))) {
419
0
        _Py_DECLARE_STR(list_err, "list index out of range");
420
0
        PyErr_SetObject(PyExc_IndexError, &_Py_STR(list_err));
421
0
        return NULL;
422
0
    }
423
124
    return ((PyListObject *)op) -> ob_item[i];
424
124
}
425
426
PyObject *
427
PyList_GetItemRef(PyObject *op, Py_ssize_t i)
428
133k
{
429
133k
    if (!PyList_Check(op)) {
430
0
        PyErr_SetString(PyExc_TypeError, "expected a list");
431
0
        return NULL;
432
0
    }
433
133k
    PyObject *item = list_get_item_ref((PyListObject *)op, i);
434
133k
    if (item == NULL) {
435
0
        _Py_DECLARE_STR(list_err, "list index out of range");
436
0
        PyErr_SetObject(PyExc_IndexError, &_Py_STR(list_err));
437
0
        return NULL;
438
0
    }
439
133k
    return item;
440
133k
}
441
442
PyObject *
443
_PyList_GetItemRef(PyListObject *list, Py_ssize_t i)
444
0
{
445
0
    return list_get_item_ref(list, i);
446
0
}
447
448
#ifdef Py_GIL_DISABLED
449
int
450
_PyList_GetItemRefNoLock(PyListObject *list, Py_ssize_t i, _PyStackRef *result)
451
{
452
    assert(_Py_IsOwnedByCurrentThread((PyObject *)list) ||
453
           _PyObject_GC_IS_SHARED(list));
454
    if (!valid_index(i, PyList_GET_SIZE(list))) {
455
        return 0;
456
    }
457
    PyObject **ob_item = _Py_atomic_load_ptr(&list->ob_item);
458
    if (ob_item == NULL) {
459
        return 0;
460
    }
461
    Py_ssize_t cap = list_capacity(ob_item);
462
    assert(cap != -1);
463
    if (!valid_index(i, cap)) {
464
        return 0;
465
    }
466
    PyObject *obj = _Py_atomic_load_ptr(&ob_item[i]);
467
    if (obj == NULL || !_Py_TryIncrefCompareStackRef(&ob_item[i], obj, result)) {
468
        return -1;
469
    }
470
    return 1;
471
}
472
#endif
473
474
int
475
PyList_SetItem(PyObject *op, Py_ssize_t i,
476
               PyObject *newitem)
477
20.4M
{
478
20.4M
    if (!PyList_Check(op)) {
479
0
        Py_XDECREF(newitem);
480
0
        PyErr_BadInternalCall();
481
0
        return -1;
482
0
    }
483
20.4M
    int ret;
484
20.4M
    PyListObject *self = ((PyListObject *)op);
485
20.4M
    Py_BEGIN_CRITICAL_SECTION(self);
486
20.4M
    if (!valid_index(i, Py_SIZE(self))) {
487
0
        Py_XDECREF(newitem);
488
0
        PyErr_SetString(PyExc_IndexError,
489
0
                        "list assignment index out of range");
490
0
        ret = -1;
491
0
        goto end;
492
0
    }
493
20.4M
    PyObject *tmp = self->ob_item[i];
494
20.4M
    FT_ATOMIC_STORE_PTR_RELEASE(self->ob_item[i], newitem);
495
20.4M
    Py_XDECREF(tmp);
496
20.4M
    ret = 0;
497
20.4M
end:;
498
20.4M
    Py_END_CRITICAL_SECTION();
499
20.4M
    return ret;
500
20.4M
}
501
502
static void ptr_wise_atomic_memmove(PyListObject *a, PyObject **dest,
503
                                    PyObject **src, Py_ssize_t n);
504
505
static inline void
506
list_shift_items_right_lock_held(PyListObject *self, Py_ssize_t first,
507
                                 Py_ssize_t last)
508
117
{
509
#ifdef Py_GIL_DISABLED
510
    ptr_wise_atomic_memmove(self, &self->ob_item[first + 1],
511
                            &self->ob_item[first], last - first);
512
#else
513
117
    PyObject **items = self->ob_item;
514
363
    for (Py_ssize_t i = last; --i >= first; ) {
515
246
        items[i + 1] = items[i];
516
246
    }
517
117
#endif
518
117
}
519
520
static inline void
521
list_shift_items_left_lock_held(PyListObject *self, Py_ssize_t first,
522
                                Py_ssize_t last)
523
7.76k
{
524
#ifdef Py_GIL_DISABLED
525
    ptr_wise_atomic_memmove(self, &self->ob_item[first],
526
                            &self->ob_item[first + 1], last - first);
527
#else
528
7.76k
    PyObject **items = self->ob_item;
529
22.1M
    for (Py_ssize_t i = first; i < last; i++) {
530
22.1M
        items[i] = items[i + 1];
531
22.1M
    }
532
7.76k
#endif
533
7.76k
}
534
535
static int
536
ins1(PyListObject *self, Py_ssize_t where, PyObject *v)
537
129
{
538
129
    Py_ssize_t n = Py_SIZE(self);
539
129
    PyObject **items;
540
129
    if (v == NULL) {
541
0
        PyErr_BadInternalCall();
542
0
        return -1;
543
0
    }
544
545
129
    assert((size_t)n + 1 < PY_SSIZE_T_MAX);
546
129
    if (list_resize(self, n+1) < 0)
547
0
        return -1;
548
549
129
    if (where < 0) {
550
0
        where += n;
551
0
        if (where < 0)
552
0
            where = 0;
553
0
    }
554
129
    if (where > n)
555
0
        where = n;
556
129
    items = self->ob_item;
557
129
    if (where < n) {
558
117
        list_shift_items_right_lock_held(self, where, n);
559
117
    }
560
129
    FT_ATOMIC_STORE_PTR_RELEASE(items[where], Py_NewRef(v));
561
129
    return 0;
562
129
}
563
564
int
565
PyList_Insert(PyObject *op, Py_ssize_t where, PyObject *newitem)
566
47
{
567
47
    if (!PyList_Check(op)) {
568
0
        PyErr_BadInternalCall();
569
0
        return -1;
570
0
    }
571
47
    PyListObject *self = (PyListObject *)op;
572
47
    int err;
573
47
    Py_BEGIN_CRITICAL_SECTION(self);
574
47
    err = ins1(self, where, newitem);
575
47
    Py_END_CRITICAL_SECTION();
576
47
    return err;
577
47
}
578
579
/* internal, used by _PyList_AppendTakeRef */
580
int
581
_PyList_AppendTakeRefListResize(PyListObject *self, PyObject *newitem)
582
75.7M
{
583
75.7M
    Py_ssize_t len = Py_SIZE(self);
584
75.7M
    assert(self->allocated == -1 || self->allocated == len);
585
75.7M
    if (list_resize(self, len + 1) < 0) {
586
0
        Py_DECREF(newitem);
587
0
        return -1;
588
0
    }
589
75.7M
    FT_ATOMIC_STORE_PTR_RELEASE(self->ob_item[len], newitem);
590
75.7M
    return 0;
591
75.7M
}
592
593
int
594
PyList_Append(PyObject *op, PyObject *newitem)
595
60.5M
{
596
60.5M
    if (PyList_Check(op) && (newitem != NULL)) {
597
60.5M
        int ret;
598
60.5M
        Py_BEGIN_CRITICAL_SECTION(op);
599
60.5M
        ret = _PyList_AppendTakeRef((PyListObject *)op, Py_NewRef(newitem));
600
60.5M
        Py_END_CRITICAL_SECTION();
601
60.5M
        return ret;
602
60.5M
    }
603
0
    PyErr_BadInternalCall();
604
0
    return -1;
605
60.5M
}
606
607
/* Methods */
608
609
static void
610
list_dealloc(PyObject *self)
611
259M
{
612
259M
    PyListObject *op = (PyListObject *)self;
613
259M
    Py_ssize_t i;
614
259M
    PyObject_GC_UnTrack(op);
615
259M
    if (op->ob_item != NULL) {
616
        /* Do it backwards, for Christian Tismer.
617
           There's a simple test case where somehow this reduces
618
           thrashing when a *very* large list is created and
619
           immediately deleted. */
620
129M
        i = Py_SIZE(op);
621
2.15G
        while (--i >= 0) {
622
2.03G
            Py_XDECREF(op->ob_item[i]);
623
2.03G
        }
624
129M
        free_list_items(op->ob_item, false);
625
129M
        op->ob_item = NULL;
626
129M
    }
627
259M
    if (PyList_CheckExact(op)) {
628
248M
        _Py_FREELIST_FREE(lists, op, PyObject_GC_Del);
629
248M
    }
630
10.4M
    else {
631
10.4M
        PyObject_GC_Del(op);
632
10.4M
    }
633
259M
}
634
635
static PyObject *
636
list_repr_impl(PyListObject *v)
637
3.81M
{
638
3.81M
    int res = Py_ReprEnter((PyObject*)v);
639
3.81M
    if (res != 0) {
640
0
        return (res > 0 ? PyUnicode_FromString("[...]") : NULL);
641
0
    }
642
643
    /* "[" + "1" + ", 2" * (len - 1) + "]" */
644
3.81M
    Py_ssize_t prealloc = 1 + 1 + (2 + 1) * (Py_SIZE(v) - 1) + 1;
645
3.81M
    PyUnicodeWriter *writer = PyUnicodeWriter_Create(prealloc);
646
3.81M
    PyObject *item = NULL;
647
3.81M
    if (writer == NULL) {
648
0
        goto error;
649
0
    }
650
651
3.81M
    if (PyUnicodeWriter_WriteChar(writer, '[') < 0) {
652
0
        goto error;
653
0
    }
654
655
    /* Do repr() on each element.  Note that this may mutate the list,
656
       so must refetch the list size on each iteration. */
657
11.1M
    for (Py_ssize_t i = 0; i < Py_SIZE(v); ++i) {
658
        /* Hold a strong reference since repr(item) can mutate the list */
659
7.36M
        item = Py_XNewRef(v->ob_item[i]);
660
661
7.36M
        if (i > 0) {
662
3.54M
            if (PyUnicodeWriter_WriteChar(writer, ',') < 0) {
663
0
                goto error;
664
0
            }
665
3.54M
            if (PyUnicodeWriter_WriteChar(writer, ' ') < 0) {
666
0
                goto error;
667
0
            }
668
3.54M
        }
669
670
7.36M
        if (PyUnicodeWriter_WriteRepr(writer, item) < 0) {
671
0
            goto error;
672
0
        }
673
7.36M
        Py_CLEAR(item);
674
7.36M
    }
675
676
3.81M
    if (PyUnicodeWriter_WriteChar(writer, ']') < 0) {
677
0
        goto error;
678
0
    }
679
680
3.81M
    Py_ReprLeave((PyObject *)v);
681
3.81M
    return PyUnicodeWriter_Finish(writer);
682
683
0
error:
684
0
    Py_XDECREF(item);
685
0
    PyUnicodeWriter_Discard(writer);
686
0
    Py_ReprLeave((PyObject *)v);
687
0
    return NULL;
688
3.81M
}
689
690
static PyObject *
691
list_repr(PyObject *self)
692
3.88M
{
693
3.88M
    if (PyList_GET_SIZE(self) == 0) {
694
71.4k
        return PyUnicode_FromString("[]");
695
71.4k
    }
696
3.81M
    PyListObject *v = (PyListObject *)self;
697
3.81M
    PyObject *ret = NULL;
698
3.81M
    Py_BEGIN_CRITICAL_SECTION(v);
699
3.81M
    ret = list_repr_impl(v);
700
3.81M
    Py_END_CRITICAL_SECTION();
701
3.81M
    return ret;
702
3.88M
}
703
704
static Py_ssize_t
705
list_length(PyObject *a)
706
40.3M
{
707
40.3M
    return PyList_GET_SIZE(a);
708
40.3M
}
709
710
static int
711
list_contains(PyObject *aa, PyObject *el)
712
7.59k
{
713
714
63.9k
    for (Py_ssize_t i = 0; ; i++) {
715
63.9k
        PyObject *item = list_get_item_ref((PyListObject *)aa, i);
716
63.9k
        if (item == NULL) {
717
            // out-of-bounds
718
5.80k
            return 0;
719
5.80k
        }
720
58.1k
        int cmp = PyObject_RichCompareBool(item, el, Py_EQ);
721
58.1k
        Py_DECREF(item);
722
58.1k
        if (cmp != 0) {
723
1.78k
            return cmp;
724
1.78k
        }
725
58.1k
    }
726
0
    return 0;
727
7.59k
}
728
729
static PyObject *
730
list_item(PyObject *aa, Py_ssize_t i)
731
27.0M
{
732
27.0M
    PyListObject *a = (PyListObject *)aa;
733
27.0M
    if (!valid_index(i, PyList_GET_SIZE(a))) {
734
1.89M
        PyErr_SetObject(PyExc_IndexError, &_Py_STR(list_err));
735
1.89M
        return NULL;
736
1.89M
    }
737
25.1M
    PyObject *item;
738
#ifdef Py_GIL_DISABLED
739
    item = list_get_item_ref(a, i);
740
    if (item == NULL) {
741
        PyErr_SetObject(PyExc_IndexError, &_Py_STR(list_err));
742
        return NULL;
743
    }
744
#else
745
25.1M
    item = Py_NewRef(a->ob_item[i]);
746
25.1M
#endif
747
25.1M
    return item;
748
27.0M
}
749
750
static PyObject *
751
list_slice_lock_held(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
752
2.69M
{
753
2.69M
    PyListObject *np;
754
2.69M
    PyObject **src, **dest;
755
2.69M
    Py_ssize_t i, len;
756
2.69M
    len = ihigh - ilow;
757
2.69M
    if (len <= 0) {
758
1.81k
        return PyList_New(0);
759
1.81k
    }
760
2.68M
    np = (PyListObject *) list_new_prealloc(len);
761
2.68M
    if (np == NULL)
762
0
        return NULL;
763
764
2.68M
    src = a->ob_item + ilow;
765
2.68M
    dest = np->ob_item;
766
24.6M
    for (i = 0; i < len; i++) {
767
21.9M
        PyObject *v = src[i];
768
21.9M
        dest[i] = Py_NewRef(v);
769
21.9M
    }
770
2.68M
    Py_SET_SIZE(np, len);
771
2.68M
    return (PyObject *)np;
772
2.68M
}
773
774
PyObject *
775
_PyList_BinarySlice(PyObject *container, PyObject *start, PyObject *stop)
776
112k
{
777
112k
    assert(PyList_CheckExact(container));
778
112k
    Py_ssize_t istart = 0;
779
112k
    Py_ssize_t istop = PY_SSIZE_T_MAX;
780
    /* Unpack the index values before acquiring the lock, since
781
     * _PyEval_SliceIndex may call __index__ which could execute
782
     * arbitrary Python code. */
783
112k
    if (!_PyEval_SliceIndex(start, &istart)) {
784
0
        return NULL;
785
0
    }
786
112k
    if (!_PyEval_SliceIndex(stop, &istop)) {
787
0
        return NULL;
788
0
    }
789
112k
    PyObject *ret;
790
112k
    Py_BEGIN_CRITICAL_SECTION(container);
791
112k
    Py_ssize_t len = Py_SIZE(container);
792
112k
    PySlice_AdjustIndices(len, &istart, &istop, 1);
793
112k
    ret = list_slice_lock_held((PyListObject *)container, istart, istop);
794
112k
    Py_END_CRITICAL_SECTION();
795
112k
    return ret;
796
112k
}
797
798
PyObject *
799
PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
800
0
{
801
0
    if (!PyList_Check(a)) {
802
0
        PyErr_BadInternalCall();
803
0
        return NULL;
804
0
    }
805
0
    PyObject *ret;
806
0
    Py_BEGIN_CRITICAL_SECTION(a);
807
0
    if (ilow < 0) {
808
0
        ilow = 0;
809
0
    }
810
0
    else if (ilow > Py_SIZE(a)) {
811
0
        ilow = Py_SIZE(a);
812
0
    }
813
0
    if (ihigh < ilow) {
814
0
        ihigh = ilow;
815
0
    }
816
0
    else if (ihigh > Py_SIZE(a)) {
817
0
        ihigh = Py_SIZE(a);
818
0
    }
819
0
    ret = list_slice_lock_held((PyListObject *)a, ilow, ihigh);
820
0
    Py_END_CRITICAL_SECTION();
821
0
    return ret;
822
0
}
823
824
static PyObject *
825
list_concat_lock_held(PyListObject *a, PyListObject *b)
826
20.1M
{
827
20.1M
    Py_ssize_t size;
828
20.1M
    Py_ssize_t i;
829
20.1M
    PyObject **src, **dest;
830
20.1M
    PyListObject *np;
831
20.1M
    assert((size_t)Py_SIZE(a) + (size_t)Py_SIZE(b) < PY_SSIZE_T_MAX);
832
20.1M
    size = Py_SIZE(a) + Py_SIZE(b);
833
20.1M
    if (size == 0) {
834
7.02M
        return PyList_New(0);
835
7.02M
    }
836
13.1M
    np = (PyListObject *) list_new_prealloc(size);
837
13.1M
    if (np == NULL) {
838
0
        return NULL;
839
0
    }
840
13.1M
    src = a->ob_item;
841
13.1M
    dest = np->ob_item;
842
641M
    for (i = 0; i < Py_SIZE(a); i++) {
843
628M
        PyObject *v = src[i];
844
628M
        dest[i] = Py_NewRef(v);
845
628M
    }
846
13.1M
    src = b->ob_item;
847
13.1M
    dest = np->ob_item + Py_SIZE(a);
848
365M
    for (i = 0; i < Py_SIZE(b); i++) {
849
352M
        PyObject *v = src[i];
850
352M
        dest[i] = Py_NewRef(v);
851
352M
    }
852
13.1M
    Py_SET_SIZE(np, size);
853
13.1M
    return (PyObject *)np;
854
13.1M
}
855
856
PyObject *
857
_PyList_Concat(PyObject *aa, PyObject *bb)
858
20.1M
{
859
20.1M
    if (!PyList_Check(bb)) {
860
0
        PyErr_Format(PyExc_TypeError,
861
0
                  "can only concatenate list (not \"%.200s\") to list",
862
0
                  Py_TYPE(bb)->tp_name);
863
0
        return NULL;
864
0
    }
865
20.1M
    PyListObject *a = (PyListObject *)aa;
866
20.1M
    PyListObject *b = (PyListObject *)bb;
867
20.1M
    PyObject *ret;
868
20.1M
    Py_BEGIN_CRITICAL_SECTION2(a, b);
869
20.1M
    ret = list_concat_lock_held(a, b);
870
20.1M
    Py_END_CRITICAL_SECTION2();
871
20.1M
    return ret;
872
20.1M
}
873
874
static PyObject *
875
list_repeat_lock_held(PyListObject *a, Py_ssize_t n)
876
22.8k
{
877
22.8k
    const Py_ssize_t input_size = Py_SIZE(a);
878
22.8k
    if (input_size == 0 || n <= 0)
879
2.73k
        return PyList_New(0);
880
22.8k
    assert(n > 0);
881
882
20.1k
    if (input_size > PY_SSIZE_T_MAX / n)
883
0
        return PyErr_NoMemory();
884
20.1k
    Py_ssize_t output_size = input_size * n;
885
886
20.1k
    PyListObject *np = (PyListObject *) list_new_prealloc(output_size);
887
20.1k
    if (np == NULL)
888
0
        return NULL;
889
890
20.1k
    PyObject **dest = np->ob_item;
891
20.1k
    if (input_size == 1) {
892
20.1k
        PyObject *elem = a->ob_item[0];
893
20.1k
        _Py_RefcntAdd(elem, n);
894
20.1k
        PyObject **dest_end = dest + output_size;
895
5.47M
        while (dest < dest_end) {
896
5.45M
            *dest++ = elem;
897
5.45M
        }
898
20.1k
    }
899
0
    else {
900
0
        PyObject **src = a->ob_item;
901
0
        PyObject **src_end = src + input_size;
902
0
        while (src < src_end) {
903
0
            _Py_RefcntAdd(*src, n);
904
0
            *dest++ = *src++;
905
0
        }
906
        // This list is not yet visible to other threads, so atomic repeat
907
        // is not necessary even in Py_GIL_DISABLED builds.
908
0
        _Py_memory_repeat((char *)np->ob_item, sizeof(PyObject *)*output_size,
909
0
                                        sizeof(PyObject *)*input_size);
910
0
    }
911
912
20.1k
    Py_SET_SIZE(np, output_size);
913
20.1k
    return (PyObject *) np;
914
20.1k
}
915
916
static PyObject *
917
list_repeat(PyObject *aa, Py_ssize_t n)
918
22.8k
{
919
22.8k
    PyObject *ret;
920
22.8k
    PyListObject *a = (PyListObject *)aa;
921
22.8k
    Py_BEGIN_CRITICAL_SECTION(a);
922
22.8k
    ret = list_repeat_lock_held(a, n);
923
22.8k
    Py_END_CRITICAL_SECTION();
924
22.8k
    return ret;
925
22.8k
}
926
927
static void
928
list_clear_impl(PyListObject *a, bool is_resize)
929
8.34M
{
930
8.34M
    PyObject **items = a->ob_item;
931
8.34M
    if (items == NULL) {
932
813k
        return;
933
813k
    }
934
935
    /* Because XDECREF can recursively invoke operations on
936
       this list, we make it empty first. */
937
7.53M
    Py_ssize_t i = Py_SIZE(a);
938
7.53M
    Py_SET_SIZE(a, 0);
939
7.53M
    FT_ATOMIC_STORE_PTR_RELEASE(a->ob_item, NULL);
940
7.53M
    a->allocated = 0;
941
15.1M
    while (--i >= 0) {
942
7.58M
        Py_XDECREF(items[i]);
943
7.58M
    }
944
#ifdef Py_GIL_DISABLED
945
    if (is_resize) {
946
        ensure_shared_on_resize(a);
947
    }
948
    bool use_qsbr = is_resize && _PyObject_GC_IS_SHARED(a);
949
#else
950
7.53M
    bool use_qsbr = false;
951
7.53M
#endif
952
7.53M
    free_list_items(items, use_qsbr);
953
    // Note that there is no guarantee that the list is actually empty
954
    // at this point, because XDECREF may have populated it indirectly again!
955
7.53M
}
956
957
static void
958
list_clear(PyListObject *a)
959
8.34M
{
960
8.34M
    list_clear_impl(a, true);
961
8.34M
}
962
963
static int
964
list_clear_slot(PyObject *self)
965
0
{
966
0
    list_clear_impl((PyListObject *)self, false);
967
0
    return 0;
968
0
}
969
970
// Pointer-by-pointer memmove for PyObject** arrays that is safe
971
// for shared lists in Py_GIL_DISABLED builds.
972
static void
973
ptr_wise_atomic_memmove(PyListObject *a, PyObject **dest, PyObject **src, Py_ssize_t n)
974
5.18M
{
975
5.18M
#ifndef Py_GIL_DISABLED
976
5.18M
    memmove(dest, src, n * sizeof(PyObject *));
977
#else
978
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(a);
979
    if (_Py_IsOwnedByCurrentThread((PyObject *)a) && !_PyObject_GC_IS_SHARED(a)) {
980
        // No other threads can read this list concurrently
981
        memmove(dest, src, n * sizeof(PyObject *));
982
        return;
983
    }
984
    if (dest < src) {
985
        for (Py_ssize_t i = 0; i != n; i++) {
986
            _Py_atomic_store_ptr_release(&dest[i], src[i]);
987
        }
988
    }
989
    else {
990
        // copy backwards to avoid overwriting src before it's read
991
        for (Py_ssize_t i = n; i != 0; i--) {
992
            _Py_atomic_store_ptr_release(&dest[i - 1], src[i - 1]);
993
        }
994
    }
995
#endif
996
5.18M
}
997
998
/* a[ilow:ihigh] = v if v != NULL.
999
 * del a[ilow:ihigh] if v == NULL.
1000
 *
1001
 * Special speed gimmick:  when v is NULL and ihigh - ilow <= 8, it's
1002
 * guaranteed the call cannot fail.
1003
 */
1004
static int
1005
list_ass_slice_lock_held(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
1006
6.61M
{
1007
    /* Because [X]DECREF can recursively invoke list operations on
1008
       this list, we must postpone all [X]DECREF activity until
1009
       after the list is back in its canonical shape.  Therefore
1010
       we must allocate an additional array, 'recycle', into which
1011
       we temporarily copy the items that are deleted from the
1012
       list. :-( */
1013
6.61M
    PyObject *recycle_on_stack[8];
1014
6.61M
    PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
1015
6.61M
    PyObject **item;
1016
6.61M
    PyObject **vitem = NULL;
1017
6.61M
    PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
1018
6.61M
    Py_ssize_t n; /* # of elements in replacement list */
1019
6.61M
    Py_ssize_t norig; /* # of elements in list getting replaced */
1020
6.61M
    Py_ssize_t d; /* Change in size */
1021
6.61M
    Py_ssize_t k;
1022
6.61M
    size_t s;
1023
6.61M
    int result = -1;            /* guilty until proved innocent */
1024
6.61M
#define b ((PyListObject *)v)
1025
6.61M
    if (v == NULL)
1026
3.88M
        n = 0;
1027
2.73M
    else {
1028
2.73M
        v_as_SF = PySequence_Fast(v, "can only assign an iterable");
1029
2.73M
        if(v_as_SF == NULL)
1030
0
            goto Error;
1031
2.73M
        n = PySequence_Fast_GET_SIZE(v_as_SF);
1032
2.73M
        vitem = PySequence_Fast_ITEMS(v_as_SF);
1033
2.73M
    }
1034
6.61M
    if (ilow < 0)
1035
0
        ilow = 0;
1036
6.61M
    else if (ilow > Py_SIZE(a))
1037
513k
        ilow = Py_SIZE(a);
1038
1039
6.61M
    if (ihigh < ilow)
1040
0
        ihigh = ilow;
1041
6.61M
    else if (ihigh > Py_SIZE(a))
1042
513k
        ihigh = Py_SIZE(a);
1043
1044
6.61M
    norig = ihigh - ilow;
1045
6.61M
    assert(norig >= 0);
1046
6.61M
    d = n - norig;
1047
6.61M
    if (Py_SIZE(a) + d == 0) {
1048
1.39M
        Py_XDECREF(v_as_SF);
1049
1.39M
        list_clear(a);
1050
1.39M
        return 0;
1051
1.39M
    }
1052
5.21M
    item = a->ob_item;
1053
    /* recycle the items that we are about to remove */
1054
5.21M
    s = norig * sizeof(PyObject *);
1055
    /* If norig == 0, item might be NULL, in which case we may not memcpy from it. */
1056
5.21M
    if (s) {
1057
4.43M
        if (s > sizeof(recycle_on_stack)) {
1058
22.2k
            recycle = (PyObject **)PyMem_Malloc(s);
1059
22.2k
            if (recycle == NULL) {
1060
0
                PyErr_NoMemory();
1061
0
                goto Error;
1062
0
            }
1063
22.2k
        }
1064
4.43M
        memcpy(recycle, &item[ilow], s);
1065
4.43M
    }
1066
1067
5.21M
    if (d < 0) { /* Delete -d items */
1068
3.31M
        Py_ssize_t tail = Py_SIZE(a) - ihigh;
1069
3.31M
        ptr_wise_atomic_memmove(a, &item[ihigh+d], &item[ihigh], tail);
1070
3.31M
        (void)list_resize(a, Py_SIZE(a) + d); // NB: shrinking a list can't fail
1071
3.31M
        item = a->ob_item;
1072
3.31M
    }
1073
1.90M
    else if (d > 0) { /* Insert d items */
1074
783k
        k = Py_SIZE(a);
1075
783k
        if (list_resize(a, k+d) < 0)
1076
0
            goto Error;
1077
783k
        item = a->ob_item;
1078
783k
        ptr_wise_atomic_memmove(a, &item[ihigh+d], &item[ihigh], k - ihigh);
1079
783k
    }
1080
178M
    for (k = 0; k < n; k++, ilow++) {
1081
173M
        PyObject *w = vitem[k];
1082
173M
        FT_ATOMIC_STORE_PTR_RELEASE(item[ilow], Py_XNewRef(w));
1083
173M
    }
1084
27.9M
    for (k = norig - 1; k >= 0; --k)
1085
22.7M
        Py_XDECREF(recycle[k]);
1086
5.21M
    result = 0;
1087
5.21M
 Error:
1088
5.21M
    if (recycle != recycle_on_stack)
1089
22.2k
        PyMem_Free(recycle);
1090
5.21M
    Py_XDECREF(v_as_SF);
1091
5.21M
    return result;
1092
5.21M
#undef b
1093
5.21M
}
1094
1095
static int
1096
list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
1097
4.38M
{
1098
4.38M
    int ret;
1099
4.38M
    if (a == (PyListObject *)v) {
1100
0
        Py_BEGIN_CRITICAL_SECTION(a);
1101
0
        Py_ssize_t n = PyList_GET_SIZE(a);
1102
0
        PyObject *copy = list_slice_lock_held(a, 0, n);
1103
0
        if (copy == NULL) {
1104
0
            ret = -1;
1105
0
        }
1106
0
        else {
1107
0
            ret = list_ass_slice_lock_held(a, ilow, ihigh, copy);
1108
0
            Py_DECREF(copy);
1109
0
        }
1110
0
        Py_END_CRITICAL_SECTION();
1111
0
    }
1112
4.38M
    else if (v != NULL && PyList_CheckExact(v)) {
1113
285k
        Py_BEGIN_CRITICAL_SECTION2(a, v);
1114
285k
        ret = list_ass_slice_lock_held(a, ilow, ihigh, v);
1115
285k
        Py_END_CRITICAL_SECTION2();
1116
285k
    }
1117
4.09M
    else {
1118
4.09M
        Py_BEGIN_CRITICAL_SECTION(a);
1119
4.09M
        ret = list_ass_slice_lock_held(a, ilow, ihigh, v);
1120
4.09M
        Py_END_CRITICAL_SECTION();
1121
4.09M
    }
1122
4.38M
    return ret;
1123
4.38M
}
1124
1125
int
1126
PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
1127
4.38M
{
1128
4.38M
    if (!PyList_Check(a)) {
1129
0
        PyErr_BadInternalCall();
1130
0
        return -1;
1131
0
    }
1132
4.38M
    return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
1133
4.38M
}
1134
1135
static int
1136
list_inplace_repeat_lock_held(PyListObject *self, Py_ssize_t n)
1137
0
{
1138
0
    Py_ssize_t input_size = PyList_GET_SIZE(self);
1139
0
    if (input_size == 0 || n == 1) {
1140
0
        return 0;
1141
0
    }
1142
1143
0
    if (n < 1) {
1144
0
        list_clear(self);
1145
0
        return 0;
1146
0
    }
1147
1148
0
    if (input_size > PY_SSIZE_T_MAX / n) {
1149
0
        PyErr_NoMemory();
1150
0
        return -1;
1151
0
    }
1152
0
    Py_ssize_t output_size = input_size * n;
1153
1154
0
    if (list_resize(self, output_size) < 0) {
1155
0
        return -1;
1156
0
    }
1157
1158
0
    PyObject **items = self->ob_item;
1159
0
    for (Py_ssize_t j = 0; j < input_size; j++) {
1160
0
        _Py_RefcntAdd(items[j], n-1);
1161
0
    }
1162
0
#ifndef Py_GIL_DISABLED
1163
0
    _Py_memory_repeat((char *)items, sizeof(PyObject *)*output_size,
1164
0
                      sizeof(PyObject *)*input_size);
1165
#else
1166
    Py_ssize_t copied = input_size;
1167
    while (copied < output_size) {
1168
        Py_ssize_t items_to_copy = Py_MIN(copied, output_size - copied);
1169
        ptr_wise_atomic_memmove(self, items + copied, items, items_to_copy);
1170
        copied += items_to_copy;
1171
    }
1172
#endif
1173
0
    return 0;
1174
0
}
1175
1176
static PyObject *
1177
list_inplace_repeat(PyObject *_self, Py_ssize_t n)
1178
0
{
1179
0
    PyObject *ret;
1180
0
    PyListObject *self = (PyListObject *) _self;
1181
0
    Py_BEGIN_CRITICAL_SECTION(self);
1182
0
    if (list_inplace_repeat_lock_held(self, n) < 0) {
1183
0
        ret = NULL;
1184
0
    }
1185
0
    else {
1186
0
        ret = Py_NewRef(self);
1187
0
    }
1188
0
    Py_END_CRITICAL_SECTION();
1189
0
    return ret;
1190
0
}
1191
1192
static int
1193
list_ass_item_lock_held(PyListObject *a, Py_ssize_t i, PyObject *v)
1194
3.94M
{
1195
3.94M
    if (!valid_index(i, Py_SIZE(a))) {
1196
0
        PyErr_SetString(PyExc_IndexError,
1197
0
                        "list assignment index out of range");
1198
0
        return -1;
1199
0
    }
1200
3.94M
    PyObject *tmp = a->ob_item[i];
1201
3.94M
    if (v == NULL) {
1202
12.0k
        Py_ssize_t size = Py_SIZE(a);
1203
12.0k
        if (i < size - 1) {
1204
7.76k
            list_shift_items_left_lock_held(a, i, size - 1);
1205
7.76k
        }
1206
12.0k
        list_resize(a, size - 1);  // NB: shrinking a list can't fail
1207
12.0k
    }
1208
3.93M
    else {
1209
3.93M
        FT_ATOMIC_STORE_PTR_RELEASE(a->ob_item[i], Py_NewRef(v));
1210
3.93M
    }
1211
3.94M
    Py_DECREF(tmp);
1212
3.94M
    return 0;
1213
3.94M
}
1214
1215
static int
1216
list_ass_item(PyObject *aa, Py_ssize_t i, PyObject *v)
1217
3.53k
{
1218
3.53k
    int ret;
1219
3.53k
    PyListObject *a = (PyListObject *)aa;
1220
3.53k
    Py_BEGIN_CRITICAL_SECTION(a);
1221
3.53k
    ret = list_ass_item_lock_held(a, i, v);
1222
3.53k
    Py_END_CRITICAL_SECTION();
1223
3.53k
    return ret;
1224
3.53k
}
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
82
{
1241
82
    if (ins1(self, index, object) == 0) {
1242
82
        Py_RETURN_NONE;
1243
82
    }
1244
0
    return NULL;
1245
82
}
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
6.41k
{
1258
6.41k
    list_clear(self);
1259
6.41k
    Py_RETURN_NONE;
1260
6.41k
}
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
97.8M
{
1290
97.8M
    if (_PyList_AppendTakeRef(self, Py_NewRef(object)) < 0) {
1291
0
        return NULL;
1292
0
    }
1293
97.8M
    Py_RETURN_NONE;
1294
97.8M
}
1295
1296
static int
1297
list_extend_fast(PyListObject *self, PyObject *iterable)
1298
15.0M
{
1299
15.0M
    Py_ssize_t n = PySequence_Fast_GET_SIZE(iterable);
1300
15.0M
    if (n == 0) {
1301
        /* short circuit when iterable is empty */
1302
8.42M
        return 0;
1303
8.42M
    }
1304
1305
6.65M
    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.65M
    assert(m < PY_SSIZE_T_MAX - n);
1309
6.65M
    if (self->ob_item == NULL) {
1310
1.35M
        if (list_preallocate_exact(self, n) < 0) {
1311
0
            return -1;
1312
0
        }
1313
1.35M
        Py_SET_SIZE(self, n);
1314
1.35M
    }
1315
5.29M
    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.65M
    PyObject **src = PySequence_Fast_ITEMS(iterable);
1326
6.65M
    PyObject **dest = self->ob_item + m;
1327
38.1M
    for (Py_ssize_t i = 0; i < n; i++) {
1328
31.4M
        PyObject *o = src[i];
1329
31.4M
        FT_ATOMIC_STORE_PTR_RELEASE(dest[i], Py_NewRef(o));
1330
31.4M
    }
1331
6.65M
    return 0;
1332
6.65M
}
1333
1334
static int
1335
list_extend_iter_lock_held(PyListObject *self, PyObject *iterable)
1336
6.31M
{
1337
6.31M
    PyObject *it = PyObject_GetIter(iterable);
1338
6.31M
    if (it == NULL) {
1339
0
        return -1;
1340
0
    }
1341
6.31M
    PyObject *(*iternext)(PyObject *) = *Py_TYPE(it)->tp_iternext;
1342
1343
    /* Guess a result list size. */
1344
6.31M
    Py_ssize_t n = PyObject_LengthHint(iterable, 8);
1345
6.31M
    if (n < 0) {
1346
0
        Py_DECREF(it);
1347
0
        return -1;
1348
0
    }
1349
1350
6.31M
    Py_ssize_t m = Py_SIZE(self);
1351
6.31M
    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
6.31M
    else if (self->ob_item == NULL) {
1358
6.01M
        if (n && list_preallocate_exact(self, n) < 0)
1359
0
            goto error;
1360
6.01M
    }
1361
293k
    else {
1362
        /* Make room. */
1363
293k
        if (list_resize(self, m + n) < 0) {
1364
0
            goto error;
1365
0
        }
1366
1367
        /* Make the list sane again. */
1368
293k
        Py_SET_SIZE(self, m);
1369
293k
    }
1370
1371
    /* Run iterator to exhaustion. */
1372
175M
    for (;;) {
1373
175M
        PyObject *item = iternext(it);
1374
175M
        if (item == NULL) {
1375
6.31M
            if (PyErr_Occurred()) {
1376
644
                if (PyErr_ExceptionMatches(PyExc_StopIteration))
1377
0
                    PyErr_Clear();
1378
644
                else
1379
644
                    goto error;
1380
644
            }
1381
6.31M
            break;
1382
6.31M
        }
1383
1384
169M
        if (Py_SIZE(self) < self->allocated) {
1385
168M
            Py_ssize_t len = Py_SIZE(self);
1386
168M
            FT_ATOMIC_STORE_PTR_RELEASE(self->ob_item[len], item);  // steals item ref
1387
168M
            Py_SET_SIZE(self, len + 1);
1388
168M
        }
1389
746k
        else {
1390
746k
            if (_PyList_AppendTakeRef(self, item) < 0)
1391
0
                goto error;
1392
746k
        }
1393
169M
    }
1394
1395
    /* Cut back result list if initial guess was too large. */
1396
6.31M
    if (Py_SIZE(self) < self->allocated) {
1397
3.84M
        if (list_resize(self, Py_SIZE(self)) < 0)
1398
0
            goto error;
1399
3.84M
    }
1400
1401
6.31M
    Py_DECREF(it);
1402
6.31M
    return 0;
1403
1404
644
  error:
1405
644
    Py_DECREF(it);
1406
644
    return -1;
1407
6.31M
}
1408
1409
static int
1410
list_extend_lock_held(PyListObject *self, PyObject *iterable)
1411
15.0M
{
1412
15.0M
    PyObject *seq = PySequence_Fast(iterable, "argument must be iterable");
1413
15.0M
    if (!seq) {
1414
0
        return -1;
1415
0
    }
1416
1417
15.0M
    int res = list_extend_fast(self, seq);
1418
15.0M
    Py_DECREF(seq);
1419
15.0M
    return res;
1420
15.0M
}
1421
1422
static int
1423
list_extend_set(PyListObject *self, PySetObject *other)
1424
1.19M
{
1425
1.19M
    Py_ssize_t m = Py_SIZE(self);
1426
1.19M
    Py_ssize_t n = PySet_GET_SIZE(other);
1427
1.19M
    Py_ssize_t r = m + n;
1428
1.19M
    if (r == 0) {
1429
4.59k
        return 0;
1430
4.59k
    }
1431
1.19M
    if (list_resize(self, r) < 0) {
1432
0
        return -1;
1433
0
    }
1434
1435
1.19M
    assert(self->ob_item != NULL);
1436
    /* populate the end of self with iterable's items */
1437
1.19M
    Py_ssize_t setpos = 0;
1438
1.19M
    Py_hash_t hash;
1439
1.19M
    PyObject *key;
1440
1.19M
    PyObject **dest = self->ob_item + m;
1441
4.10M
    while (_PySet_NextEntryRef((PyObject *)other, &setpos, &key, &hash)) {
1442
2.91M
        FT_ATOMIC_STORE_PTR_RELEASE(*dest, key);
1443
2.91M
        dest++;
1444
2.91M
    }
1445
1.19M
    Py_SET_SIZE(self, r);
1446
1.19M
    return 0;
1447
1.19M
}
1448
1449
static int
1450
list_extend_dict(PyListObject *self, PyDictObject *dict, int which_item)
1451
4.16M
{
1452
    // which_item: 0 for keys and 1 for values
1453
4.16M
    Py_ssize_t m = Py_SIZE(self);
1454
4.16M
    Py_ssize_t n = PyDict_GET_SIZE(dict);
1455
4.16M
    Py_ssize_t r = m + n;
1456
4.16M
    if (r == 0) {
1457
0
        return 0;
1458
0
    }
1459
4.16M
    if (list_resize(self, r) < 0) {
1460
0
        return -1;
1461
0
    }
1462
1463
4.16M
    assert(self->ob_item != NULL);
1464
4.16M
    PyObject **dest = self->ob_item + m;
1465
4.16M
    Py_ssize_t pos = 0;
1466
4.16M
    PyObject *keyvalue[2];
1467
10.5M
    while (_PyDict_Next((PyObject *)dict, &pos, &keyvalue[0], &keyvalue[1], NULL)) {
1468
6.40M
        PyObject *obj = keyvalue[which_item];
1469
6.40M
        Py_INCREF(obj);
1470
6.40M
        FT_ATOMIC_STORE_PTR_RELEASE(*dest, obj);
1471
6.40M
        dest++;
1472
6.40M
    }
1473
1474
4.16M
    Py_SET_SIZE(self, r);
1475
4.16M
    return 0;
1476
4.16M
}
1477
1478
static int
1479
list_extend_dictitems(PyListObject *self, PyDictObject *dict)
1480
5
{
1481
5
    Py_ssize_t m = Py_SIZE(self);
1482
5
    Py_ssize_t n = PyDict_GET_SIZE(dict);
1483
5
    Py_ssize_t r = m + n;
1484
5
    if (r == 0) {
1485
0
        return 0;
1486
0
    }
1487
5
    if (list_resize(self, r) < 0) {
1488
0
        return -1;
1489
0
    }
1490
1491
5
    assert(self->ob_item != NULL);
1492
5
    PyObject **dest = self->ob_item + m;
1493
5
    Py_ssize_t pos = 0;
1494
5
    Py_ssize_t i = 0;
1495
5
    PyObject *key, *value;
1496
211
    while (_PyDict_Next((PyObject *)dict, &pos, &key, &value, NULL)) {
1497
206
        PyObject *item = _PyTuple_FromPair(key, value);
1498
206
        if (item == NULL) {
1499
0
            Py_SET_SIZE(self, m + i);
1500
0
            return -1;
1501
0
        }
1502
206
        FT_ATOMIC_STORE_PTR_RELEASE(*dest, item);
1503
206
        dest++;
1504
206
        i++;
1505
206
    }
1506
1507
5
    Py_SET_SIZE(self, r);
1508
5
    return 0;
1509
5
}
1510
1511
static int
1512
_list_extend(PyListObject *self, PyObject *iterable)
1513
26.7M
{
1514
    // Special case:
1515
    // lists and tuples which can use PySequence_Fast ops
1516
26.7M
    int res = -1;
1517
26.7M
    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.7M
    else if (PyList_CheckExact(iterable)) {
1523
9.82M
        Py_BEGIN_CRITICAL_SECTION2(self, iterable);
1524
9.82M
        res = list_extend_lock_held(self, iterable);
1525
9.82M
        Py_END_CRITICAL_SECTION2();
1526
9.82M
    }
1527
16.9M
    else if (PyTuple_CheckExact(iterable)) {
1528
5.24M
        Py_BEGIN_CRITICAL_SECTION(self);
1529
5.24M
        res = list_extend_lock_held(self, iterable);
1530
5.24M
        Py_END_CRITICAL_SECTION();
1531
5.24M
    }
1532
11.6M
    else if (PyAnySet_CheckExact(iterable)) {
1533
1.19M
        Py_BEGIN_CRITICAL_SECTION2(self, iterable);
1534
1.19M
        res = list_extend_set(self, (PySetObject *)iterable);
1535
1.19M
        Py_END_CRITICAL_SECTION2();
1536
1.19M
    }
1537
10.4M
    else if (PyDict_CheckExact(iterable)) {
1538
4.16M
        Py_BEGIN_CRITICAL_SECTION2(self, iterable);
1539
4.16M
        res = list_extend_dict(self, (PyDictObject *)iterable, 0 /*keys*/);
1540
4.16M
        Py_END_CRITICAL_SECTION2();
1541
4.16M
    }
1542
6.31M
    else if (Py_IS_TYPE(iterable, &PyDictKeys_Type)) {
1543
556
        PyDictObject *dict = ((_PyDictViewObject *)iterable)->dv_dict;
1544
556
        Py_BEGIN_CRITICAL_SECTION2(self, dict);
1545
556
        res = list_extend_dict(self, dict, 0 /*keys*/);
1546
556
        Py_END_CRITICAL_SECTION2();
1547
556
    }
1548
6.31M
    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
6.31M
    else if (Py_IS_TYPE(iterable, &PyDictItems_Type)) {
1555
5
        PyDictObject *dict = ((_PyDictViewObject *)iterable)->dv_dict;
1556
5
        Py_BEGIN_CRITICAL_SECTION2(self, dict);
1557
5
        res = list_extend_dictitems(self, dict);
1558
5
        Py_END_CRITICAL_SECTION2();
1559
5
    }
1560
6.31M
    else {
1561
6.31M
        Py_BEGIN_CRITICAL_SECTION(self);
1562
6.31M
        res = list_extend_iter_lock_held(self, iterable);
1563
6.31M
        Py_END_CRITICAL_SECTION();
1564
6.31M
    }
1565
26.7M
    return res;
1566
26.7M
}
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
16.3M
{
1581
16.3M
    if (_list_extend(self, iterable) < 0) {
1582
644
        return NULL;
1583
644
    }
1584
16.3M
    Py_RETURN_NONE;
1585
16.3M
}
1586
1587
PyObject *
1588
_PyList_Extend(PyListObject *self, PyObject *iterable)
1589
15.0M
{
1590
15.0M
    return list_extend((PyObject*)self, iterable);
1591
15.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
135k
{
1621
135k
    PyListObject *self = (PyListObject *)_self;
1622
135k
    if (_list_extend(self, other) < 0) {
1623
0
        return NULL;
1624
0
    }
1625
135k
    return Py_NewRef(self);
1626
135k
}
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
19.2M
{
1644
19.2M
    PyObject *v;
1645
1646
19.2M
    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
19.2M
    if (index < 0)
1652
18.1M
        index += Py_SIZE(self);
1653
19.2M
    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
19.2M
    PyObject **items = self->ob_item;
1659
19.2M
    v = items[index];
1660
19.2M
    if (Py_SIZE(self) == 1) {
1661
6.93M
        Py_INCREF(v);
1662
6.93M
        list_clear(self);
1663
6.93M
        return v;
1664
6.93M
    }
1665
12.2M
    Py_ssize_t size_after_pop = Py_SIZE(self) - 1;
1666
12.2M
    if (index < size_after_pop) {
1667
1.09M
        ptr_wise_atomic_memmove(self, &items[index], &items[index+1],
1668
1.09M
                                size_after_pop - index);
1669
1.09M
    }
1670
12.2M
    list_resize(self, size_after_pop);  // NB: shrinking a list can't fail
1671
12.2M
    return v;
1672
19.2M
}
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
249k
{
1678
249k
    assert(lo && hi);
1679
1680
249k
    --hi;
1681
4.07M
    while (lo < hi) {
1682
3.82M
        PyObject *t = *lo;
1683
3.82M
        FT_ATOMIC_STORE_PTR_RELEASE(*lo, *hi);
1684
3.82M
        FT_ATOMIC_STORE_PTR_RELEASE(*hi, t);
1685
3.82M
        ++lo;
1686
3.82M
        --hi;
1687
3.82M
    }
1688
249k
}
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
35.4k
{
1711
35.4k
    s1->keys[i] = s2->keys[j];
1712
35.4k
    if (s1->values != NULL)
1713
28.9k
        s1->values[i] = s2->values[j];
1714
35.4k
}
1715
1716
Py_LOCAL_INLINE(void)
1717
sortslice_copy_incr(sortslice *dst, sortslice *src)
1718
1.17M
{
1719
1.17M
    *dst->keys++ = *src->keys++;
1720
1.17M
    if (dst->values != NULL)
1721
595k
        *dst->values++ = *src->values++;
1722
1.17M
}
1723
1724
Py_LOCAL_INLINE(void)
1725
sortslice_copy_decr(sortslice *dst, sortslice *src)
1726
2.76M
{
1727
2.76M
    *dst->keys-- = *src->keys--;
1728
2.76M
    if (dst->values != NULL)
1729
511k
        *dst->values-- = *src->values--;
1730
2.76M
}
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
177k
{
1737
177k
    memcpy(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
1738
177k
    if (s1->values != NULL)
1739
156k
        memcpy(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
1740
177k
}
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
107k
        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.21M
{
1754
1.21M
    slice->keys += n;
1755
1.21M
    if (slice->values != NULL)
1756
594k
        slice->values += n;
1757
1.21M
}
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
23.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
20.2M
#define IFLT(X, Y) if ((k = ISLT(X, Y)) < 0) goto fail;  \
1771
20.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
4.84M
#define MIN_GALLOP 7
1784
1785
/* Avoid malloc for small temp arrays. */
1786
5.90M
#define MERGESTATE_TEMP_SIZE 256
1787
1788
/* The largest value of minrun. This must be a power of 2, and >= 1 */
1789
4.63M
#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
369k
{
1870
369k
    Py_ssize_t k; /* for IFLT macro expansion */
1871
369k
    PyObject ** const a = ss->keys;
1872
369k
    PyObject ** const v = ss->values;
1873
369k
    const bool has_values = v != NULL;
1874
369k
    PyObject *pivot;
1875
369k
    Py_ssize_t M;
1876
1877
369k
    assert(0 <= ok && ok <= n && 1 <= n && n <= MAX_MINRUN);
1878
    /* assert a[:ok] is sorted */
1879
369k
    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
369k
    Py_ssize_t L, R;
1932
3.58M
    for (; ok < n; ++ok) {
1933
        /* set L to where a[ok] belongs */
1934
3.21M
        L = 0;
1935
3.21M
        R = ok;
1936
3.21M
        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.21M
        assert(L < R);
1943
12.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
12.0M
            M = (L + R) >> 1;
1947
12.0M
#if 1 // straightforward, but highly unpredictable branch on random data
1948
12.0M
            IFLT(pivot, a[M])
1949
5.33M
                R = M;
1950
6.67M
            else
1951
6.67M
                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
12.0M
        } while (L < R);
1966
3.21M
        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
20.9M
        for (M = ok; M > L; --M)
1973
17.7M
            a[M] = a[M - 1];
1974
3.21M
        a[L] = pivot;
1975
3.21M
        if (has_values) {
1976
1.50M
            pivot = v[ok];
1977
8.17M
            for (M = ok; M > L; --M)
1978
6.66M
                v[M] = v[M - 1];
1979
1.50M
            v[L] = pivot;
1980
1.50M
        }
1981
3.21M
    }
1982
369k
#endif // pick binary or regular insertion sort
1983
369k
    return 0;
1984
1985
0
 fail:
1986
0
    return -1;
1987
369k
}
1988
1989
static void
1990
sortslice_reverse(sortslice *s, Py_ssize_t n)
1991
205k
{
1992
205k
    reverse_slice(s->keys, &s->keys[n]);
1993
205k
    if (s->values != NULL)
1994
44.1k
        reverse_slice(s->values, &s->values[n]);
1995
205k
}
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
720k
{
2008
720k
    Py_ssize_t k; /* used by IFLT macro expansion */
2009
720k
    Py_ssize_t n;
2010
720k
    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
720k
#define REVERSE_LAST_NEQ                        \
2019
2.47M
    if (neq) {                                  \
2020
9.64k
        sortslice slice = *slo;                 \
2021
9.64k
        ++neq;                                  \
2022
9.64k
        sortslice_advance(&slice, n - neq);     \
2023
9.64k
        sortslice_reverse(&slice, neq);         \
2024
9.64k
        neq = 0;                                \
2025
9.64k
    }
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
720k
#define IF_NEXT_LARGER  IFLT(lo[n-1], lo[n])
2033
5.87M
#define IF_NEXT_SMALLER IFLT(lo[n], lo[n-1])
2034
2035
720k
    assert(nremaining);
2036
    /* try ascending run first */
2037
3.25M
    for (n = 1; n < nremaining; ++n) {
2038
2.94M
        IF_NEXT_SMALLER
2039
411k
            break;
2040
2.94M
    }
2041
720k
    if (n == nremaining)
2042
309k
        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
411k
    if (n > 1) {
2054
225k
        IFLT(lo[0], lo[n-1])
2055
220k
            return n;
2056
4.81k
        sortslice_reverse(slo, n);
2057
4.81k
    }
2058
190k
    ++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
190k
    Py_ssize_t neq = 0;
2065
2.51M
    for ( ; n < nremaining; ++n) {
2066
2.48M
        IF_NEXT_SMALLER {
2067
            /* This ends the most recent run of equal elements, but still in
2068
             * the "descending" direction.
2069
             */
2070
2.28M
            REVERSE_LAST_NEQ
2071
2.28M
        }
2072
193k
        else {
2073
193k
            IF_NEXT_LARGER /* descending run is over */
2074
162k
                break;
2075
30.9k
            else /* not x < y and not y < x implies x == y */
2076
30.9k
                ++neq;
2077
193k
        }
2078
2.48M
    }
2079
190k
    REVERSE_LAST_NEQ
2080
190k
    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
479k
    for ( ; n < nremaining; ++n) {
2087
449k
        IF_NEXT_SMALLER
2088
160k
            break;
2089
449k
    }
2090
2091
190k
    return n;
2092
0
fail:
2093
0
    return -1;
2094
2095
190k
#undef REVERSE_LAST_NEQ
2096
190k
#undef IF_NEXT_SMALLER
2097
190k
#undef IF_NEXT_LARGER
2098
190k
}
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
180k
{
2124
180k
    Py_ssize_t ofs;
2125
180k
    Py_ssize_t lastofs;
2126
180k
    Py_ssize_t k;
2127
2128
180k
    assert(key && a && n > 0 && hint >= 0 && hint < n);
2129
2130
180k
    a += hint;
2131
180k
    lastofs = 0;
2132
180k
    ofs = 1;
2133
180k
    IFLT(*a, key) {
2134
        /* a[hint] < key -- gallop right, until
2135
         * a[hint + lastofs] < key <= a[hint + ofs]
2136
         */
2137
92.7k
        const Py_ssize_t maxofs = n - hint;             /* &a[n-1] is highest */
2138
275k
        while (ofs < maxofs) {
2139
212k
            IFLT(a[ofs], key) {
2140
182k
                lastofs = ofs;
2141
182k
                assert(ofs <= (PY_SSIZE_T_MAX - 1) / 2);
2142
182k
                ofs = (ofs << 1) + 1;
2143
182k
            }
2144
29.2k
            else                /* key <= a[hint + ofs] */
2145
29.2k
                break;
2146
212k
        }
2147
92.7k
        if (ofs > maxofs)
2148
24.2k
            ofs = maxofs;
2149
        /* Translate back to offsets relative to &a[0]. */
2150
92.7k
        lastofs += hint;
2151
92.7k
        ofs += hint;
2152
92.7k
    }
2153
87.3k
    else {
2154
        /* key <= a[hint] -- gallop left, until
2155
         * a[hint - ofs] < key <= a[hint - lastofs]
2156
         */
2157
87.3k
        const Py_ssize_t maxofs = hint + 1;             /* &a[0] is lowest */
2158
267k
        while (ofs < maxofs) {
2159
236k
            IFLT(*(a-ofs), key)
2160
56.6k
                break;
2161
            /* key <= a[hint - ofs] */
2162
179k
            lastofs = ofs;
2163
179k
            assert(ofs <= (PY_SSIZE_T_MAX - 1) / 2);
2164
179k
            ofs = (ofs << 1) + 1;
2165
179k
        }
2166
87.3k
        if (ofs > maxofs)
2167
16.5k
            ofs = maxofs;
2168
        /* Translate back to positive offsets relative to &a[0]. */
2169
87.3k
        k = lastofs;
2170
87.3k
        lastofs = hint - ofs;
2171
87.3k
        ofs = hint - k;
2172
87.3k
    }
2173
180k
    a -= hint;
2174
2175
180k
    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
180k
    ++lastofs;
2181
495k
    while (lastofs < ofs) {
2182
315k
        Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
2183
2184
315k
        IFLT(a[m], key)
2185
160k
            lastofs = m+1;              /* a[m] < key */
2186
154k
        else
2187
154k
            ofs = m;                    /* key <= a[m] */
2188
315k
    }
2189
180k
    assert(lastofs == ofs);             /* so a[ofs-1] < key <= a[ofs] */
2190
180k
    return ofs;
2191
2192
0
fail:
2193
0
    return -1;
2194
180k
}
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
199k
{
2213
199k
    Py_ssize_t ofs;
2214
199k
    Py_ssize_t lastofs;
2215
199k
    Py_ssize_t k;
2216
2217
199k
    assert(key && a && n > 0 && hint >= 0 && hint < n);
2218
2219
199k
    a += hint;
2220
199k
    lastofs = 0;
2221
199k
    ofs = 1;
2222
199k
    IFLT(key, *a) {
2223
        /* key < a[hint] -- gallop left, until
2224
         * a[hint - ofs] <= key < a[hint - lastofs]
2225
         */
2226
77.1k
        const Py_ssize_t maxofs = hint + 1;             /* &a[0] is lowest */
2227
187k
        while (ofs < maxofs) {
2228
132k
            IFLT(key, *(a-ofs)) {
2229
110k
                lastofs = ofs;
2230
110k
                assert(ofs <= (PY_SSIZE_T_MAX - 1) / 2);
2231
110k
                ofs = (ofs << 1) + 1;
2232
110k
            }
2233
21.7k
            else                /* a[hint - ofs] <= key */
2234
21.7k
                break;
2235
132k
        }
2236
77.1k
        if (ofs > maxofs)
2237
10.7k
            ofs = maxofs;
2238
        /* Translate back to positive offsets relative to &a[0]. */
2239
77.1k
        k = lastofs;
2240
77.1k
        lastofs = hint - ofs;
2241
77.1k
        ofs = hint - k;
2242
77.1k
    }
2243
122k
    else {
2244
        /* a[hint] <= key -- gallop right, until
2245
         * a[hint + lastofs] <= key < a[hint + ofs]
2246
        */
2247
122k
        const Py_ssize_t maxofs = n - hint;             /* &a[n-1] is highest */
2248
388k
        while (ofs < maxofs) {
2249
340k
            IFLT(key, a[ofs])
2250
73.4k
                break;
2251
            /* a[hint + ofs] <= key */
2252
266k
            lastofs = ofs;
2253
266k
            assert(ofs <= (PY_SSIZE_T_MAX - 1) / 2);
2254
266k
            ofs = (ofs << 1) + 1;
2255
266k
        }
2256
122k
        if (ofs > maxofs)
2257
25.7k
            ofs = maxofs;
2258
        /* Translate back to offsets relative to &a[0]. */
2259
122k
        lastofs += hint;
2260
122k
        ofs += hint;
2261
122k
    }
2262
199k
    a -= hint;
2263
2264
199k
    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
199k
    ++lastofs;
2270
528k
    while (lastofs < ofs) {
2271
329k
        Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
2272
2273
329k
        IFLT(key, a[m])
2274
169k
            ofs = m;                    /* key < a[m] */
2275
159k
        else
2276
159k
            lastofs = m+1;              /* a[m] <= key */
2277
329k
    }
2278
199k
    assert(lastofs == ofs);             /* so a[ofs-1] <= key < a[ofs] */
2279
199k
    return ofs;
2280
2281
0
fail:
2282
0
    return -1;
2283
199k
}
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
4.60M
{
2290
4.60M
    assert(ms != NULL);
2291
4.60M
    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
649k
        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
649k
        if (MERGESTATE_TEMP_SIZE / 2 < ms->alloced)
2303
2.33k
            ms->alloced = MERGESTATE_TEMP_SIZE / 2;
2304
649k
        ms->a.values = &ms->temparray[ms->alloced];
2305
649k
    }
2306
3.95M
    else {
2307
3.95M
        ms->alloced = MERGESTATE_TEMP_SIZE;
2308
3.95M
        ms->a.values = NULL;
2309
3.95M
    }
2310
4.60M
    ms->a.keys = ms->temparray;
2311
4.60M
    ms->n = 0;
2312
4.60M
    ms->min_gallop = MIN_GALLOP;
2313
4.60M
    ms->listlen = list_size;
2314
4.60M
    ms->basekeys = lo->keys;
2315
2316
    /* State for generating minrun values. See listsort.txt. */
2317
4.60M
    ms->mr_e = 0;
2318
4.63M
    while (list_size >> ms->mr_e >= MAX_MINRUN) {
2319
29.4k
        ++ms->mr_e;
2320
29.4k
    }
2321
4.60M
    ms->mr_mask = ((Py_ssize_t)1 << ms->mr_e) - 1;
2322
4.60M
    ms->mr_current = 0;
2323
4.60M
}
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
4.60M
{
2332
4.60M
    assert(ms != NULL);
2333
4.60M
    if (ms->a.keys != ms->temparray) {
2334
4.25k
        PyMem_Free(ms->a.keys);
2335
4.25k
        ms->a.keys = NULL;
2336
4.25k
    }
2337
4.60M
}
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.25k
{
2345
4.25k
    int multiplier;
2346
2347
4.25k
    assert(ms != NULL);
2348
4.25k
    if (need <= ms->alloced)
2349
0
        return 0;
2350
2351
4.25k
    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.25k
    merge_freemem(ms);
2357
4.25k
    if ((size_t)need > PY_SSIZE_T_MAX / sizeof(PyObject *) / multiplier) {
2358
0
        PyErr_NoMemory();
2359
0
        return -1;
2360
0
    }
2361
4.25k
    ms->a.keys = (PyObject **)PyMem_Malloc(multiplier * need
2362
4.25k
                                          * sizeof(PyObject *));
2363
4.25k
    if (ms->a.keys != NULL) {
2364
4.25k
        ms->alloced = need;
2365
4.25k
        if (ms->a.values != NULL)
2366
4.17k
            ms->a.values = &ms->a.keys[need];
2367
4.25k
        return 0;
2368
4.25k
    }
2369
0
    PyErr_NoMemory();
2370
0
    return -1;
2371
4.25k
}
2372
63.7k
#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 :   \
2373
63.7k
                                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
42.0k
{
2385
42.0k
    Py_ssize_t k;
2386
42.0k
    sortslice dest;
2387
42.0k
    int result = -1;            /* guilty until proved innocent */
2388
42.0k
    Py_ssize_t min_gallop;
2389
2390
42.0k
    assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
2391
42.0k
    assert(ssa.keys + na == ssb.keys);
2392
42.0k
    if (MERGE_GETMEM(ms, na) < 0)
2393
0
        return -1;
2394
42.0k
    sortslice_memcpy(&ms->a, 0, &ssa, 0, na);
2395
42.0k
    dest = ssa;
2396
42.0k
    ssa = ms->a;
2397
2398
42.0k
    sortslice_copy_incr(&dest, &ssb);
2399
42.0k
    --nb;
2400
42.0k
    if (nb == 0)
2401
2.04k
        goto Succeed;
2402
40.0k
    if (na == 1)
2403
5.80k
        goto CopyB;
2404
2405
34.2k
    min_gallop = ms->min_gallop;
2406
61.9k
    for (;;) {
2407
61.9k
        Py_ssize_t acount = 0;          /* # of times A won in a row */
2408
61.9k
        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
997k
        for (;;) {
2414
997k
            assert(na > 1 && nb > 0);
2415
997k
            k = ISLT(ssb.keys[0], ssa.keys[0]);
2416
997k
            if (k) {
2417
508k
                if (k < 0)
2418
0
                    goto Fail;
2419
508k
                sortslice_copy_incr(&dest, &ssb);
2420
508k
                ++bcount;
2421
508k
                acount = 0;
2422
508k
                --nb;
2423
508k
                if (nb == 0)
2424
2.95k
                    goto Succeed;
2425
505k
                if (bcount >= min_gallop)
2426
25.2k
                    break;
2427
505k
            }
2428
489k
            else {
2429
489k
                sortslice_copy_incr(&dest, &ssa);
2430
489k
                ++acount;
2431
489k
                bcount = 0;
2432
489k
                --na;
2433
489k
                if (na == 1)
2434
8.32k
                    goto CopyB;
2435
481k
                if (acount >= min_gallop)
2436
25.3k
                    break;
2437
481k
            }
2438
997k
        }
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
50.6k
        ++min_gallop;
2446
80.4k
        do {
2447
80.4k
            assert(na > 1 && nb > 0);
2448
80.4k
            min_gallop -= min_gallop > 1;
2449
80.4k
            ms->min_gallop = min_gallop;
2450
80.4k
            k = gallop_right(ms, ssb.keys[0], ssa.keys, na, 0);
2451
80.4k
            acount = k;
2452
80.4k
            if (k) {
2453
48.5k
                if (k < 0)
2454
0
                    goto Fail;
2455
48.5k
                sortslice_memcpy(&dest, 0, &ssa, 0, k);
2456
48.5k
                sortslice_advance(&dest, k);
2457
48.5k
                sortslice_advance(&ssa, k);
2458
48.5k
                na -= k;
2459
48.5k
                if (na == 1)
2460
6.78k
                    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
41.8k
                if (na == 0)
2466
0
                    goto Succeed;
2467
41.8k
            }
2468
73.6k
            sortslice_copy_incr(&dest, &ssb);
2469
73.6k
            --nb;
2470
73.6k
            if (nb == 0)
2471
2.06k
                goto Succeed;
2472
2473
71.5k
            k = gallop_left(ms, ssa.keys[0], ssb.keys, nb, 0);
2474
71.5k
            bcount = k;
2475
71.5k
            if (k) {
2476
58.1k
                if (k < 0)
2477
0
                    goto Fail;
2478
58.1k
                sortslice_memmove(&dest, 0, &ssb, 0, k);
2479
58.1k
                sortslice_advance(&dest, k);
2480
58.1k
                sortslice_advance(&ssb, k);
2481
58.1k
                nb -= k;
2482
58.1k
                if (nb == 0)
2483
10.4k
                    goto Succeed;
2484
58.1k
            }
2485
61.1k
            sortslice_copy_incr(&dest, &ssa);
2486
61.1k
            --na;
2487
61.1k
            if (na == 1)
2488
3.67k
                goto CopyB;
2489
61.1k
        } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
2490
27.6k
        ++min_gallop;           /* penalize it for leaving galloping mode */
2491
27.6k
        ms->min_gallop = min_gallop;
2492
27.6k
    }
2493
17.4k
Succeed:
2494
17.4k
    result = 0;
2495
17.4k
Fail:
2496
17.4k
    if (na)
2497
17.4k
        sortslice_memcpy(&dest, 0, &ssa, 0, na);
2498
17.4k
    return result;
2499
24.5k
CopyB:
2500
24.5k
    assert(na == 1 && nb > 0);
2501
    /* The last element of ssa belongs at the end of the merge. */
2502
24.5k
    sortslice_memmove(&dest, 0, &ssb, 0, nb);
2503
24.5k
    sortslice_copy(&dest, nb, &ssa, 0);
2504
24.5k
    return 0;
2505
17.4k
}
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
21.6k
{
2517
21.6k
    Py_ssize_t k;
2518
21.6k
    sortslice dest, basea, baseb;
2519
21.6k
    int result = -1;            /* guilty until proved innocent */
2520
21.6k
    Py_ssize_t min_gallop;
2521
2522
21.6k
    assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
2523
21.6k
    assert(ssa.keys + na == ssb.keys);
2524
21.6k
    if (MERGE_GETMEM(ms, nb) < 0)
2525
0
        return -1;
2526
21.6k
    dest = ssb;
2527
21.6k
    sortslice_advance(&dest, nb-1);
2528
21.6k
    sortslice_memcpy(&ms->a, 0, &ssb, 0, nb);
2529
21.6k
    basea = ssa;
2530
21.6k
    baseb = ms->a;
2531
21.6k
    ssb.keys = ms->a.keys + nb - 1;
2532
21.6k
    if (ssb.values != NULL)
2533
20.7k
        ssb.values = ms->a.values + nb - 1;
2534
21.6k
    sortslice_advance(&ssa, na - 1);
2535
2536
21.6k
    sortslice_copy_decr(&dest, &ssa);
2537
21.6k
    --na;
2538
21.6k
    if (na == 0)
2539
0
        goto Succeed;
2540
21.6k
    if (nb == 1)
2541
804
        goto CopyA;
2542
2543
20.8k
    min_gallop = ms->min_gallop;
2544
33.3k
    for (;;) {
2545
33.3k
        Py_ssize_t acount = 0;          /* # of times A won in a row */
2546
33.3k
        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.66M
        for (;;) {
2552
2.66M
            assert(na > 0 && nb > 1);
2553
2.66M
            k = ISLT(ssb.keys[0], ssa.keys[0]);
2554
2.66M
            if (k) {
2555
1.33M
                if (k < 0)
2556
0
                    goto Fail;
2557
1.33M
                sortslice_copy_decr(&dest, &ssa);
2558
1.33M
                ++acount;
2559
1.33M
                bcount = 0;
2560
1.33M
                --na;
2561
1.33M
                if (na == 0)
2562
1.04k
                    goto Succeed;
2563
1.33M
                if (acount >= min_gallop)
2564
15.3k
                    break;
2565
1.33M
            }
2566
1.32M
            else {
2567
1.32M
                sortslice_copy_decr(&dest, &ssb);
2568
1.32M
                ++bcount;
2569
1.32M
                acount = 0;
2570
1.32M
                --nb;
2571
1.32M
                if (nb == 1)
2572
584
                    goto CopyA;
2573
1.32M
                if (bcount >= min_gallop)
2574
16.3k
                    break;
2575
1.32M
            }
2576
2.66M
        }
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
31.7k
        ++min_gallop;
2584
54.5k
        do {
2585
54.5k
            assert(na > 0 && nb > 1);
2586
54.5k
            min_gallop -= min_gallop > 1;
2587
54.5k
            ms->min_gallop = min_gallop;
2588
54.5k
            k = gallop_right(ms, ssb.keys[0], basea.keys, na, na-1);
2589
54.5k
            if (k < 0)
2590
0
                goto Fail;
2591
54.5k
            k = na - k;
2592
54.5k
            acount = k;
2593
54.5k
            if (k) {
2594
33.6k
                sortslice_advance(&dest, -k);
2595
33.6k
                sortslice_advance(&ssa, -k);
2596
33.6k
                sortslice_memmove(&dest, 1, &ssa, 1, k);
2597
33.6k
                na -= k;
2598
33.6k
                if (na == 0)
2599
9.04k
                    goto Succeed;
2600
33.6k
            }
2601
45.5k
            sortslice_copy_decr(&dest, &ssb);
2602
45.5k
            --nb;
2603
45.5k
            if (nb == 1)
2604
786
                goto CopyA;
2605
2606
44.7k
            k = gallop_left(ms, ssa.keys[0], baseb.keys, nb, nb-1);
2607
44.7k
            if (k < 0)
2608
0
                goto Fail;
2609
44.7k
            k = nb - k;
2610
44.7k
            bcount = k;
2611
44.7k
            if (k) {
2612
36.7k
                sortslice_advance(&dest, -k);
2613
36.7k
                sortslice_advance(&ssb, -k);
2614
36.7k
                sortslice_memcpy(&dest, 1, &ssb, 1, k);
2615
36.7k
                nb -= k;
2616
36.7k
                if (nb == 1)
2617
8.67k
                    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
28.0k
                if (nb == 0)
2623
0
                    goto Succeed;
2624
28.0k
            }
2625
36.0k
            sortslice_copy_decr(&dest, &ssa);
2626
36.0k
            --na;
2627
36.0k
            if (na == 0)
2628
765
                goto Succeed;
2629
36.0k
        } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
2630
12.4k
        ++min_gallop;           /* penalize it for leaving galloping mode */
2631
12.4k
        ms->min_gallop = min_gallop;
2632
12.4k
    }
2633
10.8k
Succeed:
2634
10.8k
    result = 0;
2635
10.8k
Fail:
2636
10.8k
    if (nb)
2637
10.8k
        sortslice_memcpy(&dest, -(nb-1), &baseb, 0, nb);
2638
10.8k
    return result;
2639
10.8k
CopyA:
2640
10.8k
    assert(nb == 1 && na > 0);
2641
    /* The first element of ssb belongs at the front of the merge. */
2642
10.8k
    sortslice_memmove(&dest, 1-na, &ssa, 1-na, na);
2643
10.8k
    sortslice_advance(&dest, -na);
2644
10.8k
    sortslice_advance(&ssa, -na);
2645
10.8k
    sortslice_copy(&dest, 0, &ssb, 0);
2646
10.8k
    return 0;
2647
10.8k
}
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
64.1k
{
2655
64.1k
    sortslice ssa, ssb;
2656
64.1k
    Py_ssize_t na, nb;
2657
64.1k
    Py_ssize_t k;
2658
2659
64.1k
    assert(ms != NULL);
2660
64.1k
    assert(ms->n >= 2);
2661
64.1k
    assert(i >= 0);
2662
64.1k
    assert(i == ms->n - 2 || i == ms->n - 3);
2663
2664
64.1k
    ssa = ms->pending[i].base;
2665
64.1k
    na = ms->pending[i].len;
2666
64.1k
    ssb = ms->pending[i+1].base;
2667
64.1k
    nb = ms->pending[i+1].len;
2668
64.1k
    assert(na > 0 && nb > 0);
2669
64.1k
    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
64.1k
    ms->pending[i].len = na + nb;
2676
64.1k
    if (i == ms->n - 3)
2677
411
        ms->pending[i+1] = ms->pending[i+2];
2678
64.1k
    --ms->n;
2679
2680
    /* Where does b start in a?  Elements in a before that can be
2681
     * ignored (already in place).
2682
     */
2683
64.1k
    k = gallop_right(ms, *ssb.keys, ssa.keys, na, 0);
2684
64.1k
    if (k < 0)
2685
0
        return -1;
2686
64.1k
    sortslice_advance(&ssa, k);
2687
64.1k
    na -= k;
2688
64.1k
    if (na == 0)
2689
406
        return 0;
2690
2691
    /* Where does a end in b?  Elements in b after that can be
2692
     * ignored (already in place).
2693
     */
2694
63.7k
    nb = gallop_left(ms, ssa.keys[na-1], ssb.keys, nb, nb-1);
2695
63.7k
    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
63.7k
    if (na <= nb)
2702
42.0k
        return merge_lo(ms, ssa, na, ssb, nb);
2703
21.6k
    else
2704
21.6k
        return merge_hi(ms, ssa, na, ssb, nb);
2705
63.7k
}
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
64.1k
{
2715
64.1k
    int result = 0;
2716
64.1k
    assert(s1 >= 0);
2717
64.1k
    assert(n1 > 0 && n2 > 0);
2718
64.1k
    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
64.1k
    Py_ssize_t a = 2 * s1 + n1;  /* 2*a */
2729
64.1k
    Py_ssize_t b = a + n1 + n2;  /* 2*b */
2730
    /* Emulate a/n and b/n one bit a time, until bits differ. */
2731
230k
    for (;;) {
2732
230k
        ++result;
2733
230k
        if (a >= n) {  /* both quotient bits are 1 */
2734
85.8k
            assert(b >= a);
2735
85.8k
            a -= n;
2736
85.8k
            b -= n;
2737
85.8k
        }
2738
144k
        else if (b >= n) {  /* a/n bit is 0, b/n bit is 1 */
2739
64.1k
            break;
2740
64.1k
        } /* else both quotient bits are 0 */
2741
230k
        assert(a < b && b < n);
2742
166k
        a <<= 1;
2743
166k
        b <<= 1;
2744
166k
    }
2745
64.1k
    return result;
2746
64.1k
}
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
720k
{
2762
720k
    assert(ms);
2763
720k
    if (ms->n) {
2764
64.1k
        assert(ms->n > 0);
2765
64.1k
        struct s_slice *p = ms->pending;
2766
64.1k
        Py_ssize_t s1 = p[ms->n - 1].base.keys - ms->basekeys; /* start index */
2767
64.1k
        Py_ssize_t n1 = p[ms->n - 1].len;
2768
64.1k
        int power = powerloop(s1, n1, n2, ms->listlen);
2769
101k
        while (ms->n > 1 && p[ms->n - 2].power > power) {
2770
37.4k
            if (merge_at(ms, ms->n - 2) < 0)
2771
0
                return -1;
2772
37.4k
        }
2773
64.1k
        assert(ms->n < 2 || p[ms->n - 2].power < power);
2774
64.1k
        p[ms->n - 1].power = power;
2775
64.1k
    }
2776
720k
    return 0;
2777
720k
}
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
656k
{
2787
656k
    struct s_slice *p = ms->pending;
2788
2789
656k
    assert(ms);
2790
682k
    while (ms->n > 1) {
2791
26.7k
        Py_ssize_t n = ms->n - 2;
2792
26.7k
        if (n > 0 && p[n-1].len < p[n+1].len)
2793
411
            --n;
2794
26.7k
        if (merge_at(ms, n) < 0)
2795
0
            return -1;
2796
26.7k
    }
2797
656k
    return 0;
2798
656k
}
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
720k
{
2804
720k
    ms->mr_current += ms->listlen;
2805
720k
    assert(ms->mr_current >= 0); /* no overflow */
2806
720k
    Py_ssize_t result = ms->mr_current >> ms->mr_e;
2807
720k
    ms->mr_current &= ms->mr_mask;
2808
720k
    return result;
2809
720k
}
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
10.4M
{
2835
10.4M
    PyObject *res_obj; int res;
2836
2837
    /* No assumptions, because we check first: */
2838
10.4M
    if (Py_TYPE(v)->tp_richcompare != ms->key_richcompare)
2839
0
        return PyObject_RichCompareBool(v, w, Py_LT);
2840
2841
10.4M
    assert(ms->key_richcompare != NULL);
2842
10.4M
    res_obj = (*(ms->key_richcompare))(v, w, Py_LT);
2843
2844
10.4M
    if (res_obj == Py_NotImplemented) {
2845
0
        Py_DECREF(res_obj);
2846
0
        return PyObject_RichCompareBool(v, w, Py_LT);
2847
0
    }
2848
10.4M
    if (res_obj == NULL)
2849
0
        return -1;
2850
2851
10.4M
    if (PyBool_Check(res_obj)) {
2852
10.4M
        res = (res_obj == Py_True);
2853
10.4M
        assert(_Py_IsImmortal(res_obj));
2854
10.4M
    }
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
10.4M
    return res;
2866
10.4M
}
2867
2868
/* Latin string compare: safe for any two latin (one byte per char) strings. */
2869
static int
2870
unsafe_latin_compare(PyObject *v, PyObject *w, MergeState *ms)
2871
3.34M
{
2872
3.34M
    Py_ssize_t len;
2873
3.34M
    int res;
2874
2875
    /* Modified from Objects/unicodeobject.c:unicode_compare, assuming: */
2876
3.34M
    assert(Py_IS_TYPE(v, &PyUnicode_Type));
2877
3.34M
    assert(Py_IS_TYPE(w, &PyUnicode_Type));
2878
3.34M
    assert(PyUnicode_KIND(v) == PyUnicode_KIND(w));
2879
3.34M
    assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
2880
2881
3.34M
    len = Py_MIN(PyUnicode_GET_LENGTH(v), PyUnicode_GET_LENGTH(w));
2882
3.34M
    res = memcmp(PyUnicode_DATA(v), PyUnicode_DATA(w), len);
2883
2884
3.34M
    res = (res != 0 ?
2885
3.28M
           res < 0 :
2886
3.34M
           PyUnicode_GET_LENGTH(v) < PyUnicode_GET_LENGTH(w));
2887
2888
3.34M
    assert(res == PyObject_RichCompareBool(v, w, Py_LT));;
2889
3.34M
    return res;
2890
3.34M
}
2891
2892
/* Bounded int compare: compare any two longs that fit in a single machine word. */
2893
static int
2894
unsafe_long_compare(PyObject *v, PyObject *w, MergeState *ms)
2895
8.99M
{
2896
8.99M
    PyLongObject *vl, *wl;
2897
8.99M
    intptr_t v0, w0;
2898
8.99M
    int res;
2899
2900
    /* Modified from Objects/longobject.c:long_compare, assuming: */
2901
8.99M
    assert(Py_IS_TYPE(v, &PyLong_Type));
2902
8.99M
    assert(Py_IS_TYPE(w, &PyLong_Type));
2903
8.99M
    assert(_PyLong_IsCompact((PyLongObject *)v));
2904
8.99M
    assert(_PyLong_IsCompact((PyLongObject *)w));
2905
2906
8.99M
    vl = (PyLongObject*)v;
2907
8.99M
    wl = (PyLongObject*)w;
2908
2909
8.99M
    v0 = _PyLong_CompactValue(vl);
2910
8.99M
    w0 = _PyLong_CompactValue(wl);
2911
2912
8.99M
    res = v0 < w0;
2913
8.99M
    assert(res == PyObject_RichCompareBool(v, w, Py_LT));
2914
8.99M
    return res;
2915
8.99M
}
2916
2917
/* Float compare: compare any two floats. */
2918
static int
2919
unsafe_float_compare(PyObject *v, PyObject *w, MergeState *ms)
2920
0
{
2921
0
    int res;
2922
2923
    /* Modified from Objects/floatobject.c:float_richcompare, assuming: */
2924
0
    assert(Py_IS_TYPE(v, &PyFloat_Type));
2925
0
    assert(Py_IS_TYPE(w, &PyFloat_Type));
2926
2927
0
    res = PyFloat_AS_DOUBLE(v) < PyFloat_AS_DOUBLE(w);
2928
0
    assert(res == PyObject_RichCompareBool(v, w, Py_LT));
2929
0
    return res;
2930
0
}
2931
2932
/* Tuple compare: compare *any* two tuples, using
2933
 * ms->tuple_elem_compare to compare the first elements, which is set
2934
 * using the same pre-sort check as we use for ms->key_compare,
2935
 * but run on the list [x[0] for x in L]. This allows us to optimize compares
2936
 * on two levels (as long as [x[0] for x in L] is type-homogeneous.) The idea is
2937
 * that most tuple compares don't involve x[1:]. */
2938
static int
2939
unsafe_tuple_compare(PyObject *v, PyObject *w, MergeState *ms)
2940
4.55M
{
2941
4.55M
    PyTupleObject *vt, *wt;
2942
4.55M
    Py_ssize_t i, vlen, wlen;
2943
4.55M
    int k;
2944
2945
    /* Modified from Objects/tupleobject.c:tuplerichcompare, assuming: */
2946
4.55M
    assert(Py_IS_TYPE(v, &PyTuple_Type));
2947
4.55M
    assert(Py_IS_TYPE(w, &PyTuple_Type));
2948
4.55M
    assert(Py_SIZE(v) > 0);
2949
4.55M
    assert(Py_SIZE(w) > 0);
2950
2951
4.55M
    vt = (PyTupleObject *)v;
2952
4.55M
    wt = (PyTupleObject *)w;
2953
2954
4.55M
    vlen = Py_SIZE(vt);
2955
4.55M
    wlen = Py_SIZE(wt);
2956
2957
6.78M
    for (i = 0; i < vlen && i < wlen; i++) {
2958
5.66M
        k = PyObject_RichCompareBool(vt->ob_item[i], wt->ob_item[i], Py_EQ);
2959
5.66M
        if (k < 0)
2960
0
            return -1;
2961
5.66M
        if (!k)
2962
3.44M
            break;
2963
5.66M
    }
2964
2965
4.55M
    if (i >= vlen || i >= wlen)
2966
1.11M
        return vlen < wlen;
2967
2968
3.44M
    if (i == 0)
2969
3.44M
        return ms->tuple_elem_compare(vt->ob_item[i], wt->ob_item[i], ms);
2970
1.03k
    else
2971
1.03k
        return PyObject_RichCompareBool(vt->ob_item[i], wt->ob_item[i], Py_LT);
2972
3.44M
}
2973
2974
/* An adaptive, stable, natural mergesort.  See listsort.txt.
2975
 * Returns Py_None on success, NULL on error.  Even in case of error, the
2976
 * list will be some permutation of its input state (nothing is lost or
2977
 * duplicated).
2978
 */
2979
/*[clinic input]
2980
@critical_section
2981
list.sort
2982
2983
    *
2984
    key as keyfunc: object = None
2985
    reverse: bool = False
2986
2987
Sort the list in ascending order and return None.
2988
2989
The sort is in-place (i.e. the list itself is modified) and stable
2990
(i.e. the order of two equal elements is maintained).
2991
2992
If a key function is given, apply it once to each list item and sort
2993
them, ascending or descending, according to their function values.
2994
2995
The reverse flag can be set to sort in descending order.
2996
[clinic start generated code]*/
2997
2998
static PyObject *
2999
list_sort_impl(PyListObject *self, PyObject *keyfunc, int reverse)
3000
/*[clinic end generated code: output=57b9f9c5e23fbe42 input=c145526281e1fb9f]*/
3001
4.60M
{
3002
4.60M
    MergeState ms;
3003
4.60M
    Py_ssize_t nremaining;
3004
4.60M
    Py_ssize_t minrun;
3005
4.60M
    sortslice lo;
3006
4.60M
    Py_ssize_t saved_ob_size, saved_allocated;
3007
4.60M
    PyObject **saved_ob_item;
3008
4.60M
    PyObject **final_ob_item;
3009
4.60M
    PyObject *result = NULL;            /* guilty until proved innocent */
3010
4.60M
    Py_ssize_t i;
3011
4.60M
    PyObject **keys;
3012
3013
4.60M
    assert(self != NULL);
3014
4.60M
    assert(PyList_Check(self));
3015
4.60M
    if (keyfunc == Py_None)
3016
3.93M
        keyfunc = NULL;
3017
3018
    /* The list is temporarily made empty, so that mutations performed
3019
     * by comparison functions can't affect the slice of memory we're
3020
     * sorting (allowing mutations during sorting is a core-dump
3021
     * factory, since ob_item may change).
3022
     */
3023
4.60M
    saved_ob_size = Py_SIZE(self);
3024
4.60M
    saved_ob_item = self->ob_item;
3025
4.60M
    saved_allocated = self->allocated;
3026
4.60M
    Py_SET_SIZE(self, 0);
3027
4.60M
    FT_ATOMIC_STORE_PTR_RELEASE(self->ob_item, NULL);
3028
4.60M
    self->allocated = -1; /* any operation will reset it to >= 0 */
3029
3030
4.60M
    if (keyfunc == NULL) {
3031
3.95M
        keys = NULL;
3032
3.95M
        lo.keys = saved_ob_item;
3033
3.95M
        lo.values = NULL;
3034
3.95M
    }
3035
649k
    else {
3036
649k
        if (saved_ob_size < MERGESTATE_TEMP_SIZE/2)
3037
            /* Leverage stack space we allocated but won't otherwise use */
3038
645k
            keys = &ms.temparray[saved_ob_size+1];
3039
3.96k
        else {
3040
3.96k
            keys = PyMem_Malloc(sizeof(PyObject *) * saved_ob_size);
3041
3.96k
            if (keys == NULL) {
3042
0
                PyErr_NoMemory();
3043
0
                goto keyfunc_fail;
3044
0
            }
3045
3.96k
        }
3046
3047
5.02M
        for (i = 0; i < saved_ob_size ; i++) {
3048
4.37M
            keys[i] = PyObject_CallOneArg(keyfunc, saved_ob_item[i]);
3049
4.37M
            if (keys[i] == NULL) {
3050
0
                for (i=i-1 ; i>=0 ; i--)
3051
0
                    Py_DECREF(keys[i]);
3052
0
                if (saved_ob_size >= MERGESTATE_TEMP_SIZE/2)
3053
0
                    PyMem_Free(keys);
3054
0
                goto keyfunc_fail;
3055
0
            }
3056
4.37M
        }
3057
3058
649k
        lo.keys = keys;
3059
649k
        lo.values = saved_ob_item;
3060
649k
    }
3061
3062
3063
    /* The pre-sort check: here's where we decide which compare function to use.
3064
     * How much optimization is safe? We test for homogeneity with respect to
3065
     * several properties that are expensive to check at compare-time, and
3066
     * set ms appropriately. */
3067
4.60M
    if (saved_ob_size > 1) {
3068
        /* Assume the first element is representative of the whole list. */
3069
656k
        int keys_are_in_tuples = (Py_IS_TYPE(lo.keys[0], &PyTuple_Type) &&
3070
1.20k
                                  Py_SIZE(lo.keys[0]) > 0);
3071
3072
656k
        PyTypeObject* key_type = (keys_are_in_tuples ?
3073
1.20k
                                  Py_TYPE(PyTuple_GET_ITEM(lo.keys[0], 0)) :
3074
656k
                                  Py_TYPE(lo.keys[0]));
3075
3076
656k
        int keys_are_all_same_type = 1;
3077
656k
        int strings_are_latin = 1;
3078
656k
        int ints_are_bounded = 1;
3079
3080
        /* Prove that assumption by checking every key. */
3081
9.91M
        for (i=0; i < saved_ob_size; i++) {
3082
3083
9.26M
            if (keys_are_in_tuples &&
3084
2.28M
                !(Py_IS_TYPE(lo.keys[i], &PyTuple_Type) && Py_SIZE(lo.keys[i]) != 0)) {
3085
0
                keys_are_in_tuples = 0;
3086
0
                keys_are_all_same_type = 0;
3087
0
                break;
3088
0
            }
3089
3090
            /* Note: for lists of tuples, key is the first element of the tuple
3091
             * lo.keys[i], not lo.keys[i] itself! We verify type-homogeneity
3092
             * for lists of tuples in the if-statement directly above. */
3093
9.26M
            PyObject *key = (keys_are_in_tuples ?
3094
2.28M
                             PyTuple_GET_ITEM(lo.keys[i], 0) :
3095
9.26M
                             lo.keys[i]);
3096
3097
9.26M
            if (!Py_IS_TYPE(key, key_type)) {
3098
4
                keys_are_all_same_type = 0;
3099
                /* If keys are in tuple we must loop over the whole list to make
3100
                   sure all items are tuples */
3101
4
                if (!keys_are_in_tuples) {
3102
4
                    break;
3103
4
                }
3104
4
            }
3105
3106
9.26M
            if (keys_are_all_same_type) {
3107
9.26M
                if (key_type == &PyLong_Type &&
3108
6.09M
                    ints_are_bounded &&
3109
4.56M
                    !_PyLong_IsCompact((PyLongObject *)key)) {
3110
3111
6.73k
                    ints_are_bounded = 0;
3112
6.73k
                }
3113
9.25M
                else if (key_type == &PyUnicode_Type &&
3114
2.92M
                         strings_are_latin &&
3115
1.23M
                         PyUnicode_KIND(key) != PyUnicode_1BYTE_KIND) {
3116
3117
460k
                        strings_are_latin = 0;
3118
460k
                    }
3119
9.26M
                }
3120
9.26M
            }
3121
3122
        /* Choose the best compare, given what we now know about the keys. */
3123
656k
        if (keys_are_all_same_type) {
3124
3125
656k
            if (key_type == &PyUnicode_Type && strings_are_latin) {
3126
82.1k
                ms.key_compare = unsafe_latin_compare;
3127
82.1k
            }
3128
573k
            else if (key_type == &PyLong_Type && ints_are_bounded) {
3129
83.5k
                ms.key_compare = unsafe_long_compare;
3130
83.5k
            }
3131
490k
            else if (key_type == &PyFloat_Type) {
3132
0
                ms.key_compare = unsafe_float_compare;
3133
0
            }
3134
490k
            else if ((ms.key_richcompare = key_type->tp_richcompare) != NULL) {
3135
490k
                ms.key_compare = unsafe_object_compare;
3136
490k
            }
3137
0
            else {
3138
0
                ms.key_compare = safe_object_compare;
3139
0
            }
3140
656k
        }
3141
4
        else {
3142
4
            ms.key_compare = safe_object_compare;
3143
4
        }
3144
3145
656k
        if (keys_are_in_tuples) {
3146
            /* Make sure we're not dealing with tuples of tuples
3147
             * (remember: here, key_type refers list [key[0] for key in keys]) */
3148
1.20k
            if (key_type == &PyTuple_Type) {
3149
0
                ms.tuple_elem_compare = safe_object_compare;
3150
0
            }
3151
1.20k
            else {
3152
1.20k
                ms.tuple_elem_compare = ms.key_compare;
3153
1.20k
            }
3154
3155
1.20k
            ms.key_compare = unsafe_tuple_compare;
3156
1.20k
        }
3157
656k
    }
3158
    /* End of pre-sort check: ms is now set properly! */
3159
3160
4.60M
    merge_init(&ms, saved_ob_size, keys != NULL, &lo);
3161
3162
4.60M
    nremaining = saved_ob_size;
3163
4.60M
    if (nremaining < 2)
3164
3.94M
        goto succeed;
3165
3166
    /* Reverse sort stability achieved by initially reversing the list,
3167
    applying a stable forward sort, then reversing the final result. */
3168
656k
    if (reverse) {
3169
122
        if (keys != NULL)
3170
0
            reverse_slice(&keys[0], &keys[saved_ob_size]);
3171
122
        reverse_slice(&saved_ob_item[0], &saved_ob_item[saved_ob_size]);
3172
122
    }
3173
3174
    /* March over the array once, left to right, finding natural runs,
3175
     * and extending short natural runs to minrun elements.
3176
     */
3177
720k
    do {
3178
720k
        Py_ssize_t n;
3179
3180
        /* Identify next run. */
3181
720k
        n = count_run(&ms, &lo, nremaining);
3182
720k
        if (n < 0)
3183
0
            goto fail;
3184
        /* If short, extend to min(minrun, nremaining). */
3185
720k
        minrun = minrun_next(&ms);
3186
720k
        if (n < minrun) {
3187
369k
            const Py_ssize_t force = nremaining <= minrun ?
3188
320k
                              nremaining : minrun;
3189
369k
            if (binarysort(&ms, &lo, force, n) < 0)
3190
0
                goto fail;
3191
369k
            n = force;
3192
369k
        }
3193
        /* Maybe merge pending runs. */
3194
720k
        assert(ms.n == 0 || ms.pending[ms.n -1].base.keys +
3195
720k
                            ms.pending[ms.n-1].len == lo.keys);
3196
720k
        if (found_new_run(&ms, n) < 0)
3197
0
            goto fail;
3198
        /* Push new run on stack. */
3199
720k
        assert(ms.n < MAX_MERGE_PENDING);
3200
720k
        ms.pending[ms.n].base = lo;
3201
720k
        ms.pending[ms.n].len = n;
3202
720k
        ++ms.n;
3203
        /* Advance to find next run. */
3204
720k
        sortslice_advance(&lo, n);
3205
720k
        nremaining -= n;
3206
720k
    } while (nremaining);
3207
3208
656k
    if (merge_force_collapse(&ms) < 0)
3209
0
        goto fail;
3210
656k
    assert(ms.n == 1);
3211
656k
    assert(keys == NULL
3212
656k
           ? ms.pending[0].base.keys == saved_ob_item
3213
656k
           : ms.pending[0].base.keys == &keys[0]);
3214
656k
    assert(ms.pending[0].len == saved_ob_size);
3215
656k
    lo = ms.pending[0].base;
3216
3217
4.60M
succeed:
3218
4.60M
    result = Py_None;
3219
4.60M
fail:
3220
4.60M
    if (keys != NULL) {
3221
5.02M
        for (i = 0; i < saved_ob_size; i++)
3222
4.37M
            Py_DECREF(keys[i]);
3223
649k
        if (saved_ob_size >= MERGESTATE_TEMP_SIZE/2)
3224
3.96k
            PyMem_Free(keys);
3225
649k
    }
3226
3227
4.60M
    if (self->allocated != -1 && result != NULL) {
3228
        /* The user mucked with the list during the sort,
3229
         * and we don't already have another error to report.
3230
         */
3231
0
        PyErr_SetString(PyExc_ValueError, "list modified during sort");
3232
0
        result = NULL;
3233
0
    }
3234
3235
4.60M
    if (reverse && saved_ob_size > 1)
3236
122
        reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
3237
3238
4.60M
    merge_freemem(&ms);
3239
3240
4.60M
keyfunc_fail:
3241
4.60M
    final_ob_item = self->ob_item;
3242
4.60M
    i = Py_SIZE(self);
3243
4.60M
    Py_SET_SIZE(self, saved_ob_size);
3244
4.60M
    FT_ATOMIC_STORE_PTR_RELEASE(self->ob_item, saved_ob_item);
3245
4.60M
    FT_ATOMIC_STORE_SSIZE_RELAXED(self->allocated, saved_allocated);
3246
4.60M
    if (final_ob_item != NULL) {
3247
        /* we cannot use list_clear() for this because it does not
3248
           guarantee that the list is really empty when it returns */
3249
0
        while (--i >= 0) {
3250
0
            Py_XDECREF(final_ob_item[i]);
3251
0
        }
3252
#ifdef Py_GIL_DISABLED
3253
        ensure_shared_on_resize(self);
3254
        bool use_qsbr = _PyObject_GC_IS_SHARED(self);
3255
#else
3256
0
        bool use_qsbr = false;
3257
0
#endif
3258
0
        free_list_items(final_ob_item, use_qsbr);
3259
0
    }
3260
4.60M
    return Py_XNewRef(result);
3261
4.60M
}
3262
#undef IFLT
3263
#undef ISLT
3264
3265
int
3266
PyList_Sort(PyObject *v)
3267
17.4k
{
3268
17.4k
    if (v == NULL || !PyList_Check(v)) {
3269
0
        PyErr_BadInternalCall();
3270
0
        return -1;
3271
0
    }
3272
17.4k
    Py_BEGIN_CRITICAL_SECTION(v);
3273
17.4k
    v = list_sort_impl((PyListObject *)v, NULL, 0);
3274
17.4k
    Py_END_CRITICAL_SECTION();
3275
17.4k
    if (v == NULL)
3276
0
        return -1;
3277
17.4k
    Py_DECREF(v);
3278
17.4k
    return 0;
3279
17.4k
}
3280
3281
/*[clinic input]
3282
@critical_section
3283
list.reverse
3284
3285
Reverse *IN PLACE*.
3286
[clinic start generated code]*/
3287
3288
static PyObject *
3289
list_reverse_impl(PyListObject *self)
3290
/*[clinic end generated code: output=482544fc451abea9 input=04ac8e0c6a66e4d9]*/
3291
0
{
3292
0
    if (Py_SIZE(self) > 1)
3293
0
        reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
3294
0
    Py_RETURN_NONE;
3295
0
}
3296
3297
int
3298
PyList_Reverse(PyObject *v)
3299
66
{
3300
66
    PyListObject *self = (PyListObject *)v;
3301
3302
66
    if (v == NULL || !PyList_Check(v)) {
3303
0
        PyErr_BadInternalCall();
3304
0
        return -1;
3305
0
    }
3306
66
    Py_BEGIN_CRITICAL_SECTION(self);
3307
66
    if (Py_SIZE(self) > 1) {
3308
66
        reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
3309
66
    }
3310
66
    Py_END_CRITICAL_SECTION()
3311
66
    return 0;
3312
66
}
3313
3314
PyObject *
3315
PyList_AsTuple(PyObject *v)
3316
255k
{
3317
255k
    if (v == NULL || !PyList_Check(v)) {
3318
0
        PyErr_BadInternalCall();
3319
0
        return NULL;
3320
0
    }
3321
255k
    PyObject *ret;
3322
255k
    PyListObject *self = (PyListObject *)v;
3323
255k
    Py_BEGIN_CRITICAL_SECTION(self);
3324
255k
    ret = PyTuple_FromArray(self->ob_item, Py_SIZE(v));
3325
255k
    Py_END_CRITICAL_SECTION();
3326
255k
    return ret;
3327
255k
}
3328
3329
PyObject *
3330
_PyList_AsTupleAndClear(PyListObject *self)
3331
7.91M
{
3332
7.91M
    assert(self != NULL);
3333
7.91M
    PyObject *ret;
3334
7.91M
    if (self->ob_item == NULL) {
3335
48.7k
        return PyTuple_New(0);
3336
48.7k
    }
3337
7.86M
    Py_BEGIN_CRITICAL_SECTION(self);
3338
7.86M
    PyObject **items = self->ob_item;
3339
7.86M
    Py_ssize_t size = Py_SIZE(self);
3340
7.86M
    Py_SET_SIZE(self, 0);
3341
7.86M
    ret = _PyTuple_FromArraySteal(items, size);
3342
7.86M
    Py_END_CRITICAL_SECTION();
3343
7.86M
    return ret;
3344
7.91M
}
3345
3346
PyObject *
3347
_PyList_FromStackRefStealOnSuccess(const _PyStackRef *src, Py_ssize_t n)
3348
114M
{
3349
114M
    if (n == 0) {
3350
99.8M
        return PyList_New(0);
3351
99.8M
    }
3352
3353
15.0M
    PyListObject *list = (PyListObject *)PyList_New(n);
3354
15.0M
    if (list == NULL) {
3355
0
        return NULL;
3356
0
    }
3357
3358
15.0M
    PyObject **dst = list->ob_item;
3359
33.9M
    for (Py_ssize_t i = 0; i < n; i++) {
3360
18.9M
        dst[i] = PyStackRef_AsPyObjectSteal(src[i]);
3361
18.9M
    }
3362
3363
15.0M
    return (PyObject *)list;
3364
15.0M
}
3365
3366
/*[clinic input]
3367
list.index
3368
3369
    value: object
3370
    start: slice_index(accept={int}) = 0
3371
    stop: slice_index(accept={int}, c_default="PY_SSIZE_T_MAX") = sys.maxsize
3372
    /
3373
3374
Return first index of value.
3375
3376
Raises ValueError if the value is not present.
3377
[clinic start generated code]*/
3378
3379
static PyObject *
3380
list_index_impl(PyListObject *self, PyObject *value, Py_ssize_t start,
3381
                Py_ssize_t stop)
3382
/*[clinic end generated code: output=ec51b88787e4e481 input=40ec5826303a0eb1]*/
3383
0
{
3384
0
    if (start < 0) {
3385
0
        start += Py_SIZE(self);
3386
0
        if (start < 0)
3387
0
            start = 0;
3388
0
    }
3389
0
    if (stop < 0) {
3390
0
        stop += Py_SIZE(self);
3391
0
        if (stop < 0)
3392
0
            stop = 0;
3393
0
    }
3394
0
    for (Py_ssize_t i = start; i < stop; i++) {
3395
0
        PyObject *obj = list_get_item_ref(self, i);
3396
0
        if (obj == NULL) {
3397
            // out-of-bounds
3398
0
            break;
3399
0
        }
3400
0
        int cmp = PyObject_RichCompareBool(obj, value, Py_EQ);
3401
0
        Py_DECREF(obj);
3402
0
        if (cmp > 0)
3403
0
            return PyLong_FromSsize_t(i);
3404
0
        else if (cmp < 0)
3405
0
            return NULL;
3406
0
    }
3407
0
    PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
3408
0
    return NULL;
3409
0
}
3410
3411
/*[clinic input]
3412
list.count
3413
3414
     value: object
3415
     /
3416
3417
Return number of occurrences of value.
3418
[clinic start generated code]*/
3419
3420
static PyObject *
3421
list_count_impl(PyListObject *self, PyObject *value)
3422
/*[clinic end generated code: output=eff66f14aef2df86 input=3bdc3a5e6f749565]*/
3423
24
{
3424
24
    Py_ssize_t count = 0;
3425
144
    for (Py_ssize_t i = 0; ; i++) {
3426
144
        PyObject *obj = list_get_item_ref(self, i);
3427
144
        if (obj == NULL) {
3428
            // out-of-bounds
3429
24
            break;
3430
24
        }
3431
120
        if (obj == value) {
3432
96
           count++;
3433
96
           Py_DECREF(obj);
3434
96
           continue;
3435
96
        }
3436
24
        int cmp = PyObject_RichCompareBool(obj, value, Py_EQ);
3437
24
        Py_DECREF(obj);
3438
24
        if (cmp > 0)
3439
0
            count++;
3440
24
        else if (cmp < 0)
3441
0
            return NULL;
3442
24
    }
3443
24
    return PyLong_FromSsize_t(count);
3444
24
}
3445
3446
/*[clinic input]
3447
@critical_section
3448
list.remove
3449
3450
     value: object
3451
     /
3452
3453
Remove first occurrence of value.
3454
3455
Raises ValueError if the value is not present.
3456
[clinic start generated code]*/
3457
3458
static PyObject *
3459
list_remove_impl(PyListObject *self, PyObject *value)
3460
/*[clinic end generated code: output=b9b76a6633b18778 input=26c813dbb95aa93b]*/
3461
14.0k
{
3462
14.0k
    Py_ssize_t i;
3463
3464
14.0k
    for (i = 0; i < Py_SIZE(self); i++) {
3465
14.0k
        PyObject *obj = self->ob_item[i];
3466
14.0k
        Py_INCREF(obj);
3467
14.0k
        int cmp = PyObject_RichCompareBool(obj, value, Py_EQ);
3468
14.0k
        Py_DECREF(obj);
3469
14.0k
        if (cmp > 0) {
3470
14.0k
            if (list_ass_slice_lock_held(self, i, i+1, NULL) == 0)
3471
14.0k
                Py_RETURN_NONE;
3472
0
            return NULL;
3473
14.0k
        }
3474
24
        else if (cmp < 0)
3475
0
            return NULL;
3476
14.0k
    }
3477
2
    PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
3478
2
    return NULL;
3479
14.0k
}
3480
3481
static int
3482
list_traverse(PyObject *self, visitproc visit, void *arg)
3483
143M
{
3484
143M
    PyListObject *o = (PyListObject *)self;
3485
143M
    Py_ssize_t i;
3486
3487
473M
    for (i = Py_SIZE(o); --i >= 0; )
3488
330M
        Py_VISIT(o->ob_item[i]);
3489
143M
    return 0;
3490
143M
}
3491
3492
static PyObject *
3493
list_richcompare_impl(PyObject *v, PyObject *w, int op)
3494
121k
{
3495
121k
    PyListObject *vl, *wl;
3496
121k
    Py_ssize_t i;
3497
3498
121k
    if (!PyList_Check(v) || !PyList_Check(w))
3499
1.95k
        Py_RETURN_NOTIMPLEMENTED;
3500
3501
119k
    vl = (PyListObject *)v;
3502
119k
    wl = (PyListObject *)w;
3503
3504
119k
    if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) {
3505
        /* Shortcut: if the lengths differ, the lists differ */
3506
12.9k
        if (op == Py_EQ)
3507
12.9k
            Py_RETURN_FALSE;
3508
0
        else
3509
0
            Py_RETURN_TRUE;
3510
12.9k
    }
3511
3512
    /* Search for the first index where items are different.
3513
     * We incref vitem/witem before calling PyObject_RichCompareBool, which may
3514
     * release the GIL and allow the list to be mutated in the meantime.
3515
     */
3516
144k
    for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
3517
130k
        PyObject *vitem = vl->ob_item[i];
3518
130k
        PyObject *witem = wl->ob_item[i];
3519
130k
        if (vitem == witem) {
3520
36.7k
            continue;
3521
36.7k
        }
3522
3523
93.2k
        Py_INCREF(vitem);
3524
93.2k
        Py_INCREF(witem);
3525
93.2k
        int k = PyObject_RichCompareBool(vitem, witem, Py_EQ);
3526
93.2k
        if (k < 0) {
3527
0
            Py_DECREF(vitem);
3528
0
            Py_DECREF(witem);
3529
0
            return NULL;
3530
0
        }
3531
93.2k
        if (!k) {
3532
            /* We have a differing item -- shortcuts for EQ/NE */
3533
92.0k
            if (op == Py_EQ) {
3534
92.0k
                Py_DECREF(vitem);
3535
92.0k
                Py_DECREF(witem);
3536
92.0k
                Py_RETURN_FALSE;
3537
92.0k
            }
3538
27
            if (op == Py_NE) {
3539
27
                Py_DECREF(vitem);
3540
27
                Py_DECREF(witem);
3541
27
                Py_RETURN_TRUE;
3542
27
            }
3543
            /* Compare the differing items using the proper operator */
3544
0
            PyObject *result = PyObject_RichCompare(vitem, witem, op);
3545
0
            Py_DECREF(vitem);
3546
0
            Py_DECREF(witem);
3547
0
            return result;
3548
27
        }
3549
3550
1.21k
        Py_DECREF(vitem);
3551
1.21k
        Py_DECREF(witem);
3552
1.21k
    }
3553
3554
    /* All compared elements were equal -- compare sizes */
3555
14.1k
    Py_RETURN_RICHCOMPARE(Py_SIZE(vl), Py_SIZE(wl), op);
3556
14.1k
}
3557
3558
static PyObject *
3559
list_richcompare(PyObject *v, PyObject *w, int op)
3560
121k
{
3561
121k
    PyObject *ret;
3562
121k
    Py_BEGIN_CRITICAL_SECTION2(v, w);
3563
121k
    ret = list_richcompare_impl(v, w, op);
3564
121k
    Py_END_CRITICAL_SECTION2()
3565
121k
    return ret;
3566
121k
}
3567
3568
/*[clinic input]
3569
list.__init__
3570
3571
    iterable: object(c_default="NULL") = ()
3572
    /
3573
3574
Built-in mutable sequence.
3575
3576
If no argument is given, the constructor creates a new empty list.
3577
The argument must be an iterable if specified.
3578
[clinic start generated code]*/
3579
3580
static int
3581
list___init___impl(PyListObject *self, PyObject *iterable)
3582
/*[clinic end generated code: output=0f3c21379d01de48 input=b3f3fe7206af8f6b]*/
3583
20.7M
{
3584
    /* Verify list invariants established by PyType_GenericAlloc() */
3585
20.7M
    assert(0 <= Py_SIZE(self));
3586
20.7M
    assert(Py_SIZE(self) <= self->allocated || self->allocated == -1);
3587
20.7M
    assert(self->ob_item != NULL ||
3588
20.7M
           self->allocated == 0 || self->allocated == -1);
3589
3590
    /* Empty previous contents */
3591
20.7M
    if (self->ob_item != NULL) {
3592
0
        Py_BEGIN_CRITICAL_SECTION(self);
3593
0
        list_clear(self);
3594
0
        Py_END_CRITICAL_SECTION();
3595
0
    }
3596
20.7M
    if (iterable != NULL) {
3597
10.2M
        if (_list_extend(self, iterable) < 0) {
3598
0
            return -1;
3599
0
        }
3600
10.2M
    }
3601
20.7M
    return 0;
3602
20.7M
}
3603
3604
static PyObject *
3605
list_vectorcall(PyObject *type, PyObject * const*args,
3606
                size_t nargsf, PyObject *kwnames)
3607
10.2M
{
3608
10.2M
    if (!_PyArg_NoKwnames("list", kwnames)) {
3609
0
        return NULL;
3610
0
    }
3611
10.2M
    Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
3612
10.2M
    if (!_PyArg_CheckPositional("list", nargs, 0, 1)) {
3613
0
        return NULL;
3614
0
    }
3615
3616
10.2M
    PyObject *list = PyType_GenericAlloc(_PyType_CAST(type), 0);
3617
10.2M
    if (list == NULL) {
3618
0
        return NULL;
3619
0
    }
3620
10.2M
    if (nargs) {
3621
10.2M
        if (list___init___impl((PyListObject *)list, args[0])) {
3622
0
            Py_DECREF(list);
3623
0
            return NULL;
3624
0
        }
3625
10.2M
    }
3626
10.2M
    return list;
3627
10.2M
}
3628
3629
3630
/*[clinic input]
3631
list.__sizeof__
3632
3633
Return the size of the list in memory, in bytes.
3634
[clinic start generated code]*/
3635
3636
static PyObject *
3637
list___sizeof___impl(PyListObject *self)
3638
/*[clinic end generated code: output=3417541f95f9a53e input=b8030a5d5ce8a187]*/
3639
0
{
3640
0
    size_t res = _PyObject_SIZE(Py_TYPE(self));
3641
#ifdef Py_GIL_DISABLED
3642
    PyObject **ob_item = _Py_atomic_load_ptr(&self->ob_item);
3643
    if (ob_item != NULL) {
3644
        res += list_capacity(ob_item) * sizeof(PyObject *);
3645
    }
3646
#else
3647
0
    res += (size_t)self->allocated * sizeof(PyObject *);
3648
0
#endif
3649
0
    return PyLong_FromSize_t(res);
3650
0
}
3651
3652
static PyObject *list_iter(PyObject *seq);
3653
static PyObject *list_subscript(PyObject*, PyObject*);
3654
3655
static PyMethodDef list_methods[] = {
3656
    {"__getitem__", list_subscript, METH_O|METH_COEXIST,
3657
     PyDoc_STR("__getitem__($self, index, /)\n--\n\nReturn self[index].")},
3658
    LIST___REVERSED___METHODDEF
3659
    LIST___SIZEOF___METHODDEF
3660
    PY_LIST_CLEAR_METHODDEF
3661
    LIST_COPY_METHODDEF
3662
    LIST_APPEND_METHODDEF
3663
    LIST_INSERT_METHODDEF
3664
    LIST_EXTEND_METHODDEF
3665
    LIST_POP_METHODDEF
3666
    LIST_REMOVE_METHODDEF
3667
    LIST_INDEX_METHODDEF
3668
    LIST_COUNT_METHODDEF
3669
    LIST_REVERSE_METHODDEF
3670
    LIST_SORT_METHODDEF
3671
    {"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS,
3672
     PyDoc_STR("lists are generic over the type of their contents")},
3673
    {NULL,              NULL}           /* sentinel */
3674
};
3675
3676
static PySequenceMethods list_as_sequence = {
3677
    list_length,                                /* sq_length */
3678
    _PyList_Concat,                             /* sq_concat */
3679
    list_repeat,                                /* sq_repeat */
3680
    list_item,                                  /* sq_item */
3681
    0,                                          /* sq_slice */
3682
    list_ass_item,                              /* sq_ass_item */
3683
    0,                                          /* sq_ass_slice */
3684
    list_contains,                              /* sq_contains */
3685
    list_inplace_concat,                        /* sq_inplace_concat */
3686
    list_inplace_repeat,                        /* sq_inplace_repeat */
3687
};
3688
3689
static inline PyObject *
3690
list_slice_step_lock_held(PyListObject *a, Py_ssize_t start, Py_ssize_t step, Py_ssize_t len)
3691
525
{
3692
525
    PyListObject *np = (PyListObject *)list_new_prealloc(len);
3693
525
    if (np == NULL) {
3694
0
        return NULL;
3695
0
    }
3696
525
    size_t cur;
3697
525
    Py_ssize_t i;
3698
525
    PyObject **src = a->ob_item;
3699
525
    PyObject **dest = np->ob_item;
3700
7.61k
    for (cur = start, i = 0; i < len;
3701
7.09k
            cur += (size_t)step, i++) {
3702
7.09k
        PyObject *v = src[cur];
3703
7.09k
        dest[i] = Py_NewRef(v);
3704
7.09k
    }
3705
525
    Py_SET_SIZE(np, len);
3706
525
    return (PyObject *)np;
3707
525
}
3708
3709
static PyObject *
3710
list_slice_wrap(PyListObject *aa, Py_ssize_t start, Py_ssize_t stop, Py_ssize_t step)
3711
3.00M
{
3712
3.00M
    PyObject *res = NULL;
3713
3.00M
    Py_BEGIN_CRITICAL_SECTION(aa);
3714
3.00M
    Py_ssize_t len = PySlice_AdjustIndices(Py_SIZE(aa), &start, &stop, step);
3715
3.00M
    if (len <= 0) {
3716
428k
        res = PyList_New(0);
3717
428k
    }
3718
2.57M
    else if (step == 1) {
3719
2.57M
        res = list_slice_lock_held(aa, start, stop);
3720
2.57M
    }
3721
525
    else {
3722
525
        res = list_slice_step_lock_held(aa, start, step, len);
3723
525
    }
3724
3.00M
    Py_END_CRITICAL_SECTION();
3725
3.00M
    return res;
3726
3.00M
}
3727
3728
static inline PyObject*
3729
list_slice_subscript(PyObject* self, PyObject* item)
3730
3.00M
{
3731
3.00M
    assert(PyList_Check(self));
3732
3.00M
    assert(PySlice_Check(item));
3733
3.00M
    Py_ssize_t start, stop, step;
3734
3.00M
    if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
3735
0
        return NULL;
3736
0
    }
3737
3.00M
    return list_slice_wrap((PyListObject *)self, start, stop, step);
3738
3.00M
}
3739
3740
PyObject *
3741
_PyList_SliceSubscript(PyObject* _self, PyObject* item)
3742
3.00M
{
3743
3.00M
    return list_slice_subscript(_self, item);
3744
3.00M
}
3745
3746
static PyObject *
3747
list_subscript(PyObject* _self, PyObject* item)
3748
26.9M
{
3749
26.9M
    PyListObject* self = (PyListObject*)_self;
3750
26.9M
    if (_PyIndex_Check(item)) {
3751
26.9M
        Py_ssize_t i;
3752
26.9M
        i = PyNumber_AsSsize_t(item, PyExc_IndexError);
3753
26.9M
        if (i == -1 && PyErr_Occurred())
3754
29
            return NULL;
3755
26.9M
        if (i < 0)
3756
21.3M
            i += PyList_GET_SIZE(self);
3757
26.9M
        return list_item((PyObject *)self, i);
3758
26.9M
    }
3759
277
    else if (PySlice_Check(item)) {
3760
277
        return list_slice_subscript(_self, item);
3761
277
    }
3762
0
    else {
3763
0
        PyErr_Format(PyExc_TypeError,
3764
0
                     "list indices must be integers or slices, not %.200s",
3765
0
                     Py_TYPE(item)->tp_name);
3766
0
        return NULL;
3767
0
    }
3768
26.9M
}
3769
3770
static Py_ssize_t
3771
adjust_slice_indexes(PyListObject *lst,
3772
                     Py_ssize_t *start, Py_ssize_t *stop,
3773
                     Py_ssize_t step)
3774
2.21M
{
3775
2.21M
    Py_ssize_t slicelength = PySlice_AdjustIndices(Py_SIZE(lst), start, stop,
3776
2.21M
                                                   step);
3777
3778
    /* Make sure s[5:2] = [..] inserts at the right place:
3779
        before 5, not before 2. */
3780
2.21M
    if ((step < 0 && *start < *stop) ||
3781
2.21M
        (step > 0 && *start > *stop))
3782
0
        *stop = *start;
3783
3784
2.21M
    return slicelength;
3785
2.21M
}
3786
3787
static int
3788
list_ass_subscript_lock_held(PyObject *_self, PyObject *item, PyObject *value)
3789
6.16M
{
3790
6.16M
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(_self);
3791
3792
6.16M
    PyListObject *self = (PyListObject *)_self;
3793
6.16M
    if (_PyIndex_Check(item)) {
3794
3.94M
        Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
3795
3.94M
        if (i == -1 && PyErr_Occurred())
3796
0
            return -1;
3797
3.94M
        if (i < 0)
3798
3.93M
            i += PyList_GET_SIZE(self);
3799
3.94M
        return list_ass_item_lock_held(self, i, value);
3800
3.94M
    }
3801
2.21M
    else if (PySlice_Check(item)) {
3802
2.21M
        Py_ssize_t start, stop, step;
3803
3804
2.21M
        if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
3805
0
            return -1;
3806
0
        }
3807
3808
2.21M
        if (value == NULL) {
3809
            /* delete slice */
3810
131
            PyObject **garbage;
3811
131
            size_t cur;
3812
131
            Py_ssize_t i;
3813
131
            int res;
3814
3815
131
            Py_ssize_t slicelength = adjust_slice_indexes(self, &start, &stop,
3816
131
                                                          step);
3817
3818
131
            if (step == 1)
3819
131
                return list_ass_slice_lock_held(self, start, stop, value);
3820
3821
0
            if (slicelength <= 0)
3822
0
                return 0;
3823
3824
0
            if (step < 0) {
3825
0
                stop = start + 1;
3826
0
                start = stop + step*(slicelength - 1) - 1;
3827
0
                step = -step;
3828
0
            }
3829
3830
0
            garbage = (PyObject**)
3831
0
                PyMem_Malloc(slicelength*sizeof(PyObject*));
3832
0
            if (!garbage) {
3833
0
                PyErr_NoMemory();
3834
0
                return -1;
3835
0
            }
3836
3837
            /* drawing pictures might help understand these for
3838
               loops. Basically, we memmove the parts of the
3839
               list that are *not* part of the slice: step-1
3840
               items for each item that is part of the slice,
3841
               and then tail end of the list that was not
3842
               covered by the slice */
3843
0
            for (cur = start, i = 0;
3844
0
                 cur < (size_t)stop;
3845
0
                 cur += step, i++) {
3846
0
                Py_ssize_t lim = step - 1;
3847
3848
0
                garbage[i] = PyList_GET_ITEM(self, cur);
3849
3850
0
                if (cur + step >= (size_t)Py_SIZE(self)) {
3851
0
                    lim = Py_SIZE(self) - cur - 1;
3852
0
                }
3853
3854
0
                ptr_wise_atomic_memmove(self, self->ob_item + cur - i,
3855
0
                    self->ob_item + cur + 1, lim);
3856
0
            }
3857
0
            cur = start + (size_t)slicelength * step;
3858
0
            if (cur < (size_t)Py_SIZE(self)) {
3859
0
                ptr_wise_atomic_memmove(self, self->ob_item + cur - slicelength,
3860
0
                    self->ob_item + cur, Py_SIZE(self) - cur);
3861
0
            }
3862
3863
0
            Py_SET_SIZE(self, Py_SIZE(self) - slicelength);
3864
0
            res = list_resize(self, Py_SIZE(self));
3865
3866
0
            for (i = 0; i < slicelength; i++) {
3867
0
                Py_DECREF(garbage[i]);
3868
0
            }
3869
0
            PyMem_Free(garbage);
3870
3871
0
            return res;
3872
0
        }
3873
2.21M
        else {
3874
            /* assign slice */
3875
2.21M
            PyObject *ins, *seq;
3876
2.21M
            PyObject **garbage, **seqitems, **selfitems;
3877
2.21M
            Py_ssize_t i;
3878
2.21M
            size_t cur;
3879
3880
            /* protect against a[::-1] = a */
3881
2.21M
            if (self == (PyListObject*)value) {
3882
0
                seq = list_slice_lock_held((PyListObject *)value, 0,
3883
0
                                            Py_SIZE(value));
3884
0
            }
3885
2.21M
            else {
3886
2.21M
                seq = PySequence_Fast(value,
3887
2.21M
                                      "must assign iterable "
3888
2.21M
                                      "to extended slice");
3889
2.21M
            }
3890
2.21M
            if (!seq)
3891
0
                return -1;
3892
3893
2.21M
            Py_ssize_t slicelength = adjust_slice_indexes(self, &start, &stop,
3894
2.21M
                                                          step);
3895
3896
2.21M
            if (step == 1) {
3897
2.21M
                int res = list_ass_slice_lock_held(self, start, stop, seq);
3898
2.21M
                Py_DECREF(seq);
3899
2.21M
                return res;
3900
2.21M
            }
3901
3902
0
            if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
3903
0
                PyErr_Format(PyExc_ValueError,
3904
0
                    "attempt to assign sequence of "
3905
0
                    "size %zd to extended slice of "
3906
0
                    "size %zd",
3907
0
                         PySequence_Fast_GET_SIZE(seq),
3908
0
                         slicelength);
3909
0
                Py_DECREF(seq);
3910
0
                return -1;
3911
0
            }
3912
3913
0
            if (!slicelength) {
3914
0
                Py_DECREF(seq);
3915
0
                return 0;
3916
0
            }
3917
3918
0
            garbage = (PyObject**)
3919
0
                PyMem_Malloc(slicelength*sizeof(PyObject*));
3920
0
            if (!garbage) {
3921
0
                Py_DECREF(seq);
3922
0
                PyErr_NoMemory();
3923
0
                return -1;
3924
0
            }
3925
3926
0
            selfitems = self->ob_item;
3927
0
            seqitems = PySequence_Fast_ITEMS(seq);
3928
0
            for (cur = start, i = 0; i < slicelength;
3929
0
                 cur += (size_t)step, i++) {
3930
0
                garbage[i] = selfitems[cur];
3931
0
                ins = Py_NewRef(seqitems[i]);
3932
0
                FT_ATOMIC_STORE_PTR_RELEASE(selfitems[cur], ins);
3933
0
            }
3934
3935
0
            for (i = 0; i < slicelength; i++) {
3936
0
                Py_DECREF(garbage[i]);
3937
0
            }
3938
3939
0
            PyMem_Free(garbage);
3940
0
            Py_DECREF(seq);
3941
3942
0
            return 0;
3943
0
        }
3944
2.21M
    }
3945
0
    else {
3946
0
        PyErr_Format(PyExc_TypeError,
3947
0
                     "list indices must be integers or slices, not %.200s",
3948
0
                     Py_TYPE(item)->tp_name);
3949
0
        return -1;
3950
0
    }
3951
6.16M
}
3952
3953
static int
3954
list_ass_subscript(PyObject *self, PyObject *item, PyObject *value)
3955
6.16M
{
3956
6.16M
    int res;
3957
#ifdef Py_GIL_DISABLED
3958
    if (PySlice_Check(item) && value != NULL && PyList_CheckExact(value)) {
3959
        Py_BEGIN_CRITICAL_SECTION2(self, value);
3960
        res = list_ass_subscript_lock_held(self, item, value);
3961
        Py_END_CRITICAL_SECTION2();
3962
        return res;
3963
    }
3964
#endif
3965
6.16M
    Py_BEGIN_CRITICAL_SECTION(self);
3966
6.16M
    res = list_ass_subscript_lock_held(self, item, value);
3967
6.16M
    Py_END_CRITICAL_SECTION();
3968
6.16M
    return res;
3969
6.16M
}
3970
3971
static _PyObjectIndexPair
3972
list_iteritem(PyObject *obj, Py_ssize_t index)
3973
2.09M
{
3974
2.09M
    PyObject *result = list_get_item_ref((PyListObject *)obj, index);
3975
2.09M
    return (_PyObjectIndexPair) { .object = result, .index = index + 1 };
3976
2.09M
}
3977
3978
static PyMappingMethods list_as_mapping = {
3979
    list_length,
3980
    list_subscript,
3981
    list_ass_subscript
3982
};
3983
3984
PyTypeObject PyList_Type = {
3985
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
3986
    "list",
3987
    sizeof(PyListObject),
3988
    0,
3989
    list_dealloc,                               /* tp_dealloc */
3990
    0,                                          /* tp_vectorcall_offset */
3991
    0,                                          /* tp_getattr */
3992
    0,                                          /* tp_setattr */
3993
    0,                                          /* tp_as_async */
3994
    list_repr,                                  /* tp_repr */
3995
    0,                                          /* tp_as_number */
3996
    &list_as_sequence,                          /* tp_as_sequence */
3997
    &list_as_mapping,                           /* tp_as_mapping */
3998
    PyObject_HashNotImplemented,                /* tp_hash */
3999
    0,                                          /* tp_call */
4000
    0,                                          /* tp_str */
4001
    PyObject_GenericGetAttr,                    /* tp_getattro */
4002
    0,                                          /* tp_setattro */
4003
    0,                                          /* tp_as_buffer */
4004
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
4005
        Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS |
4006
        _Py_TPFLAGS_MATCH_SELF | Py_TPFLAGS_SEQUENCE,  /* tp_flags */
4007
    list___init____doc__,                       /* tp_doc */
4008
    list_traverse,                              /* tp_traverse */
4009
    list_clear_slot,                            /* tp_clear */
4010
    list_richcompare,                           /* tp_richcompare */
4011
    0,                                          /* tp_weaklistoffset */
4012
    list_iter,                                  /* tp_iter */
4013
    0,                                          /* tp_iternext */
4014
    list_methods,                               /* tp_methods */
4015
    0,                                          /* tp_members */
4016
    0,                                          /* tp_getset */
4017
    0,                                          /* tp_base */
4018
    0,                                          /* tp_dict */
4019
    0,                                          /* tp_descr_get */
4020
    0,                                          /* tp_descr_set */
4021
    0,                                          /* tp_dictoffset */
4022
    list___init__,                              /* tp_init */
4023
    PyType_GenericAlloc,                        /* tp_alloc */
4024
    PyType_GenericNew,                          /* tp_new */
4025
    PyObject_GC_Del,                            /* tp_free */
4026
    .tp_vectorcall = list_vectorcall,
4027
    .tp_version_tag = _Py_TYPE_VERSION_LIST,
4028
    ._tp_iteritem = list_iteritem,
4029
};
4030
4031
/*********************** List Iterator **************************/
4032
4033
static void listiter_dealloc(PyObject *);
4034
static int listiter_traverse(PyObject *, visitproc, void *);
4035
static PyObject *listiter_next(PyObject *);
4036
static PyObject *listiter_len(PyObject *, PyObject *);
4037
static PyObject *listiter_reduce_general(void *_it, int forward);
4038
static PyObject *listiter_reduce(PyObject *, PyObject *);
4039
static PyObject *listiter_setstate(PyObject *, PyObject *state);
4040
4041
PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
4042
PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
4043
PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
4044
4045
static PyMethodDef listiter_methods[] = {
4046
    {"__length_hint__", listiter_len, METH_NOARGS, length_hint_doc},
4047
    {"__reduce__", listiter_reduce, METH_NOARGS, reduce_doc},
4048
    {"__setstate__", listiter_setstate, METH_O, setstate_doc},
4049
    {NULL,              NULL}           /* sentinel */
4050
};
4051
4052
PyTypeObject PyListIter_Type = {
4053
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
4054
    "list_iterator",                            /* tp_name */
4055
    sizeof(_PyListIterObject),                  /* tp_basicsize */
4056
    0,                                          /* tp_itemsize */
4057
    /* methods */
4058
    listiter_dealloc,               /* tp_dealloc */
4059
    0,                                          /* tp_vectorcall_offset */
4060
    0,                                          /* tp_getattr */
4061
    0,                                          /* tp_setattr */
4062
    0,                                          /* tp_as_async */
4063
    0,                                          /* tp_repr */
4064
    0,                                          /* tp_as_number */
4065
    0,                                          /* tp_as_sequence */
4066
    0,                                          /* tp_as_mapping */
4067
    0,                                          /* tp_hash */
4068
    0,                                          /* tp_call */
4069
    0,                                          /* tp_str */
4070
    PyObject_GenericGetAttr,                    /* tp_getattro */
4071
    0,                                          /* tp_setattro */
4072
    0,                                          /* tp_as_buffer */
4073
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
4074
    0,                                          /* tp_doc */
4075
    listiter_traverse,                          /* tp_traverse */
4076
    0,                                          /* tp_clear */
4077
    0,                                          /* tp_richcompare */
4078
    0,                                          /* tp_weaklistoffset */
4079
    PyObject_SelfIter,                          /* tp_iter */
4080
    listiter_next,                              /* tp_iternext */
4081
    listiter_methods,                           /* tp_methods */
4082
    0,                                          /* tp_members */
4083
};
4084
4085
4086
static PyObject *
4087
list_iter(PyObject *seq)
4088
35.4M
{
4089
35.4M
    if (!PyList_Check(seq)) {
4090
0
        PyErr_BadInternalCall();
4091
0
        return NULL;
4092
0
    }
4093
35.4M
    _PyListIterObject *it = _Py_FREELIST_POP(_PyListIterObject, list_iters);
4094
35.4M
    if (it == NULL) {
4095
2.32M
        it = PyObject_GC_New(_PyListIterObject, &PyListIter_Type);
4096
2.32M
        if (it == NULL) {
4097
0
            return NULL;
4098
0
        }
4099
2.32M
    }
4100
35.4M
    it->it_index = 0;
4101
35.4M
    it->it_seq = (PyListObject *)Py_NewRef(seq);
4102
35.4M
    _PyObject_GC_TRACK(it);
4103
35.4M
    return (PyObject *)it;
4104
35.4M
}
4105
4106
static void
4107
listiter_dealloc(PyObject *self)
4108
35.4M
{
4109
35.4M
    _PyListIterObject *it = (_PyListIterObject *)self;
4110
35.4M
    _PyObject_GC_UNTRACK(it);
4111
35.4M
    Py_XDECREF(it->it_seq);
4112
35.4M
    assert(Py_IS_TYPE(self, &PyListIter_Type));
4113
35.4M
    _Py_FREELIST_FREE(list_iters, it, PyObject_GC_Del);
4114
35.4M
}
4115
4116
static int
4117
listiter_traverse(PyObject *it, visitproc visit, void *arg)
4118
885k
{
4119
885k
    Py_VISIT(((_PyListIterObject *)it)->it_seq);
4120
885k
    return 0;
4121
885k
}
4122
4123
static PyObject *
4124
listiter_next(PyObject *self)
4125
193M
{
4126
193M
    _PyListIterObject *it = (_PyListIterObject *)self;
4127
193M
    Py_ssize_t index = FT_ATOMIC_LOAD_SSIZE_RELAXED(it->it_index);
4128
193M
    if (index < 0) {
4129
186
        return NULL;
4130
186
    }
4131
4132
193M
    PyObject *item = list_get_item_ref(it->it_seq, index);
4133
193M
    if (item == NULL) {
4134
        // out-of-bounds
4135
34.9M
        FT_ATOMIC_STORE_SSIZE_RELAXED(it->it_index, -1);
4136
34.9M
#ifndef Py_GIL_DISABLED
4137
34.9M
        PyListObject *seq = it->it_seq;
4138
34.9M
        it->it_seq = NULL;
4139
34.9M
        Py_DECREF(seq);
4140
34.9M
#endif
4141
34.9M
        return NULL;
4142
34.9M
    }
4143
159M
    FT_ATOMIC_STORE_SSIZE_RELAXED(it->it_index, index + 1);
4144
159M
    return item;
4145
193M
}
4146
4147
static PyObject *
4148
listiter_len(PyObject *self, PyObject *Py_UNUSED(ignored))
4149
1.16M
{
4150
1.16M
    assert(self != NULL);
4151
1.16M
    _PyListIterObject *it = (_PyListIterObject *)self;
4152
1.16M
    Py_ssize_t index = FT_ATOMIC_LOAD_SSIZE_RELAXED(it->it_index);
4153
1.16M
    if (index >= 0) {
4154
1.16M
        Py_ssize_t len = PyList_GET_SIZE(it->it_seq) - index;
4155
1.16M
        if (len >= 0)
4156
1.16M
            return PyLong_FromSsize_t(len);
4157
1.16M
    }
4158
0
    return PyLong_FromLong(0);
4159
1.16M
}
4160
4161
static PyObject *
4162
listiter_reduce(PyObject *it, PyObject *Py_UNUSED(ignored))
4163
0
{
4164
0
    return listiter_reduce_general(it, 1);
4165
0
}
4166
4167
static PyObject *
4168
listiter_setstate(PyObject *self, PyObject *state)
4169
0
{
4170
0
    _PyListIterObject *it = (_PyListIterObject *)self;
4171
0
    Py_ssize_t index = PyLong_AsSsize_t(state);
4172
0
    if (index == -1 && PyErr_Occurred())
4173
0
        return NULL;
4174
0
    if (it->it_seq != NULL) {
4175
0
        if (index < -1)
4176
0
            index = -1;
4177
0
        else if (index > PyList_GET_SIZE(it->it_seq))
4178
0
            index = PyList_GET_SIZE(it->it_seq); /* iterator exhausted */
4179
0
        FT_ATOMIC_STORE_SSIZE_RELAXED(it->it_index, index);
4180
0
    }
4181
0
    Py_RETURN_NONE;
4182
0
}
4183
4184
/*********************** List Reverse Iterator **************************/
4185
4186
typedef struct {
4187
    PyObject_HEAD
4188
    Py_ssize_t it_index;
4189
    PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
4190
} listreviterobject;
4191
4192
static void listreviter_dealloc(PyObject *);
4193
static int listreviter_traverse(PyObject *, visitproc, void *);
4194
static PyObject *listreviter_next(PyObject *);
4195
static PyObject *listreviter_len(PyObject *, PyObject *);
4196
static PyObject *listreviter_reduce(PyObject *, PyObject *);
4197
static PyObject *listreviter_setstate(PyObject *, PyObject *);
4198
4199
static PyMethodDef listreviter_methods[] = {
4200
    {"__length_hint__", listreviter_len, METH_NOARGS, length_hint_doc},
4201
    {"__reduce__", listreviter_reduce, METH_NOARGS, reduce_doc},
4202
    {"__setstate__", listreviter_setstate, METH_O, setstate_doc},
4203
    {NULL,              NULL}           /* sentinel */
4204
};
4205
4206
PyTypeObject PyListRevIter_Type = {
4207
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
4208
    "list_reverseiterator",                     /* tp_name */
4209
    sizeof(listreviterobject),                  /* tp_basicsize */
4210
    0,                                          /* tp_itemsize */
4211
    /* methods */
4212
    listreviter_dealloc,                        /* tp_dealloc */
4213
    0,                                          /* tp_vectorcall_offset */
4214
    0,                                          /* tp_getattr */
4215
    0,                                          /* tp_setattr */
4216
    0,                                          /* tp_as_async */
4217
    0,                                          /* tp_repr */
4218
    0,                                          /* tp_as_number */
4219
    0,                                          /* tp_as_sequence */
4220
    0,                                          /* tp_as_mapping */
4221
    0,                                          /* tp_hash */
4222
    0,                                          /* tp_call */
4223
    0,                                          /* tp_str */
4224
    PyObject_GenericGetAttr,                    /* tp_getattro */
4225
    0,                                          /* tp_setattro */
4226
    0,                                          /* tp_as_buffer */
4227
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
4228
    0,                                          /* tp_doc */
4229
    listreviter_traverse,                       /* tp_traverse */
4230
    0,                                          /* tp_clear */
4231
    0,                                          /* tp_richcompare */
4232
    0,                                          /* tp_weaklistoffset */
4233
    PyObject_SelfIter,                          /* tp_iter */
4234
    listreviter_next,                           /* tp_iternext */
4235
    listreviter_methods,                /* tp_methods */
4236
    0,
4237
};
4238
4239
/*[clinic input]
4240
list.__reversed__
4241
4242
Return a reverse iterator over the list.
4243
[clinic start generated code]*/
4244
4245
static PyObject *
4246
list___reversed___impl(PyListObject *self)
4247
/*[clinic end generated code: output=b166f073208c888c input=eadb6e17f8a6a280]*/
4248
41.7M
{
4249
41.7M
    listreviterobject *it;
4250
4251
41.7M
    it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
4252
41.7M
    if (it == NULL)
4253
0
        return NULL;
4254
41.7M
    assert(PyList_Check(self));
4255
41.7M
    it->it_index = PyList_GET_SIZE(self) - 1;
4256
41.7M
    it->it_seq = (PyListObject*)Py_NewRef(self);
4257
41.7M
    PyObject_GC_Track(it);
4258
41.7M
    return (PyObject *)it;
4259
41.7M
}
4260
4261
static void
4262
listreviter_dealloc(PyObject *self)
4263
41.7M
{
4264
41.7M
    listreviterobject *it = (listreviterobject *)self;
4265
41.7M
    PyObject_GC_UnTrack(it);
4266
41.7M
    Py_XDECREF(it->it_seq);
4267
41.7M
    PyObject_GC_Del(it);
4268
41.7M
}
4269
4270
static int
4271
listreviter_traverse(PyObject *it, visitproc visit, void *arg)
4272
12.5k
{
4273
12.5k
    Py_VISIT(((listreviterobject *)it)->it_seq);
4274
12.5k
    return 0;
4275
12.5k
}
4276
4277
static PyObject *
4278
listreviter_next(PyObject *self)
4279
51.3M
{
4280
51.3M
    listreviterobject *it = (listreviterobject *)self;
4281
51.3M
    assert(it != NULL);
4282
51.3M
    Py_ssize_t index = FT_ATOMIC_LOAD_SSIZE_RELAXED(it->it_index);
4283
51.3M
    if (index < 0) {
4284
27.1M
        return NULL;
4285
27.1M
    }
4286
4287
24.2M
    PyListObject *seq = it->it_seq;
4288
24.2M
    assert(PyList_Check(seq));
4289
24.2M
    PyObject *item = list_get_item_ref(seq, index);
4290
24.2M
    if (item != NULL) {
4291
24.2M
        FT_ATOMIC_STORE_SSIZE_RELAXED(it->it_index, index - 1);
4292
24.2M
        return item;
4293
24.2M
    }
4294
0
    FT_ATOMIC_STORE_SSIZE_RELAXED(it->it_index, -1);
4295
0
#ifndef Py_GIL_DISABLED
4296
0
    it->it_seq = NULL;
4297
0
    Py_DECREF(seq);
4298
0
#endif
4299
0
    return NULL;
4300
24.2M
}
4301
4302
static PyObject *
4303
listreviter_len(PyObject *self, PyObject *Py_UNUSED(ignored))
4304
0
{
4305
0
    listreviterobject *it = (listreviterobject *)self;
4306
0
    Py_ssize_t index = FT_ATOMIC_LOAD_SSIZE_RELAXED(it->it_index);
4307
0
    Py_ssize_t len = index + 1;
4308
0
    if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
4309
0
        len = 0;
4310
0
    return PyLong_FromSsize_t(len);
4311
0
}
4312
4313
static PyObject *
4314
listreviter_reduce(PyObject *it, PyObject *Py_UNUSED(ignored))
4315
0
{
4316
0
    return listiter_reduce_general(it, 0);
4317
0
}
4318
4319
static PyObject *
4320
listreviter_setstate(PyObject *self, PyObject *state)
4321
0
{
4322
0
    listreviterobject *it = (listreviterobject *)self;
4323
0
    Py_ssize_t index = PyLong_AsSsize_t(state);
4324
0
    if (index == -1 && PyErr_Occurred())
4325
0
        return NULL;
4326
0
    if (it->it_seq != NULL) {
4327
0
        if (index < -1)
4328
0
            index = -1;
4329
0
        else if (index > PyList_GET_SIZE(it->it_seq) - 1)
4330
0
            index = PyList_GET_SIZE(it->it_seq) - 1;
4331
0
        FT_ATOMIC_STORE_SSIZE_RELAXED(it->it_index, index);
4332
0
    }
4333
0
    Py_RETURN_NONE;
4334
0
}
4335
4336
/* common pickling support */
4337
4338
static PyObject *
4339
listiter_reduce_general(void *_it, int forward)
4340
0
{
4341
0
    PyObject *list;
4342
0
    PyObject *iter;
4343
4344
    /* _PyEval_GetBuiltin can invoke arbitrary code,
4345
     * call must be before access of iterator pointers.
4346
     * see issue #101765 */
4347
4348
0
    if (forward) {
4349
0
        iter = _PyEval_GetBuiltin(&_Py_ID(iter));
4350
0
        _PyListIterObject *it = (_PyListIterObject *)_it;
4351
0
        Py_ssize_t idx = FT_ATOMIC_LOAD_SSIZE_RELAXED(it->it_index);
4352
0
        if (idx >= 0) {
4353
0
            return Py_BuildValue("N(O)n", iter, it->it_seq, idx);
4354
0
        }
4355
0
    } else {
4356
0
        iter = _PyEval_GetBuiltin(&_Py_ID(reversed));
4357
0
        listreviterobject *it = (listreviterobject *)_it;
4358
0
        Py_ssize_t idx = FT_ATOMIC_LOAD_SSIZE_RELAXED(it->it_index);
4359
0
        if (idx >= 0) {
4360
0
            return Py_BuildValue("N(O)n", iter, it->it_seq, idx);
4361
0
        }
4362
0
    }
4363
    /* empty iterator, create an empty list */
4364
0
    list = PyList_New(0);
4365
0
    if (list == NULL) {
4366
0
        Py_DECREF(iter);
4367
0
        return NULL;
4368
0
    }
4369
0
    return Py_BuildValue("N(N)", iter, list);
4370
0
}