Coverage Report

Created: 2026-06-14 06:25

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/Python-3.8.3/Objects/listobject.c
Line
Count
Source
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
62.3k
{
38
62.3k
    PyObject **items;
39
62.3k
    size_t new_allocated, num_allocated_bytes;
40
62.3k
    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
62.3k
    if (allocated >= newsize && newsize >= (allocated >> 1)) {
47
54.4k
        assert(self->ob_item != NULL || newsize == 0);
48
54.4k
        Py_SIZE(self) = newsize;
49
54.4k
        return 0;
50
54.4k
    }
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
7.86k
    new_allocated = (size_t)newsize + (newsize >> 3) + (newsize < 9 ? 3 : 6);
62
7.86k
    if (new_allocated > (size_t)PY_SSIZE_T_MAX / sizeof(PyObject *)) {
63
0
        PyErr_NoMemory();
64
0
        return -1;
65
0
    }
66
67
7.86k
    if (newsize == 0)
68
0
        new_allocated = 0;
69
7.86k
    num_allocated_bytes = new_allocated * sizeof(PyObject *);
70
7.86k
    items = (PyObject **)PyMem_Realloc(self->ob_item, num_allocated_bytes);
71
7.86k
    if (items == NULL) {
72
0
        PyErr_NoMemory();
73
0
        return -1;
74
0
    }
75
7.86k
    self->ob_item = items;
76
7.86k
    Py_SIZE(self) = newsize;
77
7.86k
    self->allocated = new_allocated;
78
7.86k
    return 0;
79
7.86k
}
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
11.8k
#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.32k
{
158
6.32k
    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.32k
    if (size < 0) {
168
0
        PyErr_BadInternalCall();
169
0
        return NULL;
170
0
    }
171
6.32k
    if (numfree) {
172
5.79k
        numfree--;
173
5.79k
        op = free_list[numfree];
174
5.79k
        _Py_NewReference((PyObject *)op);
175
#ifdef SHOW_ALLOC_COUNT
176
        count_reuse++;
177
#endif
178
5.79k
    } else {
179
534
        op = PyObject_GC_New(PyListObject, &PyList_Type);
180
534
        if (op == NULL)
181
0
            return NULL;
182
#ifdef SHOW_ALLOC_COUNT
183
        count_alloc++;
184
#endif
185
534
    }
186
6.32k
    if (size <= 0)
187
4.95k
        op->ob_item = NULL;
188
1.37k
    else {
189
1.37k
        op->ob_item = (PyObject **) PyMem_Calloc(size, sizeof(PyObject *));
190
1.37k
        if (op->ob_item == NULL) {
191
0
            Py_DECREF(op);
192
0
            return PyErr_NoMemory();
193
0
        }
194
1.37k
    }
195
6.32k
    Py_SIZE(op) = size;
196
6.32k
    op->allocated = size;
197
6.32k
    _PyObject_GC_TRACK(op);
198
6.32k
    return (PyObject *) op;
199
6.32k
}
200
201
static PyObject *
202
list_new_prealloc(Py_ssize_t size)
203
59
{
204
59
    PyListObject *op = (PyListObject *) PyList_New(0);
205
59
    if (size == 0 || op == NULL) {
206
0
        return (PyObject *) op;
207
0
    }
208
59
    assert(op->ob_item == NULL);
209
59
    op->ob_item = PyMem_New(PyObject *, size);
210
59
    if (op->ob_item == NULL) {
211
0
        Py_DECREF(op);
212
0
        return PyErr_NoMemory();
213
0
    }
214
59
    op->allocated = size;
215
59
    return (PyObject *) op;
216
59
}
217
218
Py_ssize_t
219
PyList_Size(PyObject *op)
220
61
{
221
61
    if (!PyList_Check(op)) {
222
0
        PyErr_BadInternalCall();
223
0
        return -1;
224
0
    }
225
61
    else
226
61
        return Py_SIZE(op);
227
61
}
228
229
static inline int
230
valid_index(Py_ssize_t i, Py_ssize_t limit)
231
7.21k
{
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.21k
    return (size_t) i < (size_t) limit;
240
7.21k
}
241
242
static PyObject *indexerr = NULL;
243
244
PyObject *
245
PyList_GetItem(PyObject *op, Py_ssize_t i)
246
27
{
247
27
    if (!PyList_Check(op)) {
248
0
        PyErr_BadInternalCall();
249
0
        return NULL;
250
0
    }
251
27
    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
27
    return ((PyListObject *)op) -> ob_item[i];
262
27
}
263
264
int
265
PyList_SetItem(PyObject *op, Py_ssize_t i,
266
               PyObject *newitem)
267
189
{
268
189
    PyObject **p;
269
189
    if (!PyList_Check(op)) {
270
0
        Py_XDECREF(newitem);
271
0
        PyErr_BadInternalCall();
272
0
        return -1;
273
0
    }
274
189
    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
189
    p = ((PyListObject *)op) -> ob_item + i;
281
189
    Py_XSETREF(*p, newitem);
282
189
    return 0;
283
189
}
284
285
static int
286
ins1(PyListObject *self, Py_ssize_t where, PyObject *v)
287
13
{
288
13
    Py_ssize_t i, n = Py_SIZE(self);
289
13
    PyObject **items;
290
13
    if (v == NULL) {
291
0
        PyErr_BadInternalCall();
292
0
        return -1;
293
0
    }
294
13
    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
13
    if (list_resize(self, n+1) < 0)
301
0
        return -1;
302
303
13
    if (where < 0) {
304
0
        where += n;
305
0
        if (where < 0)
306
0
            where = 0;
307
0
    }
308
13
    if (where > n)
309
0
        where = n;
310
13
    items = self->ob_item;
311
26
    for (i = n; --i >= where; )
312
13
        items[i+1] = items[i];
313
13
    Py_INCREF(v);
314
13
    items[where] = v;
315
13
    return 0;
316
13
}
317
318
int
319
PyList_Insert(PyObject *op, Py_ssize_t where, PyObject *newitem)
320
13
{
321
13
    if (!PyList_Check(op)) {
322
0
        PyErr_BadInternalCall();
323
0
        return -1;
324
0
    }
325
13
    return ins1((PyListObject *)op, where, newitem);
326
13
}
327
328
static int
329
app1(PyListObject *self, PyObject *v)
330
60.3k
{
331
60.3k
    Py_ssize_t n = PyList_GET_SIZE(self);
332
333
60.3k
    assert (v != NULL);
334
60.3k
    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
60.3k
    if (list_resize(self, n+1) < 0)
341
0
        return -1;
342
343
60.3k
    Py_INCREF(v);
344
60.3k
    PyList_SET_ITEM(self, n, v);
345
60.3k
    return 0;
346
60.3k
}
347
348
int
349
PyList_Append(PyObject *op, PyObject *newitem)
350
58.4k
{
351
58.4k
    if (PyList_Check(op) && (newitem != NULL))
352
58.4k
        return app1((PyListObject *)op, newitem);
353
0
    PyErr_BadInternalCall();
354
0
    return -1;
355
58.4k
}
356
357
/* Methods */
358
359
static void
360
list_dealloc(PyListObject *op)
361
5.91k
{
362
5.91k
    Py_ssize_t i;
363
5.91k
    PyObject_GC_UnTrack(op);
364
5.91k
    Py_TRASHCAN_BEGIN(op, list_dealloc)
365
5.91k
    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.62k
        i = Py_SIZE(op);
371
86.5k
        while (--i >= 0) {
372
81.9k
            Py_XDECREF(op->ob_item[i]);
373
81.9k
        }
374
4.62k
        PyMem_FREE(op->ob_item);
375
4.62k
    }
376
5.91k
    if (numfree < PyList_MAXFREELIST && PyList_CheckExact(op))
377
5.90k
        free_list[numfree++] = op;
378
14
    else
379
14
        Py_TYPE(op)->tp_free((PyObject *)op);
380
5.91k
    Py_TRASHCAN_END
381
5.91k
}
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.68k
{
442
1.68k
    return Py_SIZE(a);
443
1.68k
}
444
445
static int
446
list_contains(PyListObject *a, PyObject *el)
447
572
{
448
572
    PyObject *item;
449
572
    Py_ssize_t i;
450
572
    int cmp;
451
452
15.3k
    for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i) {
453
14.8k
        item = PyList_GET_ITEM(a, i);
454
14.8k
        Py_INCREF(item);
455
14.8k
        cmp = PyObject_RichCompareBool(el, item, Py_EQ);
456
14.8k
        Py_DECREF(item);
457
14.8k
    }
458
572
    return cmp;
459
572
}
460
461
static PyObject *
462
list_item(PyListObject *a, Py_ssize_t i)
463
6.85k
{
464
6.85k
    if (!valid_index(i, Py_SIZE(a))) {
465
124
        if (indexerr == NULL) {
466
13
            indexerr = PyUnicode_FromString(
467
13
                "list index out of range");
468
13
            if (indexerr == NULL)
469
0
                return NULL;
470
13
        }
471
124
        PyErr_SetObject(PyExc_IndexError, indexerr);
472
124
        return NULL;
473
124
    }
474
6.72k
    Py_INCREF(a->ob_item[i]);
475
6.72k
    return a->ob_item[i];
476
6.85k
}
477
478
static PyObject *
479
list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
480
44
{
481
44
    PyListObject *np;
482
44
    PyObject **src, **dest;
483
44
    Py_ssize_t i, len;
484
44
    len = ihigh - ilow;
485
44
    np = (PyListObject *) list_new_prealloc(len);
486
44
    if (np == NULL)
487
0
        return NULL;
488
489
44
    src = a->ob_item + ilow;
490
44
    dest = np->ob_item;
491
127
    for (i = 0; i < len; i++) {
492
83
        PyObject *v = src[i];
493
83
        Py_INCREF(v);
494
83
        dest[i] = v;
495
83
    }
496
44
    Py_SIZE(np) = len;
497
44
    return (PyObject *)np;
498
44
}
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
23
{
607
23
    Py_ssize_t i;
608
23
    PyObject **item = a->ob_item;
609
23
    if (item != NULL) {
610
        /* Because XDECREF can recursively invoke operations on
611
           this list, we make it empty first. */
612
23
        i = Py_SIZE(a);
613
23
        Py_SIZE(a) = 0;
614
23
        a->ob_item = NULL;
615
23
        a->allocated = 0;
616
46
        while (--i >= 0) {
617
23
            Py_XDECREF(item[i]);
618
23
        }
619
23
        PyMem_FREE(item);
620
23
    }
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
23
    return 0;
625
23
}
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
47
{
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
47
    PyObject *recycle_on_stack[8];
643
47
    PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
644
47
    PyObject **item;
645
47
    PyObject **vitem = NULL;
646
47
    PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
647
47
    Py_ssize_t n; /* # of elements in replacement list */
648
47
    Py_ssize_t norig; /* # of elements in list getting replaced */
649
47
    Py_ssize_t d; /* Change in size */
650
47
    Py_ssize_t k;
651
47
    size_t s;
652
47
    int result = -1;            /* guilty until proved innocent */
653
47
#define b ((PyListObject *)v)
654
47
    if (v == NULL)
655
30
        n = 0;
656
17
    else {
657
17
        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
17
        v_as_SF = PySequence_Fast(v, "can only assign an iterable");
667
17
        if(v_as_SF == NULL)
668
0
            goto Error;
669
17
        n = PySequence_Fast_GET_SIZE(v_as_SF);
670
17
        vitem = PySequence_Fast_ITEMS(v_as_SF);
671
17
    }
672
47
    if (ilow < 0)
673
0
        ilow = 0;
674
47
    else if (ilow > Py_SIZE(a))
675
0
        ilow = Py_SIZE(a);
676
677
47
    if (ihigh < ilow)
678
0
        ihigh = ilow;
679
47
    else if (ihigh > Py_SIZE(a))
680
0
        ihigh = Py_SIZE(a);
681
682
47
    norig = ihigh - ilow;
683
47
    assert(norig >= 0);
684
47
    d = n - norig;
685
47
    if (Py_SIZE(a) + d == 0) {
686
23
        Py_XDECREF(v_as_SF);
687
23
        return _list_clear(a);
688
23
    }
689
24
    item = a->ob_item;
690
    /* recycle the items that we are about to remove */
691
24
    s = norig * sizeof(PyObject *);
692
    /* If norig == 0, item might be NULL, in which case we may not memcpy from it. */
693
24
    if (s) {
694
22
        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
22
        memcpy(recycle, &item[ilow], s);
702
22
    }
703
704
24
    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
17
    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
208
    for (k = 0; k < n; k++, ilow++) {
724
184
        PyObject *w = vitem[k];
725
184
        Py_XINCREF(w);
726
184
        item[ilow] = w;
727
184
    }
728
86
    for (k = norig - 1; k >= 0; --k)
729
62
        Py_XDECREF(recycle[k]);
730
24
    result = 0;
731
24
 Error:
732
24
    if (recycle != recycle_on_stack)
733
0
        PyMem_FREE(recycle);
734
24
    Py_XDECREF(v_as_SF);
735
24
    return result;
736
24
#undef b
737
24
}
738
739
int
740
PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
741
23
{
742
23
    if (!PyList_Check(a)) {
743
0
        PyErr_BadInternalCall();
744
0
        return -1;
745
0
    }
746
23
    return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
747
23
}
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.92k
{
862
1.92k
    if (app1(self, object) == 0)
863
1.92k
        Py_RETURN_NONE;
864
0
    return NULL;
865
1.92k
}
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.67k
{
880
1.67k
    PyObject *it;      /* iter(v) */
881
1.67k
    Py_ssize_t m;                  /* size of self */
882
1.67k
    Py_ssize_t n;                  /* guess for size of iterable */
883
1.67k
    Py_ssize_t mn;                 /* m + n */
884
1.67k
    Py_ssize_t i;
885
1.67k
    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.67k
    if (PyList_CheckExact(iterable) || PyTuple_CheckExact(iterable) ||
892
1.13k
                (PyObject *)self == iterable) {
893
1.13k
        PyObject **src, **dest;
894
1.13k
        iterable = PySequence_Fast(iterable, "argument must be iterable");
895
1.13k
        if (!iterable)
896
0
            return NULL;
897
1.13k
        n = PySequence_Fast_GET_SIZE(iterable);
898
1.13k
        if (n == 0) {
899
            /* short circuit when iterable is empty */
900
235
            Py_DECREF(iterable);
901
235
            Py_RETURN_NONE;
902
235
        }
903
903
        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
903
        assert(m < PY_SSIZE_T_MAX - n);
907
903
        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
903
        src = PySequence_Fast_ITEMS(iterable);
918
903
        dest = self->ob_item + m;
919
11.3k
        for (i = 0; i < n; i++) {
920
10.4k
            PyObject *o = src[i];
921
10.4k
            Py_INCREF(o);
922
10.4k
            dest[i] = o;
923
10.4k
        }
924
903
        Py_DECREF(iterable);
925
903
        Py_RETURN_NONE;
926
903
    }
927
928
535
    it = PyObject_GetIter(iterable);
929
535
    if (it == NULL)
930
0
        return NULL;
931
535
    iternext = *it->ob_type->tp_iternext;
932
933
    /* Guess a result list size. */
934
535
    n = PyObject_LengthHint(iterable, 8);
935
535
    if (n < 0) {
936
0
        Py_DECREF(it);
937
0
        return NULL;
938
0
    }
939
535
    m = Py_SIZE(self);
940
535
    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
535
    else {
947
535
        mn = m + n;
948
        /* Make room. */
949
535
        if (list_resize(self, mn) < 0)
950
0
            goto error;
951
        /* Make the list sane again. */
952
535
        Py_SIZE(self) = m;
953
535
    }
954
955
    /* Run iterator to exhaustion. */
956
4.14k
    for (;;) {
957
4.14k
        PyObject *item = iternext(it);
958
4.14k
        if (item == NULL) {
959
535
            if (PyErr_Occurred()) {
960
83
                if (PyErr_ExceptionMatches(PyExc_StopIteration))
961
83
                    PyErr_Clear();
962
0
                else
963
0
                    goto error;
964
83
            }
965
535
            break;
966
535
        }
967
3.60k
        if (Py_SIZE(self) < self->allocated) {
968
            /* steals ref */
969
3.59k
            PyList_SET_ITEM(self, Py_SIZE(self), item);
970
3.59k
            ++Py_SIZE(self);
971
3.59k
        }
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.60k
    }
979
980
    /* Cut back result list if initial guess was too large. */
981
535
    if (Py_SIZE(self) < self->allocated) {
982
516
        if (list_resize(self, Py_SIZE(self)) < 0)
983
0
            goto error;
984
516
    }
985
986
535
    Py_DECREF(it);
987
535
    Py_RETURN_NONE;
988
989
0
  error:
990
0
    Py_DECREF(it);
991
0
    return NULL;
992
535
}
993
994
PyObject *
995
_PyList_Extend(PyListObject *self, PyObject *iterable)
996
1.35k
{
997
1.35k
    return list_extend(self, iterable);
998
1.35k
}
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
118
{
1063
118
    assert(lo && hi);
1064
1065
118
    --hi;
1066
302
    while (lo < hi) {
1067
184
        PyObject *t = *lo;
1068
184
        *lo = *hi;
1069
184
        *hi = t;
1070
184
        ++lo;
1071
184
        --hi;
1072
184
    }
1073
118
}
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
13
{
1096
13
    s1->keys[i] = s2->keys[j];
1097
13
    if (s1->values != NULL)
1098
0
        s1->values[i] = s2->values[j];
1099
13
}
1100
1101
Py_LOCAL_INLINE(void)
1102
sortslice_copy_incr(sortslice *dst, sortslice *src)
1103
2.43k
{
1104
2.43k
    *dst->keys++ = *src->keys++;
1105
2.43k
    if (dst->values != NULL)
1106
0
        *dst->values++ = *src->values++;
1107
2.43k
}
1108
1109
Py_LOCAL_INLINE(void)
1110
sortslice_copy_decr(sortslice *dst, sortslice *src)
1111
5.82k
{
1112
5.82k
    *dst->keys-- = *src->keys--;
1113
5.82k
    if (dst->values != NULL)
1114
0
        *dst->values-- = *src->values--;
1115
5.82k
}
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
247
{
1122
247
    memcpy(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
1123
247
    if (s1->values != NULL)
1124
0
        memcpy(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
1125
247
}
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
143
{
1131
143
    memmove(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
1132
143
    if (s1->values != NULL)
1133
0
        memmove(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
1134
143
}
1135
1136
Py_LOCAL_INLINE(void)
1137
sortslice_advance(sortslice *slice, Py_ssize_t n)
1138
798
{
1139
798
    slice->keys += n;
1140
798
    if (slice->values != NULL)
1141
1
        slice->values += n;
1142
798
}
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
26.9k
#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
19.1k
#define IFLT(X, Y) if ((k = ISLT(X, Y)) < 0) goto fail;  \
1156
19.1k
           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
916
#define MIN_GALLOP 7
1170
1171
/* Avoid malloc for small temp arrays. */
1172
426
#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
156
{
1241
156
    Py_ssize_t k;
1242
156
    PyObject **l, **p, **r;
1243
156
    PyObject *pivot;
1244
1245
156
    assert(lo.keys <= start && start <= hi);
1246
    /* assert [lo, start) is sorted */
1247
156
    if (lo.keys == start)
1248
0
        ++start;
1249
4.39k
    for (; start < hi; ++start) {
1250
        /* set l to where *start belongs */
1251
4.23k
        l = lo.keys;
1252
4.23k
        r = start;
1253
4.23k
        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.23k
        assert(l < r);
1260
17.0k
        do {
1261
17.0k
            p = l + ((r - l) >> 1);
1262
17.0k
            IFLT(pivot, *p)
1263
8.67k
                r = p;
1264
8.41k
            else
1265
8.41k
                l = p+1;
1266
17.0k
        } while (l < r);
1267
4.23k
        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
37.2k
        for (p = start; p > l; --p)
1276
33.0k
            *p = *(p-1);
1277
4.23k
        *l = pivot;
1278
4.23k
        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.23k
    }
1288
156
    return 0;
1289
1290
0
 fail:
1291
0
    return -1;
1292
156
}
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
161
{
1315
161
    Py_ssize_t k;
1316
161
    Py_ssize_t n;
1317
1318
161
    assert(lo < hi);
1319
161
    *descending = 0;
1320
161
    ++lo;
1321
161
    if (lo == hi)
1322
0
        return 1;
1323
1324
161
    n = 2;
1325
161
    IFLT(*lo, *(lo-1)) {
1326
112
        *descending = 1;
1327
176
        for (lo = lo+1; lo < hi; ++lo, ++n) {
1328
172
            IFLT(*lo, *(lo-1))
1329
64
                ;
1330
108
            else
1331
108
                break;
1332
172
        }
1333
112
    }
1334
49
    else {
1335
65
        for (lo = lo+1; lo < hi; ++lo, ++n) {
1336
64
            IFLT(*lo, *(lo-1))
1337
48
                break;
1338
64
        }
1339
49
    }
1340
1341
161
    return n;
1342
0
fail:
1343
0
    return -1;
1344
161
}
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
273
{
1370
273
    Py_ssize_t ofs;
1371
273
    Py_ssize_t lastofs;
1372
273
    Py_ssize_t k;
1373
1374
273
    assert(key && a && n > 0 && hint >= 0 && hint < n);
1375
1376
273
    a += hint;
1377
273
    lastofs = 0;
1378
273
    ofs = 1;
1379
273
    IFLT(*a, key) {
1380
        /* a[hint] < key -- gallop right, until
1381
         * a[hint + lastofs] < key <= a[hint + ofs]
1382
         */
1383
130
        const Py_ssize_t maxofs = n - hint;             /* &a[n-1] is highest */
1384
169
        while (ofs < maxofs) {
1385
78
            IFLT(a[ofs], key) {
1386
39
                lastofs = ofs;
1387
39
                assert(ofs <= (PY_SSIZE_T_MAX - 1) / 2);
1388
39
                ofs = (ofs << 1) + 1;
1389
39
            }
1390
39
            else                /* key <= a[hint + ofs] */
1391
39
                break;
1392
78
        }
1393
130
        if (ofs > maxofs)
1394
0
            ofs = maxofs;
1395
        /* Translate back to offsets relative to &a[0]. */
1396
130
        lastofs += hint;
1397
130
        ofs += hint;
1398
130
    }
1399
143
    else {
1400
        /* key <= a[hint] -- gallop left, until
1401
         * a[hint - ofs] < key <= a[hint - lastofs]
1402
         */
1403
143
        const Py_ssize_t maxofs = hint + 1;             /* &a[0] is lowest */
1404
351
        while (ofs < maxofs) {
1405
312
            IFLT(*(a-ofs), key)
1406
104
                break;
1407
            /* key <= a[hint - ofs] */
1408
208
            lastofs = ofs;
1409
208
            assert(ofs <= (PY_SSIZE_T_MAX - 1) / 2);
1410
208
            ofs = (ofs << 1) + 1;
1411
208
        }
1412
143
        if (ofs > maxofs)
1413
26
            ofs = maxofs;
1414
        /* Translate back to positive offsets relative to &a[0]. */
1415
143
        k = lastofs;
1416
143
        lastofs = hint - ofs;
1417
143
        ofs = hint - k;
1418
143
    }
1419
273
    a -= hint;
1420
1421
273
    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
273
    ++lastofs;
1427
520
    while (lastofs < ofs) {
1428
247
        Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
1429
1430
247
        IFLT(a[m], key)
1431
78
            lastofs = m+1;              /* a[m] < key */
1432
169
        else
1433
169
            ofs = m;                    /* key <= a[m] */
1434
247
    }
1435
273
    assert(lastofs == ofs);             /* so a[ofs-1] < key <= a[ofs] */
1436
273
    return ofs;
1437
1438
0
fail:
1439
0
    return -1;
1440
273
}
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
286
{
1459
286
    Py_ssize_t ofs;
1460
286
    Py_ssize_t lastofs;
1461
286
    Py_ssize_t k;
1462
1463
286
    assert(key && a && n > 0 && hint >= 0 && hint < n);
1464
1465
286
    a += hint;
1466
286
    lastofs = 0;
1467
286
    ofs = 1;
1468
286
    IFLT(key, *a) {
1469
        /* key < a[hint] -- gallop left, until
1470
         * a[hint - ofs] <= key < a[hint - lastofs]
1471
         */
1472
221
        const Py_ssize_t maxofs = hint + 1;             /* &a[0] is lowest */
1473
351
        while (ofs < maxofs) {
1474
221
            IFLT(key, *(a-ofs)) {
1475
130
                lastofs = ofs;
1476
130
                assert(ofs <= (PY_SSIZE_T_MAX - 1) / 2);
1477
130
                ofs = (ofs << 1) + 1;
1478
130
            }
1479
91
            else                /* a[hint - ofs] <= key */
1480
91
                break;
1481
221
        }
1482
221
        if (ofs > maxofs)
1483
0
            ofs = maxofs;
1484
        /* Translate back to positive offsets relative to &a[0]. */
1485
221
        k = lastofs;
1486
221
        lastofs = hint - ofs;
1487
221
        ofs = hint - k;
1488
221
    }
1489
65
    else {
1490
        /* a[hint] <= key -- gallop right, until
1491
         * a[hint + lastofs] <= key < a[hint + ofs]
1492
        */
1493
65
        const Py_ssize_t maxofs = n - hint;             /* &a[n-1] is highest */
1494
117
        while (ofs < maxofs) {
1495
78
            IFLT(key, a[ofs])
1496
26
                break;
1497
            /* a[hint + ofs] <= key */
1498
52
            lastofs = ofs;
1499
52
            assert(ofs <= (PY_SSIZE_T_MAX - 1) / 2);
1500
52
            ofs = (ofs << 1) + 1;
1501
52
        }
1502
65
        if (ofs > maxofs)
1503
0
            ofs = maxofs;
1504
        /* Translate back to offsets relative to &a[0]. */
1505
65
        lastofs += hint;
1506
65
        ofs += hint;
1507
65
    }
1508
286
    a -= hint;
1509
1510
286
    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
286
    ++lastofs;
1516
468
    while (lastofs < ofs) {
1517
182
        Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
1518
1519
182
        IFLT(key, a[m])
1520
78
            ofs = m;                    /* key < a[m] */
1521
104
        else
1522
104
            lastofs = m+1;              /* a[m] <= key */
1523
182
    }
1524
286
    assert(lastofs == ofs);             /* so a[ofs-1] <= key < a[ofs] */
1525
286
    return ofs;
1526
1527
0
fail:
1528
0
    return -1;
1529
286
}
1530
1531
/* Conceptually a MergeState's constructor. */
1532
static void
1533
merge_init(MergeState *ms, Py_ssize_t list_size, int has_keyfunc)
1534
422
{
1535
422
    assert(ms != NULL);
1536
422
    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
420
    else {
1552
420
        ms->alloced = MERGESTATE_TEMP_SIZE;
1553
420
        ms->a.values = NULL;
1554
420
    }
1555
422
    ms->a.keys = ms->temparray;
1556
422
    ms->n = 0;
1557
422
    ms->min_gallop = MIN_GALLOP;
1558
422
}
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
422
{
1567
422
    assert(ms != NULL);
1568
422
    if (ms->a.keys != ms->temparray)
1569
0
        PyMem_Free(ms->a.keys);
1570
422
}
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
91
#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 :   \
1606
91
                                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
39
{
1618
39
    Py_ssize_t k;
1619
39
    sortslice dest;
1620
39
    int result = -1;            /* guilty until proved innocent */
1621
39
    Py_ssize_t min_gallop;
1622
1623
39
    assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
1624
39
    assert(ssa.keys + na == ssb.keys);
1625
39
    if (MERGE_GETMEM(ms, na) < 0)
1626
0
        return -1;
1627
39
    sortslice_memcpy(&ms->a, 0, &ssa, 0, na);
1628
39
    dest = ssa;
1629
39
    ssa = ms->a;
1630
1631
39
    sortslice_copy_incr(&dest, &ssb);
1632
39
    --nb;
1633
39
    if (nb == 0)
1634
0
        goto Succeed;
1635
39
    if (na == 1)
1636
0
        goto CopyB;
1637
1638
39
    min_gallop = ms->min_gallop;
1639
91
    for (;;) {
1640
91
        Py_ssize_t acount = 0;          /* # of times A won in a row */
1641
91
        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.27k
        for (;;) {
1647
2.27k
            assert(na > 1 && nb > 0);
1648
2.27k
            k = ISLT(ssb.keys[0], ssa.keys[0]);
1649
2.27k
            if (k) {
1650
1.26k
                if (k < 0)
1651
0
                    goto Fail;
1652
1.26k
                sortslice_copy_incr(&dest, &ssb);
1653
1.26k
                ++bcount;
1654
1.26k
                acount = 0;
1655
1.26k
                --nb;
1656
1.26k
                if (nb == 0)
1657
26
                    goto Succeed;
1658
1.23k
                if (bcount >= min_gallop)
1659
52
                    break;
1660
1.23k
            }
1661
1.01k
            else {
1662
1.01k
                sortslice_copy_incr(&dest, &ssa);
1663
1.01k
                ++acount;
1664
1.01k
                bcount = 0;
1665
1.01k
                --na;
1666
1.01k
                if (na == 1)
1667
0
                    goto CopyB;
1668
1.01k
                if (acount >= min_gallop)
1669
13
                    break;
1670
1.01k
            }
1671
2.27k
        }
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
65
        ++min_gallop;
1679
65
        do {
1680
65
            assert(na > 1 && nb > 0);
1681
65
            min_gallop -= min_gallop > 1;
1682
65
            ms->min_gallop = min_gallop;
1683
65
            k = gallop_right(ms, ssb.keys[0], ssa.keys, na, 0);
1684
65
            acount = k;
1685
65
            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
65
            sortslice_copy_incr(&dest, &ssb);
1702
65
            --nb;
1703
65
            if (nb == 0)
1704
13
                goto Succeed;
1705
1706
52
            k = gallop_left(ms, ssa.keys[0], ssb.keys, nb, 0);
1707
52
            bcount = k;
1708
52
            if (k) {
1709
39
                if (k < 0)
1710
0
                    goto Fail;
1711
39
                sortslice_memmove(&dest, 0, &ssb, 0, k);
1712
39
                sortslice_advance(&dest, k);
1713
39
                sortslice_advance(&ssb, k);
1714
39
                nb -= k;
1715
39
                if (nb == 0)
1716
0
                    goto Succeed;
1717
39
            }
1718
52
            sortslice_copy_incr(&dest, &ssa);
1719
52
            --na;
1720
52
            if (na == 1)
1721
0
                goto CopyB;
1722
52
        } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
1723
52
        ++min_gallop;           /* penalize it for leaving galloping mode */
1724
52
        ms->min_gallop = min_gallop;
1725
52
    }
1726
39
Succeed:
1727
39
    result = 0;
1728
39
Fail:
1729
39
    if (na)
1730
39
        sortslice_memcpy(&dest, 0, &ssa, 0, na);
1731
39
    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
39
}
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
52
{
1750
52
    Py_ssize_t k;
1751
52
    sortslice dest, basea, baseb;
1752
52
    int result = -1;            /* guilty until proved innocent */
1753
52
    Py_ssize_t min_gallop;
1754
1755
52
    assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
1756
52
    assert(ssa.keys + na == ssb.keys);
1757
52
    if (MERGE_GETMEM(ms, nb) < 0)
1758
0
        return -1;
1759
52
    dest = ssb;
1760
52
    sortslice_advance(&dest, nb-1);
1761
52
    sortslice_memcpy(&ms->a, 0, &ssb, 0, nb);
1762
52
    basea = ssa;
1763
52
    baseb = ms->a;
1764
52
    ssb.keys = ms->a.keys + nb - 1;
1765
52
    if (ssb.values != NULL)
1766
0
        ssb.values = ms->a.values + nb - 1;
1767
52
    sortslice_advance(&ssa, na - 1);
1768
1769
52
    sortslice_copy_decr(&dest, &ssa);
1770
52
    --na;
1771
52
    if (na == 0)
1772
0
        goto Succeed;
1773
52
    if (nb == 1)
1774
0
        goto CopyA;
1775
1776
52
    min_gallop = ms->min_gallop;
1777
156
    for (;;) {
1778
156
        Py_ssize_t acount = 0;          /* # of times A won in a row */
1779
156
        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.52k
        for (;;) {
1785
5.52k
            assert(na > 0 && nb > 1);
1786
5.52k
            k = ISLT(ssb.keys[0], ssa.keys[0]);
1787
5.52k
            if (k) {
1788
3.83k
                if (k < 0)
1789
0
                    goto Fail;
1790
3.83k
                sortslice_copy_decr(&dest, &ssa);
1791
3.83k
                ++acount;
1792
3.83k
                bcount = 0;
1793
3.83k
                --na;
1794
3.83k
                if (na == 0)
1795
39
                    goto Succeed;
1796
3.79k
                if (acount >= min_gallop)
1797
91
                    break;
1798
3.79k
            }
1799
1.69k
            else {
1800
1.69k
                sortslice_copy_decr(&dest, &ssb);
1801
1.69k
                ++bcount;
1802
1.69k
                acount = 0;
1803
1.69k
                --nb;
1804
1.69k
                if (nb == 1)
1805
0
                    goto CopyA;
1806
1.69k
                if (bcount >= min_gallop)
1807
26
                    break;
1808
1.69k
            }
1809
5.52k
        }
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
117
        ++min_gallop;
1817
130
        do {
1818
130
            assert(na > 0 && nb > 1);
1819
130
            min_gallop -= min_gallop > 1;
1820
130
            ms->min_gallop = min_gallop;
1821
130
            k = gallop_right(ms, ssb.keys[0], basea.keys, na, na-1);
1822
130
            if (k < 0)
1823
0
                goto Fail;
1824
130
            k = na - k;
1825
130
            acount = k;
1826
130
            if (k) {
1827
91
                sortslice_advance(&dest, -k);
1828
91
                sortslice_advance(&ssa, -k);
1829
91
                sortslice_memmove(&dest, 1, &ssa, 1, k);
1830
91
                na -= k;
1831
91
                if (na == 0)
1832
0
                    goto Succeed;
1833
91
            }
1834
130
            sortslice_copy_decr(&dest, &ssb);
1835
130
            --nb;
1836
130
            if (nb == 1)
1837
0
                goto CopyA;
1838
1839
130
            k = gallop_left(ms, ssa.keys[0], baseb.keys, nb, nb-1);
1840
130
            if (k < 0)
1841
0
                goto Fail;
1842
130
            k = nb - k;
1843
130
            bcount = k;
1844
130
            if (k) {
1845
78
                sortslice_advance(&dest, -k);
1846
78
                sortslice_advance(&ssb, -k);
1847
78
                sortslice_memcpy(&dest, 1, &ssb, 1, k);
1848
78
                nb -= k;
1849
78
                if (nb == 1)
1850
13
                    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
65
                if (nb == 0)
1856
0
                    goto Succeed;
1857
65
            }
1858
117
            sortslice_copy_decr(&dest, &ssa);
1859
117
            --na;
1860
117
            if (na == 0)
1861
0
                goto Succeed;
1862
117
        } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
1863
104
        ++min_gallop;           /* penalize it for leaving galloping mode */
1864
104
        ms->min_gallop = min_gallop;
1865
104
    }
1866
39
Succeed:
1867
39
    result = 0;
1868
39
Fail:
1869
39
    if (nb)
1870
39
        sortslice_memcpy(&dest, -(nb-1), &baseb, 0, nb);
1871
39
    return result;
1872
13
CopyA:
1873
13
    assert(nb == 1 && na > 0);
1874
    /* The first element of ssb belongs at the front of the merge. */
1875
13
    sortslice_memmove(&dest, 1-na, &ssa, 1-na, na);
1876
13
    sortslice_advance(&dest, -na);
1877
13
    sortslice_advance(&ssa, -na);
1878
13
    sortslice_copy(&dest, 0, &ssb, 0);
1879
13
    return 0;
1880
39
}
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
91
{
1888
91
    sortslice ssa, ssb;
1889
91
    Py_ssize_t na, nb;
1890
91
    Py_ssize_t k;
1891
1892
91
    assert(ms != NULL);
1893
91
    assert(ms->n >= 2);
1894
91
    assert(i >= 0);
1895
91
    assert(i == ms->n - 2 || i == ms->n - 3);
1896
1897
91
    ssa = ms->pending[i].base;
1898
91
    na = ms->pending[i].len;
1899
91
    ssb = ms->pending[i+1].base;
1900
91
    nb = ms->pending[i+1].len;
1901
91
    assert(na > 0 && nb > 0);
1902
91
    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
91
    ms->pending[i].len = na + nb;
1909
91
    if (i == ms->n - 3)
1910
0
        ms->pending[i+1] = ms->pending[i+2];
1911
91
    --ms->n;
1912
1913
    /* Where does b start in a?  Elements in a before that can be
1914
     * ignored (already in place).
1915
     */
1916
91
    k = gallop_right(ms, *ssb.keys, ssa.keys, na, 0);
1917
91
    if (k < 0)
1918
0
        return -1;
1919
91
    sortslice_advance(&ssa, k);
1920
91
    na -= k;
1921
91
    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
91
    nb = gallop_left(ms, ssa.keys[na-1], ssb.keys, nb, nb-1);
1928
91
    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
91
    if (na <= nb)
1935
39
        return merge_lo(ms, ssa, na, ssb, nb);
1936
52
    else
1937
52
        return merge_hi(ms, ssa, na, ssb, nb);
1938
91
}
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
161
{
1953
161
    struct s_slice *p = ms->pending;
1954
1955
161
    assert(ms);
1956
213
    while (ms->n > 1) {
1957
117
        Py_ssize_t n = ms->n - 2;
1958
117
        if ((n > 0 && p[n-1].len <= p[n].len + p[n+1].len) ||
1959
104
            (n > 1 && p[n-2].len <= p[n-1].len + p[n].len)) {
1960
13
            if (p[n-1].len < p[n+1].len)
1961
0
                --n;
1962
13
            if (merge_at(ms, n) < 0)
1963
0
                return -1;
1964
13
        }
1965
104
        else if (p[n].len <= p[n+1].len) {
1966
39
            if (merge_at(ms, n) < 0)
1967
0
                return -1;
1968
39
        }
1969
65
        else
1970
65
            break;
1971
117
    }
1972
161
    return 0;
1973
161
}
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
70
{
1983
70
    struct s_slice *p = ms->pending;
1984
1985
70
    assert(ms);
1986
109
    while (ms->n > 1) {
1987
39
        Py_ssize_t n = ms->n - 2;
1988
39
        if (n > 0 && p[n-1].len < p[n+1].len)
1989
0
            --n;
1990
39
        if (merge_at(ms, n) < 0)
1991
0
            return -1;
1992
39
    }
1993
70
    return 0;
1994
70
}
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
70
{
2009
70
    Py_ssize_t r = 0;           /* becomes 1 if any 1 bits are shifted off */
2010
2011
70
    assert(n >= 0);
2012
109
    while (n >= 64) {
2013
39
        r |= n & 1;
2014
39
        n >>= 1;
2015
39
    }
2016
70
    return n + r;
2017
70
}
2018
2019
static void
2020
reverse_sortslice(sortslice *s, Py_ssize_t n)
2021
112
{
2022
112
    reverse_slice(s->keys, &s->keys[n]);
2023
112
    if (s->values != NULL)
2024
1
        reverse_slice(s->values, &s->values[n]);
2025
112
}
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
26.9k
{
2087
26.9k
    Py_ssize_t len;
2088
26.9k
    int res;
2089
2090
    /* Modified from Objects/unicodeobject.c:unicode_compare, assuming: */
2091
26.9k
    assert(v->ob_type == w->ob_type);
2092
26.9k
    assert(v->ob_type == &PyUnicode_Type);
2093
26.9k
    assert(PyUnicode_KIND(v) == PyUnicode_KIND(w));
2094
26.9k
    assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
2095
2096
26.9k
    len = Py_MIN(PyUnicode_GET_LENGTH(v), PyUnicode_GET_LENGTH(w));
2097
26.9k
    res = memcmp(PyUnicode_DATA(v), PyUnicode_DATA(w), len);
2098
2099
26.9k
    res = (res != 0 ?
2100
26.5k
           res < 0 :
2101
26.9k
           PyUnicode_GET_LENGTH(v) < PyUnicode_GET_LENGTH(w));
2102
2103
26.9k
    assert(res == PyObject_RichCompareBool(v, w, Py_LT));;
2104
26.9k
    return res;
2105
26.9k
}
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
422
{
2219
422
    MergeState ms;
2220
422
    Py_ssize_t nremaining;
2221
422
    Py_ssize_t minrun;
2222
422
    sortslice lo;
2223
422
    Py_ssize_t saved_ob_size, saved_allocated;
2224
422
    PyObject **saved_ob_item;
2225
422
    PyObject **final_ob_item;
2226
422
    PyObject *result = NULL;            /* guilty until proved innocent */
2227
422
    Py_ssize_t i;
2228
422
    PyObject **keys;
2229
2230
422
    assert(self != NULL);
2231
422
    assert(PyList_Check(self));
2232
422
    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
422
    saved_ob_size = Py_SIZE(self);
2241
422
    saved_ob_item = self->ob_item;
2242
422
    saved_allocated = self->allocated;
2243
422
    Py_SIZE(self) = 0;
2244
422
    self->ob_item = NULL;
2245
422
    self->allocated = -1; /* any operation will reset it to >= 0 */
2246
2247
422
    if (keyfunc == NULL) {
2248
420
        keys = NULL;
2249
420
        lo.keys = saved_ob_item;
2250
420
        lo.values = NULL;
2251
420
    }
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
422
    if (saved_ob_size > 1) {
2286
        /* Assume the first element is representative of the whole list. */
2287
70
        int keys_are_in_tuples = (lo.keys[0]->ob_type == &PyTuple_Type &&
2288
0
                                  Py_SIZE(lo.keys[0]) > 0);
2289
2290
70
        PyTypeObject* key_type = (keys_are_in_tuples ?
2291
0
                                  PyTuple_GET_ITEM(lo.keys[0], 0)->ob_type :
2292
70
                                  lo.keys[0]->ob_type);
2293
2294
70
        int keys_are_all_same_type = 1;
2295
70
        int strings_are_latin = 1;
2296
70
        int ints_are_bounded = 1;
2297
2298
        /* Prove that assumption by checking every key. */
2299
4.70k
        for (i=0; i < saved_ob_size; i++) {
2300
2301
4.63k
            if (keys_are_in_tuples &&
2302
0
                !(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.63k
            PyObject *key = (keys_are_in_tuples ?
2312
0
                             PyTuple_GET_ITEM(lo.keys[i], 0) :
2313
4.63k
                             lo.keys[i]);
2314
2315
4.63k
            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.63k
            if (keys_are_all_same_type) {
2325
4.63k
                if (key_type == &PyLong_Type &&
2326
2
                    ints_are_bounded &&
2327
2
                    Py_ABS(Py_SIZE(key)) > 1) {
2328
2329
0
                    ints_are_bounded = 0;
2330
0
                }
2331
4.63k
                else if (key_type == &PyUnicode_Type &&
2332
4.63k
                         strings_are_latin &&
2333
4.63k
                         PyUnicode_KIND(key) != PyUnicode_1BYTE_KIND) {
2334
2335
0
                        strings_are_latin = 0;
2336
0
                    }
2337
4.63k
                }
2338
4.63k
            }
2339
2340
        /* Choose the best compare, given what we now know about the keys. */
2341
70
        if (keys_are_all_same_type) {
2342
2343
70
            if (key_type == &PyUnicode_Type && strings_are_latin) {
2344
69
                ms.key_compare = unsafe_latin_compare;
2345
69
            }
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
70
        }
2359
0
        else {
2360
0
            ms.key_compare = safe_object_compare;
2361
0
        }
2362
2363
70
        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
70
    }
2376
    /* End of pre-sort check: ms is now set properly! */
2377
2378
422
    merge_init(&ms, saved_ob_size, keys != NULL);
2379
2380
422
    nremaining = saved_ob_size;
2381
422
    if (nremaining < 2)
2382
352
        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
70
    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
70
    minrun = merge_compute_minrun(nremaining);
2396
161
    do {
2397
161
        int descending;
2398
161
        Py_ssize_t n;
2399
2400
        /* Identify next run. */
2401
161
        n = count_run(&ms, lo.keys, lo.keys + nremaining, &descending);
2402
161
        if (n < 0)
2403
0
            goto fail;
2404
161
        if (descending)
2405
112
            reverse_sortslice(&lo, n);
2406
        /* If short, extend to min(minrun, nremaining). */
2407
161
        if (n < minrun) {
2408
156
            const Py_ssize_t force = nremaining <= minrun ?
2409
91
                              nremaining : minrun;
2410
156
            if (binarysort(&ms, lo, lo.keys + force, lo.keys + n) < 0)
2411
0
                goto fail;
2412
156
            n = force;
2413
156
        }
2414
        /* Push run onto pending-runs stack, and maybe merge. */
2415
161
        assert(ms.n < MAX_MERGE_PENDING);
2416
161
        ms.pending[ms.n].base = lo;
2417
161
        ms.pending[ms.n].len = n;
2418
161
        ++ms.n;
2419
161
        if (merge_collapse(&ms) < 0)
2420
0
            goto fail;
2421
        /* Advance to find next run. */
2422
161
        sortslice_advance(&lo, n);
2423
161
        nremaining -= n;
2424
161
    } while (nremaining);
2425
2426
70
    if (merge_force_collapse(&ms) < 0)
2427
0
        goto fail;
2428
70
    assert(ms.n == 1);
2429
70
    assert(keys == NULL
2430
70
           ? ms.pending[0].base.keys == saved_ob_item
2431
70
           : ms.pending[0].base.keys == &keys[0]);
2432
70
    assert(ms.pending[0].len == saved_ob_size);
2433
70
    lo = ms.pending[0].base;
2434
2435
422
succeed:
2436
422
    result = Py_None;
2437
422
fail:
2438
422
    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
422
    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
422
    if (reverse && saved_ob_size > 1)
2454
2
        reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2455
2456
422
    merge_freemem(&ms);
2457
2458
422
keyfunc_fail:
2459
422
    final_ob_item = self->ob_item;
2460
422
    i = Py_SIZE(self);
2461
422
    Py_SIZE(self) = saved_ob_size;
2462
422
    self->ob_item = saved_ob_item;
2463
422
    self->allocated = saved_allocated;
2464
422
    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
422
    Py_XINCREF(result);
2473
422
    return result;
2474
422
}
2475
#undef IFLT
2476
#undef ISLT
2477
2478
int
2479
PyList_Sort(PyObject *v)
2480
419
{
2481
419
    if (v == NULL || !PyList_Check(v)) {
2482
0
        PyErr_BadInternalCall();
2483
0
        return -1;
2484
0
    }
2485
419
    v = list_sort_impl((PyListObject *)v, NULL, 0);
2486
419
    if (v == NULL)
2487
0
        return -1;
2488
419
    Py_DECREF(v);
2489
419
    return 0;
2490
419
}
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.52k
{
2524
1.52k
    if (v == NULL || !PyList_Check(v)) {
2525
0
        PyErr_BadInternalCall();
2526
0
        return NULL;
2527
0
    }
2528
1.52k
    return _PyTuple_FromArray(((PyListObject *)v)->ob_item, Py_SIZE(v));
2529
1.52k
}
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
868
{
2646
868
    Py_ssize_t i;
2647
2648
16.0k
    for (i = Py_SIZE(o); --i >= 0; )
2649
15.1k
        Py_VISIT(o->ob_item[i]);
2650
868
    return 0;
2651
868
}
2652
2653
static PyObject *
2654
list_richcompare(PyObject *v, PyObject *w, int op)
2655
233
{
2656
233
    PyListObject *vl, *wl;
2657
233
    Py_ssize_t i;
2658
2659
233
    if (!PyList_Check(v) || !PyList_Check(w))
2660
205
        Py_RETURN_NOTIMPLEMENTED;
2661
2662
28
    vl = (PyListObject *)v;
2663
28
    wl = (PyListObject *)w;
2664
2665
28
    if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) {
2666
        /* Shortcut: if the lengths differ, the lists differ */
2667
15
        if (op == Py_EQ)
2668
15
            Py_RETURN_FALSE;
2669
0
        else
2670
0
            Py_RETURN_TRUE;
2671
15
    }
2672
2673
    /* Search for the first index where items are different */
2674
65
    for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
2675
52
        PyObject *vitem = vl->ob_item[i];
2676
52
        PyObject *witem = wl->ob_item[i];
2677
52
        if (vitem == witem) {
2678
0
            continue;
2679
0
        }
2680
2681
52
        Py_INCREF(vitem);
2682
52
        Py_INCREF(witem);
2683
52
        int k = PyObject_RichCompareBool(vl->ob_item[i],
2684
52
                                         wl->ob_item[i], Py_EQ);
2685
52
        Py_DECREF(vitem);
2686
52
        Py_DECREF(witem);
2687
52
        if (k < 0)
2688
0
            return NULL;
2689
52
        if (!k)
2690
0
            break;
2691
52
    }
2692
2693
13
    if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) {
2694
        /* No more items to compare -- compare sizes */
2695
13
        Py_RETURN_RICHCOMPARE(Py_SIZE(vl), Py_SIZE(wl), op);
2696
13
    }
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
938
{
2811
938
    if (PyIndex_Check(item)) {
2812
894
        Py_ssize_t i;
2813
894
        i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2814
894
        if (i == -1 && PyErr_Occurred())
2815
0
            return NULL;
2816
894
        if (i < 0)
2817
1
            i += PyList_GET_SIZE(self);
2818
894
        return list_item(self, i);
2819
894
    }
2820
44
    else if (PySlice_Check(item)) {
2821
44
        Py_ssize_t start, stop, step, slicelength, cur, i;
2822
44
        PyObject* result;
2823
44
        PyObject* it;
2824
44
        PyObject **src, **dest;
2825
2826
44
        if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
2827
0
            return NULL;
2828
0
        }
2829
44
        slicelength = PySlice_AdjustIndices(Py_SIZE(self), &start, &stop,
2830
44
                                            step);
2831
2832
44
        if (slicelength <= 0) {
2833
0
            return PyList_New(0);
2834
0
        }
2835
44
        else if (step == 1) {
2836
44
            return list_slice(self, start, stop);
2837
44
        }
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
44
    }
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
938
}
2861
2862
static int
2863
list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2864
165
{
2865
165
    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
18
    else if (PySlice_Check(item)) {
2874
18
        Py_ssize_t start, stop, step, slicelength;
2875
2876
18
        if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
2877
0
            return -1;
2878
0
        }
2879
18
        slicelength = PySlice_AdjustIndices(Py_SIZE(self), &start, &stop,
2880
18
                                            step);
2881
2882
18
        if (step == 1)
2883
18
            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
165
}
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.63k
{
3137
1.63k
    listiterobject *it;
3138
3139
1.63k
    if (!PyList_Check(seq)) {
3140
0
        PyErr_BadInternalCall();
3141
0
        return NULL;
3142
0
    }
3143
1.63k
    it = PyObject_GC_New(listiterobject, &PyListIter_Type);
3144
1.63k
    if (it == NULL)
3145
0
        return NULL;
3146
1.63k
    it->it_index = 0;
3147
1.63k
    Py_INCREF(seq);
3148
1.63k
    it->it_seq = (PyListObject *)seq;
3149
1.63k
    _PyObject_GC_TRACK(it);
3150
1.63k
    return (PyObject *)it;
3151
1.63k
}
3152
3153
static void
3154
listiter_dealloc(listiterobject *it)
3155
1.63k
{
3156
1.63k
    _PyObject_GC_UNTRACK(it);
3157
1.63k
    Py_XDECREF(it->it_seq);
3158
1.63k
    PyObject_GC_Del(it);
3159
1.63k
}
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
13.3k
{
3171
13.3k
    PyListObject *seq;
3172
13.3k
    PyObject *item;
3173
3174
13.3k
    assert(it != NULL);
3175
13.3k
    seq = it->it_seq;
3176
13.3k
    if (seq == NULL)
3177
0
        return NULL;
3178
13.3k
    assert(PyList_Check(seq));
3179
3180
13.3k
    if (it->it_index < PyList_GET_SIZE(seq)) {
3181
12.5k
        item = PyList_GET_ITEM(seq, it->it_index);
3182
12.5k
        ++it->it_index;
3183
12.5k
        Py_INCREF(item);
3184
12.5k
        return item;
3185
12.5k
    }
3186
3187
798
    it->it_seq = NULL;
3188
798
    Py_DECREF(seq);
3189
798
    return NULL;
3190
13.3k
}
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
15
{
3291
15
    listreviterobject *it;
3292
3293
15
    it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
3294
15
    if (it == NULL)
3295
0
        return NULL;
3296
15
    assert(PyList_Check(self));
3297
15
    it->it_index = PyList_GET_SIZE(self) - 1;
3298
15
    Py_INCREF(self);
3299
15
    it->it_seq = self;
3300
15
    PyObject_GC_Track(it);
3301
15
    return (PyObject *)it;
3302
15
}
3303
3304
static void
3305
listreviter_dealloc(listreviterobject *it)
3306
15
{
3307
15
    PyObject_GC_UnTrack(it);
3308
15
    Py_XDECREF(it->it_seq);
3309
15
    PyObject_GC_Del(it);
3310
15
}
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
}