Coverage Report

Created: 2022-07-08 09:39

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