Coverage Report

Created: 2025-07-11 06:59

/src/Python-3.8.3/Objects/listobject.c
Line
Count
Source (jump to first uncovered line)
1
/* List object implementation */
2
3
#include "Python.h"
4
#include "pycore_object.h"
5
#include "pycore_pystate.h"
6
#include "pycore_tupleobject.h"
7
#include "pycore_accu.h"
8
9
#ifdef STDC_HEADERS
10
#include <stddef.h>
11
#else
12
#include <sys/types.h>          /* For size_t */
13
#endif
14
15
/*[clinic input]
16
class list "PyListObject *" "&PyList_Type"
17
[clinic start generated code]*/
18
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=f9b222678f9f71e0]*/
19
20
#include "clinic/listobject.c.h"
21
22
/* Ensure ob_item has room for at least newsize elements, and set
23
 * ob_size to newsize.  If newsize > ob_size on entry, the content
24
 * of the new slots at exit is undefined heap trash; it's the caller's
25
 * responsibility to overwrite them with sane values.
26
 * The number of allocated elements may grow, shrink, or stay the same.
27
 * Failure is impossible if newsize <= self.allocated on entry, although
28
 * that partly relies on an assumption that the system realloc() never
29
 * fails when passed a number of bytes <= the number of bytes last
30
 * allocated (the C standard doesn't guarantee this, but it's hard to
31
 * imagine a realloc implementation where it wouldn't be true).
32
 * Note that self->ob_item may change, and even if newsize is less
33
 * than ob_size on entry.
34
 */
35
static int
36
list_resize(PyListObject *self, Py_ssize_t newsize)
37
66.5k
{
38
66.5k
    PyObject **items;
39
66.5k
    size_t new_allocated, num_allocated_bytes;
40
66.5k
    Py_ssize_t allocated = self->allocated;
41
42
    /* Bypass realloc() when a previous overallocation is large enough
43
       to accommodate the newsize.  If the newsize falls lower than half
44
       the allocated size, then proceed with the realloc() to shrink the list.
45
    */
46
66.5k
    if (allocated >= newsize && newsize >= (allocated >> 1)) {
47
58.1k
        assert(self->ob_item != NULL || newsize == 0);
48
58.1k
        Py_SIZE(self) = newsize;
49
58.1k
        return 0;
50
58.1k
    }
51
52
    /* This over-allocates proportional to the list size, making room
53
     * for additional growth.  The over-allocation is mild, but is
54
     * enough to give linear-time amortized behavior over a long
55
     * sequence of appends() in the presence of a poorly-performing
56
     * system realloc().
57
     * The growth pattern is:  0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
58
     * Note: new_allocated won't overflow because the largest possible value
59
     *       is PY_SSIZE_T_MAX * (9 / 8) + 6 which always fits in a size_t.
60
     */
61
8.37k
    new_allocated = (size_t)newsize + (newsize >> 3) + (newsize < 9 ? 3 : 6);
62
8.37k
    if (new_allocated > (size_t)PY_SSIZE_T_MAX / sizeof(PyObject *)) {
63
0
        PyErr_NoMemory();
64
0
        return -1;
65
0
    }
66
67
8.37k
    if (newsize == 0)
68
0
        new_allocated = 0;
69
8.37k
    num_allocated_bytes = new_allocated * sizeof(PyObject *);
70
8.37k
    items = (PyObject **)PyMem_Realloc(self->ob_item, num_allocated_bytes);
71
8.37k
    if (items == NULL) {
72
0
        PyErr_NoMemory();
73
0
        return -1;
74
0
    }
75
8.37k
    self->ob_item = items;
76
8.37k
    Py_SIZE(self) = newsize;
77
8.37k
    self->allocated = new_allocated;
78
8.37k
    return 0;
79
8.37k
}
80
81
static int
82
list_preallocate_exact(PyListObject *self, Py_ssize_t size)
83
19
{
84
19
    assert(self->ob_item == NULL);
85
19
    assert(size > 0);
86
87
19
    PyObject **items = PyMem_New(PyObject*, size);
88
19
    if (items == NULL) {
89
0
        PyErr_NoMemory();
90
0
        return -1;
91
0
    }
92
19
    self->ob_item = items;
93
19
    self->allocated = size;
94
19
    return 0;
95
19
}
96
97
/* Debug statistic to compare allocations with reuse through the free list */
98
#undef SHOW_ALLOC_COUNT
99
#ifdef SHOW_ALLOC_COUNT
100
static size_t count_alloc = 0;
101
static size_t count_reuse = 0;
102
103
static void
104
show_alloc(void)
105
{
106
    PyInterpreterState *interp = _PyInterpreterState_Get();
107
    if (!interp->config.show_alloc_count) {
108
        return;
109
    }
110
111
    fprintf(stderr, "List allocations: %" PY_FORMAT_SIZE_T "d\n",
112
        count_alloc);
113
    fprintf(stderr, "List reuse through freelist: %" PY_FORMAT_SIZE_T
114
        "d\n", count_reuse);
115
    fprintf(stderr, "%.2f%% reuse rate\n\n",
116
        (100.0*count_reuse/(count_alloc+count_reuse)));
117
}
118
#endif
119
120
/* Empty list reuse scheme to save calls to malloc and free */
121
#ifndef PyList_MAXFREELIST
122
12.5k
#define PyList_MAXFREELIST 80
123
#endif
124
static PyListObject *free_list[PyList_MAXFREELIST];
125
static int numfree = 0;
126
127
int
128
PyList_ClearFreeList(void)
129
0
{
130
0
    PyListObject *op;
131
0
    int ret = numfree;
132
0
    while (numfree) {
133
0
        op = free_list[--numfree];
134
0
        assert(PyList_CheckExact(op));
135
0
        PyObject_GC_Del(op);
136
0
    }
137
0
    return ret;
138
0
}
139
140
void
141
PyList_Fini(void)
142
0
{
143
0
    PyList_ClearFreeList();
144
0
}
145
146
/* Print summary info about the state of the optimized allocator */
147
void
148
_PyList_DebugMallocStats(FILE *out)
149
0
{
150
0
    _PyDebugAllocatorStats(out,
151
0
                           "free PyListObject",
152
0
                           numfree, sizeof(PyListObject));
153
0
}
154
155
PyObject *
156
PyList_New(Py_ssize_t size)
157
6.72k
{
158
6.72k
    PyListObject *op;
159
#ifdef SHOW_ALLOC_COUNT
160
    static int initialized = 0;
161
    if (!initialized) {
162
        Py_AtExit(show_alloc);
163
        initialized = 1;
164
    }
165
#endif
166
167
6.72k
    if (size < 0) {
168
0
        PyErr_BadInternalCall();
169
0
        return NULL;
170
0
    }
171
6.72k
    if (numfree) {
172
6.15k
        numfree--;
173
6.15k
        op = free_list[numfree];
174
6.15k
        _Py_NewReference((PyObject *)op);
175
#ifdef SHOW_ALLOC_COUNT
176
        count_reuse++;
177
#endif
178
6.15k
    } else {
179
570
        op = PyObject_GC_New(PyListObject, &PyList_Type);
180
570
        if (op == NULL)
181
0
            return NULL;
182
#ifdef SHOW_ALLOC_COUNT
183
        count_alloc++;
184
#endif
185
570
    }
186
6.72k
    if (size <= 0)
187
5.26k
        op->ob_item = NULL;
188
1.46k
    else {
189
1.46k
        op->ob_item = (PyObject **) PyMem_Calloc(size, sizeof(PyObject *));
190
1.46k
        if (op->ob_item == NULL) {
191
0
            Py_DECREF(op);
192
0
            return PyErr_NoMemory();
193
0
        }
194
1.46k
    }
195
6.72k
    Py_SIZE(op) = size;
196
6.72k
    op->allocated = size;
197
6.72k
    _PyObject_GC_TRACK(op);
198
6.72k
    return (PyObject *) op;
199
6.72k
}
200
201
static PyObject *
202
list_new_prealloc(Py_ssize_t size)
203
60
{
204
60
    PyListObject *op = (PyListObject *) PyList_New(0);
205
60
    if (size == 0 || op == NULL) {
206
0
        return (PyObject *) op;
207
0
    }
208
60
    assert(op->ob_item == NULL);
209
60
    op->ob_item = PyMem_New(PyObject *, size);
210
60
    if (op->ob_item == NULL) {
211
0
        Py_DECREF(op);
212
0
        return PyErr_NoMemory();
213
0
    }
214
60
    op->allocated = size;
215
60
    return (PyObject *) op;
216
60
}
217
218
Py_ssize_t
219
PyList_Size(PyObject *op)
220
65
{
221
65
    if (!PyList_Check(op)) {
222
0
        PyErr_BadInternalCall();
223
0
        return -1;
224
0
    }
225
65
    else
226
65
        return Py_SIZE(op);
227
65
}
228
229
static inline int
230
valid_index(Py_ssize_t i, Py_ssize_t limit)
231
7.69k
{
232
    /* The cast to size_t lets us use just a single comparison
233
       to check whether i is in the range: 0 <= i < limit.
234
235
       See:  Section 14.2 "Bounds Checking" in the Agner Fog
236
       optimization manual found at:
237
       https://www.agner.org/optimize/optimizing_cpp.pdf
238
    */
239
7.69k
    return (size_t) i < (size_t) limit;
240
7.69k
}
241
242
static PyObject *indexerr = NULL;
243
244
PyObject *
245
PyList_GetItem(PyObject *op, Py_ssize_t i)
246
29
{
247
29
    if (!PyList_Check(op)) {
248
0
        PyErr_BadInternalCall();
249
0
        return NULL;
250
0
    }
251
29
    if (!valid_index(i, Py_SIZE(op))) {
252
0
        if (indexerr == NULL) {
253
0
            indexerr = PyUnicode_FromString(
254
0
                "list index out of range");
255
0
            if (indexerr == NULL)
256
0
                return NULL;
257
0
        }
258
0
        PyErr_SetObject(PyExc_IndexError, indexerr);
259
0
        return NULL;
260
0
    }
261
29
    return ((PyListObject *)op) -> ob_item[i];
262
29
}
263
264
int
265
PyList_SetItem(PyObject *op, Py_ssize_t i,
266
               PyObject *newitem)
267
203
{
268
203
    PyObject **p;
269
203
    if (!PyList_Check(op)) {
270
0
        Py_XDECREF(newitem);
271
0
        PyErr_BadInternalCall();
272
0
        return -1;
273
0
    }
274
203
    if (!valid_index(i, Py_SIZE(op))) {
275
0
        Py_XDECREF(newitem);
276
0
        PyErr_SetString(PyExc_IndexError,
277
0
                        "list assignment index out of range");
278
0
        return -1;
279
0
    }
280
203
    p = ((PyListObject *)op) -> ob_item + i;
281
203
    Py_XSETREF(*p, newitem);
282
203
    return 0;
283
203
}
284
285
static int
286
ins1(PyListObject *self, Py_ssize_t where, PyObject *v)
287
14
{
288
14
    Py_ssize_t i, n = Py_SIZE(self);
289
14
    PyObject **items;
290
14
    if (v == NULL) {
291
0
        PyErr_BadInternalCall();
292
0
        return -1;
293
0
    }
294
14
    if (n == PY_SSIZE_T_MAX) {
295
0
        PyErr_SetString(PyExc_OverflowError,
296
0
            "cannot add more objects to list");
297
0
        return -1;
298
0
    }
299
300
14
    if (list_resize(self, n+1) < 0)
301
0
        return -1;
302
303
14
    if (where < 0) {
304
0
        where += n;
305
0
        if (where < 0)
306
0
            where = 0;
307
0
    }
308
14
    if (where > n)
309
0
        where = n;
310
14
    items = self->ob_item;
311
28
    for (i = n; --i >= where; )
312
14
        items[i+1] = items[i];
313
14
    Py_INCREF(v);
314
14
    items[where] = v;
315
14
    return 0;
316
14
}
317
318
int
319
PyList_Insert(PyObject *op, Py_ssize_t where, PyObject *newitem)
320
14
{
321
14
    if (!PyList_Check(op)) {
322
0
        PyErr_BadInternalCall();
323
0
        return -1;
324
0
    }
325
14
    return ins1((PyListObject *)op, where, newitem);
326
14
}
327
328
static int
329
app1(PyListObject *self, PyObject *v)
330
64.4k
{
331
64.4k
    Py_ssize_t n = PyList_GET_SIZE(self);
332
333
64.4k
    assert (v != NULL);
334
64.4k
    if (n == PY_SSIZE_T_MAX) {
335
0
        PyErr_SetString(PyExc_OverflowError,
336
0
            "cannot add more objects to list");
337
0
        return -1;
338
0
    }
339
340
64.4k
    if (list_resize(self, n+1) < 0)
341
0
        return -1;
342
343
64.4k
    Py_INCREF(v);
344
64.4k
    PyList_SET_ITEM(self, n, v);
345
64.4k
    return 0;
346
64.4k
}
347
348
int
349
PyList_Append(PyObject *op, PyObject *newitem)
350
62.4k
{
351
62.4k
    if (PyList_Check(op) && (newitem != NULL))
352
62.4k
        return app1((PyListObject *)op, newitem);
353
0
    PyErr_BadInternalCall();
354
0
    return -1;
355
62.4k
}
356
357
/* Methods */
358
359
static void
360
list_dealloc(PyListObject *op)
361
6.28k
{
362
6.28k
    Py_ssize_t i;
363
6.28k
    PyObject_GC_UnTrack(op);
364
6.28k
    Py_TRASHCAN_BEGIN(op, list_dealloc)
365
6.28k
    if (op->ob_item != NULL) {
366
        /* Do it backwards, for Christian Tismer.
367
           There's a simple test case where somehow this reduces
368
           thrashing when a *very* large list is created and
369
           immediately deleted. */
370
4.90k
        i = Py_SIZE(op);
371
92.4k
        while (--i >= 0) {
372
87.5k
            Py_XDECREF(op->ob_item[i]);
373
87.5k
        }
374
4.90k
        PyMem_FREE(op->ob_item);
375
4.90k
    }
376
6.28k
    if (numfree < PyList_MAXFREELIST && PyList_CheckExact(op))
377
6.27k
        free_list[numfree++] = op;
378
14
    else
379
14
        Py_TYPE(op)->tp_free((PyObject *)op);
380
6.28k
    Py_TRASHCAN_END
381
6.28k
}
382
383
static PyObject *
384
list_repr(PyListObject *v)
385
0
{
386
0
    Py_ssize_t i;
387
0
    PyObject *s;
388
0
    _PyUnicodeWriter writer;
389
390
0
    if (Py_SIZE(v) == 0) {
391
0
        return PyUnicode_FromString("[]");
392
0
    }
393
394
0
    i = Py_ReprEnter((PyObject*)v);
395
0
    if (i != 0) {
396
0
        return i > 0 ? PyUnicode_FromString("[...]") : NULL;
397
0
    }
398
399
0
    _PyUnicodeWriter_Init(&writer);
400
0
    writer.overallocate = 1;
401
    /* "[" + "1" + ", 2" * (len - 1) + "]" */
402
0
    writer.min_length = 1 + 1 + (2 + 1) * (Py_SIZE(v) - 1) + 1;
403
404
0
    if (_PyUnicodeWriter_WriteChar(&writer, '[') < 0)
405
0
        goto error;
406
407
    /* Do repr() on each element.  Note that this may mutate the list,
408
       so must refetch the list size on each iteration. */
409
0
    for (i = 0; i < Py_SIZE(v); ++i) {
410
0
        if (i > 0) {
411
0
            if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0)
412
0
                goto error;
413
0
        }
414
415
0
        s = PyObject_Repr(v->ob_item[i]);
416
0
        if (s == NULL)
417
0
            goto error;
418
419
0
        if (_PyUnicodeWriter_WriteStr(&writer, s) < 0) {
420
0
            Py_DECREF(s);
421
0
            goto error;
422
0
        }
423
0
        Py_DECREF(s);
424
0
    }
425
426
0
    writer.overallocate = 0;
427
0
    if (_PyUnicodeWriter_WriteChar(&writer, ']') < 0)
428
0
        goto error;
429
430
0
    Py_ReprLeave((PyObject *)v);
431
0
    return _PyUnicodeWriter_Finish(&writer);
432
433
0
error:
434
0
    _PyUnicodeWriter_Dealloc(&writer);
435
0
    Py_ReprLeave((PyObject *)v);
436
0
    return NULL;
437
0
}
438
439
static Py_ssize_t
440
list_length(PyListObject *a)
441
1.72k
{
442
1.72k
    return Py_SIZE(a);
443
1.72k
}
444
445
static int
446
list_contains(PyListObject *a, PyObject *el)
447
613
{
448
613
    PyObject *item;
449
613
    Py_ssize_t i;
450
613
    int cmp;
451
452
16.5k
    for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i) {
453
15.9k
        item = PyList_GET_ITEM(a, i);
454
15.9k
        Py_INCREF(item);
455
15.9k
        cmp = PyObject_RichCompareBool(el, item, Py_EQ);
456
15.9k
        Py_DECREF(item);
457
15.9k
    }
458
613
    return cmp;
459
613
}
460
461
static PyObject *
462
list_item(PyListObject *a, Py_ssize_t i)
463
7.31k
{
464
7.31k
    if (!valid_index(i, Py_SIZE(a))) {
465
128
        if (indexerr == NULL) {
466
14
            indexerr = PyUnicode_FromString(
467
14
                "list index out of range");
468
14
            if (indexerr == NULL)
469
0
                return NULL;
470
14
        }
471
128
        PyErr_SetObject(PyExc_IndexError, indexerr);
472
128
        return NULL;
473
128
    }
474
7.18k
    Py_INCREF(a->ob_item[i]);
475
7.18k
    return a->ob_item[i];
476
7.31k
}
477
478
static PyObject *
479
list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
480
45
{
481
45
    PyListObject *np;
482
45
    PyObject **src, **dest;
483
45
    Py_ssize_t i, len;
484
45
    len = ihigh - ilow;
485
45
    np = (PyListObject *) list_new_prealloc(len);
486
45
    if (np == NULL)
487
0
        return NULL;
488
489
45
    src = a->ob_item + ilow;
490
45
    dest = np->ob_item;
491
132
    for (i = 0; i < len; i++) {
492
87
        PyObject *v = src[i];
493
87
        Py_INCREF(v);
494
87
        dest[i] = v;
495
87
    }
496
45
    Py_SIZE(np) = len;
497
45
    return (PyObject *)np;
498
45
}
499
500
PyObject *
501
PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
502
0
{
503
0
    if (!PyList_Check(a)) {
504
0
        PyErr_BadInternalCall();
505
0
        return NULL;
506
0
    }
507
0
    if (ilow < 0) {
508
0
        ilow = 0;
509
0
    }
510
0
    else if (ilow > Py_SIZE(a)) {
511
0
        ilow = Py_SIZE(a);
512
0
    }
513
0
    if (ihigh < ilow) {
514
0
        ihigh = ilow;
515
0
    }
516
0
    else if (ihigh > Py_SIZE(a)) {
517
0
        ihigh = Py_SIZE(a);
518
0
    }
519
0
    return list_slice((PyListObject *)a, ilow, ihigh);
520
0
}
521
522
static PyObject *
523
list_concat(PyListObject *a, PyObject *bb)
524
5
{
525
5
    Py_ssize_t size;
526
5
    Py_ssize_t i;
527
5
    PyObject **src, **dest;
528
5
    PyListObject *np;
529
5
    if (!PyList_Check(bb)) {
530
0
        PyErr_Format(PyExc_TypeError,
531
0
                  "can only concatenate list (not \"%.200s\") to list",
532
0
                  bb->ob_type->tp_name);
533
0
        return NULL;
534
0
    }
535
5
#define b ((PyListObject *)bb)
536
5
    if (Py_SIZE(a) > PY_SSIZE_T_MAX - Py_SIZE(b))
537
0
        return PyErr_NoMemory();
538
5
    size = Py_SIZE(a) + Py_SIZE(b);
539
5
    np = (PyListObject *) list_new_prealloc(size);
540
5
    if (np == NULL) {
541
0
        return NULL;
542
0
    }
543
5
    src = a->ob_item;
544
5
    dest = np->ob_item;
545
78
    for (i = 0; i < Py_SIZE(a); i++) {
546
73
        PyObject *v = src[i];
547
73
        Py_INCREF(v);
548
73
        dest[i] = v;
549
73
    }
550
5
    src = b->ob_item;
551
5
    dest = np->ob_item + Py_SIZE(a);
552
147
    for (i = 0; i < Py_SIZE(b); i++) {
553
142
        PyObject *v = src[i];
554
142
        Py_INCREF(v);
555
142
        dest[i] = v;
556
142
    }
557
5
    Py_SIZE(np) = size;
558
5
    return (PyObject *)np;
559
5
#undef b
560
5
}
561
562
static PyObject *
563
list_repeat(PyListObject *a, Py_ssize_t n)
564
10
{
565
10
    Py_ssize_t i, j;
566
10
    Py_ssize_t size;
567
10
    PyListObject *np;
568
10
    PyObject **p, **items;
569
10
    PyObject *elem;
570
10
    if (n < 0)
571
0
        n = 0;
572
10
    if (n > 0 && Py_SIZE(a) > PY_SSIZE_T_MAX / n)
573
0
        return PyErr_NoMemory();
574
10
    size = Py_SIZE(a) * n;
575
10
    if (size == 0)
576
0
        return PyList_New(0);
577
10
    np = (PyListObject *) list_new_prealloc(size);
578
10
    if (np == NULL)
579
0
        return NULL;
580
581
10
    if (Py_SIZE(a) == 1) {
582
10
        items = np->ob_item;
583
10
        elem = a->ob_item[0];
584
35
        for (i = 0; i < n; i++) {
585
25
            items[i] = elem;
586
25
            Py_INCREF(elem);
587
25
        }
588
10
    }
589
0
    else {
590
0
        p = np->ob_item;
591
0
        items = a->ob_item;
592
0
        for (i = 0; i < n; i++) {
593
0
            for (j = 0; j < Py_SIZE(a); j++) {
594
0
                *p = items[j];
595
0
                Py_INCREF(*p);
596
0
                p++;
597
0
            }
598
0
        }
599
0
    }
600
10
    Py_SIZE(np) = size;
601
10
    return (PyObject *) np;
602
10
}
603
604
static int
605
_list_clear(PyListObject *a)
606
24
{
607
24
    Py_ssize_t i;
608
24
    PyObject **item = a->ob_item;
609
24
    if (item != NULL) {
610
        /* Because XDECREF can recursively invoke operations on
611
           this list, we make it empty first. */
612
24
        i = Py_SIZE(a);
613
24
        Py_SIZE(a) = 0;
614
24
        a->ob_item = NULL;
615
24
        a->allocated = 0;
616
48
        while (--i >= 0) {
617
24
            Py_XDECREF(item[i]);
618
24
        }
619
24
        PyMem_FREE(item);
620
24
    }
621
    /* Never fails; the return value can be ignored.
622
       Note that there is no guarantee that the list is actually empty
623
       at this point, because XDECREF may have populated it again! */
624
24
    return 0;
625
24
}
626
627
/* a[ilow:ihigh] = v if v != NULL.
628
 * del a[ilow:ihigh] if v == NULL.
629
 *
630
 * Special speed gimmick:  when v is NULL and ihigh - ilow <= 8, it's
631
 * guaranteed the call cannot fail.
632
 */
633
static int
634
list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
635
49
{
636
    /* Because [X]DECREF can recursively invoke list operations on
637
       this list, we must postpone all [X]DECREF activity until
638
       after the list is back in its canonical shape.  Therefore
639
       we must allocate an additional array, 'recycle', into which
640
       we temporarily copy the items that are deleted from the
641
       list. :-( */
642
49
    PyObject *recycle_on_stack[8];
643
49
    PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
644
49
    PyObject **item;
645
49
    PyObject **vitem = NULL;
646
49
    PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
647
49
    Py_ssize_t n; /* # of elements in replacement list */
648
49
    Py_ssize_t norig; /* # of elements in list getting replaced */
649
49
    Py_ssize_t d; /* Change in size */
650
49
    Py_ssize_t k;
651
49
    size_t s;
652
49
    int result = -1;            /* guilty until proved innocent */
653
49
#define b ((PyListObject *)v)
654
49
    if (v == NULL)
655
31
        n = 0;
656
18
    else {
657
18
        if (a == b) {
658
            /* Special case "a[i:j] = a" -- copy b first */
659
0
            v = list_slice(b, 0, Py_SIZE(b));
660
0
            if (v == NULL)
661
0
                return result;
662
0
            result = list_ass_slice(a, ilow, ihigh, v);
663
0
            Py_DECREF(v);
664
0
            return result;
665
0
        }
666
18
        v_as_SF = PySequence_Fast(v, "can only assign an iterable");
667
18
        if(v_as_SF == NULL)
668
0
            goto Error;
669
18
        n = PySequence_Fast_GET_SIZE(v_as_SF);
670
18
        vitem = PySequence_Fast_ITEMS(v_as_SF);
671
18
    }
672
49
    if (ilow < 0)
673
0
        ilow = 0;
674
49
    else if (ilow > Py_SIZE(a))
675
0
        ilow = Py_SIZE(a);
676
677
49
    if (ihigh < ilow)
678
0
        ihigh = ilow;
679
49
    else if (ihigh > Py_SIZE(a))
680
0
        ihigh = Py_SIZE(a);
681
682
49
    norig = ihigh - ilow;
683
49
    assert(norig >= 0);
684
49
    d = n - norig;
685
49
    if (Py_SIZE(a) + d == 0) {
686
24
        Py_XDECREF(v_as_SF);
687
24
        return _list_clear(a);
688
24
    }
689
25
    item = a->ob_item;
690
    /* recycle the items that we are about to remove */
691
25
    s = norig * sizeof(PyObject *);
692
    /* If norig == 0, item might be NULL, in which case we may not memcpy from it. */
693
25
    if (s) {
694
23
        if (s > sizeof(recycle_on_stack)) {
695
0
            recycle = (PyObject **)PyMem_MALLOC(s);
696
0
            if (recycle == NULL) {
697
0
                PyErr_NoMemory();
698
0
                goto Error;
699
0
            }
700
0
        }
701
23
        memcpy(recycle, &item[ilow], s);
702
23
    }
703
704
25
    if (d < 0) { /* Delete -d items */
705
7
        Py_ssize_t tail;
706
7
        tail = (Py_SIZE(a) - ihigh) * sizeof(PyObject *);
707
7
        memmove(&item[ihigh+d], &item[ihigh], tail);
708
7
        if (list_resize(a, Py_SIZE(a) + d) < 0) {
709
0
            memmove(&item[ihigh], &item[ihigh+d], tail);
710
0
            memcpy(&item[ilow], recycle, s);
711
0
            goto Error;
712
0
        }
713
7
        item = a->ob_item;
714
7
    }
715
18
    else if (d > 0) { /* Insert d items */
716
2
        k = Py_SIZE(a);
717
2
        if (list_resize(a, k+d) < 0)
718
0
            goto Error;
719
2
        item = a->ob_item;
720
2
        memmove(&item[ihigh+d], &item[ihigh],
721
2
            (k - ihigh)*sizeof(PyObject *));
722
2
    }
723
213
    for (k = 0; k < n; k++, ilow++) {
724
188
        PyObject *w = vitem[k];
725
188
        Py_XINCREF(w);
726
188
        item[ilow] = w;
727
188
    }
728
91
    for (k = norig - 1; k >= 0; --k)
729
66
        Py_XDECREF(recycle[k]);
730
25
    result = 0;
731
25
 Error:
732
25
    if (recycle != recycle_on_stack)
733
0
        PyMem_FREE(recycle);
734
25
    Py_XDECREF(v_as_SF);
735
25
    return result;
736
25
#undef b
737
25
}
738
739
int
740
PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
741
24
{
742
24
    if (!PyList_Check(a)) {
743
0
        PyErr_BadInternalCall();
744
0
        return -1;
745
0
    }
746
24
    return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
747
24
}
748
749
static PyObject *
750
list_inplace_repeat(PyListObject *self, Py_ssize_t n)
751
0
{
752
0
    PyObject **items;
753
0
    Py_ssize_t size, i, j, p;
754
755
756
0
    size = PyList_GET_SIZE(self);
757
0
    if (size == 0 || n == 1) {
758
0
        Py_INCREF(self);
759
0
        return (PyObject *)self;
760
0
    }
761
762
0
    if (n < 1) {
763
0
        (void)_list_clear(self);
764
0
        Py_INCREF(self);
765
0
        return (PyObject *)self;
766
0
    }
767
768
0
    if (size > PY_SSIZE_T_MAX / n) {
769
0
        return PyErr_NoMemory();
770
0
    }
771
772
0
    if (list_resize(self, size*n) < 0)
773
0
        return NULL;
774
775
0
    p = size;
776
0
    items = self->ob_item;
777
0
    for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
778
0
        for (j = 0; j < size; j++) {
779
0
            PyObject *o = items[j];
780
0
            Py_INCREF(o);
781
0
            items[p++] = o;
782
0
        }
783
0
    }
784
0
    Py_INCREF(self);
785
0
    return (PyObject *)self;
786
0
}
787
788
static int
789
list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v)
790
153
{
791
153
    if (!valid_index(i, Py_SIZE(a))) {
792
0
        PyErr_SetString(PyExc_IndexError,
793
0
                        "list assignment index out of range");
794
0
        return -1;
795
0
    }
796
153
    if (v == NULL)
797
6
        return list_ass_slice(a, i, i+1, v);
798
147
    Py_INCREF(v);
799
147
    Py_SETREF(a->ob_item[i], v);
800
147
    return 0;
801
153
}
802
803
/*[clinic input]
804
list.insert
805
806
    index: Py_ssize_t
807
    object: object
808
    /
809
810
Insert object before index.
811
[clinic start generated code]*/
812
813
static PyObject *
814
list_insert_impl(PyListObject *self, Py_ssize_t index, PyObject *object)
815
/*[clinic end generated code: output=7f35e32f60c8cb78 input=858514cf894c7eab]*/
816
0
{
817
0
    if (ins1(self, index, object) == 0)
818
0
        Py_RETURN_NONE;
819
0
    return NULL;
820
0
}
821
822
/*[clinic input]
823
list.clear
824
825
Remove all items from list.
826
[clinic start generated code]*/
827
828
static PyObject *
829
list_clear_impl(PyListObject *self)
830
/*[clinic end generated code: output=67a1896c01f74362 input=ca3c1646856742f6]*/
831
0
{
832
0
    _list_clear(self);
833
0
    Py_RETURN_NONE;
834
0
}
835
836
/*[clinic input]
837
list.copy
838
839
Return a shallow copy of the list.
840
[clinic start generated code]*/
841
842
static PyObject *
843
list_copy_impl(PyListObject *self)
844
/*[clinic end generated code: output=ec6b72d6209d418e input=6453ab159e84771f]*/
845
0
{
846
0
    return list_slice(self, 0, Py_SIZE(self));
847
0
}
848
849
/*[clinic input]
850
list.append
851
852
     object: object
853
     /
854
855
Append object to the end of the list.
856
[clinic start generated code]*/
857
858
static PyObject *
859
list_append(PyListObject *self, PyObject *object)
860
/*[clinic end generated code: output=7c096003a29c0eae input=43a3fe48a7066e91]*/
861
1.99k
{
862
1.99k
    if (app1(self, object) == 0)
863
1.99k
        Py_RETURN_NONE;
864
0
    return NULL;
865
1.99k
}
866
867
/*[clinic input]
868
list.extend
869
870
     iterable: object
871
     /
872
873
Extend list by appending elements from the iterable.
874
[clinic start generated code]*/
875
876
static PyObject *
877
list_extend(PyListObject *self, PyObject *iterable)
878
/*[clinic end generated code: output=630fb3bca0c8e789 input=9ec5ba3a81be3a4d]*/
879
1.78k
{
880
1.78k
    PyObject *it;      /* iter(v) */
881
1.78k
    Py_ssize_t m;                  /* size of self */
882
1.78k
    Py_ssize_t n;                  /* guess for size of iterable */
883
1.78k
    Py_ssize_t mn;                 /* m + n */
884
1.78k
    Py_ssize_t i;
885
1.78k
    PyObject *(*iternext)(PyObject *);
886
887
    /* Special cases:
888
       1) lists and tuples which can use PySequence_Fast ops
889
       2) extending self to self requires making a copy first
890
    */
891
1.78k
    if (PyList_CheckExact(iterable) || PyTuple_CheckExact(iterable) ||
892
1.78k
                (PyObject *)self == iterable) {
893
1.21k
        PyObject **src, **dest;
894
1.21k
        iterable = PySequence_Fast(iterable, "argument must be iterable");
895
1.21k
        if (!iterable)
896
0
            return NULL;
897
1.21k
        n = PySequence_Fast_GET_SIZE(iterable);
898
1.21k
        if (n == 0) {
899
            /* short circuit when iterable is empty */
900
250
            Py_DECREF(iterable);
901
250
            Py_RETURN_NONE;
902
250
        }
903
960
        m = Py_SIZE(self);
904
        /* It should not be possible to allocate a list large enough to cause
905
        an overflow on any relevant platform */
906
960
        assert(m < PY_SSIZE_T_MAX - n);
907
960
        if (list_resize(self, m + n) < 0) {
908
0
            Py_DECREF(iterable);
909
0
            return NULL;
910
0
        }
911
        /* note that we may still have self == iterable here for the
912
         * situation a.extend(a), but the following code works
913
         * in that case too.  Just make sure to resize self
914
         * before calling PySequence_Fast_ITEMS.
915
         */
916
        /* populate the end of self with iterable's items */
917
960
        src = PySequence_Fast_ITEMS(iterable);
918
960
        dest = self->ob_item + m;
919
12.1k
        for (i = 0; i < n; i++) {
920
11.1k
            PyObject *o = src[i];
921
11.1k
            Py_INCREF(o);
922
11.1k
            dest[i] = o;
923
11.1k
        }
924
960
        Py_DECREF(iterable);
925
960
        Py_RETURN_NONE;
926
960
    }
927
928
573
    it = PyObject_GetIter(iterable);
929
573
    if (it == NULL)
930
0
        return NULL;
931
573
    iternext = *it->ob_type->tp_iternext;
932
933
    /* Guess a result list size. */
934
573
    n = PyObject_LengthHint(iterable, 8);
935
573
    if (n < 0) {
936
0
        Py_DECREF(it);
937
0
        return NULL;
938
0
    }
939
573
    m = Py_SIZE(self);
940
573
    if (m > PY_SSIZE_T_MAX - n) {
941
        /* m + n overflowed; on the chance that n lied, and there really
942
         * is enough room, ignore it.  If n was telling the truth, we'll
943
         * eventually run out of memory during the loop.
944
         */
945
0
    }
946
573
    else {
947
573
        mn = m + n;
948
        /* Make room. */
949
573
        if (list_resize(self, mn) < 0)
950
0
            goto error;
951
        /* Make the list sane again. */
952
573
        Py_SIZE(self) = m;
953
573
    }
954
955
    /* Run iterator to exhaustion. */
956
4.40k
    for (;;) {
957
4.40k
        PyObject *item = iternext(it);
958
4.40k
        if (item == NULL) {
959
573
            if (PyErr_Occurred()) {
960
89
                if (PyErr_ExceptionMatches(PyExc_StopIteration))
961
89
                    PyErr_Clear();
962
0
                else
963
0
                    goto error;
964
89
            }
965
573
            break;
966
573
        }
967
3.83k
        if (Py_SIZE(self) < self->allocated) {
968
            /* steals ref */
969
3.81k
            PyList_SET_ITEM(self, Py_SIZE(self), item);
970
3.81k
            ++Py_SIZE(self);
971
3.81k
        }
972
14
        else {
973
14
            int status = app1(self, item);
974
14
            Py_DECREF(item);  /* append creates a new ref */
975
14
            if (status < 0)
976
0
                goto error;
977
14
        }
978
3.83k
    }
979
980
    /* Cut back result list if initial guess was too large. */
981
573
    if (Py_SIZE(self) < self->allocated) {
982
554
        if (list_resize(self, Py_SIZE(self)) < 0)
983
0
            goto error;
984
554
    }
985
986
573
    Py_DECREF(it);
987
573
    Py_RETURN_NONE;
988
989
0
  error:
990
0
    Py_DECREF(it);
991
0
    return NULL;
992
573
}
993
994
PyObject *
995
_PyList_Extend(PyListObject *self, PyObject *iterable)
996
1.44k
{
997
1.44k
    return list_extend(self, iterable);
998
1.44k
}
999
1000
static PyObject *
1001
list_inplace_concat(PyListObject *self, PyObject *other)
1002
26
{
1003
26
    PyObject *result;
1004
1005
26
    result = list_extend(self, other);
1006
26
    if (result == NULL)
1007
0
        return result;
1008
26
    Py_DECREF(result);
1009
26
    Py_INCREF(self);
1010
26
    return (PyObject *)self;
1011
26
}
1012
1013
/*[clinic input]
1014
list.pop
1015
1016
    index: Py_ssize_t = -1
1017
    /
1018
1019
Remove and return item at index (default last).
1020
1021
Raises IndexError if list is empty or index is out of range.
1022
[clinic start generated code]*/
1023
1024
static PyObject *
1025
list_pop_impl(PyListObject *self, Py_ssize_t index)
1026
/*[clinic end generated code: output=6bd69dcb3f17eca8 input=b83675976f329e6f]*/
1027
0
{
1028
0
    PyObject *v;
1029
0
    int status;
1030
1031
0
    if (Py_SIZE(self) == 0) {
1032
        /* Special-case most common failure cause */
1033
0
        PyErr_SetString(PyExc_IndexError, "pop from empty list");
1034
0
        return NULL;
1035
0
    }
1036
0
    if (index < 0)
1037
0
        index += Py_SIZE(self);
1038
0
    if (!valid_index(index, Py_SIZE(self))) {
1039
0
        PyErr_SetString(PyExc_IndexError, "pop index out of range");
1040
0
        return NULL;
1041
0
    }
1042
0
    v = self->ob_item[index];
1043
0
    if (index == Py_SIZE(self) - 1) {
1044
0
        status = list_resize(self, Py_SIZE(self) - 1);
1045
0
        if (status >= 0)
1046
0
            return v; /* and v now owns the reference the list had */
1047
0
        else
1048
0
            return NULL;
1049
0
    }
1050
0
    Py_INCREF(v);
1051
0
    status = list_ass_slice(self, index, index+1, (PyObject *)NULL);
1052
0
    if (status < 0) {
1053
0
        Py_DECREF(v);
1054
0
        return NULL;
1055
0
    }
1056
0
    return v;
1057
0
}
1058
1059
/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
1060
static void
1061
reverse_slice(PyObject **lo, PyObject **hi)
1062
127
{
1063
127
    assert(lo && hi);
1064
1065
127
    --hi;
1066
320
    while (lo < hi) {
1067
193
        PyObject *t = *lo;
1068
193
        *lo = *hi;
1069
193
        *hi = t;
1070
193
        ++lo;
1071
193
        --hi;
1072
193
    }
1073
127
}
1074
1075
/* Lots of code for an adaptive, stable, natural mergesort.  There are many
1076
 * pieces to this algorithm; read listsort.txt for overviews and details.
1077
 */
1078
1079
/* A sortslice contains a pointer to an array of keys and a pointer to
1080
 * an array of corresponding values.  In other words, keys[i]
1081
 * corresponds with values[i].  If values == NULL, then the keys are
1082
 * also the values.
1083
 *
1084
 * Several convenience routines are provided here, so that keys and
1085
 * values are always moved in sync.
1086
 */
1087
1088
typedef struct {
1089
    PyObject **keys;
1090
    PyObject **values;
1091
} sortslice;
1092
1093
Py_LOCAL_INLINE(void)
1094
sortslice_copy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j)
1095
14
{
1096
14
    s1->keys[i] = s2->keys[j];
1097
14
    if (s1->values != NULL)
1098
0
        s1->values[i] = s2->values[j];
1099
14
}
1100
1101
Py_LOCAL_INLINE(void)
1102
sortslice_copy_incr(sortslice *dst, sortslice *src)
1103
2.61k
{
1104
2.61k
    *dst->keys++ = *src->keys++;
1105
2.61k
    if (dst->values != NULL)
1106
0
        *dst->values++ = *src->values++;
1107
2.61k
}
1108
1109
Py_LOCAL_INLINE(void)
1110
sortslice_copy_decr(sortslice *dst, sortslice *src)
1111
6.27k
{
1112
6.27k
    *dst->keys-- = *src->keys--;
1113
6.27k
    if (dst->values != NULL)
1114
0
        *dst->values-- = *src->values--;
1115
6.27k
}
1116
1117
1118
Py_LOCAL_INLINE(void)
1119
sortslice_memcpy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
1120
                 Py_ssize_t n)
1121
266
{
1122
266
    memcpy(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
1123
266
    if (s1->values != NULL)
1124
0
        memcpy(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
1125
266
}
1126
1127
Py_LOCAL_INLINE(void)
1128
sortslice_memmove(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
1129
                  Py_ssize_t n)
1130
154
{
1131
154
    memmove(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
1132
154
    if (s1->values != NULL)
1133
0
        memmove(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
1134
154
}
1135
1136
Py_LOCAL_INLINE(void)
1137
sortslice_advance(sortslice *slice, Py_ssize_t n)
1138
858
{
1139
858
    slice->keys += n;
1140
858
    if (slice->values != NULL)
1141
1
        slice->values += n;
1142
858
}
1143
1144
/* Comparison function: ms->key_compare, which is set at run-time in
1145
 * listsort_impl to optimize for various special cases.
1146
 * Returns -1 on error, 1 if x < y, 0 if x >= y.
1147
 */
1148
1149
29.0k
#define ISLT(X, Y) (*(ms->key_compare))(X, Y, ms)
1150
1151
/* Compare X to Y via "<".  Goto "fail" if the comparison raises an
1152
   error.  Else "k" is set to true iff X<Y, and an "if (k)" block is
1153
   started.  It makes more sense in context <wink>.  X and Y are PyObject*s.
1154
*/
1155
20.6k
#define IFLT(X, Y) if ((k = ISLT(X, Y)) < 0) goto fail;  \
1156
20.6k
           if (k)
1157
1158
/* The maximum number of entries in a MergeState's pending-runs stack.
1159
 * This is enough to sort arrays of size up to about
1160
 *     32 * phi ** MAX_MERGE_PENDING
1161
 * where phi ~= 1.618.  85 is ridiculouslylarge enough, good for an array
1162
 * with 2**64 elements.
1163
 */
1164
#define MAX_MERGE_PENDING 85
1165
1166
/* When we get into galloping mode, we stay there until both runs win less
1167
 * often than MIN_GALLOP consecutive times.  See listsort.txt for more info.
1168
 */
1169
984
#define MIN_GALLOP 7
1170
1171
/* Avoid malloc for small temp arrays. */
1172
456
#define MERGESTATE_TEMP_SIZE 256
1173
1174
/* One MergeState exists on the stack per invocation of mergesort.  It's just
1175
 * a convenient way to pass state around among the helper functions.
1176
 */
1177
struct s_slice {
1178
    sortslice base;
1179
    Py_ssize_t len;
1180
};
1181
1182
typedef struct s_MergeState MergeState;
1183
struct s_MergeState {
1184
    /* This controls when we get *into* galloping mode.  It's initialized
1185
     * to MIN_GALLOP.  merge_lo and merge_hi tend to nudge it higher for
1186
     * random data, and lower for highly structured data.
1187
     */
1188
    Py_ssize_t min_gallop;
1189
1190
    /* 'a' is temp storage to help with merges.  It contains room for
1191
     * alloced entries.
1192
     */
1193
    sortslice a;        /* may point to temparray below */
1194
    Py_ssize_t alloced;
1195
1196
    /* A stack of n pending runs yet to be merged.  Run #i starts at
1197
     * address base[i] and extends for len[i] elements.  It's always
1198
     * true (so long as the indices are in bounds) that
1199
     *
1200
     *     pending[i].base + pending[i].len == pending[i+1].base
1201
     *
1202
     * so we could cut the storage for this, but it's a minor amount,
1203
     * and keeping all the info explicit simplifies the code.
1204
     */
1205
    int n;
1206
    struct s_slice pending[MAX_MERGE_PENDING];
1207
1208
    /* 'a' points to this when possible, rather than muck with malloc. */
1209
    PyObject *temparray[MERGESTATE_TEMP_SIZE];
1210
1211
    /* This is the function we will use to compare two keys,
1212
     * even when none of our special cases apply and we have to use
1213
     * safe_object_compare. */
1214
    int (*key_compare)(PyObject *, PyObject *, MergeState *);
1215
1216
    /* This function is used by unsafe_object_compare to optimize comparisons
1217
     * when we know our list is type-homogeneous but we can't assume anything else.
1218
     * In the pre-sort check it is set equal to key->ob_type->tp_richcompare */
1219
    PyObject *(*key_richcompare)(PyObject *, PyObject *, int);
1220
1221
    /* This function is used by unsafe_tuple_compare to compare the first elements
1222
     * of tuples. It may be set to safe_object_compare, but the idea is that hopefully
1223
     * we can assume more, and use one of the special-case compares. */
1224
    int (*tuple_elem_compare)(PyObject *, PyObject *, MergeState *);
1225
};
1226
1227
/* binarysort is the best method for sorting small arrays: it does
1228
   few compares, but can do data movement quadratic in the number of
1229
   elements.
1230
   [lo, hi) is a contiguous slice of a list, and is sorted via
1231
   binary insertion.  This sort is stable.
1232
   On entry, must have lo <= start <= hi, and that [lo, start) is already
1233
   sorted (pass start == lo if you don't know!).
1234
   If islt() complains return -1, else 0.
1235
   Even in case of error, the output slice will be some permutation of
1236
   the input (nothing is lost or duplicated).
1237
*/
1238
static int
1239
binarysort(MergeState *ms, sortslice lo, PyObject **hi, PyObject **start)
1240
167
{
1241
167
    Py_ssize_t k;
1242
167
    PyObject **l, **p, **r;
1243
167
    PyObject *pivot;
1244
1245
167
    assert(lo.keys <= start && start <= hi);
1246
    /* assert [lo, start) is sorted */
1247
167
    if (lo.keys == start)
1248
0
        ++start;
1249
4.72k
    for (; start < hi; ++start) {
1250
        /* set l to where *start belongs */
1251
4.55k
        l = lo.keys;
1252
4.55k
        r = start;
1253
4.55k
        pivot = *r;
1254
        /* Invariants:
1255
         * pivot >= all in [lo, l).
1256
         * pivot  < all in [r, start).
1257
         * The second is vacuously true at the start.
1258
         */
1259
4.55k
        assert(l < r);
1260
18.3k
        do {
1261
18.3k
            p = l + ((r - l) >> 1);
1262
18.3k
            IFLT(pivot, *p)
1263
9.33k
                r = p;
1264
9.05k
            else
1265
9.05k
                l = p+1;
1266
18.3k
        } while (l < r);
1267
4.55k
        assert(l == r);
1268
        /* The invariants still hold, so pivot >= all in [lo, l) and
1269
           pivot < all in [l, start), so pivot belongs at l.  Note
1270
           that if there are elements equal to pivot, l points to the
1271
           first slot after them -- that's why this sort is stable.
1272
           Slide over to make room.
1273
           Caution: using memmove is much slower under MSVC 5;
1274
           we're not usually moving many slots. */
1275
40.1k
        for (p = start; p > l; --p)
1276
35.5k
            *p = *(p-1);
1277
4.55k
        *l = pivot;
1278
4.55k
        if (lo.values != NULL) {
1279
0
            Py_ssize_t offset = lo.values - lo.keys;
1280
0
            p = start + offset;
1281
0
            pivot = *p;
1282
0
            l += offset;
1283
0
            for (p = start + offset; p > l; --p)
1284
0
                *p = *(p-1);
1285
0
            *l = pivot;
1286
0
        }
1287
4.55k
    }
1288
167
    return 0;
1289
1290
0
 fail:
1291
0
    return -1;
1292
167
}
1293
1294
/*
1295
Return the length of the run beginning at lo, in the slice [lo, hi).  lo < hi
1296
is required on entry.  "A run" is the longest ascending sequence, with
1297
1298
    lo[0] <= lo[1] <= lo[2] <= ...
1299
1300
or the longest descending sequence, with
1301
1302
    lo[0] > lo[1] > lo[2] > ...
1303
1304
Boolean *descending is set to 0 in the former case, or to 1 in the latter.
1305
For its intended use in a stable mergesort, the strictness of the defn of
1306
"descending" is needed so that the caller can safely reverse a descending
1307
sequence without violating stability (strict > ensures there are no equal
1308
elements to get out of order).
1309
1310
Returns -1 in case of error.
1311
*/
1312
static Py_ssize_t
1313
count_run(MergeState *ms, PyObject **lo, PyObject **hi, int *descending)
1314
172
{
1315
172
    Py_ssize_t k;
1316
172
    Py_ssize_t n;
1317
1318
172
    assert(lo < hi);
1319
172
    *descending = 0;
1320
172
    ++lo;
1321
172
    if (lo == hi)
1322
0
        return 1;
1323
1324
172
    n = 2;
1325
172
    IFLT(*lo, *(lo-1)) {
1326
121
        *descending = 1;
1327
186
        for (lo = lo+1; lo < hi; ++lo, ++n) {
1328
182
            IFLT(*lo, *(lo-1))
1329
65
                ;
1330
117
            else
1331
117
                break;
1332
182
        }
1333
121
    }
1334
51
    else {
1335
68
        for (lo = lo+1; lo < hi; ++lo, ++n) {
1336
67
            IFLT(*lo, *(lo-1))
1337
50
                break;
1338
67
        }
1339
51
    }
1340
1341
172
    return n;
1342
0
fail:
1343
0
    return -1;
1344
172
}
1345
1346
/*
1347
Locate the proper position of key in a sorted vector; if the vector contains
1348
an element equal to key, return the position immediately to the left of
1349
the leftmost equal element.  [gallop_right() does the same except returns
1350
the position to the right of the rightmost equal element (if any).]
1351
1352
"a" is a sorted vector with n elements, starting at a[0].  n must be > 0.
1353
1354
"hint" is an index at which to begin the search, 0 <= hint < n.  The closer
1355
hint is to the final result, the faster this runs.
1356
1357
The return value is the int k in 0..n such that
1358
1359
    a[k-1] < key <= a[k]
1360
1361
pretending that *(a-1) is minus infinity and a[n] is plus infinity.  IOW,
1362
key belongs at index k; or, IOW, the first k elements of a should precede
1363
key, and the last n-k should follow key.
1364
1365
Returns -1 on error.  See listsort.txt for info on the method.
1366
*/
1367
static Py_ssize_t
1368
gallop_left(MergeState *ms, PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
1369
294
{
1370
294
    Py_ssize_t ofs;
1371
294
    Py_ssize_t lastofs;
1372
294
    Py_ssize_t k;
1373
1374
294
    assert(key && a && n > 0 && hint >= 0 && hint < n);
1375
1376
294
    a += hint;
1377
294
    lastofs = 0;
1378
294
    ofs = 1;
1379
294
    IFLT(*a, key) {
1380
        /* a[hint] < key -- gallop right, until
1381
         * a[hint + lastofs] < key <= a[hint + ofs]
1382
         */
1383
140
        const Py_ssize_t maxofs = n - hint;             /* &a[n-1] is highest */
1384
182
        while (ofs < maxofs) {
1385
84
            IFLT(a[ofs], key) {
1386
42
                lastofs = ofs;
1387
42
                assert(ofs <= (PY_SSIZE_T_MAX - 1) / 2);
1388
42
                ofs = (ofs << 1) + 1;
1389
42
            }
1390
42
            else                /* key <= a[hint + ofs] */
1391
42
                break;
1392
84
        }
1393
140
        if (ofs > maxofs)
1394
0
            ofs = maxofs;
1395
        /* Translate back to offsets relative to &a[0]. */
1396
140
        lastofs += hint;
1397
140
        ofs += hint;
1398
140
    }
1399
154
    else {
1400
        /* key <= a[hint] -- gallop left, until
1401
         * a[hint - ofs] < key <= a[hint - lastofs]
1402
         */
1403
154
        const Py_ssize_t maxofs = hint + 1;             /* &a[0] is lowest */
1404
378
        while (ofs < maxofs) {
1405
336
            IFLT(*(a-ofs), key)
1406
112
                break;
1407
            /* key <= a[hint - ofs] */
1408
224
            lastofs = ofs;
1409
224
            assert(ofs <= (PY_SSIZE_T_MAX - 1) / 2);
1410
224
            ofs = (ofs << 1) + 1;
1411
224
        }
1412
154
        if (ofs > maxofs)
1413
28
            ofs = maxofs;
1414
        /* Translate back to positive offsets relative to &a[0]. */
1415
154
        k = lastofs;
1416
154
        lastofs = hint - ofs;
1417
154
        ofs = hint - k;
1418
154
    }
1419
294
    a -= hint;
1420
1421
294
    assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1422
    /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1423
     * right of lastofs but no farther right than ofs.  Do a binary
1424
     * search, with invariant a[lastofs-1] < key <= a[ofs].
1425
     */
1426
294
    ++lastofs;
1427
560
    while (lastofs < ofs) {
1428
266
        Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
1429
1430
266
        IFLT(a[m], key)
1431
84
            lastofs = m+1;              /* a[m] < key */
1432
182
        else
1433
182
            ofs = m;                    /* key <= a[m] */
1434
266
    }
1435
294
    assert(lastofs == ofs);             /* so a[ofs-1] < key <= a[ofs] */
1436
294
    return ofs;
1437
1438
0
fail:
1439
0
    return -1;
1440
294
}
1441
1442
/*
1443
Exactly like gallop_left(), except that if key already exists in a[0:n],
1444
finds the position immediately to the right of the rightmost equal value.
1445
1446
The return value is the int k in 0..n such that
1447
1448
    a[k-1] <= key < a[k]
1449
1450
or -1 if error.
1451
1452
The code duplication is massive, but this is enough different given that
1453
we're sticking to "<" comparisons that it's much harder to follow if
1454
written as one routine with yet another "left or right?" flag.
1455
*/
1456
static Py_ssize_t
1457
gallop_right(MergeState *ms, PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
1458
308
{
1459
308
    Py_ssize_t ofs;
1460
308
    Py_ssize_t lastofs;
1461
308
    Py_ssize_t k;
1462
1463
308
    assert(key && a && n > 0 && hint >= 0 && hint < n);
1464
1465
308
    a += hint;
1466
308
    lastofs = 0;
1467
308
    ofs = 1;
1468
308
    IFLT(key, *a) {
1469
        /* key < a[hint] -- gallop left, until
1470
         * a[hint - ofs] <= key < a[hint - lastofs]
1471
         */
1472
238
        const Py_ssize_t maxofs = hint + 1;             /* &a[0] is lowest */
1473
378
        while (ofs < maxofs) {
1474
238
            IFLT(key, *(a-ofs)) {
1475
140
                lastofs = ofs;
1476
140
                assert(ofs <= (PY_SSIZE_T_MAX - 1) / 2);
1477
140
                ofs = (ofs << 1) + 1;
1478
140
            }
1479
98
            else                /* a[hint - ofs] <= key */
1480
98
                break;
1481
238
        }
1482
238
        if (ofs > maxofs)
1483
0
            ofs = maxofs;
1484
        /* Translate back to positive offsets relative to &a[0]. */
1485
238
        k = lastofs;
1486
238
        lastofs = hint - ofs;
1487
238
        ofs = hint - k;
1488
238
    }
1489
70
    else {
1490
        /* a[hint] <= key -- gallop right, until
1491
         * a[hint + lastofs] <= key < a[hint + ofs]
1492
        */
1493
70
        const Py_ssize_t maxofs = n - hint;             /* &a[n-1] is highest */
1494
126
        while (ofs < maxofs) {
1495
84
            IFLT(key, a[ofs])
1496
28
                break;
1497
            /* a[hint + ofs] <= key */
1498
56
            lastofs = ofs;
1499
56
            assert(ofs <= (PY_SSIZE_T_MAX - 1) / 2);
1500
56
            ofs = (ofs << 1) + 1;
1501
56
        }
1502
70
        if (ofs > maxofs)
1503
0
            ofs = maxofs;
1504
        /* Translate back to offsets relative to &a[0]. */
1505
70
        lastofs += hint;
1506
70
        ofs += hint;
1507
70
    }
1508
308
    a -= hint;
1509
1510
308
    assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1511
    /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1512
     * right of lastofs but no farther right than ofs.  Do a binary
1513
     * search, with invariant a[lastofs-1] <= key < a[ofs].
1514
     */
1515
308
    ++lastofs;
1516
504
    while (lastofs < ofs) {
1517
196
        Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
1518
1519
196
        IFLT(key, a[m])
1520
84
            ofs = m;                    /* key < a[m] */
1521
112
        else
1522
112
            lastofs = m+1;              /* a[m] <= key */
1523
196
    }
1524
308
    assert(lastofs == ofs);             /* so a[ofs-1] <= key < a[ofs] */
1525
308
    return ofs;
1526
1527
0
fail:
1528
0
    return -1;
1529
308
}
1530
1531
/* Conceptually a MergeState's constructor. */
1532
static void
1533
merge_init(MergeState *ms, Py_ssize_t list_size, int has_keyfunc)
1534
452
{
1535
452
    assert(ms != NULL);
1536
452
    if (has_keyfunc) {
1537
        /* The temporary space for merging will need at most half the list
1538
         * size rounded up.  Use the minimum possible space so we can use the
1539
         * rest of temparray for other things.  In particular, if there is
1540
         * enough extra space, listsort() will use it to store the keys.
1541
         */
1542
2
        ms->alloced = (list_size + 1) / 2;
1543
1544
        /* ms->alloced describes how many keys will be stored at
1545
           ms->temparray, but we also need to store the values.  Hence,
1546
           ms->alloced is capped at half of MERGESTATE_TEMP_SIZE. */
1547
2
        if (MERGESTATE_TEMP_SIZE / 2 < ms->alloced)
1548
0
            ms->alloced = MERGESTATE_TEMP_SIZE / 2;
1549
2
        ms->a.values = &ms->temparray[ms->alloced];
1550
2
    }
1551
450
    else {
1552
450
        ms->alloced = MERGESTATE_TEMP_SIZE;
1553
450
        ms->a.values = NULL;
1554
450
    }
1555
452
    ms->a.keys = ms->temparray;
1556
452
    ms->n = 0;
1557
452
    ms->min_gallop = MIN_GALLOP;
1558
452
}
1559
1560
/* Free all the temp memory owned by the MergeState.  This must be called
1561
 * when you're done with a MergeState, and may be called before then if
1562
 * you want to free the temp memory early.
1563
 */
1564
static void
1565
merge_freemem(MergeState *ms)
1566
452
{
1567
452
    assert(ms != NULL);
1568
452
    if (ms->a.keys != ms->temparray)
1569
0
        PyMem_Free(ms->a.keys);
1570
452
}
1571
1572
/* Ensure enough temp memory for 'need' array slots is available.
1573
 * Returns 0 on success and -1 if the memory can't be gotten.
1574
 */
1575
static int
1576
merge_getmem(MergeState *ms, Py_ssize_t need)
1577
0
{
1578
0
    int multiplier;
1579
1580
0
    assert(ms != NULL);
1581
0
    if (need <= ms->alloced)
1582
0
        return 0;
1583
1584
0
    multiplier = ms->a.values != NULL ? 2 : 1;
1585
1586
    /* Don't realloc!  That can cost cycles to copy the old data, but
1587
     * we don't care what's in the block.
1588
     */
1589
0
    merge_freemem(ms);
1590
0
    if ((size_t)need > PY_SSIZE_T_MAX / sizeof(PyObject *) / multiplier) {
1591
0
        PyErr_NoMemory();
1592
0
        return -1;
1593
0
    }
1594
0
    ms->a.keys = (PyObject **)PyMem_Malloc(multiplier * need
1595
0
                                          * sizeof(PyObject *));
1596
0
    if (ms->a.keys != NULL) {
1597
0
        ms->alloced = need;
1598
0
        if (ms->a.values != NULL)
1599
0
            ms->a.values = &ms->a.keys[need];
1600
0
        return 0;
1601
0
    }
1602
0
    PyErr_NoMemory();
1603
0
    return -1;
1604
0
}
1605
98
#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 :   \
1606
98
                                merge_getmem(MS, NEED))
1607
1608
/* Merge the na elements starting at ssa with the nb elements starting at
1609
 * ssb.keys = ssa.keys + na in a stable way, in-place.  na and nb must be > 0.
1610
 * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
1611
 * should have na <= nb.  See listsort.txt for more info.  Return 0 if
1612
 * successful, -1 if error.
1613
 */
1614
static Py_ssize_t
1615
merge_lo(MergeState *ms, sortslice ssa, Py_ssize_t na,
1616
         sortslice ssb, Py_ssize_t nb)
1617
42
{
1618
42
    Py_ssize_t k;
1619
42
    sortslice dest;
1620
42
    int result = -1;            /* guilty until proved innocent */
1621
42
    Py_ssize_t min_gallop;
1622
1623
42
    assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
1624
42
    assert(ssa.keys + na == ssb.keys);
1625
42
    if (MERGE_GETMEM(ms, na) < 0)
1626
0
        return -1;
1627
42
    sortslice_memcpy(&ms->a, 0, &ssa, 0, na);
1628
42
    dest = ssa;
1629
42
    ssa = ms->a;
1630
1631
42
    sortslice_copy_incr(&dest, &ssb);
1632
42
    --nb;
1633
42
    if (nb == 0)
1634
0
        goto Succeed;
1635
42
    if (na == 1)
1636
0
        goto CopyB;
1637
1638
42
    min_gallop = ms->min_gallop;
1639
98
    for (;;) {
1640
98
        Py_ssize_t acount = 0;          /* # of times A won in a row */
1641
98
        Py_ssize_t bcount = 0;          /* # of times B won in a row */
1642
1643
        /* Do the straightforward thing until (if ever) one run
1644
         * appears to win consistently.
1645
         */
1646
2.45k
        for (;;) {
1647
2.45k
            assert(na > 1 && nb > 0);
1648
2.45k
            k = ISLT(ssb.keys[0], ssa.keys[0]);
1649
2.45k
            if (k) {
1650
1.35k
                if (k < 0)
1651
0
                    goto Fail;
1652
1.35k
                sortslice_copy_incr(&dest, &ssb);
1653
1.35k
                ++bcount;
1654
1.35k
                acount = 0;
1655
1.35k
                --nb;
1656
1.35k
                if (nb == 0)
1657
28
                    goto Succeed;
1658
1.33k
                if (bcount >= min_gallop)
1659
56
                    break;
1660
1.33k
            }
1661
1.09k
            else {
1662
1.09k
                sortslice_copy_incr(&dest, &ssa);
1663
1.09k
                ++acount;
1664
1.09k
                bcount = 0;
1665
1.09k
                --na;
1666
1.09k
                if (na == 1)
1667
0
                    goto CopyB;
1668
1.09k
                if (acount >= min_gallop)
1669
14
                    break;
1670
1.09k
            }
1671
2.45k
        }
1672
1673
        /* One run is winning so consistently that galloping may
1674
         * be a huge win.  So try that, and continue galloping until
1675
         * (if ever) neither run appears to be winning consistently
1676
         * anymore.
1677
         */
1678
70
        ++min_gallop;
1679
70
        do {
1680
70
            assert(na > 1 && nb > 0);
1681
70
            min_gallop -= min_gallop > 1;
1682
70
            ms->min_gallop = min_gallop;
1683
70
            k = gallop_right(ms, ssb.keys[0], ssa.keys, na, 0);
1684
70
            acount = k;
1685
70
            if (k) {
1686
0
                if (k < 0)
1687
0
                    goto Fail;
1688
0
                sortslice_memcpy(&dest, 0, &ssa, 0, k);
1689
0
                sortslice_advance(&dest, k);
1690
0
                sortslice_advance(&ssa, k);
1691
0
                na -= k;
1692
0
                if (na == 1)
1693
0
                    goto CopyB;
1694
                /* na==0 is impossible now if the comparison
1695
                 * function is consistent, but we can't assume
1696
                 * that it is.
1697
                 */
1698
0
                if (na == 0)
1699
0
                    goto Succeed;
1700
0
            }
1701
70
            sortslice_copy_incr(&dest, &ssb);
1702
70
            --nb;
1703
70
            if (nb == 0)
1704
14
                goto Succeed;
1705
1706
56
            k = gallop_left(ms, ssa.keys[0], ssb.keys, nb, 0);
1707
56
            bcount = k;
1708
56
            if (k) {
1709
42
                if (k < 0)
1710
0
                    goto Fail;
1711
42
                sortslice_memmove(&dest, 0, &ssb, 0, k);
1712
42
                sortslice_advance(&dest, k);
1713
42
                sortslice_advance(&ssb, k);
1714
42
                nb -= k;
1715
42
                if (nb == 0)
1716
0
                    goto Succeed;
1717
42
            }
1718
56
            sortslice_copy_incr(&dest, &ssa);
1719
56
            --na;
1720
56
            if (na == 1)
1721
0
                goto CopyB;
1722
56
        } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
1723
56
        ++min_gallop;           /* penalize it for leaving galloping mode */
1724
56
        ms->min_gallop = min_gallop;
1725
56
    }
1726
42
Succeed:
1727
42
    result = 0;
1728
42
Fail:
1729
42
    if (na)
1730
42
        sortslice_memcpy(&dest, 0, &ssa, 0, na);
1731
42
    return result;
1732
0
CopyB:
1733
0
    assert(na == 1 && nb > 0);
1734
    /* The last element of ssa belongs at the end of the merge. */
1735
0
    sortslice_memmove(&dest, 0, &ssb, 0, nb);
1736
0
    sortslice_copy(&dest, nb, &ssa, 0);
1737
0
    return 0;
1738
42
}
1739
1740
/* Merge the na elements starting at pa with the nb elements starting at
1741
 * ssb.keys = ssa.keys + na in a stable way, in-place.  na and nb must be > 0.
1742
 * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
1743
 * should have na >= nb.  See listsort.txt for more info.  Return 0 if
1744
 * successful, -1 if error.
1745
 */
1746
static Py_ssize_t
1747
merge_hi(MergeState *ms, sortslice ssa, Py_ssize_t na,
1748
         sortslice ssb, Py_ssize_t nb)
1749
56
{
1750
56
    Py_ssize_t k;
1751
56
    sortslice dest, basea, baseb;
1752
56
    int result = -1;            /* guilty until proved innocent */
1753
56
    Py_ssize_t min_gallop;
1754
1755
56
    assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
1756
56
    assert(ssa.keys + na == ssb.keys);
1757
56
    if (MERGE_GETMEM(ms, nb) < 0)
1758
0
        return -1;
1759
56
    dest = ssb;
1760
56
    sortslice_advance(&dest, nb-1);
1761
56
    sortslice_memcpy(&ms->a, 0, &ssb, 0, nb);
1762
56
    basea = ssa;
1763
56
    baseb = ms->a;
1764
56
    ssb.keys = ms->a.keys + nb - 1;
1765
56
    if (ssb.values != NULL)
1766
0
        ssb.values = ms->a.values + nb - 1;
1767
56
    sortslice_advance(&ssa, na - 1);
1768
1769
56
    sortslice_copy_decr(&dest, &ssa);
1770
56
    --na;
1771
56
    if (na == 0)
1772
0
        goto Succeed;
1773
56
    if (nb == 1)
1774
0
        goto CopyA;
1775
1776
56
    min_gallop = ms->min_gallop;
1777
168
    for (;;) {
1778
168
        Py_ssize_t acount = 0;          /* # of times A won in a row */
1779
168
        Py_ssize_t bcount = 0;          /* # of times B won in a row */
1780
1781
        /* Do the straightforward thing until (if ever) one run
1782
         * appears to win consistently.
1783
         */
1784
5.95k
        for (;;) {
1785
5.95k
            assert(na > 0 && nb > 1);
1786
5.95k
            k = ISLT(ssb.keys[0], ssa.keys[0]);
1787
5.95k
            if (k) {
1788
4.13k
                if (k < 0)
1789
0
                    goto Fail;
1790
4.13k
                sortslice_copy_decr(&dest, &ssa);
1791
4.13k
                ++acount;
1792
4.13k
                bcount = 0;
1793
4.13k
                --na;
1794
4.13k
                if (na == 0)
1795
42
                    goto Succeed;
1796
4.08k
                if (acount >= min_gallop)
1797
98
                    break;
1798
4.08k
            }
1799
1.82k
            else {
1800
1.82k
                sortslice_copy_decr(&dest, &ssb);
1801
1.82k
                ++bcount;
1802
1.82k
                acount = 0;
1803
1.82k
                --nb;
1804
1.82k
                if (nb == 1)
1805
0
                    goto CopyA;
1806
1.82k
                if (bcount >= min_gallop)
1807
28
                    break;
1808
1.82k
            }
1809
5.95k
        }
1810
1811
        /* One run is winning so consistently that galloping may
1812
         * be a huge win.  So try that, and continue galloping until
1813
         * (if ever) neither run appears to be winning consistently
1814
         * anymore.
1815
         */
1816
126
        ++min_gallop;
1817
140
        do {
1818
140
            assert(na > 0 && nb > 1);
1819
140
            min_gallop -= min_gallop > 1;
1820
140
            ms->min_gallop = min_gallop;
1821
140
            k = gallop_right(ms, ssb.keys[0], basea.keys, na, na-1);
1822
140
            if (k < 0)
1823
0
                goto Fail;
1824
140
            k = na - k;
1825
140
            acount = k;
1826
140
            if (k) {
1827
98
                sortslice_advance(&dest, -k);
1828
98
                sortslice_advance(&ssa, -k);
1829
98
                sortslice_memmove(&dest, 1, &ssa, 1, k);
1830
98
                na -= k;
1831
98
                if (na == 0)
1832
0
                    goto Succeed;
1833
98
            }
1834
140
            sortslice_copy_decr(&dest, &ssb);
1835
140
            --nb;
1836
140
            if (nb == 1)
1837
0
                goto CopyA;
1838
1839
140
            k = gallop_left(ms, ssa.keys[0], baseb.keys, nb, nb-1);
1840
140
            if (k < 0)
1841
0
                goto Fail;
1842
140
            k = nb - k;
1843
140
            bcount = k;
1844
140
            if (k) {
1845
84
                sortslice_advance(&dest, -k);
1846
84
                sortslice_advance(&ssb, -k);
1847
84
                sortslice_memcpy(&dest, 1, &ssb, 1, k);
1848
84
                nb -= k;
1849
84
                if (nb == 1)
1850
14
                    goto CopyA;
1851
                /* nb==0 is impossible now if the comparison
1852
                 * function is consistent, but we can't assume
1853
                 * that it is.
1854
                 */
1855
70
                if (nb == 0)
1856
0
                    goto Succeed;
1857
70
            }
1858
126
            sortslice_copy_decr(&dest, &ssa);
1859
126
            --na;
1860
126
            if (na == 0)
1861
0
                goto Succeed;
1862
126
        } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
1863
112
        ++min_gallop;           /* penalize it for leaving galloping mode */
1864
112
        ms->min_gallop = min_gallop;
1865
112
    }
1866
42
Succeed:
1867
42
    result = 0;
1868
42
Fail:
1869
42
    if (nb)
1870
42
        sortslice_memcpy(&dest, -(nb-1), &baseb, 0, nb);
1871
42
    return result;
1872
14
CopyA:
1873
14
    assert(nb == 1 && na > 0);
1874
    /* The first element of ssb belongs at the front of the merge. */
1875
14
    sortslice_memmove(&dest, 1-na, &ssa, 1-na, na);
1876
14
    sortslice_advance(&dest, -na);
1877
14
    sortslice_advance(&ssa, -na);
1878
14
    sortslice_copy(&dest, 0, &ssb, 0);
1879
14
    return 0;
1880
42
}
1881
1882
/* Merge the two runs at stack indices i and i+1.
1883
 * Returns 0 on success, -1 on error.
1884
 */
1885
static Py_ssize_t
1886
merge_at(MergeState *ms, Py_ssize_t i)
1887
98
{
1888
98
    sortslice ssa, ssb;
1889
98
    Py_ssize_t na, nb;
1890
98
    Py_ssize_t k;
1891
1892
98
    assert(ms != NULL);
1893
98
    assert(ms->n >= 2);
1894
98
    assert(i >= 0);
1895
98
    assert(i == ms->n - 2 || i == ms->n - 3);
1896
1897
98
    ssa = ms->pending[i].base;
1898
98
    na = ms->pending[i].len;
1899
98
    ssb = ms->pending[i+1].base;
1900
98
    nb = ms->pending[i+1].len;
1901
98
    assert(na > 0 && nb > 0);
1902
98
    assert(ssa.keys + na == ssb.keys);
1903
1904
    /* Record the length of the combined runs; if i is the 3rd-last
1905
     * run now, also slide over the last run (which isn't involved
1906
     * in this merge).  The current run i+1 goes away in any case.
1907
     */
1908
98
    ms->pending[i].len = na + nb;
1909
98
    if (i == ms->n - 3)
1910
0
        ms->pending[i+1] = ms->pending[i+2];
1911
98
    --ms->n;
1912
1913
    /* Where does b start in a?  Elements in a before that can be
1914
     * ignored (already in place).
1915
     */
1916
98
    k = gallop_right(ms, *ssb.keys, ssa.keys, na, 0);
1917
98
    if (k < 0)
1918
0
        return -1;
1919
98
    sortslice_advance(&ssa, k);
1920
98
    na -= k;
1921
98
    if (na == 0)
1922
0
        return 0;
1923
1924
    /* Where does a end in b?  Elements in b after that can be
1925
     * ignored (already in place).
1926
     */
1927
98
    nb = gallop_left(ms, ssa.keys[na-1], ssb.keys, nb, nb-1);
1928
98
    if (nb <= 0)
1929
0
        return nb;
1930
1931
    /* Merge what remains of the runs, using a temp array with
1932
     * min(na, nb) elements.
1933
     */
1934
98
    if (na <= nb)
1935
42
        return merge_lo(ms, ssa, na, ssb, nb);
1936
56
    else
1937
56
        return merge_hi(ms, ssa, na, ssb, nb);
1938
98
}
1939
1940
/* Examine the stack of runs waiting to be merged, merging adjacent runs
1941
 * until the stack invariants are re-established:
1942
 *
1943
 * 1. len[-3] > len[-2] + len[-1]
1944
 * 2. len[-2] > len[-1]
1945
 *
1946
 * See listsort.txt for more info.
1947
 *
1948
 * Returns 0 on success, -1 on error.
1949
 */
1950
static int
1951
merge_collapse(MergeState *ms)
1952
172
{
1953
172
    struct s_slice *p = ms->pending;
1954
1955
172
    assert(ms);
1956
228
    while (ms->n > 1) {
1957
126
        Py_ssize_t n = ms->n - 2;
1958
126
        if ((n > 0 && p[n-1].len <= p[n].len + p[n+1].len) ||
1959
126
            (n > 1 && p[n-2].len <= p[n-1].len + p[n].len)) {
1960
14
            if (p[n-1].len < p[n+1].len)
1961
0
                --n;
1962
14
            if (merge_at(ms, n) < 0)
1963
0
                return -1;
1964
14
        }
1965
112
        else if (p[n].len <= p[n+1].len) {
1966
42
            if (merge_at(ms, n) < 0)
1967
0
                return -1;
1968
42
        }
1969
70
        else
1970
70
            break;
1971
126
    }
1972
172
    return 0;
1973
172
}
1974
1975
/* Regardless of invariants, merge all runs on the stack until only one
1976
 * remains.  This is used at the end of the mergesort.
1977
 *
1978
 * Returns 0 on success, -1 on error.
1979
 */
1980
static int
1981
merge_force_collapse(MergeState *ms)
1982
74
{
1983
74
    struct s_slice *p = ms->pending;
1984
1985
74
    assert(ms);
1986
116
    while (ms->n > 1) {
1987
42
        Py_ssize_t n = ms->n - 2;
1988
42
        if (n > 0 && p[n-1].len < p[n+1].len)
1989
0
            --n;
1990
42
        if (merge_at(ms, n) < 0)
1991
0
            return -1;
1992
42
    }
1993
74
    return 0;
1994
74
}
1995
1996
/* Compute a good value for the minimum run length; natural runs shorter
1997
 * than this are boosted artificially via binary insertion.
1998
 *
1999
 * If n < 64, return n (it's too small to bother with fancy stuff).
2000
 * Else if n is an exact power of 2, return 32.
2001
 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
2002
 * strictly less than, an exact power of 2.
2003
 *
2004
 * See listsort.txt for more info.
2005
 */
2006
static Py_ssize_t
2007
merge_compute_minrun(Py_ssize_t n)
2008
74
{
2009
74
    Py_ssize_t r = 0;           /* becomes 1 if any 1 bits are shifted off */
2010
2011
74
    assert(n >= 0);
2012
116
    while (n >= 64) {
2013
42
        r |= n & 1;
2014
42
        n >>= 1;
2015
42
    }
2016
74
    return n + r;
2017
74
}
2018
2019
static void
2020
reverse_sortslice(sortslice *s, Py_ssize_t n)
2021
121
{
2022
121
    reverse_slice(s->keys, &s->keys[n]);
2023
121
    if (s->values != NULL)
2024
1
        reverse_slice(s->values, &s->values[n]);
2025
121
}
2026
2027
/* Here we define custom comparison functions to optimize for the cases one commonly
2028
 * encounters in practice: homogeneous lists, often of one of the basic types. */
2029
2030
/* This struct holds the comparison function and helper functions
2031
 * selected in the pre-sort check. */
2032
2033
/* These are the special case compare functions.
2034
 * ms->key_compare will always point to one of these: */
2035
2036
/* Heterogeneous compare: default, always safe to fall back on. */
2037
static int
2038
safe_object_compare(PyObject *v, PyObject *w, MergeState *ms)
2039
0
{
2040
    /* No assumptions necessary! */
2041
0
    return PyObject_RichCompareBool(v, w, Py_LT);
2042
0
}
2043
2044
/* Homogeneous compare: safe for any two compareable objects of the same type.
2045
 * (ms->key_richcompare is set to ob_type->tp_richcompare in the
2046
 *  pre-sort check.)
2047
 */
2048
static int
2049
unsafe_object_compare(PyObject *v, PyObject *w, MergeState *ms)
2050
0
{
2051
0
    PyObject *res_obj; int res;
2052
2053
    /* No assumptions, because we check first: */
2054
0
    if (v->ob_type->tp_richcompare != ms->key_richcompare)
2055
0
        return PyObject_RichCompareBool(v, w, Py_LT);
2056
2057
0
    assert(ms->key_richcompare != NULL);
2058
0
    res_obj = (*(ms->key_richcompare))(v, w, Py_LT);
2059
2060
0
    if (res_obj == Py_NotImplemented) {
2061
0
        Py_DECREF(res_obj);
2062
0
        return PyObject_RichCompareBool(v, w, Py_LT);
2063
0
    }
2064
0
    if (res_obj == NULL)
2065
0
        return -1;
2066
2067
0
    if (PyBool_Check(res_obj)) {
2068
0
        res = (res_obj == Py_True);
2069
0
    }
2070
0
    else {
2071
0
        res = PyObject_IsTrue(res_obj);
2072
0
    }
2073
0
    Py_DECREF(res_obj);
2074
2075
    /* Note that we can't assert
2076
     *     res == PyObject_RichCompareBool(v, w, Py_LT);
2077
     * because of evil compare functions like this:
2078
     *     lambda a, b:  int(random.random() * 3) - 1)
2079
     * (which is actually in test_sort.py) */
2080
0
    return res;
2081
0
}
2082
2083
/* Latin string compare: safe for any two latin (one byte per char) strings. */
2084
static int
2085
unsafe_latin_compare(PyObject *v, PyObject *w, MergeState *ms)
2086
29.0k
{
2087
29.0k
    Py_ssize_t len;
2088
29.0k
    int res;
2089
2090
    /* Modified from Objects/unicodeobject.c:unicode_compare, assuming: */
2091
29.0k
    assert(v->ob_type == w->ob_type);
2092
29.0k
    assert(v->ob_type == &PyUnicode_Type);
2093
29.0k
    assert(PyUnicode_KIND(v) == PyUnicode_KIND(w));
2094
29.0k
    assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
2095
2096
29.0k
    len = Py_MIN(PyUnicode_GET_LENGTH(v), PyUnicode_GET_LENGTH(w));
2097
29.0k
    res = memcmp(PyUnicode_DATA(v), PyUnicode_DATA(w), len);
2098
2099
29.0k
    res = (res != 0 ?
2100
28.5k
           res < 0 :
2101
29.0k
           PyUnicode_GET_LENGTH(v) < PyUnicode_GET_LENGTH(w));
2102
2103
29.0k
    assert(res == PyObject_RichCompareBool(v, w, Py_LT));;
2104
29.0k
    return res;
2105
29.0k
}
2106
2107
/* Bounded int compare: compare any two longs that fit in a single machine word. */
2108
static int
2109
unsafe_long_compare(PyObject *v, PyObject *w, MergeState *ms)
2110
1
{
2111
1
    PyLongObject *vl, *wl; sdigit v0, w0; int res;
2112
2113
    /* Modified from Objects/longobject.c:long_compare, assuming: */
2114
1
    assert(v->ob_type == w->ob_type);
2115
1
    assert(v->ob_type == &PyLong_Type);
2116
1
    assert(Py_ABS(Py_SIZE(v)) <= 1);
2117
1
    assert(Py_ABS(Py_SIZE(w)) <= 1);
2118
2119
1
    vl = (PyLongObject*)v;
2120
1
    wl = (PyLongObject*)w;
2121
2122
1
    v0 = Py_SIZE(vl) == 0 ? 0 : (sdigit)vl->ob_digit[0];
2123
1
    w0 = Py_SIZE(wl) == 0 ? 0 : (sdigit)wl->ob_digit[0];
2124
2125
1
    if (Py_SIZE(vl) < 0)
2126
0
        v0 = -v0;
2127
1
    if (Py_SIZE(wl) < 0)
2128
0
        w0 = -w0;
2129
2130
1
    res = v0 < w0;
2131
1
    assert(res == PyObject_RichCompareBool(v, w, Py_LT));
2132
1
    return res;
2133
1
}
2134
2135
/* Float compare: compare any two floats. */
2136
static int
2137
unsafe_float_compare(PyObject *v, PyObject *w, MergeState *ms)
2138
0
{
2139
0
    int res;
2140
2141
    /* Modified from Objects/floatobject.c:float_richcompare, assuming: */
2142
0
    assert(v->ob_type == w->ob_type);
2143
0
    assert(v->ob_type == &PyFloat_Type);
2144
2145
0
    res = PyFloat_AS_DOUBLE(v) < PyFloat_AS_DOUBLE(w);
2146
0
    assert(res == PyObject_RichCompareBool(v, w, Py_LT));
2147
0
    return res;
2148
0
}
2149
2150
/* Tuple compare: compare *any* two tuples, using
2151
 * ms->tuple_elem_compare to compare the first elements, which is set
2152
 * using the same pre-sort check as we use for ms->key_compare,
2153
 * but run on the list [x[0] for x in L]. This allows us to optimize compares
2154
 * on two levels (as long as [x[0] for x in L] is type-homogeneous.) The idea is
2155
 * that most tuple compares don't involve x[1:]. */
2156
static int
2157
unsafe_tuple_compare(PyObject *v, PyObject *w, MergeState *ms)
2158
0
{
2159
0
    PyTupleObject *vt, *wt;
2160
0
    Py_ssize_t i, vlen, wlen;
2161
0
    int k;
2162
2163
    /* Modified from Objects/tupleobject.c:tuplerichcompare, assuming: */
2164
0
    assert(v->ob_type == w->ob_type);
2165
0
    assert(v->ob_type == &PyTuple_Type);
2166
0
    assert(Py_SIZE(v) > 0);
2167
0
    assert(Py_SIZE(w) > 0);
2168
2169
0
    vt = (PyTupleObject *)v;
2170
0
    wt = (PyTupleObject *)w;
2171
2172
0
    vlen = Py_SIZE(vt);
2173
0
    wlen = Py_SIZE(wt);
2174
2175
0
    for (i = 0; i < vlen && i < wlen; i++) {
2176
0
        k = PyObject_RichCompareBool(vt->ob_item[i], wt->ob_item[i], Py_EQ);
2177
0
        if (k < 0)
2178
0
            return -1;
2179
0
        if (!k)
2180
0
            break;
2181
0
    }
2182
2183
0
    if (i >= vlen || i >= wlen)
2184
0
        return vlen < wlen;
2185
2186
0
    if (i == 0)
2187
0
        return ms->tuple_elem_compare(vt->ob_item[i], wt->ob_item[i], ms);
2188
0
    else
2189
0
        return PyObject_RichCompareBool(vt->ob_item[i], wt->ob_item[i], Py_LT);
2190
0
}
2191
2192
/* An adaptive, stable, natural mergesort.  See listsort.txt.
2193
 * Returns Py_None on success, NULL on error.  Even in case of error, the
2194
 * list will be some permutation of its input state (nothing is lost or
2195
 * duplicated).
2196
 */
2197
/*[clinic input]
2198
list.sort
2199
2200
    *
2201
    key as keyfunc: object = None
2202
    reverse: bool(accept={int}) = False
2203
2204
Sort the list in ascending order and return None.
2205
2206
The sort is in-place (i.e. the list itself is modified) and stable (i.e. the
2207
order of two equal elements is maintained).
2208
2209
If a key function is given, apply it once to each list item and sort them,
2210
ascending or descending, according to their function values.
2211
2212
The reverse flag can be set to sort in descending order.
2213
[clinic start generated code]*/
2214
2215
static PyObject *
2216
list_sort_impl(PyListObject *self, PyObject *keyfunc, int reverse)
2217
/*[clinic end generated code: output=57b9f9c5e23fbe42 input=cb56cd179a713060]*/
2218
452
{
2219
452
    MergeState ms;
2220
452
    Py_ssize_t nremaining;
2221
452
    Py_ssize_t minrun;
2222
452
    sortslice lo;
2223
452
    Py_ssize_t saved_ob_size, saved_allocated;
2224
452
    PyObject **saved_ob_item;
2225
452
    PyObject **final_ob_item;
2226
452
    PyObject *result = NULL;            /* guilty until proved innocent */
2227
452
    Py_ssize_t i;
2228
452
    PyObject **keys;
2229
2230
452
    assert(self != NULL);
2231
452
    assert(PyList_Check(self));
2232
452
    if (keyfunc == Py_None)
2233
1
        keyfunc = NULL;
2234
2235
    /* The list is temporarily made empty, so that mutations performed
2236
     * by comparison functions can't affect the slice of memory we're
2237
     * sorting (allowing mutations during sorting is a core-dump
2238
     * factory, since ob_item may change).
2239
     */
2240
452
    saved_ob_size = Py_SIZE(self);
2241
452
    saved_ob_item = self->ob_item;
2242
452
    saved_allocated = self->allocated;
2243
452
    Py_SIZE(self) = 0;
2244
452
    self->ob_item = NULL;
2245
452
    self->allocated = -1; /* any operation will reset it to >= 0 */
2246
2247
452
    if (keyfunc == NULL) {
2248
450
        keys = NULL;
2249
450
        lo.keys = saved_ob_item;
2250
450
        lo.values = NULL;
2251
450
    }
2252
2
    else {
2253
2
        if (saved_ob_size < MERGESTATE_TEMP_SIZE/2)
2254
            /* Leverage stack space we allocated but won't otherwise use */
2255
2
            keys = &ms.temparray[saved_ob_size+1];
2256
0
        else {
2257
0
            keys = PyMem_MALLOC(sizeof(PyObject *) * saved_ob_size);
2258
0
            if (keys == NULL) {
2259
0
                PyErr_NoMemory();
2260
0
                goto keyfunc_fail;
2261
0
            }
2262
0
        }
2263
2264
4
        for (i = 0; i < saved_ob_size ; i++) {
2265
2
            keys[i] = PyObject_CallFunctionObjArgs(keyfunc, saved_ob_item[i],
2266
2
                                                   NULL);
2267
2
            if (keys[i] == NULL) {
2268
0
                for (i=i-1 ; i>=0 ; i--)
2269
0
                    Py_DECREF(keys[i]);
2270
0
                if (saved_ob_size >= MERGESTATE_TEMP_SIZE/2)
2271
0
                    PyMem_FREE(keys);
2272
0
                goto keyfunc_fail;
2273
0
            }
2274
2
        }
2275
2276
2
        lo.keys = keys;
2277
2
        lo.values = saved_ob_item;
2278
2
    }
2279
2280
2281
    /* The pre-sort check: here's where we decide which compare function to use.
2282
     * How much optimization is safe? We test for homogeneity with respect to
2283
     * several properties that are expensive to check at compare-time, and
2284
     * set ms appropriately. */
2285
452
    if (saved_ob_size > 1) {
2286
        /* Assume the first element is representative of the whole list. */
2287
74
        int keys_are_in_tuples = (lo.keys[0]->ob_type == &PyTuple_Type &&
2288
74
                                  Py_SIZE(lo.keys[0]) > 0);
2289
2290
74
        PyTypeObject* key_type = (keys_are_in_tuples ?
2291
0
                                  PyTuple_GET_ITEM(lo.keys[0], 0)->ob_type :
2292
74
                                  lo.keys[0]->ob_type);
2293
2294
74
        int keys_are_all_same_type = 1;
2295
74
        int strings_are_latin = 1;
2296
74
        int ints_are_bounded = 1;
2297
2298
        /* Prove that assumption by checking every key. */
2299
5.05k
        for (i=0; i < saved_ob_size; i++) {
2300
2301
4.98k
            if (keys_are_in_tuples &&
2302
4.98k
                !(lo.keys[i]->ob_type == &PyTuple_Type && Py_SIZE(lo.keys[i]) != 0)) {
2303
0
                keys_are_in_tuples = 0;
2304
0
                keys_are_all_same_type = 0;
2305
0
                break;
2306
0
            }
2307
2308
            /* Note: for lists of tuples, key is the first element of the tuple
2309
             * lo.keys[i], not lo.keys[i] itself! We verify type-homogeneity
2310
             * for lists of tuples in the if-statement directly above. */
2311
4.98k
            PyObject *key = (keys_are_in_tuples ?
2312
0
                             PyTuple_GET_ITEM(lo.keys[i], 0) :
2313
4.98k
                             lo.keys[i]);
2314
2315
4.98k
            if (key->ob_type != key_type) {
2316
0
                keys_are_all_same_type = 0;
2317
                /* If keys are in tuple we must loop over the whole list to make
2318
                   sure all items are tuples */
2319
0
                if (!keys_are_in_tuples) {
2320
0
                    break;
2321
0
                }
2322
0
            }
2323
2324
4.98k
            if (keys_are_all_same_type) {
2325
4.98k
                if (key_type == &PyLong_Type &&
2326
4.98k
                    ints_are_bounded &&
2327
4.98k
                    Py_ABS(Py_SIZE(key)) > 1) {
2328
2329
0
                    ints_are_bounded = 0;
2330
0
                }
2331
4.98k
                else if (key_type == &PyUnicode_Type &&
2332
4.98k
                         strings_are_latin &&
2333
4.98k
                         PyUnicode_KIND(key) != PyUnicode_1BYTE_KIND) {
2334
2335
0
                        strings_are_latin = 0;
2336
0
                    }
2337
4.98k
                }
2338
4.98k
            }
2339
2340
        /* Choose the best compare, given what we now know about the keys. */
2341
74
        if (keys_are_all_same_type) {
2342
2343
74
            if (key_type == &PyUnicode_Type && strings_are_latin) {
2344
73
                ms.key_compare = unsafe_latin_compare;
2345
73
            }
2346
1
            else if (key_type == &PyLong_Type && ints_are_bounded) {
2347
1
                ms.key_compare = unsafe_long_compare;
2348
1
            }
2349
0
            else if (key_type == &PyFloat_Type) {
2350
0
                ms.key_compare = unsafe_float_compare;
2351
0
            }
2352
0
            else if ((ms.key_richcompare = key_type->tp_richcompare) != NULL) {
2353
0
                ms.key_compare = unsafe_object_compare;
2354
0
            }
2355
0
            else {
2356
0
                ms.key_compare = safe_object_compare;
2357
0
            }
2358
74
        }
2359
0
        else {
2360
0
            ms.key_compare = safe_object_compare;
2361
0
        }
2362
2363
74
        if (keys_are_in_tuples) {
2364
            /* Make sure we're not dealing with tuples of tuples
2365
             * (remember: here, key_type refers list [key[0] for key in keys]) */
2366
0
            if (key_type == &PyTuple_Type) {
2367
0
                ms.tuple_elem_compare = safe_object_compare;
2368
0
            }
2369
0
            else {
2370
0
                ms.tuple_elem_compare = ms.key_compare;
2371
0
            }
2372
2373
0
            ms.key_compare = unsafe_tuple_compare;
2374
0
        }
2375
74
    }
2376
    /* End of pre-sort check: ms is now set properly! */
2377
2378
452
    merge_init(&ms, saved_ob_size, keys != NULL);
2379
2380
452
    nremaining = saved_ob_size;
2381
452
    if (nremaining < 2)
2382
378
        goto succeed;
2383
2384
    /* Reverse sort stability achieved by initially reversing the list,
2385
    applying a stable forward sort, then reversing the final result. */
2386
74
    if (reverse) {
2387
2
        if (keys != NULL)
2388
1
            reverse_slice(&keys[0], &keys[saved_ob_size]);
2389
2
        reverse_slice(&saved_ob_item[0], &saved_ob_item[saved_ob_size]);
2390
2
    }
2391
2392
    /* March over the array once, left to right, finding natural runs,
2393
     * and extending short natural runs to minrun elements.
2394
     */
2395
74
    minrun = merge_compute_minrun(nremaining);
2396
172
    do {
2397
172
        int descending;
2398
172
        Py_ssize_t n;
2399
2400
        /* Identify next run. */
2401
172
        n = count_run(&ms, lo.keys, lo.keys + nremaining, &descending);
2402
172
        if (n < 0)
2403
0
            goto fail;
2404
172
        if (descending)
2405
121
            reverse_sortslice(&lo, n);
2406
        /* If short, extend to min(minrun, nremaining). */
2407
172
        if (n < minrun) {
2408
167
            const Py_ssize_t force = nremaining <= minrun ?
2409
98
                              nremaining : minrun;
2410
167
            if (binarysort(&ms, lo, lo.keys + force, lo.keys + n) < 0)
2411
0
                goto fail;
2412
167
            n = force;
2413
167
        }
2414
        /* Push run onto pending-runs stack, and maybe merge. */
2415
172
        assert(ms.n < MAX_MERGE_PENDING);
2416
172
        ms.pending[ms.n].base = lo;
2417
172
        ms.pending[ms.n].len = n;
2418
172
        ++ms.n;
2419
172
        if (merge_collapse(&ms) < 0)
2420
0
            goto fail;
2421
        /* Advance to find next run. */
2422
172
        sortslice_advance(&lo, n);
2423
172
        nremaining -= n;
2424
172
    } while (nremaining);
2425
2426
74
    if (merge_force_collapse(&ms) < 0)
2427
0
        goto fail;
2428
74
    assert(ms.n == 1);
2429
74
    assert(keys == NULL
2430
74
           ? ms.pending[0].base.keys == saved_ob_item
2431
74
           : ms.pending[0].base.keys == &keys[0]);
2432
74
    assert(ms.pending[0].len == saved_ob_size);
2433
74
    lo = ms.pending[0].base;
2434
2435
452
succeed:
2436
452
    result = Py_None;
2437
452
fail:
2438
452
    if (keys != NULL) {
2439
4
        for (i = 0; i < saved_ob_size; i++)
2440
2
            Py_DECREF(keys[i]);
2441
2
        if (saved_ob_size >= MERGESTATE_TEMP_SIZE/2)
2442
0
            PyMem_FREE(keys);
2443
2
    }
2444
2445
452
    if (self->allocated != -1 && result != NULL) {
2446
        /* The user mucked with the list during the sort,
2447
         * and we don't already have another error to report.
2448
         */
2449
0
        PyErr_SetString(PyExc_ValueError, "list modified during sort");
2450
0
        result = NULL;
2451
0
    }
2452
2453
452
    if (reverse && saved_ob_size > 1)
2454
2
        reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2455
2456
452
    merge_freemem(&ms);
2457
2458
452
keyfunc_fail:
2459
452
    final_ob_item = self->ob_item;
2460
452
    i = Py_SIZE(self);
2461
452
    Py_SIZE(self) = saved_ob_size;
2462
452
    self->ob_item = saved_ob_item;
2463
452
    self->allocated = saved_allocated;
2464
452
    if (final_ob_item != NULL) {
2465
        /* we cannot use _list_clear() for this because it does not
2466
           guarantee that the list is really empty when it returns */
2467
0
        while (--i >= 0) {
2468
0
            Py_XDECREF(final_ob_item[i]);
2469
0
        }
2470
0
        PyMem_FREE(final_ob_item);
2471
0
    }
2472
452
    Py_XINCREF(result);
2473
452
    return result;
2474
452
}
2475
#undef IFLT
2476
#undef ISLT
2477
2478
int
2479
PyList_Sort(PyObject *v)
2480
449
{
2481
449
    if (v == NULL || !PyList_Check(v)) {
2482
0
        PyErr_BadInternalCall();
2483
0
        return -1;
2484
0
    }
2485
449
    v = list_sort_impl((PyListObject *)v, NULL, 0);
2486
449
    if (v == NULL)
2487
0
        return -1;
2488
449
    Py_DECREF(v);
2489
449
    return 0;
2490
449
}
2491
2492
/*[clinic input]
2493
list.reverse
2494
2495
Reverse *IN PLACE*.
2496
[clinic start generated code]*/
2497
2498
static PyObject *
2499
list_reverse_impl(PyListObject *self)
2500
/*[clinic end generated code: output=482544fc451abea9 input=eefd4c3ae1bc9887]*/
2501
0
{
2502
0
    if (Py_SIZE(self) > 1)
2503
0
        reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
2504
0
    Py_RETURN_NONE;
2505
0
}
2506
2507
int
2508
PyList_Reverse(PyObject *v)
2509
0
{
2510
0
    PyListObject *self = (PyListObject *)v;
2511
2512
0
    if (v == NULL || !PyList_Check(v)) {
2513
0
        PyErr_BadInternalCall();
2514
0
        return -1;
2515
0
    }
2516
0
    if (Py_SIZE(self) > 1)
2517
0
        reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
2518
0
    return 0;
2519
0
}
2520
2521
PyObject *
2522
PyList_AsTuple(PyObject *v)
2523
1.63k
{
2524
1.63k
    if (v == NULL || !PyList_Check(v)) {
2525
0
        PyErr_BadInternalCall();
2526
0
        return NULL;
2527
0
    }
2528
1.63k
    return _PyTuple_FromArray(((PyListObject *)v)->ob_item, Py_SIZE(v));
2529
1.63k
}
2530
2531
/*[clinic input]
2532
list.index
2533
2534
    value: object
2535
    start: slice_index(accept={int}) = 0
2536
    stop: slice_index(accept={int}, c_default="PY_SSIZE_T_MAX") = sys.maxsize
2537
    /
2538
2539
Return first index of value.
2540
2541
Raises ValueError if the value is not present.
2542
[clinic start generated code]*/
2543
2544
static PyObject *
2545
list_index_impl(PyListObject *self, PyObject *value, Py_ssize_t start,
2546
                Py_ssize_t stop)
2547
/*[clinic end generated code: output=ec51b88787e4e481 input=40ec5826303a0eb1]*/
2548
0
{
2549
0
    Py_ssize_t i;
2550
2551
0
    if (start < 0) {
2552
0
        start += Py_SIZE(self);
2553
0
        if (start < 0)
2554
0
            start = 0;
2555
0
    }
2556
0
    if (stop < 0) {
2557
0
        stop += Py_SIZE(self);
2558
0
        if (stop < 0)
2559
0
            stop = 0;
2560
0
    }
2561
0
    for (i = start; i < stop && i < Py_SIZE(self); i++) {
2562
0
        PyObject *obj = self->ob_item[i];
2563
0
        Py_INCREF(obj);
2564
0
        int cmp = PyObject_RichCompareBool(obj, value, Py_EQ);
2565
0
        Py_DECREF(obj);
2566
0
        if (cmp > 0)
2567
0
            return PyLong_FromSsize_t(i);
2568
0
        else if (cmp < 0)
2569
0
            return NULL;
2570
0
    }
2571
0
    PyErr_Format(PyExc_ValueError, "%R is not in list", value);
2572
0
    return NULL;
2573
0
}
2574
2575
/*[clinic input]
2576
list.count
2577
2578
     value: object
2579
     /
2580
2581
Return number of occurrences of value.
2582
[clinic start generated code]*/
2583
2584
static PyObject *
2585
list_count(PyListObject *self, PyObject *value)
2586
/*[clinic end generated code: output=b1f5d284205ae714 input=3bdc3a5e6f749565]*/
2587
0
{
2588
0
    Py_ssize_t count = 0;
2589
0
    Py_ssize_t i;
2590
2591
0
    for (i = 0; i < Py_SIZE(self); i++) {
2592
0
        PyObject *obj = self->ob_item[i];
2593
0
        if (obj == value) {
2594
0
           count++;
2595
0
           continue;
2596
0
        }
2597
0
        Py_INCREF(obj);
2598
0
        int cmp = PyObject_RichCompareBool(obj, value, Py_EQ);
2599
0
        Py_DECREF(obj);
2600
0
        if (cmp > 0)
2601
0
            count++;
2602
0
        else if (cmp < 0)
2603
0
            return NULL;
2604
0
    }
2605
0
    return PyLong_FromSsize_t(count);
2606
0
}
2607
2608
/*[clinic input]
2609
list.remove
2610
2611
     value: object
2612
     /
2613
2614
Remove first occurrence of value.
2615
2616
Raises ValueError if the value is not present.
2617
[clinic start generated code]*/
2618
2619
static PyObject *
2620
list_remove(PyListObject *self, PyObject *value)
2621
/*[clinic end generated code: output=f087e1951a5e30d1 input=2dc2ba5bb2fb1f82]*/
2622
0
{
2623
0
    Py_ssize_t i;
2624
2625
0
    for (i = 0; i < Py_SIZE(self); i++) {
2626
0
        PyObject *obj = self->ob_item[i];
2627
0
        Py_INCREF(obj);
2628
0
        int cmp = PyObject_RichCompareBool(obj, value, Py_EQ);
2629
0
        Py_DECREF(obj);
2630
0
        if (cmp > 0) {
2631
0
            if (list_ass_slice(self, i, i+1,
2632
0
                               (PyObject *)NULL) == 0)
2633
0
                Py_RETURN_NONE;
2634
0
            return NULL;
2635
0
        }
2636
0
        else if (cmp < 0)
2637
0
            return NULL;
2638
0
    }
2639
0
    PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
2640
0
    return NULL;
2641
0
}
2642
2643
static int
2644
list_traverse(PyListObject *o, visitproc visit, void *arg)
2645
926
{
2646
926
    Py_ssize_t i;
2647
2648
16.7k
    for (i = Py_SIZE(o); --i >= 0; )
2649
15.7k
        Py_VISIT(o->ob_item[i]);
2650
926
    return 0;
2651
926
}
2652
2653
static PyObject *
2654
list_richcompare(PyObject *v, PyObject *w, int op)
2655
249
{
2656
249
    PyListObject *vl, *wl;
2657
249
    Py_ssize_t i;
2658
2659
249
    if (!PyList_Check(v) || !PyList_Check(w))
2660
219
        Py_RETURN_NOTIMPLEMENTED;
2661
2662
30
    vl = (PyListObject *)v;
2663
30
    wl = (PyListObject *)w;
2664
2665
30
    if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) {
2666
        /* Shortcut: if the lengths differ, the lists differ */
2667
16
        if (op == Py_EQ)
2668
16
            Py_RETURN_FALSE;
2669
0
        else
2670
0
            Py_RETURN_TRUE;
2671
16
    }
2672
2673
    /* Search for the first index where items are different */
2674
70
    for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
2675
56
        PyObject *vitem = vl->ob_item[i];
2676
56
        PyObject *witem = wl->ob_item[i];
2677
56
        if (vitem == witem) {
2678
0
            continue;
2679
0
        }
2680
2681
56
        Py_INCREF(vitem);
2682
56
        Py_INCREF(witem);
2683
56
        int k = PyObject_RichCompareBool(vl->ob_item[i],
2684
56
                                         wl->ob_item[i], Py_EQ);
2685
56
        Py_DECREF(vitem);
2686
56
        Py_DECREF(witem);
2687
56
        if (k < 0)
2688
0
            return NULL;
2689
56
        if (!k)
2690
0
            break;
2691
56
    }
2692
2693
14
    if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) {
2694
        /* No more items to compare -- compare sizes */
2695
14
        Py_RETURN_RICHCOMPARE(Py_SIZE(vl), Py_SIZE(wl), op);
2696
14
    }
2697
2698
    /* We have an item that differs -- shortcuts for EQ/NE */
2699
0
    if (op == Py_EQ) {
2700
0
        Py_RETURN_FALSE;
2701
0
    }
2702
0
    if (op == Py_NE) {
2703
0
        Py_RETURN_TRUE;
2704
0
    }
2705
2706
    /* Compare the final item again using the proper operator */
2707
0
    return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
2708
0
}
2709
2710
/*[clinic input]
2711
list.__init__
2712
2713
    iterable: object(c_default="NULL") = ()
2714
    /
2715
2716
Built-in mutable sequence.
2717
2718
If no argument is given, the constructor creates a new empty list.
2719
The argument must be an iterable if specified.
2720
[clinic start generated code]*/
2721
2722
static int
2723
list___init___impl(PyListObject *self, PyObject *iterable)
2724
/*[clinic end generated code: output=0f3c21379d01de48 input=b3f3fe7206af8f6b]*/
2725
35
{
2726
    /* Verify list invariants established by PyType_GenericAlloc() */
2727
35
    assert(0 <= Py_SIZE(self));
2728
35
    assert(Py_SIZE(self) <= self->allocated || self->allocated == -1);
2729
35
    assert(self->ob_item != NULL ||
2730
35
           self->allocated == 0 || self->allocated == -1);
2731
2732
    /* Empty previous contents */
2733
35
    if (self->ob_item != NULL) {
2734
0
        (void)_list_clear(self);
2735
0
    }
2736
35
    if (iterable != NULL) {
2737
21
        if (_PyObject_HasLen(iterable)) {
2738
19
            Py_ssize_t iter_len = PyObject_Size(iterable);
2739
19
            if (iter_len == -1) {
2740
0
                if (!PyErr_ExceptionMatches(PyExc_TypeError)) {
2741
0
                    return -1;
2742
0
                }
2743
0
                PyErr_Clear();
2744
0
            }
2745
19
            if (iter_len > 0 && self->ob_item == NULL
2746
19
                && list_preallocate_exact(self, iter_len)) {
2747
0
                return -1;
2748
0
            }
2749
19
        }
2750
21
        PyObject *rv = list_extend(self, iterable);
2751
21
        if (rv == NULL)
2752
0
            return -1;
2753
21
        Py_DECREF(rv);
2754
21
    }
2755
35
    return 0;
2756
35
}
2757
2758
/*[clinic input]
2759
list.__sizeof__
2760
2761
Return the size of the list in memory, in bytes.
2762
[clinic start generated code]*/
2763
2764
static PyObject *
2765
list___sizeof___impl(PyListObject *self)
2766
/*[clinic end generated code: output=3417541f95f9a53e input=b8030a5d5ce8a187]*/
2767
0
{
2768
0
    Py_ssize_t res;
2769
2770
0
    res = _PyObject_SIZE(Py_TYPE(self)) + self->allocated * sizeof(void*);
2771
0
    return PyLong_FromSsize_t(res);
2772
0
}
2773
2774
static PyObject *list_iter(PyObject *seq);
2775
static PyObject *list_subscript(PyListObject*, PyObject*);
2776
2777
static PyMethodDef list_methods[] = {
2778
    {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, "x.__getitem__(y) <==> x[y]"},
2779
    LIST___REVERSED___METHODDEF
2780
    LIST___SIZEOF___METHODDEF
2781
    LIST_CLEAR_METHODDEF
2782
    LIST_COPY_METHODDEF
2783
    LIST_APPEND_METHODDEF
2784
    LIST_INSERT_METHODDEF
2785
    LIST_EXTEND_METHODDEF
2786
    LIST_POP_METHODDEF
2787
    LIST_REMOVE_METHODDEF
2788
    LIST_INDEX_METHODDEF
2789
    LIST_COUNT_METHODDEF
2790
    LIST_REVERSE_METHODDEF
2791
    LIST_SORT_METHODDEF
2792
    {NULL,              NULL}           /* sentinel */
2793
};
2794
2795
static PySequenceMethods list_as_sequence = {
2796
    (lenfunc)list_length,                       /* sq_length */
2797
    (binaryfunc)list_concat,                    /* sq_concat */
2798
    (ssizeargfunc)list_repeat,                  /* sq_repeat */
2799
    (ssizeargfunc)list_item,                    /* sq_item */
2800
    0,                                          /* sq_slice */
2801
    (ssizeobjargproc)list_ass_item,             /* sq_ass_item */
2802
    0,                                          /* sq_ass_slice */
2803
    (objobjproc)list_contains,                  /* sq_contains */
2804
    (binaryfunc)list_inplace_concat,            /* sq_inplace_concat */
2805
    (ssizeargfunc)list_inplace_repeat,          /* sq_inplace_repeat */
2806
};
2807
2808
static PyObject *
2809
list_subscript(PyListObject* self, PyObject* item)
2810
970
{
2811
970
    if (PyIndex_Check(item)) {
2812
925
        Py_ssize_t i;
2813
925
        i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2814
925
        if (i == -1 && PyErr_Occurred())
2815
0
            return NULL;
2816
925
        if (i < 0)
2817
1
            i += PyList_GET_SIZE(self);
2818
925
        return list_item(self, i);
2819
925
    }
2820
45
    else if (PySlice_Check(item)) {
2821
45
        Py_ssize_t start, stop, step, slicelength, cur, i;
2822
45
        PyObject* result;
2823
45
        PyObject* it;
2824
45
        PyObject **src, **dest;
2825
2826
45
        if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
2827
0
            return NULL;
2828
0
        }
2829
45
        slicelength = PySlice_AdjustIndices(Py_SIZE(self), &start, &stop,
2830
45
                                            step);
2831
2832
45
        if (slicelength <= 0) {
2833
0
            return PyList_New(0);
2834
0
        }
2835
45
        else if (step == 1) {
2836
45
            return list_slice(self, start, stop);
2837
45
        }
2838
0
        else {
2839
0
            result = list_new_prealloc(slicelength);
2840
0
            if (!result) return NULL;
2841
2842
0
            src = self->ob_item;
2843
0
            dest = ((PyListObject *)result)->ob_item;
2844
0
            for (cur = start, i = 0; i < slicelength;
2845
0
                 cur += (size_t)step, i++) {
2846
0
                it = src[cur];
2847
0
                Py_INCREF(it);
2848
0
                dest[i] = it;
2849
0
            }
2850
0
            Py_SIZE(result) = slicelength;
2851
0
            return result;
2852
0
        }
2853
45
    }
2854
0
    else {
2855
0
        PyErr_Format(PyExc_TypeError,
2856
0
                     "list indices must be integers or slices, not %.200s",
2857
0
                     item->ob_type->tp_name);
2858
0
        return NULL;
2859
0
    }
2860
970
}
2861
2862
static int
2863
list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2864
166
{
2865
166
    if (PyIndex_Check(item)) {
2866
147
        Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2867
147
        if (i == -1 && PyErr_Occurred())
2868
0
            return -1;
2869
147
        if (i < 0)
2870
31
            i += PyList_GET_SIZE(self);
2871
147
        return list_ass_item(self, i, value);
2872
147
    }
2873
19
    else if (PySlice_Check(item)) {
2874
19
        Py_ssize_t start, stop, step, slicelength;
2875
2876
19
        if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
2877
0
            return -1;
2878
0
        }
2879
19
        slicelength = PySlice_AdjustIndices(Py_SIZE(self), &start, &stop,
2880
19
                                            step);
2881
2882
19
        if (step == 1)
2883
19
            return list_ass_slice(self, start, stop, value);
2884
2885
        /* Make sure s[5:2] = [..] inserts at the right place:
2886
           before 5, not before 2. */
2887
0
        if ((step < 0 && start < stop) ||
2888
0
            (step > 0 && start > stop))
2889
0
            stop = start;
2890
2891
0
        if (value == NULL) {
2892
            /* delete slice */
2893
0
            PyObject **garbage;
2894
0
            size_t cur;
2895
0
            Py_ssize_t i;
2896
0
            int res;
2897
2898
0
            if (slicelength <= 0)
2899
0
                return 0;
2900
2901
0
            if (step < 0) {
2902
0
                stop = start + 1;
2903
0
                start = stop + step*(slicelength - 1) - 1;
2904
0
                step = -step;
2905
0
            }
2906
2907
0
            garbage = (PyObject**)
2908
0
                PyMem_MALLOC(slicelength*sizeof(PyObject*));
2909
0
            if (!garbage) {
2910
0
                PyErr_NoMemory();
2911
0
                return -1;
2912
0
            }
2913
2914
            /* drawing pictures might help understand these for
2915
               loops. Basically, we memmove the parts of the
2916
               list that are *not* part of the slice: step-1
2917
               items for each item that is part of the slice,
2918
               and then tail end of the list that was not
2919
               covered by the slice */
2920
0
            for (cur = start, i = 0;
2921
0
                 cur < (size_t)stop;
2922
0
                 cur += step, i++) {
2923
0
                Py_ssize_t lim = step - 1;
2924
2925
0
                garbage[i] = PyList_GET_ITEM(self, cur);
2926
2927
0
                if (cur + step >= (size_t)Py_SIZE(self)) {
2928
0
                    lim = Py_SIZE(self) - cur - 1;
2929
0
                }
2930
2931
0
                memmove(self->ob_item + cur - i,
2932
0
                    self->ob_item + cur + 1,
2933
0
                    lim * sizeof(PyObject *));
2934
0
            }
2935
0
            cur = start + (size_t)slicelength * step;
2936
0
            if (cur < (size_t)Py_SIZE(self)) {
2937
0
                memmove(self->ob_item + cur - slicelength,
2938
0
                    self->ob_item + cur,
2939
0
                    (Py_SIZE(self) - cur) *
2940
0
                     sizeof(PyObject *));
2941
0
            }
2942
2943
0
            Py_SIZE(self) -= slicelength;
2944
0
            res = list_resize(self, Py_SIZE(self));
2945
2946
0
            for (i = 0; i < slicelength; i++) {
2947
0
                Py_DECREF(garbage[i]);
2948
0
            }
2949
0
            PyMem_FREE(garbage);
2950
2951
0
            return res;
2952
0
        }
2953
0
        else {
2954
            /* assign slice */
2955
0
            PyObject *ins, *seq;
2956
0
            PyObject **garbage, **seqitems, **selfitems;
2957
0
            Py_ssize_t cur, i;
2958
2959
            /* protect against a[::-1] = a */
2960
0
            if (self == (PyListObject*)value) {
2961
0
                seq = list_slice((PyListObject*)value, 0,
2962
0
                                   PyList_GET_SIZE(value));
2963
0
            }
2964
0
            else {
2965
0
                seq = PySequence_Fast(value,
2966
0
                                      "must assign iterable "
2967
0
                                      "to extended slice");
2968
0
            }
2969
0
            if (!seq)
2970
0
                return -1;
2971
2972
0
            if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2973
0
                PyErr_Format(PyExc_ValueError,
2974
0
                    "attempt to assign sequence of "
2975
0
                    "size %zd to extended slice of "
2976
0
                    "size %zd",
2977
0
                         PySequence_Fast_GET_SIZE(seq),
2978
0
                         slicelength);
2979
0
                Py_DECREF(seq);
2980
0
                return -1;
2981
0
            }
2982
2983
0
            if (!slicelength) {
2984
0
                Py_DECREF(seq);
2985
0
                return 0;
2986
0
            }
2987
2988
0
            garbage = (PyObject**)
2989
0
                PyMem_MALLOC(slicelength*sizeof(PyObject*));
2990
0
            if (!garbage) {
2991
0
                Py_DECREF(seq);
2992
0
                PyErr_NoMemory();
2993
0
                return -1;
2994
0
            }
2995
2996
0
            selfitems = self->ob_item;
2997
0
            seqitems = PySequence_Fast_ITEMS(seq);
2998
0
            for (cur = start, i = 0; i < slicelength;
2999
0
                 cur += (size_t)step, i++) {
3000
0
                garbage[i] = selfitems[cur];
3001
0
                ins = seqitems[i];
3002
0
                Py_INCREF(ins);
3003
0
                selfitems[cur] = ins;
3004
0
            }
3005
3006
0
            for (i = 0; i < slicelength; i++) {
3007
0
                Py_DECREF(garbage[i]);
3008
0
            }
3009
3010
0
            PyMem_FREE(garbage);
3011
0
            Py_DECREF(seq);
3012
3013
0
            return 0;
3014
0
        }
3015
0
    }
3016
0
    else {
3017
0
        PyErr_Format(PyExc_TypeError,
3018
0
                     "list indices must be integers or slices, not %.200s",
3019
0
                     item->ob_type->tp_name);
3020
0
        return -1;
3021
0
    }
3022
166
}
3023
3024
static PyMappingMethods list_as_mapping = {
3025
    (lenfunc)list_length,
3026
    (binaryfunc)list_subscript,
3027
    (objobjargproc)list_ass_subscript
3028
};
3029
3030
PyTypeObject PyList_Type = {
3031
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
3032
    "list",
3033
    sizeof(PyListObject),
3034
    0,
3035
    (destructor)list_dealloc,                   /* tp_dealloc */
3036
    0,                                          /* tp_vectorcall_offset */
3037
    0,                                          /* tp_getattr */
3038
    0,                                          /* tp_setattr */
3039
    0,                                          /* tp_as_async */
3040
    (reprfunc)list_repr,                        /* tp_repr */
3041
    0,                                          /* tp_as_number */
3042
    &list_as_sequence,                          /* tp_as_sequence */
3043
    &list_as_mapping,                           /* tp_as_mapping */
3044
    PyObject_HashNotImplemented,                /* tp_hash */
3045
    0,                                          /* tp_call */
3046
    0,                                          /* tp_str */
3047
    PyObject_GenericGetAttr,                    /* tp_getattro */
3048
    0,                                          /* tp_setattro */
3049
    0,                                          /* tp_as_buffer */
3050
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3051
        Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */
3052
    list___init____doc__,                       /* tp_doc */
3053
    (traverseproc)list_traverse,                /* tp_traverse */
3054
    (inquiry)_list_clear,                       /* tp_clear */
3055
    list_richcompare,                           /* tp_richcompare */
3056
    0,                                          /* tp_weaklistoffset */
3057
    list_iter,                                  /* tp_iter */
3058
    0,                                          /* tp_iternext */
3059
    list_methods,                               /* tp_methods */
3060
    0,                                          /* tp_members */
3061
    0,                                          /* tp_getset */
3062
    0,                                          /* tp_base */
3063
    0,                                          /* tp_dict */
3064
    0,                                          /* tp_descr_get */
3065
    0,                                          /* tp_descr_set */
3066
    0,                                          /* tp_dictoffset */
3067
    (initproc)list___init__,                    /* tp_init */
3068
    PyType_GenericAlloc,                        /* tp_alloc */
3069
    PyType_GenericNew,                          /* tp_new */
3070
    PyObject_GC_Del,                            /* tp_free */
3071
};
3072
3073
/*********************** List Iterator **************************/
3074
3075
typedef struct {
3076
    PyObject_HEAD
3077
    Py_ssize_t it_index;
3078
    PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
3079
} listiterobject;
3080
3081
static void listiter_dealloc(listiterobject *);
3082
static int listiter_traverse(listiterobject *, visitproc, void *);
3083
static PyObject *listiter_next(listiterobject *);
3084
static PyObject *listiter_len(listiterobject *, PyObject *);
3085
static PyObject *listiter_reduce_general(void *_it, int forward);
3086
static PyObject *listiter_reduce(listiterobject *, PyObject *);
3087
static PyObject *listiter_setstate(listiterobject *, PyObject *state);
3088
3089
PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
3090
PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
3091
PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
3092
3093
static PyMethodDef listiter_methods[] = {
3094
    {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc},
3095
    {"__reduce__", (PyCFunction)listiter_reduce, METH_NOARGS, reduce_doc},
3096
    {"__setstate__", (PyCFunction)listiter_setstate, METH_O, setstate_doc},
3097
    {NULL,              NULL}           /* sentinel */
3098
};
3099
3100
PyTypeObject PyListIter_Type = {
3101
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
3102
    "list_iterator",                            /* tp_name */
3103
    sizeof(listiterobject),                     /* tp_basicsize */
3104
    0,                                          /* tp_itemsize */
3105
    /* methods */
3106
    (destructor)listiter_dealloc,               /* tp_dealloc */
3107
    0,                                          /* tp_vectorcall_offset */
3108
    0,                                          /* tp_getattr */
3109
    0,                                          /* tp_setattr */
3110
    0,                                          /* tp_as_async */
3111
    0,                                          /* tp_repr */
3112
    0,                                          /* tp_as_number */
3113
    0,                                          /* tp_as_sequence */
3114
    0,                                          /* tp_as_mapping */
3115
    0,                                          /* tp_hash */
3116
    0,                                          /* tp_call */
3117
    0,                                          /* tp_str */
3118
    PyObject_GenericGetAttr,                    /* tp_getattro */
3119
    0,                                          /* tp_setattro */
3120
    0,                                          /* tp_as_buffer */
3121
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3122
    0,                                          /* tp_doc */
3123
    (traverseproc)listiter_traverse,            /* tp_traverse */
3124
    0,                                          /* tp_clear */
3125
    0,                                          /* tp_richcompare */
3126
    0,                                          /* tp_weaklistoffset */
3127
    PyObject_SelfIter,                          /* tp_iter */
3128
    (iternextfunc)listiter_next,                /* tp_iternext */
3129
    listiter_methods,                           /* tp_methods */
3130
    0,                                          /* tp_members */
3131
};
3132
3133
3134
static PyObject *
3135
list_iter(PyObject *seq)
3136
1.71k
{
3137
1.71k
    listiterobject *it;
3138
3139
1.71k
    if (!PyList_Check(seq)) {
3140
0
        PyErr_BadInternalCall();
3141
0
        return NULL;
3142
0
    }
3143
1.71k
    it = PyObject_GC_New(listiterobject, &PyListIter_Type);
3144
1.71k
    if (it == NULL)
3145
0
        return NULL;
3146
1.71k
    it->it_index = 0;
3147
1.71k
    Py_INCREF(seq);
3148
1.71k
    it->it_seq = (PyListObject *)seq;
3149
1.71k
    _PyObject_GC_TRACK(it);
3150
1.71k
    return (PyObject *)it;
3151
1.71k
}
3152
3153
static void
3154
listiter_dealloc(listiterobject *it)
3155
1.71k
{
3156
1.71k
    _PyObject_GC_UNTRACK(it);
3157
1.71k
    Py_XDECREF(it->it_seq);
3158
1.71k
    PyObject_GC_Del(it);
3159
1.71k
}
3160
3161
static int
3162
listiter_traverse(listiterobject *it, visitproc visit, void *arg)
3163
0
{
3164
0
    Py_VISIT(it->it_seq);
3165
0
    return 0;
3166
0
}
3167
3168
static PyObject *
3169
listiter_next(listiterobject *it)
3170
14.1k
{
3171
14.1k
    PyListObject *seq;
3172
14.1k
    PyObject *item;
3173
3174
14.1k
    assert(it != NULL);
3175
14.1k
    seq = it->it_seq;
3176
14.1k
    if (seq == NULL)
3177
0
        return NULL;
3178
14.1k
    assert(PyList_Check(seq));
3179
3180
14.1k
    if (it->it_index < PyList_GET_SIZE(seq)) {
3181
13.3k
        item = PyList_GET_ITEM(seq, it->it_index);
3182
13.3k
        ++it->it_index;
3183
13.3k
        Py_INCREF(item);
3184
13.3k
        return item;
3185
13.3k
    }
3186
3187
827
    it->it_seq = NULL;
3188
827
    Py_DECREF(seq);
3189
827
    return NULL;
3190
14.1k
}
3191
3192
static PyObject *
3193
listiter_len(listiterobject *it, PyObject *Py_UNUSED(ignored))
3194
0
{
3195
0
    Py_ssize_t len;
3196
0
    if (it->it_seq) {
3197
0
        len = PyList_GET_SIZE(it->it_seq) - it->it_index;
3198
0
        if (len >= 0)
3199
0
            return PyLong_FromSsize_t(len);
3200
0
    }
3201
0
    return PyLong_FromLong(0);
3202
0
}
3203
3204
static PyObject *
3205
listiter_reduce(listiterobject *it, PyObject *Py_UNUSED(ignored))
3206
0
{
3207
0
    return listiter_reduce_general(it, 1);
3208
0
}
3209
3210
static PyObject *
3211
listiter_setstate(listiterobject *it, PyObject *state)
3212
0
{
3213
0
    Py_ssize_t index = PyLong_AsSsize_t(state);
3214
0
    if (index == -1 && PyErr_Occurred())
3215
0
        return NULL;
3216
0
    if (it->it_seq != NULL) {
3217
0
        if (index < 0)
3218
0
            index = 0;
3219
0
        else if (index > PyList_GET_SIZE(it->it_seq))
3220
0
            index = PyList_GET_SIZE(it->it_seq); /* iterator exhausted */
3221
0
        it->it_index = index;
3222
0
    }
3223
0
    Py_RETURN_NONE;
3224
0
}
3225
3226
/*********************** List Reverse Iterator **************************/
3227
3228
typedef struct {
3229
    PyObject_HEAD
3230
    Py_ssize_t it_index;
3231
    PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
3232
} listreviterobject;
3233
3234
static void listreviter_dealloc(listreviterobject *);
3235
static int listreviter_traverse(listreviterobject *, visitproc, void *);
3236
static PyObject *listreviter_next(listreviterobject *);
3237
static PyObject *listreviter_len(listreviterobject *, PyObject *);
3238
static PyObject *listreviter_reduce(listreviterobject *, PyObject *);
3239
static PyObject *listreviter_setstate(listreviterobject *, PyObject *);
3240
3241
static PyMethodDef listreviter_methods[] = {
3242
    {"__length_hint__", (PyCFunction)listreviter_len, METH_NOARGS, length_hint_doc},
3243
    {"__reduce__", (PyCFunction)listreviter_reduce, METH_NOARGS, reduce_doc},
3244
    {"__setstate__", (PyCFunction)listreviter_setstate, METH_O, setstate_doc},
3245
    {NULL,              NULL}           /* sentinel */
3246
};
3247
3248
PyTypeObject PyListRevIter_Type = {
3249
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
3250
    "list_reverseiterator",                     /* tp_name */
3251
    sizeof(listreviterobject),                  /* tp_basicsize */
3252
    0,                                          /* tp_itemsize */
3253
    /* methods */
3254
    (destructor)listreviter_dealloc,            /* tp_dealloc */
3255
    0,                                          /* tp_vectorcall_offset */
3256
    0,                                          /* tp_getattr */
3257
    0,                                          /* tp_setattr */
3258
    0,                                          /* tp_as_async */
3259
    0,                                          /* tp_repr */
3260
    0,                                          /* tp_as_number */
3261
    0,                                          /* tp_as_sequence */
3262
    0,                                          /* tp_as_mapping */
3263
    0,                                          /* tp_hash */
3264
    0,                                          /* tp_call */
3265
    0,                                          /* tp_str */
3266
    PyObject_GenericGetAttr,                    /* tp_getattro */
3267
    0,                                          /* tp_setattro */
3268
    0,                                          /* tp_as_buffer */
3269
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3270
    0,                                          /* tp_doc */
3271
    (traverseproc)listreviter_traverse,         /* tp_traverse */
3272
    0,                                          /* tp_clear */
3273
    0,                                          /* tp_richcompare */
3274
    0,                                          /* tp_weaklistoffset */
3275
    PyObject_SelfIter,                          /* tp_iter */
3276
    (iternextfunc)listreviter_next,             /* tp_iternext */
3277
    listreviter_methods,                /* tp_methods */
3278
    0,
3279
};
3280
3281
/*[clinic input]
3282
list.__reversed__
3283
3284
Return a reverse iterator over the list.
3285
[clinic start generated code]*/
3286
3287
static PyObject *
3288
list___reversed___impl(PyListObject *self)
3289
/*[clinic end generated code: output=b166f073208c888c input=eadb6e17f8a6a280]*/
3290
16
{
3291
16
    listreviterobject *it;
3292
3293
16
    it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
3294
16
    if (it == NULL)
3295
0
        return NULL;
3296
16
    assert(PyList_Check(self));
3297
16
    it->it_index = PyList_GET_SIZE(self) - 1;
3298
16
    Py_INCREF(self);
3299
16
    it->it_seq = self;
3300
16
    PyObject_GC_Track(it);
3301
16
    return (PyObject *)it;
3302
16
}
3303
3304
static void
3305
listreviter_dealloc(listreviterobject *it)
3306
16
{
3307
16
    PyObject_GC_UnTrack(it);
3308
16
    Py_XDECREF(it->it_seq);
3309
16
    PyObject_GC_Del(it);
3310
16
}
3311
3312
static int
3313
listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
3314
0
{
3315
0
    Py_VISIT(it->it_seq);
3316
0
    return 0;
3317
0
}
3318
3319
static PyObject *
3320
listreviter_next(listreviterobject *it)
3321
4
{
3322
4
    PyObject *item;
3323
4
    Py_ssize_t index;
3324
4
    PyListObject *seq;
3325
3326
4
    assert(it != NULL);
3327
4
    seq = it->it_seq;
3328
4
    if (seq == NULL) {
3329
0
        return NULL;
3330
0
    }
3331
4
    assert(PyList_Check(seq));
3332
3333
4
    index = it->it_index;
3334
4
    if (index>=0 && index < PyList_GET_SIZE(seq)) {
3335
2
        item = PyList_GET_ITEM(seq, index);
3336
2
        it->it_index--;
3337
2
        Py_INCREF(item);
3338
2
        return item;
3339
2
    }
3340
2
    it->it_index = -1;
3341
2
    it->it_seq = NULL;
3342
2
    Py_DECREF(seq);
3343
2
    return NULL;
3344
4
}
3345
3346
static PyObject *
3347
listreviter_len(listreviterobject *it, PyObject *Py_UNUSED(ignored))
3348
0
{
3349
0
    Py_ssize_t len = it->it_index + 1;
3350
0
    if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
3351
0
        len = 0;
3352
0
    return PyLong_FromSsize_t(len);
3353
0
}
3354
3355
static PyObject *
3356
listreviter_reduce(listreviterobject *it, PyObject *Py_UNUSED(ignored))
3357
0
{
3358
0
    return listiter_reduce_general(it, 0);
3359
0
}
3360
3361
static PyObject *
3362
listreviter_setstate(listreviterobject *it, PyObject *state)
3363
0
{
3364
0
    Py_ssize_t index = PyLong_AsSsize_t(state);
3365
0
    if (index == -1 && PyErr_Occurred())
3366
0
        return NULL;
3367
0
    if (it->it_seq != NULL) {
3368
0
        if (index < -1)
3369
0
            index = -1;
3370
0
        else if (index > PyList_GET_SIZE(it->it_seq) - 1)
3371
0
            index = PyList_GET_SIZE(it->it_seq) - 1;
3372
0
        it->it_index = index;
3373
0
    }
3374
0
    Py_RETURN_NONE;
3375
0
}
3376
3377
/* common pickling support */
3378
3379
static PyObject *
3380
listiter_reduce_general(void *_it, int forward)
3381
0
{
3382
0
    _Py_IDENTIFIER(iter);
3383
0
    _Py_IDENTIFIER(reversed);
3384
0
    PyObject *list;
3385
3386
    /* the objects are not the same, index is of different types! */
3387
0
    if (forward) {
3388
0
        listiterobject *it = (listiterobject *)_it;
3389
0
        if (it->it_seq)
3390
0
            return Py_BuildValue("N(O)n", _PyEval_GetBuiltinId(&PyId_iter),
3391
0
                                 it->it_seq, it->it_index);
3392
0
    } else {
3393
0
        listreviterobject *it = (listreviterobject *)_it;
3394
0
        if (it->it_seq)
3395
0
            return Py_BuildValue("N(O)n", _PyEval_GetBuiltinId(&PyId_reversed),
3396
0
                                 it->it_seq, it->it_index);
3397
0
    }
3398
    /* empty iterator, create an empty list */
3399
0
    list = PyList_New(0);
3400
0
    if (list == NULL)
3401
0
        return NULL;
3402
0
    return Py_BuildValue("N(N)", _PyEval_GetBuiltinId(&PyId_iter), list);
3403
0
}