PageRenderTime 66ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/Objects/listobject.c

https://bitbucket.org/akruis/fg2python
C | 2982 lines | 2324 code | 277 blank | 381 comment | 605 complexity | ed79700e882f124225429add52a9b118 MD5 | raw file
Possible License(s): 0BSD
  1. /* List object implementation */
  2. #include "Python.h"
  3. #include "accu.h"
  4. #ifdef STDC_HEADERS
  5. #include <stddef.h>
  6. #else
  7. #include <sys/types.h> /* For size_t */
  8. #endif
  9. /* Ensure ob_item has room for at least newsize elements, and set
  10. * ob_size to newsize. If newsize > ob_size on entry, the content
  11. * of the new slots at exit is undefined heap trash; it's the caller's
  12. * responsibility to overwrite them with sane values.
  13. * The number of allocated elements may grow, shrink, or stay the same.
  14. * Failure is impossible if newsize <= self.allocated on entry, although
  15. * that partly relies on an assumption that the system realloc() never
  16. * fails when passed a number of bytes <= the number of bytes last
  17. * allocated (the C standard doesn't guarantee this, but it's hard to
  18. * imagine a realloc implementation where it wouldn't be true).
  19. * Note that self->ob_item may change, and even if newsize is less
  20. * than ob_size on entry.
  21. */
  22. static int
  23. list_resize(PyListObject *self, Py_ssize_t newsize)
  24. {
  25. PyObject **items;
  26. size_t new_allocated;
  27. Py_ssize_t allocated = self->allocated;
  28. /* Bypass realloc() when a previous overallocation is large enough
  29. to accommodate the newsize. If the newsize falls lower than half
  30. the allocated size, then proceed with the realloc() to shrink the list.
  31. */
  32. if (allocated >= newsize && newsize >= (allocated >> 1)) {
  33. assert(self->ob_item != NULL || newsize == 0);
  34. Py_SIZE(self) = newsize;
  35. return 0;
  36. }
  37. /* This over-allocates proportional to the list size, making room
  38. * for additional growth. The over-allocation is mild, but is
  39. * enough to give linear-time amortized behavior over a long
  40. * sequence of appends() in the presence of a poorly-performing
  41. * system realloc().
  42. * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
  43. */
  44. new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6);
  45. /* check for integer overflow */
  46. if (new_allocated > PY_SIZE_MAX - newsize) {
  47. PyErr_NoMemory();
  48. return -1;
  49. } else {
  50. new_allocated += newsize;
  51. }
  52. if (newsize == 0)
  53. new_allocated = 0;
  54. items = self->ob_item;
  55. if (new_allocated <= (PY_SIZE_MAX / sizeof(PyObject *)))
  56. PyMem_RESIZE(items, PyObject *, new_allocated);
  57. else
  58. items = NULL;
  59. if (items == NULL) {
  60. PyErr_NoMemory();
  61. return -1;
  62. }
  63. self->ob_item = items;
  64. Py_SIZE(self) = newsize;
  65. self->allocated = new_allocated;
  66. return 0;
  67. }
  68. /* Debug statistic to compare allocations with reuse through the free list */
  69. #undef SHOW_ALLOC_COUNT
  70. #ifdef SHOW_ALLOC_COUNT
  71. static size_t count_alloc = 0;
  72. static size_t count_reuse = 0;
  73. static void
  74. show_alloc(void)
  75. {
  76. fprintf(stderr, "List allocations: %" PY_FORMAT_SIZE_T "d\n",
  77. count_alloc);
  78. fprintf(stderr, "List reuse through freelist: %" PY_FORMAT_SIZE_T
  79. "d\n", count_reuse);
  80. fprintf(stderr, "%.2f%% reuse rate\n\n",
  81. (100.0*count_reuse/(count_alloc+count_reuse)));
  82. }
  83. #endif
  84. /* Empty list reuse scheme to save calls to malloc and free */
  85. #ifndef PyList_MAXFREELIST
  86. #define PyList_MAXFREELIST 80
  87. #endif
  88. static PyListObject *free_list[PyList_MAXFREELIST];
  89. static int numfree = 0;
  90. int
  91. PyList_ClearFreeList(void)
  92. {
  93. PyListObject *op;
  94. int ret = numfree;
  95. while (numfree) {
  96. op = free_list[--numfree];
  97. assert(PyList_CheckExact(op));
  98. PyObject_GC_Del(op);
  99. }
  100. return ret;
  101. }
  102. void
  103. PyList_Fini(void)
  104. {
  105. PyList_ClearFreeList();
  106. }
  107. /* Print summary info about the state of the optimized allocator */
  108. void
  109. _PyList_DebugMallocStats(FILE *out)
  110. {
  111. _PyDebugAllocatorStats(out,
  112. "free PyListObject",
  113. numfree, sizeof(PyListObject));
  114. }
  115. PyObject *
  116. PyList_New(Py_ssize_t size)
  117. {
  118. PyListObject *op;
  119. size_t nbytes;
  120. #ifdef SHOW_ALLOC_COUNT
  121. static int initialized = 0;
  122. if (!initialized) {
  123. Py_AtExit(show_alloc);
  124. initialized = 1;
  125. }
  126. #endif
  127. if (size < 0) {
  128. PyErr_BadInternalCall();
  129. return NULL;
  130. }
  131. /* Check for overflow without an actual overflow,
  132. * which can cause compiler to optimise out */
  133. if ((size_t)size > PY_SIZE_MAX / sizeof(PyObject *))
  134. return PyErr_NoMemory();
  135. nbytes = size * sizeof(PyObject *);
  136. if (numfree) {
  137. numfree--;
  138. op = free_list[numfree];
  139. _Py_NewReference((PyObject *)op);
  140. #ifdef SHOW_ALLOC_COUNT
  141. count_reuse++;
  142. #endif
  143. } else {
  144. op = PyObject_GC_New(PyListObject, &PyList_Type);
  145. if (op == NULL)
  146. return NULL;
  147. #ifdef SHOW_ALLOC_COUNT
  148. count_alloc++;
  149. #endif
  150. }
  151. if (size <= 0)
  152. op->ob_item = NULL;
  153. else {
  154. op->ob_item = (PyObject **) PyMem_MALLOC(nbytes);
  155. if (op->ob_item == NULL) {
  156. Py_DECREF(op);
  157. return PyErr_NoMemory();
  158. }
  159. memset(op->ob_item, 0, nbytes);
  160. }
  161. Py_SIZE(op) = size;
  162. op->allocated = size;
  163. _PyObject_GC_TRACK(op);
  164. return (PyObject *) op;
  165. }
  166. Py_ssize_t
  167. PyList_Size(PyObject *op)
  168. {
  169. if (!PyList_Check(op)) {
  170. PyErr_BadInternalCall();
  171. return -1;
  172. }
  173. else
  174. return Py_SIZE(op);
  175. }
  176. static PyObject *indexerr = NULL;
  177. PyObject *
  178. PyList_GetItem(PyObject *op, Py_ssize_t i)
  179. {
  180. if (!PyList_Check(op)) {
  181. PyErr_BadInternalCall();
  182. return NULL;
  183. }
  184. if (i < 0 || i >= Py_SIZE(op)) {
  185. if (indexerr == NULL) {
  186. indexerr = PyUnicode_FromString(
  187. "list index out of range");
  188. if (indexerr == NULL)
  189. return NULL;
  190. }
  191. PyErr_SetObject(PyExc_IndexError, indexerr);
  192. return NULL;
  193. }
  194. return ((PyListObject *)op) -> ob_item[i];
  195. }
  196. int
  197. PyList_SetItem(PyObject *op, Py_ssize_t i,
  198. PyObject *newitem)
  199. {
  200. PyObject *olditem;
  201. PyObject **p;
  202. if (!PyList_Check(op)) {
  203. Py_XDECREF(newitem);
  204. PyErr_BadInternalCall();
  205. return -1;
  206. }
  207. if (i < 0 || i >= Py_SIZE(op)) {
  208. Py_XDECREF(newitem);
  209. PyErr_SetString(PyExc_IndexError,
  210. "list assignment index out of range");
  211. return -1;
  212. }
  213. p = ((PyListObject *)op) -> ob_item + i;
  214. olditem = *p;
  215. *p = newitem;
  216. Py_XDECREF(olditem);
  217. return 0;
  218. }
  219. static int
  220. ins1(PyListObject *self, Py_ssize_t where, PyObject *v)
  221. {
  222. Py_ssize_t i, n = Py_SIZE(self);
  223. PyObject **items;
  224. if (v == NULL) {
  225. PyErr_BadInternalCall();
  226. return -1;
  227. }
  228. if (n == PY_SSIZE_T_MAX) {
  229. PyErr_SetString(PyExc_OverflowError,
  230. "cannot add more objects to list");
  231. return -1;
  232. }
  233. if (list_resize(self, n+1) == -1)
  234. return -1;
  235. if (where < 0) {
  236. where += n;
  237. if (where < 0)
  238. where = 0;
  239. }
  240. if (where > n)
  241. where = n;
  242. items = self->ob_item;
  243. for (i = n; --i >= where; )
  244. items[i+1] = items[i];
  245. Py_INCREF(v);
  246. items[where] = v;
  247. return 0;
  248. }
  249. int
  250. PyList_Insert(PyObject *op, Py_ssize_t where, PyObject *newitem)
  251. {
  252. if (!PyList_Check(op)) {
  253. PyErr_BadInternalCall();
  254. return -1;
  255. }
  256. return ins1((PyListObject *)op, where, newitem);
  257. }
  258. static int
  259. app1(PyListObject *self, PyObject *v)
  260. {
  261. Py_ssize_t n = PyList_GET_SIZE(self);
  262. assert (v != NULL);
  263. if (n == PY_SSIZE_T_MAX) {
  264. PyErr_SetString(PyExc_OverflowError,
  265. "cannot add more objects to list");
  266. return -1;
  267. }
  268. if (list_resize(self, n+1) == -1)
  269. return -1;
  270. Py_INCREF(v);
  271. PyList_SET_ITEM(self, n, v);
  272. return 0;
  273. }
  274. int
  275. PyList_Append(PyObject *op, PyObject *newitem)
  276. {
  277. if (PyList_Check(op) && (newitem != NULL))
  278. return app1((PyListObject *)op, newitem);
  279. PyErr_BadInternalCall();
  280. return -1;
  281. }
  282. /* Methods */
  283. static void
  284. list_dealloc(PyListObject *op)
  285. {
  286. Py_ssize_t i;
  287. PyObject_GC_UnTrack(op);
  288. Py_TRASHCAN_SAFE_BEGIN(op)
  289. if (op->ob_item != NULL) {
  290. /* Do it backwards, for Christian Tismer.
  291. There's a simple test case where somehow this reduces
  292. thrashing when a *very* large list is created and
  293. immediately deleted. */
  294. i = Py_SIZE(op);
  295. while (--i >= 0) {
  296. Py_XDECREF(op->ob_item[i]);
  297. }
  298. PyMem_FREE(op->ob_item);
  299. }
  300. if (numfree < PyList_MAXFREELIST && PyList_CheckExact(op))
  301. free_list[numfree++] = op;
  302. else
  303. Py_TYPE(op)->tp_free((PyObject *)op);
  304. Py_TRASHCAN_SAFE_END(op)
  305. }
  306. static PyObject *
  307. list_repr(PyListObject *v)
  308. {
  309. Py_ssize_t i;
  310. PyObject *s;
  311. _PyUnicodeWriter writer;
  312. if (Py_SIZE(v) == 0) {
  313. return PyUnicode_FromString("[]");
  314. }
  315. i = Py_ReprEnter((PyObject*)v);
  316. if (i != 0) {
  317. return i > 0 ? PyUnicode_FromString("[...]") : NULL;
  318. }
  319. _PyUnicodeWriter_Init(&writer);
  320. writer.overallocate = 1;
  321. /* "[" + "1" + ", 2" * (len - 1) + "]" */
  322. writer.min_length = 1 + 1 + (2 + 1) * (Py_SIZE(v) - 1) + 1;
  323. if (_PyUnicodeWriter_WriteChar(&writer, '[') < 0)
  324. goto error;
  325. /* Do repr() on each element. Note that this may mutate the list,
  326. so must refetch the list size on each iteration. */
  327. for (i = 0; i < Py_SIZE(v); ++i) {
  328. if (i > 0) {
  329. if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0)
  330. goto error;
  331. }
  332. if (Py_EnterRecursiveCall(" while getting the repr of a list"))
  333. goto error;
  334. s = PyObject_Repr(v->ob_item[i]);
  335. Py_LeaveRecursiveCall();
  336. if (s == NULL)
  337. goto error;
  338. if (_PyUnicodeWriter_WriteStr(&writer, s) < 0) {
  339. Py_DECREF(s);
  340. goto error;
  341. }
  342. Py_DECREF(s);
  343. }
  344. writer.overallocate = 0;
  345. if (_PyUnicodeWriter_WriteChar(&writer, ']') < 0)
  346. goto error;
  347. Py_ReprLeave((PyObject *)v);
  348. return _PyUnicodeWriter_Finish(&writer);
  349. error:
  350. _PyUnicodeWriter_Dealloc(&writer);
  351. Py_ReprLeave((PyObject *)v);
  352. return NULL;
  353. }
  354. static Py_ssize_t
  355. list_length(PyListObject *a)
  356. {
  357. return Py_SIZE(a);
  358. }
  359. static int
  360. list_contains(PyListObject *a, PyObject *el)
  361. {
  362. Py_ssize_t i;
  363. int cmp;
  364. for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i)
  365. cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
  366. Py_EQ);
  367. return cmp;
  368. }
  369. static PyObject *
  370. list_item(PyListObject *a, Py_ssize_t i)
  371. {
  372. if (i < 0 || i >= Py_SIZE(a)) {
  373. if (indexerr == NULL) {
  374. indexerr = PyUnicode_FromString(
  375. "list index out of range");
  376. if (indexerr == NULL)
  377. return NULL;
  378. }
  379. PyErr_SetObject(PyExc_IndexError, indexerr);
  380. return NULL;
  381. }
  382. Py_INCREF(a->ob_item[i]);
  383. return a->ob_item[i];
  384. }
  385. static PyObject *
  386. list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
  387. {
  388. PyListObject *np;
  389. PyObject **src, **dest;
  390. Py_ssize_t i, len;
  391. if (ilow < 0)
  392. ilow = 0;
  393. else if (ilow > Py_SIZE(a))
  394. ilow = Py_SIZE(a);
  395. if (ihigh < ilow)
  396. ihigh = ilow;
  397. else if (ihigh > Py_SIZE(a))
  398. ihigh = Py_SIZE(a);
  399. len = ihigh - ilow;
  400. np = (PyListObject *) PyList_New(len);
  401. if (np == NULL)
  402. return NULL;
  403. src = a->ob_item + ilow;
  404. dest = np->ob_item;
  405. for (i = 0; i < len; i++) {
  406. PyObject *v = src[i];
  407. Py_INCREF(v);
  408. dest[i] = v;
  409. }
  410. return (PyObject *)np;
  411. }
  412. PyObject *
  413. PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
  414. {
  415. if (!PyList_Check(a)) {
  416. PyErr_BadInternalCall();
  417. return NULL;
  418. }
  419. return list_slice((PyListObject *)a, ilow, ihigh);
  420. }
  421. static PyObject *
  422. list_concat(PyListObject *a, PyObject *bb)
  423. {
  424. Py_ssize_t size;
  425. Py_ssize_t i;
  426. PyObject **src, **dest;
  427. PyListObject *np;
  428. if (!PyList_Check(bb)) {
  429. PyErr_Format(PyExc_TypeError,
  430. "can only concatenate list (not \"%.200s\") to list",
  431. bb->ob_type->tp_name);
  432. return NULL;
  433. }
  434. #define b ((PyListObject *)bb)
  435. size = Py_SIZE(a) + Py_SIZE(b);
  436. if (size < 0)
  437. return PyErr_NoMemory();
  438. np = (PyListObject *) PyList_New(size);
  439. if (np == NULL) {
  440. return NULL;
  441. }
  442. src = a->ob_item;
  443. dest = np->ob_item;
  444. for (i = 0; i < Py_SIZE(a); i++) {
  445. PyObject *v = src[i];
  446. Py_INCREF(v);
  447. dest[i] = v;
  448. }
  449. src = b->ob_item;
  450. dest = np->ob_item + Py_SIZE(a);
  451. for (i = 0; i < Py_SIZE(b); i++) {
  452. PyObject *v = src[i];
  453. Py_INCREF(v);
  454. dest[i] = v;
  455. }
  456. return (PyObject *)np;
  457. #undef b
  458. }
  459. static PyObject *
  460. list_repeat(PyListObject *a, Py_ssize_t n)
  461. {
  462. Py_ssize_t i, j;
  463. Py_ssize_t size;
  464. PyListObject *np;
  465. PyObject **p, **items;
  466. PyObject *elem;
  467. if (n < 0)
  468. n = 0;
  469. if (n > 0 && Py_SIZE(a) > PY_SSIZE_T_MAX / n)
  470. return PyErr_NoMemory();
  471. size = Py_SIZE(a) * n;
  472. if (size == 0)
  473. return PyList_New(0);
  474. np = (PyListObject *) PyList_New(size);
  475. if (np == NULL)
  476. return NULL;
  477. items = np->ob_item;
  478. if (Py_SIZE(a) == 1) {
  479. elem = a->ob_item[0];
  480. for (i = 0; i < n; i++) {
  481. items[i] = elem;
  482. Py_INCREF(elem);
  483. }
  484. return (PyObject *) np;
  485. }
  486. p = np->ob_item;
  487. items = a->ob_item;
  488. for (i = 0; i < n; i++) {
  489. for (j = 0; j < Py_SIZE(a); j++) {
  490. *p = items[j];
  491. Py_INCREF(*p);
  492. p++;
  493. }
  494. }
  495. return (PyObject *) np;
  496. }
  497. static int
  498. list_clear(PyListObject *a)
  499. {
  500. Py_ssize_t i;
  501. PyObject **item = a->ob_item;
  502. if (item != NULL) {
  503. /* Because XDECREF can recursively invoke operations on
  504. this list, we make it empty first. */
  505. i = Py_SIZE(a);
  506. Py_SIZE(a) = 0;
  507. a->ob_item = NULL;
  508. a->allocated = 0;
  509. while (--i >= 0) {
  510. Py_XDECREF(item[i]);
  511. }
  512. PyMem_FREE(item);
  513. }
  514. /* Never fails; the return value can be ignored.
  515. Note that there is no guarantee that the list is actually empty
  516. at this point, because XDECREF may have populated it again! */
  517. return 0;
  518. }
  519. /* a[ilow:ihigh] = v if v != NULL.
  520. * del a[ilow:ihigh] if v == NULL.
  521. *
  522. * Special speed gimmick: when v is NULL and ihigh - ilow <= 8, it's
  523. * guaranteed the call cannot fail.
  524. */
  525. static int
  526. list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
  527. {
  528. /* Because [X]DECREF can recursively invoke list operations on
  529. this list, we must postpone all [X]DECREF activity until
  530. after the list is back in its canonical shape. Therefore
  531. we must allocate an additional array, 'recycle', into which
  532. we temporarily copy the items that are deleted from the
  533. list. :-( */
  534. PyObject *recycle_on_stack[8];
  535. PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
  536. PyObject **item;
  537. PyObject **vitem = NULL;
  538. PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
  539. Py_ssize_t n; /* # of elements in replacement list */
  540. Py_ssize_t norig; /* # of elements in list getting replaced */
  541. Py_ssize_t d; /* Change in size */
  542. Py_ssize_t k;
  543. size_t s;
  544. int result = -1; /* guilty until proved innocent */
  545. #define b ((PyListObject *)v)
  546. if (v == NULL)
  547. n = 0;
  548. else {
  549. if (a == b) {
  550. /* Special case "a[i:j] = a" -- copy b first */
  551. v = list_slice(b, 0, Py_SIZE(b));
  552. if (v == NULL)
  553. return result;
  554. result = list_ass_slice(a, ilow, ihigh, v);
  555. Py_DECREF(v);
  556. return result;
  557. }
  558. v_as_SF = PySequence_Fast(v, "can only assign an iterable");
  559. if(v_as_SF == NULL)
  560. goto Error;
  561. n = PySequence_Fast_GET_SIZE(v_as_SF);
  562. vitem = PySequence_Fast_ITEMS(v_as_SF);
  563. }
  564. if (ilow < 0)
  565. ilow = 0;
  566. else if (ilow > Py_SIZE(a))
  567. ilow = Py_SIZE(a);
  568. if (ihigh < ilow)
  569. ihigh = ilow;
  570. else if (ihigh > Py_SIZE(a))
  571. ihigh = Py_SIZE(a);
  572. norig = ihigh - ilow;
  573. assert(norig >= 0);
  574. d = n - norig;
  575. if (Py_SIZE(a) + d == 0) {
  576. Py_XDECREF(v_as_SF);
  577. return list_clear(a);
  578. }
  579. item = a->ob_item;
  580. /* recycle the items that we are about to remove */
  581. s = norig * sizeof(PyObject *);
  582. if (s > sizeof(recycle_on_stack)) {
  583. recycle = (PyObject **)PyMem_MALLOC(s);
  584. if (recycle == NULL) {
  585. PyErr_NoMemory();
  586. goto Error;
  587. }
  588. }
  589. memcpy(recycle, &item[ilow], s);
  590. if (d < 0) { /* Delete -d items */
  591. Py_ssize_t tail;
  592. tail = (Py_SIZE(a) - ihigh) * sizeof(PyObject *);
  593. memmove(&item[ihigh+d], &item[ihigh], tail);
  594. if (list_resize(a, Py_SIZE(a) + d) < 0) {
  595. memmove(&item[ihigh], &item[ihigh+d], tail);
  596. memcpy(&item[ilow], recycle, s);
  597. goto Error;
  598. }
  599. item = a->ob_item;
  600. }
  601. else if (d > 0) { /* Insert d items */
  602. k = Py_SIZE(a);
  603. if (list_resize(a, k+d) < 0)
  604. goto Error;
  605. item = a->ob_item;
  606. memmove(&item[ihigh+d], &item[ihigh],
  607. (k - ihigh)*sizeof(PyObject *));
  608. }
  609. for (k = 0; k < n; k++, ilow++) {
  610. PyObject *w = vitem[k];
  611. Py_XINCREF(w);
  612. item[ilow] = w;
  613. }
  614. for (k = norig - 1; k >= 0; --k)
  615. Py_XDECREF(recycle[k]);
  616. result = 0;
  617. Error:
  618. if (recycle != recycle_on_stack)
  619. PyMem_FREE(recycle);
  620. Py_XDECREF(v_as_SF);
  621. return result;
  622. #undef b
  623. }
  624. int
  625. PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
  626. {
  627. if (!PyList_Check(a)) {
  628. PyErr_BadInternalCall();
  629. return -1;
  630. }
  631. return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
  632. }
  633. static PyObject *
  634. list_inplace_repeat(PyListObject *self, Py_ssize_t n)
  635. {
  636. PyObject **items;
  637. Py_ssize_t size, i, j, p;
  638. size = PyList_GET_SIZE(self);
  639. if (size == 0 || n == 1) {
  640. Py_INCREF(self);
  641. return (PyObject *)self;
  642. }
  643. if (n < 1) {
  644. (void)list_clear(self);
  645. Py_INCREF(self);
  646. return (PyObject *)self;
  647. }
  648. if (size > PY_SSIZE_T_MAX / n) {
  649. return PyErr_NoMemory();
  650. }
  651. if (list_resize(self, size*n) == -1)
  652. return NULL;
  653. p = size;
  654. items = self->ob_item;
  655. for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
  656. for (j = 0; j < size; j++) {
  657. PyObject *o = items[j];
  658. Py_INCREF(o);
  659. items[p++] = o;
  660. }
  661. }
  662. Py_INCREF(self);
  663. return (PyObject *)self;
  664. }
  665. static int
  666. list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v)
  667. {
  668. PyObject *old_value;
  669. if (i < 0 || i >= Py_SIZE(a)) {
  670. PyErr_SetString(PyExc_IndexError,
  671. "list assignment index out of range");
  672. return -1;
  673. }
  674. if (v == NULL)
  675. return list_ass_slice(a, i, i+1, v);
  676. Py_INCREF(v);
  677. old_value = a->ob_item[i];
  678. a->ob_item[i] = v;
  679. Py_DECREF(old_value);
  680. return 0;
  681. }
  682. static PyObject *
  683. listinsert(PyListObject *self, PyObject *args)
  684. {
  685. Py_ssize_t i;
  686. PyObject *v;
  687. if (!PyArg_ParseTuple(args, "nO:insert", &i, &v))
  688. return NULL;
  689. if (ins1(self, i, v) == 0)
  690. Py_RETURN_NONE;
  691. return NULL;
  692. }
  693. static PyObject *
  694. listclear(PyListObject *self)
  695. {
  696. list_clear(self);
  697. Py_RETURN_NONE;
  698. }
  699. static PyObject *
  700. listcopy(PyListObject *self)
  701. {
  702. return list_slice(self, 0, Py_SIZE(self));
  703. }
  704. static PyObject *
  705. listappend(PyListObject *self, PyObject *v)
  706. {
  707. if (app1(self, v) == 0)
  708. Py_RETURN_NONE;
  709. return NULL;
  710. }
  711. static PyObject *
  712. listextend(PyListObject *self, PyObject *b)
  713. {
  714. PyObject *it; /* iter(v) */
  715. Py_ssize_t m; /* size of self */
  716. Py_ssize_t n; /* guess for size of b */
  717. Py_ssize_t mn; /* m + n */
  718. Py_ssize_t i;
  719. PyObject *(*iternext)(PyObject *);
  720. /* Special cases:
  721. 1) lists and tuples which can use PySequence_Fast ops
  722. 2) extending self to self requires making a copy first
  723. */
  724. if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
  725. PyObject **src, **dest;
  726. b = PySequence_Fast(b, "argument must be iterable");
  727. if (!b)
  728. return NULL;
  729. n = PySequence_Fast_GET_SIZE(b);
  730. if (n == 0) {
  731. /* short circuit when b is empty */
  732. Py_DECREF(b);
  733. Py_RETURN_NONE;
  734. }
  735. m = Py_SIZE(self);
  736. if (list_resize(self, m + n) == -1) {
  737. Py_DECREF(b);
  738. return NULL;
  739. }
  740. /* note that we may still have self == b here for the
  741. * situation a.extend(a), but the following code works
  742. * in that case too. Just make sure to resize self
  743. * before calling PySequence_Fast_ITEMS.
  744. */
  745. /* populate the end of self with b's items */
  746. src = PySequence_Fast_ITEMS(b);
  747. dest = self->ob_item + m;
  748. for (i = 0; i < n; i++) {
  749. PyObject *o = src[i];
  750. Py_INCREF(o);
  751. dest[i] = o;
  752. }
  753. Py_DECREF(b);
  754. Py_RETURN_NONE;
  755. }
  756. it = PyObject_GetIter(b);
  757. if (it == NULL)
  758. return NULL;
  759. iternext = *it->ob_type->tp_iternext;
  760. /* Guess a result list size. */
  761. n = PyObject_LengthHint(b, 8);
  762. if (n == -1) {
  763. Py_DECREF(it);
  764. return NULL;
  765. }
  766. m = Py_SIZE(self);
  767. mn = m + n;
  768. if (mn >= m) {
  769. /* Make room. */
  770. if (list_resize(self, mn) == -1)
  771. goto error;
  772. /* Make the list sane again. */
  773. Py_SIZE(self) = m;
  774. }
  775. /* Else m + n overflowed; on the chance that n lied, and there really
  776. * is enough room, ignore it. If n was telling the truth, we'll
  777. * eventually run out of memory during the loop.
  778. */
  779. /* Run iterator to exhaustion. */
  780. for (;;) {
  781. PyObject *item = iternext(it);
  782. if (item == NULL) {
  783. if (PyErr_Occurred()) {
  784. if (PyErr_ExceptionMatches(PyExc_StopIteration))
  785. PyErr_Clear();
  786. else
  787. goto error;
  788. }
  789. break;
  790. }
  791. if (Py_SIZE(self) < self->allocated) {
  792. /* steals ref */
  793. PyList_SET_ITEM(self, Py_SIZE(self), item);
  794. ++Py_SIZE(self);
  795. }
  796. else {
  797. int status = app1(self, item);
  798. Py_DECREF(item); /* append creates a new ref */
  799. if (status < 0)
  800. goto error;
  801. }
  802. }
  803. /* Cut back result list if initial guess was too large. */
  804. if (Py_SIZE(self) < self->allocated) {
  805. if (list_resize(self, Py_SIZE(self)) < 0)
  806. goto error;
  807. }
  808. Py_DECREF(it);
  809. Py_RETURN_NONE;
  810. error:
  811. Py_DECREF(it);
  812. return NULL;
  813. }
  814. PyObject *
  815. _PyList_Extend(PyListObject *self, PyObject *b)
  816. {
  817. return listextend(self, b);
  818. }
  819. static PyObject *
  820. list_inplace_concat(PyListObject *self, PyObject *other)
  821. {
  822. PyObject *result;
  823. result = listextend(self, other);
  824. if (result == NULL)
  825. return result;
  826. Py_DECREF(result);
  827. Py_INCREF(self);
  828. return (PyObject *)self;
  829. }
  830. static PyObject *
  831. listpop(PyListObject *self, PyObject *args)
  832. {
  833. Py_ssize_t i = -1;
  834. PyObject *v;
  835. int status;
  836. if (!PyArg_ParseTuple(args, "|n:pop", &i))
  837. return NULL;
  838. if (Py_SIZE(self) == 0) {
  839. /* Special-case most common failure cause */
  840. PyErr_SetString(PyExc_IndexError, "pop from empty list");
  841. return NULL;
  842. }
  843. if (i < 0)
  844. i += Py_SIZE(self);
  845. if (i < 0 || i >= Py_SIZE(self)) {
  846. PyErr_SetString(PyExc_IndexError, "pop index out of range");
  847. return NULL;
  848. }
  849. v = self->ob_item[i];
  850. if (i == Py_SIZE(self) - 1) {
  851. status = list_resize(self, Py_SIZE(self) - 1);
  852. if (status >= 0)
  853. return v; /* and v now owns the reference the list had */
  854. else
  855. return NULL;
  856. }
  857. Py_INCREF(v);
  858. status = list_ass_slice(self, i, i+1, (PyObject *)NULL);
  859. if (status < 0) {
  860. Py_DECREF(v);
  861. return NULL;
  862. }
  863. return v;
  864. }
  865. /* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
  866. static void
  867. reverse_slice(PyObject **lo, PyObject **hi)
  868. {
  869. assert(lo && hi);
  870. --hi;
  871. while (lo < hi) {
  872. PyObject *t = *lo;
  873. *lo = *hi;
  874. *hi = t;
  875. ++lo;
  876. --hi;
  877. }
  878. }
  879. /* Lots of code for an adaptive, stable, natural mergesort. There are many
  880. * pieces to this algorithm; read listsort.txt for overviews and details.
  881. */
  882. /* A sortslice contains a pointer to an array of keys and a pointer to
  883. * an array of corresponding values. In other words, keys[i]
  884. * corresponds with values[i]. If values == NULL, then the keys are
  885. * also the values.
  886. *
  887. * Several convenience routines are provided here, so that keys and
  888. * values are always moved in sync.
  889. */
  890. typedef struct {
  891. PyObject **keys;
  892. PyObject **values;
  893. } sortslice;
  894. Py_LOCAL_INLINE(void)
  895. sortslice_copy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j)
  896. {
  897. s1->keys[i] = s2->keys[j];
  898. if (s1->values != NULL)
  899. s1->values[i] = s2->values[j];
  900. }
  901. Py_LOCAL_INLINE(void)
  902. sortslice_copy_incr(sortslice *dst, sortslice *src)
  903. {
  904. *dst->keys++ = *src->keys++;
  905. if (dst->values != NULL)
  906. *dst->values++ = *src->values++;
  907. }
  908. Py_LOCAL_INLINE(void)
  909. sortslice_copy_decr(sortslice *dst, sortslice *src)
  910. {
  911. *dst->keys-- = *src->keys--;
  912. if (dst->values != NULL)
  913. *dst->values-- = *src->values--;
  914. }
  915. Py_LOCAL_INLINE(void)
  916. sortslice_memcpy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
  917. Py_ssize_t n)
  918. {
  919. memcpy(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
  920. if (s1->values != NULL)
  921. memcpy(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
  922. }
  923. Py_LOCAL_INLINE(void)
  924. sortslice_memmove(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
  925. Py_ssize_t n)
  926. {
  927. memmove(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
  928. if (s1->values != NULL)
  929. memmove(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
  930. }
  931. Py_LOCAL_INLINE(void)
  932. sortslice_advance(sortslice *slice, Py_ssize_t n)
  933. {
  934. slice->keys += n;
  935. if (slice->values != NULL)
  936. slice->values += n;
  937. }
  938. /* Comparison function: PyObject_RichCompareBool with Py_LT.
  939. * Returns -1 on error, 1 if x < y, 0 if x >= y.
  940. */
  941. #define ISLT(X, Y) (PyObject_RichCompareBool(X, Y, Py_LT))
  942. /* Compare X to Y via "<". Goto "fail" if the comparison raises an
  943. error. Else "k" is set to true iff X<Y, and an "if (k)" block is
  944. started. It makes more sense in context <wink>. X and Y are PyObject*s.
  945. */
  946. #define IFLT(X, Y) if ((k = ISLT(X, Y)) < 0) goto fail; \
  947. if (k)
  948. /* binarysort is the best method for sorting small arrays: it does
  949. few compares, but can do data movement quadratic in the number of
  950. elements.
  951. [lo, hi) is a contiguous slice of a list, and is sorted via
  952. binary insertion. This sort is stable.
  953. On entry, must have lo <= start <= hi, and that [lo, start) is already
  954. sorted (pass start == lo if you don't know!).
  955. If islt() complains return -1, else 0.
  956. Even in case of error, the output slice will be some permutation of
  957. the input (nothing is lost or duplicated).
  958. */
  959. static int
  960. binarysort(sortslice lo, PyObject **hi, PyObject **start)
  961. {
  962. Py_ssize_t k;
  963. PyObject **l, **p, **r;
  964. PyObject *pivot;
  965. assert(lo.keys <= start && start <= hi);
  966. /* assert [lo, start) is sorted */
  967. if (lo.keys == start)
  968. ++start;
  969. for (; start < hi; ++start) {
  970. /* set l to where *start belongs */
  971. l = lo.keys;
  972. r = start;
  973. pivot = *r;
  974. /* Invariants:
  975. * pivot >= all in [lo, l).
  976. * pivot < all in [r, start).
  977. * The second is vacuously true at the start.
  978. */
  979. assert(l < r);
  980. do {
  981. p = l + ((r - l) >> 1);
  982. IFLT(pivot, *p)
  983. r = p;
  984. else
  985. l = p+1;
  986. } while (l < r);
  987. assert(l == r);
  988. /* The invariants still hold, so pivot >= all in [lo, l) and
  989. pivot < all in [l, start), so pivot belongs at l. Note
  990. that if there are elements equal to pivot, l points to the
  991. first slot after them -- that's why this sort is stable.
  992. Slide over to make room.
  993. Caution: using memmove is much slower under MSVC 5;
  994. we're not usually moving many slots. */
  995. for (p = start; p > l; --p)
  996. *p = *(p-1);
  997. *l = pivot;
  998. if (lo.values != NULL) {
  999. Py_ssize_t offset = lo.values - lo.keys;
  1000. p = start + offset;
  1001. pivot = *p;
  1002. l += offset;
  1003. for (p = start + offset; p > l; --p)
  1004. *p = *(p-1);
  1005. *l = pivot;
  1006. }
  1007. }
  1008. return 0;
  1009. fail:
  1010. return -1;
  1011. }
  1012. /*
  1013. Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
  1014. is required on entry. "A run" is the longest ascending sequence, with
  1015. lo[0] <= lo[1] <= lo[2] <= ...
  1016. or the longest descending sequence, with
  1017. lo[0] > lo[1] > lo[2] > ...
  1018. Boolean *descending is set to 0 in the former case, or to 1 in the latter.
  1019. For its intended use in a stable mergesort, the strictness of the defn of
  1020. "descending" is needed so that the caller can safely reverse a descending
  1021. sequence without violating stability (strict > ensures there are no equal
  1022. elements to get out of order).
  1023. Returns -1 in case of error.
  1024. */
  1025. static Py_ssize_t
  1026. count_run(PyObject **lo, PyObject **hi, int *descending)
  1027. {
  1028. Py_ssize_t k;
  1029. Py_ssize_t n;
  1030. assert(lo < hi);
  1031. *descending = 0;
  1032. ++lo;
  1033. if (lo == hi)
  1034. return 1;
  1035. n = 2;
  1036. IFLT(*lo, *(lo-1)) {
  1037. *descending = 1;
  1038. for (lo = lo+1; lo < hi; ++lo, ++n) {
  1039. IFLT(*lo, *(lo-1))
  1040. ;
  1041. else
  1042. break;
  1043. }
  1044. }
  1045. else {
  1046. for (lo = lo+1; lo < hi; ++lo, ++n) {
  1047. IFLT(*lo, *(lo-1))
  1048. break;
  1049. }
  1050. }
  1051. return n;
  1052. fail:
  1053. return -1;
  1054. }
  1055. /*
  1056. Locate the proper position of key in a sorted vector; if the vector contains
  1057. an element equal to key, return the position immediately to the left of
  1058. the leftmost equal element. [gallop_right() does the same except returns
  1059. the position to the right of the rightmost equal element (if any).]
  1060. "a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
  1061. "hint" is an index at which to begin the search, 0 <= hint < n. The closer
  1062. hint is to the final result, the faster this runs.
  1063. The return value is the int k in 0..n such that
  1064. a[k-1] < key <= a[k]
  1065. pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
  1066. key belongs at index k; or, IOW, the first k elements of a should precede
  1067. key, and the last n-k should follow key.
  1068. Returns -1 on error. See listsort.txt for info on the method.
  1069. */
  1070. static Py_ssize_t
  1071. gallop_left(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
  1072. {
  1073. Py_ssize_t ofs;
  1074. Py_ssize_t lastofs;
  1075. Py_ssize_t k;
  1076. assert(key && a && n > 0 && hint >= 0 && hint < n);
  1077. a += hint;
  1078. lastofs = 0;
  1079. ofs = 1;
  1080. IFLT(*a, key) {
  1081. /* a[hint] < key -- gallop right, until
  1082. * a[hint + lastofs] < key <= a[hint + ofs]
  1083. */
  1084. const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
  1085. while (ofs < maxofs) {
  1086. IFLT(a[ofs], key) {
  1087. lastofs = ofs;
  1088. ofs = (ofs << 1) + 1;
  1089. if (ofs <= 0) /* int overflow */
  1090. ofs = maxofs;
  1091. }
  1092. else /* key <= a[hint + ofs] */
  1093. break;
  1094. }
  1095. if (ofs > maxofs)
  1096. ofs = maxofs;
  1097. /* Translate back to offsets relative to &a[0]. */
  1098. lastofs += hint;
  1099. ofs += hint;
  1100. }
  1101. else {
  1102. /* key <= a[hint] -- gallop left, until
  1103. * a[hint - ofs] < key <= a[hint - lastofs]
  1104. */
  1105. const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
  1106. while (ofs < maxofs) {
  1107. IFLT(*(a-ofs), key)
  1108. break;
  1109. /* key <= a[hint - ofs] */
  1110. lastofs = ofs;
  1111. ofs = (ofs << 1) + 1;
  1112. if (ofs <= 0) /* int overflow */
  1113. ofs = maxofs;
  1114. }
  1115. if (ofs > maxofs)
  1116. ofs = maxofs;
  1117. /* Translate back to positive offsets relative to &a[0]. */
  1118. k = lastofs;
  1119. lastofs = hint - ofs;
  1120. ofs = hint - k;
  1121. }
  1122. a -= hint;
  1123. assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
  1124. /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
  1125. * right of lastofs but no farther right than ofs. Do a binary
  1126. * search, with invariant a[lastofs-1] < key <= a[ofs].
  1127. */
  1128. ++lastofs;
  1129. while (lastofs < ofs) {
  1130. Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
  1131. IFLT(a[m], key)
  1132. lastofs = m+1; /* a[m] < key */
  1133. else
  1134. ofs = m; /* key <= a[m] */
  1135. }
  1136. assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
  1137. return ofs;
  1138. fail:
  1139. return -1;
  1140. }
  1141. /*
  1142. Exactly like gallop_left(), except that if key already exists in a[0:n],
  1143. finds the position immediately to the right of the rightmost equal value.
  1144. The return value is the int k in 0..n such that
  1145. a[k-1] <= key < a[k]
  1146. or -1 if error.
  1147. The code duplication is massive, but this is enough different given that
  1148. we're sticking to "<" comparisons that it's much harder to follow if
  1149. written as one routine with yet another "left or right?" flag.
  1150. */
  1151. static Py_ssize_t
  1152. gallop_right(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
  1153. {
  1154. Py_ssize_t ofs;
  1155. Py_ssize_t lastofs;
  1156. Py_ssize_t k;
  1157. assert(key && a && n > 0 && hint >= 0 && hint < n);
  1158. a += hint;
  1159. lastofs = 0;
  1160. ofs = 1;
  1161. IFLT(key, *a) {
  1162. /* key < a[hint] -- gallop left, until
  1163. * a[hint - ofs] <= key < a[hint - lastofs]
  1164. */
  1165. const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
  1166. while (ofs < maxofs) {
  1167. IFLT(key, *(a-ofs)) {
  1168. lastofs = ofs;
  1169. ofs = (ofs << 1) + 1;
  1170. if (ofs <= 0) /* int overflow */
  1171. ofs = maxofs;
  1172. }
  1173. else /* a[hint - ofs] <= key */
  1174. break;
  1175. }
  1176. if (ofs > maxofs)
  1177. ofs = maxofs;
  1178. /* Translate back to positive offsets relative to &a[0]. */
  1179. k = lastofs;
  1180. lastofs = hint - ofs;
  1181. ofs = hint - k;
  1182. }
  1183. else {
  1184. /* a[hint] <= key -- gallop right, until
  1185. * a[hint + lastofs] <= key < a[hint + ofs]
  1186. */
  1187. const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
  1188. while (ofs < maxofs) {
  1189. IFLT(key, a[ofs])
  1190. break;
  1191. /* a[hint + ofs] <= key */
  1192. lastofs = ofs;
  1193. ofs = (ofs << 1) + 1;
  1194. if (ofs <= 0) /* int overflow */
  1195. ofs = maxofs;
  1196. }
  1197. if (ofs > maxofs)
  1198. ofs = maxofs;
  1199. /* Translate back to offsets relative to &a[0]. */
  1200. lastofs += hint;
  1201. ofs += hint;
  1202. }
  1203. a -= hint;
  1204. assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
  1205. /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
  1206. * right of lastofs but no farther right than ofs. Do a binary
  1207. * search, with invariant a[lastofs-1] <= key < a[ofs].
  1208. */
  1209. ++lastofs;
  1210. while (lastofs < ofs) {
  1211. Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
  1212. IFLT(key, a[m])
  1213. ofs = m; /* key < a[m] */
  1214. else
  1215. lastofs = m+1; /* a[m] <= key */
  1216. }
  1217. assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
  1218. return ofs;
  1219. fail:
  1220. return -1;
  1221. }
  1222. /* The maximum number of entries in a MergeState's pending-runs stack.
  1223. * This is enough to sort arrays of size up to about
  1224. * 32 * phi ** MAX_MERGE_PENDING
  1225. * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
  1226. * with 2**64 elements.
  1227. */
  1228. #define MAX_MERGE_PENDING 85
  1229. /* When we get into galloping mode, we stay there until both runs win less
  1230. * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
  1231. */
  1232. #define MIN_GALLOP 7
  1233. /* Avoid malloc for small temp arrays. */
  1234. #define MERGESTATE_TEMP_SIZE 256
  1235. /* One MergeState exists on the stack per invocation of mergesort. It's just
  1236. * a convenient way to pass state around among the helper functions.
  1237. */
  1238. struct s_slice {
  1239. sortslice base;
  1240. Py_ssize_t len;
  1241. };
  1242. typedef struct s_MergeState {
  1243. /* This controls when we get *into* galloping mode. It's initialized
  1244. * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
  1245. * random data, and lower for highly structured data.
  1246. */
  1247. Py_ssize_t min_gallop;
  1248. /* 'a' is temp storage to help with merges. It contains room for
  1249. * alloced entries.
  1250. */
  1251. sortslice a; /* may point to temparray below */
  1252. Py_ssize_t alloced;
  1253. /* A stack of n pending runs yet to be merged. Run #i starts at
  1254. * address base[i] and extends for len[i] elements. It's always
  1255. * true (so long as the indices are in bounds) that
  1256. *
  1257. * pending[i].base + pending[i].len == pending[i+1].base
  1258. *
  1259. * so we could cut the storage for this, but it's a minor amount,
  1260. * and keeping all the info explicit simplifies the code.
  1261. */
  1262. int n;
  1263. struct s_slice pending[MAX_MERGE_PENDING];
  1264. /* 'a' points to this when possible, rather than muck with malloc. */
  1265. PyObject *temparray[MERGESTATE_TEMP_SIZE];
  1266. } MergeState;
  1267. /* Conceptually a MergeState's constructor. */
  1268. static void
  1269. merge_init(MergeState *ms, Py_ssize_t list_size, int has_keyfunc)
  1270. {
  1271. assert(ms != NULL);
  1272. if (has_keyfunc) {
  1273. /* The temporary space for merging will need at most half the list
  1274. * size rounded up. Use the minimum possible space so we can use the
  1275. * rest of temparray for other things. In particular, if there is
  1276. * enough extra space, listsort() will use it to store the keys.
  1277. */
  1278. ms->alloced = (list_size + 1) / 2;
  1279. /* ms->alloced describes how many keys will be stored at
  1280. ms->temparray, but we also need to store the values. Hence,
  1281. ms->alloced is capped at half of MERGESTATE_TEMP_SIZE. */
  1282. if (MERGESTATE_TEMP_SIZE / 2 < ms->alloced)
  1283. ms->alloced = MERGESTATE_TEMP_SIZE / 2;
  1284. ms->a.values = &ms->temparray[ms->alloced];
  1285. }
  1286. else {
  1287. ms->alloced = MERGESTATE_TEMP_SIZE;
  1288. ms->a.values = NULL;
  1289. }
  1290. ms->a.keys = ms->temparray;
  1291. ms->n = 0;
  1292. ms->min_gallop = MIN_GALLOP;
  1293. }
  1294. /* Free all the temp memory owned by the MergeState. This must be called
  1295. * when you're done with a MergeState, and may be called before then if
  1296. * you want to free the temp memory early.
  1297. */
  1298. static void
  1299. merge_freemem(MergeState *ms)
  1300. {
  1301. assert(ms != NULL);
  1302. if (ms->a.keys != ms->temparray)
  1303. PyMem_Free(ms->a.keys);
  1304. }
  1305. /* Ensure enough temp memory for 'need' array slots is available.
  1306. * Returns 0 on success and -1 if the memory can't be gotten.
  1307. */
  1308. static int
  1309. merge_getmem(MergeState *ms, Py_ssize_t need)
  1310. {
  1311. int multiplier;
  1312. assert(ms != NULL);
  1313. if (need <= ms->alloced)
  1314. return 0;
  1315. multiplier = ms->a.values != NULL ? 2 : 1;
  1316. /* Don't realloc! That can cost cycles to copy the old data, but
  1317. * we don't care what's in the block.
  1318. */
  1319. merge_freemem(ms);
  1320. if ((size_t)need > PY_SSIZE_T_MAX / sizeof(PyObject*) / multiplier) {
  1321. PyErr_NoMemory();
  1322. return -1;
  1323. }
  1324. ms->a.keys = (PyObject**)PyMem_Malloc(multiplier * need
  1325. * sizeof(PyObject *));
  1326. if (ms->a.keys != NULL) {
  1327. ms->alloced = need;
  1328. if (ms->a.values != NULL)
  1329. ms->a.values = &ms->a.keys[need];
  1330. return 0;
  1331. }
  1332. PyErr_NoMemory();
  1333. return -1;
  1334. }
  1335. #define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
  1336. merge_getmem(MS, NEED))
  1337. /* Merge the na elements starting at ssa with the nb elements starting at
  1338. * ssb.keys = ssa.keys + na in a stable way, in-place. na and nb must be > 0.
  1339. * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
  1340. * should have na <= nb. See listsort.txt for more info. Return 0 if
  1341. * successful, -1 if error.
  1342. */
  1343. static Py_ssize_t
  1344. merge_lo(MergeState *ms, sortslice ssa, Py_ssize_t na,
  1345. sortslice ssb, Py_ssize_t nb)
  1346. {
  1347. Py_ssize_t k;
  1348. sortslice dest;
  1349. int result = -1; /* guilty until proved innocent */
  1350. Py_ssize_t min_gallop;
  1351. assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
  1352. assert(ssa.keys + na == ssb.keys);
  1353. if (MERGE_GETMEM(ms, na) < 0)
  1354. return -1;
  1355. sortslice_memcpy(&ms->a, 0, &ssa, 0, na);
  1356. dest = ssa;
  1357. ssa = ms->a;
  1358. sortslice_copy_incr(&dest, &ssb);
  1359. --nb;
  1360. if (nb == 0)
  1361. goto Succeed;
  1362. if (na == 1)
  1363. goto CopyB;
  1364. min_gallop = ms->min_gallop;
  1365. for (;;) {
  1366. Py_ssize_t acount = 0; /* # of times A won in a row */
  1367. Py_ssize_t bcount = 0; /* # of times B won in a row */
  1368. /* Do the straightforward thing until (if ever) one run
  1369. * appears to win consistently.
  1370. */
  1371. for (;;) {
  1372. assert(na > 1 && nb > 0);
  1373. k = ISLT(ssb.keys[0], ssa.keys[0]);
  1374. if (k) {
  1375. if (k < 0)
  1376. goto Fail;
  1377. sortslice_copy_incr(&dest, &ssb);
  1378. ++bcount;
  1379. acount = 0;
  1380. --nb;
  1381. if (nb == 0)
  1382. goto Succeed;
  1383. if (bcount >= min_gallop)
  1384. break;
  1385. }
  1386. else {
  1387. sortslice_copy_incr(&dest, &ssa);
  1388. ++acount;
  1389. bcount = 0;
  1390. --na;
  1391. if (na == 1)
  1392. goto CopyB;
  1393. if (acount >= min_gallop)
  1394. break;
  1395. }
  1396. }
  1397. /* One run is winning so consistently that galloping may
  1398. * be a huge win. So try that, and continue galloping until
  1399. * (if ever) neither run appears to be winning consistently
  1400. * anymore.
  1401. */
  1402. ++min_gallop;
  1403. do {
  1404. assert(na > 1 && nb > 0);
  1405. min_gallop -= min_gallop > 1;
  1406. ms->min_gallop = min_gallop;
  1407. k = gallop_right(ssb.keys[0], ssa.keys, na, 0);
  1408. acount = k;
  1409. if (k) {
  1410. if (k < 0)
  1411. goto Fail;
  1412. sortslice_memcpy(&dest, 0, &ssa, 0, k);
  1413. sortslice_advance(&dest, k);
  1414. sortslice_advance(&ssa, k);
  1415. na -= k;
  1416. if (na == 1)
  1417. goto CopyB;
  1418. /* na==0 is impossible now if the comparison
  1419. * function is consistent, but we can't assume
  1420. * that it is.
  1421. */
  1422. if (na == 0)
  1423. goto Succeed;
  1424. }
  1425. sortslice_copy_incr(&dest, &ssb);
  1426. --nb;
  1427. if (nb == 0)
  1428. goto Succeed;
  1429. k = gallop_left(ssa.keys[0], ssb.keys, nb, 0);
  1430. bcount = k;
  1431. if (k) {
  1432. if (k < 0)
  1433. goto Fail;
  1434. sortslice_memmove(&dest, 0, &ssb, 0, k);
  1435. sortslice_advance(&dest, k);
  1436. sortslice_advance(&ssb, k);
  1437. nb -= k;
  1438. if (nb == 0)
  1439. goto Succeed;
  1440. }
  1441. sortslice_copy_incr(&dest, &ssa);
  1442. --na;
  1443. if (na == 1)
  1444. goto CopyB;
  1445. } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
  1446. ++min_gallop; /* penalize it for leaving galloping mode */
  1447. ms->min_gallop = min_gallop;
  1448. }
  1449. Succeed:
  1450. result = 0;
  1451. Fail:
  1452. if (na)
  1453. sortslice_memcpy(&dest, 0, &ssa, 0, na);
  1454. return result;
  1455. CopyB:
  1456. assert(na == 1 && nb > 0);
  1457. /* The last element of ssa belongs at the end of the merge. */
  1458. sortslice_memmove(&dest, 0, &ssb, 0, nb);
  1459. sortslice_copy(&dest, nb, &ssa, 0);
  1460. return 0;
  1461. }
  1462. /* Merge the na elements starting at pa with the nb elements starting at
  1463. * ssb.keys = ssa.keys + na in a stable way, in-place. na and nb must be > 0.
  1464. * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
  1465. * should have na >= nb. See listsort.txt for more info. Return 0 if
  1466. * successful, -1 if error.
  1467. */
  1468. static Py_ssize_t
  1469. merge_hi(MergeState *ms, sortslice ssa, Py_ssize_t na,
  1470. sortslice ssb, Py_ssize_t nb)
  1471. {
  1472. Py_ssize_t k;
  1473. sortslice dest, basea, baseb;
  1474. int result = -1; /* guilty until proved innocent */
  1475. Py_ssize_t min_gallop;
  1476. assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
  1477. assert(ssa.keys + na == ssb.keys);
  1478. if (MERGE_GETMEM(ms, nb) < 0)
  1479. return -1;
  1480. dest = ssb;
  1481. sortslice_advance(&dest, nb-1);
  1482. sortslice_memcpy(&ms->a, 0, &ssb, 0, nb);
  1483. basea = ssa;
  1484. baseb = ms->a;
  1485. ssb.keys = ms->a.keys + nb - 1;
  1486. if (ssb.values != NULL)
  1487. ssb.values = ms->a.values + nb - 1;
  1488. sortslice_advance(&ssa, na - 1);
  1489. sortslice_copy_decr(&dest, &ssa);
  1490. --na;
  1491. if (na == 0)
  1492. goto Succeed;
  1493. if (nb == 1)
  1494. goto CopyA;
  1495. min_gallop = ms->min_gallop;
  1496. for (;;) {
  1497. Py_ssize_t acount = 0; /* # of times A won in a row */
  1498. Py_ssize_t bcount = 0; /* # of times B won in a row */
  1499. /* Do the straightforward thing until (if ever) one run
  1500. * appears to win consistently.
  1501. */
  1502. for (;;) {
  1503. assert(na > 0 && nb > 1);
  1504. k = ISLT(ssb.keys[0], ssa.keys[0]);
  1505. if (k) {
  1506. if (k < 0)
  1507. goto Fail;
  1508. sortslice_copy_decr(&dest, &ssa);
  1509. ++acount;
  1510. bcount = 0;
  1511. --na;
  1512. if (na == 0)
  1513. goto Succeed;
  1514. if (acount >= min_gallop)
  1515. break;
  1516. }
  1517. else {
  1518. sortslice_copy_decr(&dest, &ssb);
  1519. ++bcount;
  1520. acount = 0;
  1521. --nb;
  1522. if (nb == 1)
  1523. goto CopyA;
  1524. if (bcount >= min_gallop)
  1525. break;
  1526. }
  1527. }
  1528. /* One run is winning so consistently that galloping may
  1529. * be a huge win. So try that, and continue galloping until
  1530. * (if ever) neither run appears to be winning consistently
  1531. * anymore.
  1532. */
  1533. ++min_gallop;
  1534. do {
  1535. assert(na > 0 && nb > 1);
  1536. min_gallop -= min_gallop > 1;
  1537. ms->min_gallop = min_gallop;
  1538. k = gallop_right(ssb.keys[0], basea.keys, na, na-1);
  1539. if (k < 0)
  1540. goto Fail;
  1541. k = na - k;
  1542. acount = k;
  1543. if (k) {
  1544. sortslice_advance(&dest, -k);
  1545. sortslice_advance(&ssa, -k);
  1546. sortslice_memmove(&dest, 1, &ssa, 1, k);
  1547. na -= k;
  1548. if (na == 0)
  1549. goto Succeed;
  1550. }
  1551. sortslice_copy_decr(&dest, &ssb);
  1552. --nb;
  1553. if (nb == 1)
  1554. goto CopyA;
  1555. k = gallop_left(ssa.keys[0], baseb.keys, nb, nb-1);
  1556. if (k < 0)
  1557. goto Fail;
  1558. k = nb - k;
  1559. bcount = k;
  1560. if (k) {
  1561. sortslice_advance(&dest, -k);
  1562. sortslice_advance(&ssb, -k);
  1563. sortslice_memcpy(&dest, 1, &ssb, 1, k);
  1564. nb -= k;
  1565. if (nb == 1)
  1566. goto CopyA;
  1567. /* nb==0 is impossible now if the comparison
  1568. * function is consistent, but we can't assume
  1569. * that it is.
  1570. */
  1571. if (nb == 0)
  1572. goto Succeed;
  1573. }
  1574. sortslice_copy_decr(&dest, &ssa);
  1575. --na;
  1576. if (na == 0)
  1577. goto Succeed;
  1578. } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
  1579. ++min_gallop; /* penalize it for leaving galloping mode */
  1580. ms->min_gallop = min_gallop;
  1581. }
  1582. Succeed:
  1583. result = 0;
  1584. Fail:
  1585. if (nb)
  1586. sortslice_memcpy(&dest, -(nb-1), &baseb, 0, nb);
  1587. return result;
  1588. CopyA:
  1589. assert(nb == 1 && na > 0);
  1590. /* The first element of ssb belongs at the front of the merge. */
  1591. sortslice_memmove(&dest, 1-na, &ssa, 1-na, na);
  1592. sortslice_advance(&dest, -na);
  1593. sortslice_advance(&ssa, -na);
  1594. sortslice_copy(&dest, 0, &ssb, 0);
  1595. return 0;
  1596. }
  1597. /* Merge the two runs at stack indices i and i+1.
  1598. * Returns 0 on success, -1 on error.
  1599. */
  1600. static Py_ssize_t
  1601. merge_at(MergeState *ms, Py_ssize_t i)
  1602. {
  1603. sortslice ssa, ssb;
  1604. Py_ssize_t na, nb;
  1605. Py_ssize_t k;
  1606. assert(ms != NULL);
  1607. assert(ms->n >= 2);
  1608. assert(i >= 0);
  1609. assert(i == ms->n - 2 || i == ms->n - 3);
  1610. ssa = ms->pending[i].base;
  1611. na = ms->pending[i].len;
  1612. ssb = ms->pending[i+1].base;
  1613. nb = ms->pending[i+1].len;
  1614. assert(na > 0 && nb > 0);
  1615. assert(ssa.keys + na == ssb.keys);
  1616. /* Record the length of the combined runs; if i is the 3rd-last
  1617. * run now, also slide over the last run (which isn't involved
  1618. * in this merge). The current run i+1 goes away in any case.
  1619. */
  1620. ms->pending[i].len = na + nb;
  1621. if (i == ms->n - 3)
  1622. ms->pending[i+1] = ms->pending[i+2];
  1623. --ms->n;
  1624. /* Where does b start in a? Elements in a before that can be
  1625. * ignored (already in place).
  1626. */
  1627. k = gallop_right(*ssb.keys, ssa.keys, na, 0);
  1628. if (k < 0)
  1629. return -1;
  1630. sortslice_advance(&ssa, k);
  1631. na -= k;
  1632. if (na == 0)
  1633. return 0;
  1634. /* Where does a end in b? Elements in b after that can be
  1635. * ignored (already in place).
  1636. */
  1637. nb = gallop_left(ssa.keys[na-1], ssb.keys, nb, nb-1);
  1638. if (nb <= 0)
  1639. return nb;
  1640. /* Merge what remains of the runs, using a temp array with
  1641. * min(na, nb) elements.
  1642. */
  1643. if (na <= nb)
  1644. return merge_lo(ms, ssa, na, ssb, nb);
  1645. else
  1646. return merge_hi(ms, ssa, na, ssb, nb);
  1647. }
  1648. /* Examine the stack of runs waiting to be merged, merging adjacent runs
  1649. * until the stack invariants are re-established:
  1650. *
  1651. * 1. len[-3] > len[-2] + len[-1]
  1652. * 2. len[-2] > len[-1]
  1653. *
  1654. * See listsort.txt for more info.
  1655. *
  1656. * Returns 0 on success, -1 on error.
  1657. */
  1658. static int
  1659. merge_collapse(MergeState *ms)
  1660. {
  1661. struct s_slice *p = ms->pending;
  1662. assert(ms);
  1663. while (ms->n > 1) {
  1664. Py_ssize_t n = ms->n - 2;
  1665. if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) {
  1666. if (p[n-1].len < p[n+1].len)
  1667. --n;
  1668. if (merge_at(ms, n) < 0)
  1669. return -1;
  1670. }
  1671. else if (p[n].len <= p[n+1].len) {
  1672. if (merge_at(ms, n) < 0)
  1673. return -1;
  1674. }
  1675. else
  1676. break;
  1677. }
  1678. return 0;
  1679. }
  1680. /* Regardless of invariants, merge all runs on the stack until only one
  1681. * remains. This is used at the end of the mergesort.
  1682. *
  1683. * Returns 0 on success, -1 on error.
  1684. */
  1685. static int
  1686. merge_force_collapse(MergeState *ms)
  1687. {
  1688. struct s_slice *p = ms->pending;
  1689. assert(ms);
  1690. while (ms->n > 1) {
  1691. Py_ssize_t n = ms->n - 2;
  1692. if (n > 0 && p[n-1].len < p[n+1].len)
  1693. --n;
  1694. if (merge_at(ms, n) < 0)
  1695. return -1;
  1696. }
  1697. return 0;
  1698. }
  1699. /* Compute a good value for the minimum run length; natural runs shorter
  1700. * than this are boosted artificially via binary insertion.
  1701. *
  1702. * If n < 64, return n (it's too small to bother with fancy stuff).
  1703. * Else if n is an exact power of 2, return 32.
  1704. * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
  1705. * strictly less than, an exact power of 2.
  1706. *
  1707. * See listsort.txt for more info.
  1708. */
  1709. static Py_ssize_t
  1710. merge_compute_minrun(Py_ssize_t n)
  1711. {
  1712. Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */
  1713. assert(n >= 0);
  1714. while (n >= 64) {
  1715. r |= n & 1;
  1716. n >>= 1;
  1717. }
  1718. return n + r;
  1719. }
  1720. static void
  1721. reverse_sortslice(sortslice *s, Py_ssize_t n)
  1722. {
  1723. reverse_slice(s->keys, &s->keys[n]);
  1724. if (s->values != NULL)
  1725. reverse_slice(s->values, &s->values[n]);
  1726. }
  1727. /* An adaptive, stable, natural mergesort. See listsort.txt.
  1728. * Returns Py_None on success, NULL on error. Even in case of error, the
  1729. * list will be some permutation of its input state (nothing is lost or
  1730. * duplicated).
  1731. */
  1732. static PyObject *
  1733. listsort(PyListObject *self, PyObject *args, PyObject *kwds)
  1734. {
  1735. MergeState ms;
  1736. Py_ssize_t nremaining;
  1737. Py_ssize_t minrun;
  1738. sortslice lo;
  1739. Py_ssize_t saved_ob_size, saved_allocated;
  1740. PyObject **saved_ob_item;
  1741. PyObject **final_ob_item;
  1742. PyObject *result = NULL; /* guilty until proved innocent */
  1743. int reverse = 0;
  1744. PyObject *keyfunc = NULL;
  1745. Py_ssize_t i;
  1746. static char *kwlist[] = {"key", "reverse", 0};
  1747. PyObject **keys;
  1748. assert(self != NULL);
  1749. assert (PyList_Check(self));
  1750. if (args != NULL) {
  1751. if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:sort",
  1752. kwlist, &keyfunc, &reverse))
  1753. return NULL;
  1754. if (Py_SIZE(args) > 0) {
  1755. PyErr_SetString(PyExc_TypeError,
  1756. "must use keyword argument for key function");
  1757. return NULL;
  1758. }
  1759. }
  1760. if (keyfunc == Py_None)
  1761. keyfunc = NULL;
  1762. /* The list is temporarily made empty, so that mutations performed
  1763. * by comparison functions can't affect the slice of memory we're
  1764. * sorting (allowing mutations during sorting is a core-dump
  1765. * factory, since ob_item may change).
  1766. */
  1767. saved_ob_size = Py_SIZE(self);
  1768. saved_ob_item = self->ob_item;
  1769. saved_allocated = self->allocated;
  1770. Py_SIZE(self) = 0;
  1771. self->ob_item = NULL;
  1772. self->allocated = -1; /* any operation will reset it to >= 0 */
  1773. if (keyfunc == NULL) {
  1774. keys = NULL;
  1775. lo.keys = saved_ob_item;
  1776. lo.values = NULL;
  1777. }
  1778. else {
  1779. if (saved_ob_size < MERGESTATE_TEMP_SIZE/2)
  1780. /* Leverage stack space we allocated but won't otherwise use */
  1781. keys = &ms.temparray[saved_ob_size+1];
  1782. else {
  1783. keys = PyMem_MALLOC(sizeof(PyObject *) * saved_ob_size);
  1784. if (keys == NULL)
  1785. return NULL;
  1786. }
  1787. for (i = 0; i < saved_ob_size ; i++) {
  1788. keys[i] = PyObject_CallFunctionObjArgs(keyfunc, saved_ob_item[i],
  1789. NULL);
  1790. if (keys[i] == NULL) {
  1791. for (i=i-1 ; i>=0 ; i--)
  1792. Py_DECREF(keys[i]);
  1793. if (keys != &ms.temparray[saved_ob_size+1])
  1794. PyMem_FREE(keys);
  1795. goto keyfunc_fail;
  1796. }
  1797. }
  1798. lo.keys = keys;
  1799. lo.values = saved_ob_item;
  1800. }
  1801. merge_init(&ms, saved_ob_size, keys != NULL);
  1802. nremaining = saved_ob_size;
  1803. if (nremaining < 2)
  1804. goto succeed;
  1805. /* Reverse sort stability achieved by initially reversing the list,
  1806. applying a stable forward sort, then reversing the final result. */
  1807. if (reverse) {
  1808. if (keys != NULL)
  1809. reverse_slice(&keys[0], &keys[saved_ob_size]);
  1810. reverse_slice(&saved_ob_item[0], &saved_ob_item[saved_ob_size]);
  1811. }
  1812. /* March over the array once, left to right, finding natural runs,
  1813. * and extending short natural runs to minrun elements.
  1814. */
  1815. minrun = merge_compute_minrun(nremaining);
  1816. do {
  1817. int descending;
  1818. Py_ssize_t n;
  1819. /* Identify next run. */
  1820. n = count_run(lo.keys, lo.keys + nremaining, &descending);
  1821. if (n < 0)
  1822. goto fail;
  1823. if (descending)
  1824. reverse_sortslice(&lo, n);
  1825. /* If short, extend to min(minrun, nremaining). */
  1826. if (n < minrun) {
  1827. const Py_ssize_t force = nremaining <= minrun ?
  1828. nremaining : minrun;
  1829. if (binarysort(lo, lo.keys + force, lo.keys + n) < 0)
  1830. goto fail;
  1831. n = force;
  1832. }
  1833. /* Push run onto pending-runs stack, and maybe merge. */
  1834. assert(ms.n < MAX_MERGE_PENDING);
  1835. ms.pending[ms.n].base = lo;
  1836. ms.pending[ms.n].len = n;
  1837. ++ms.n;
  1838. if (merge_collapse(&ms) < 0)
  1839. goto fail;
  1840. /* Advance to find next run. */
  1841. sortslice_advance(&lo, n);
  1842. nremaining -= n;
  1843. } while (nremaining);
  1844. if (merge_force_collapse(&ms) < 0)
  1845. goto fail;
  1846. assert(ms.n == 1);
  1847. assert(keys == NULL
  1848. ? ms.pending[0].base.keys == saved_ob_item
  1849. : ms.pending[0].base.keys == &keys[0]);
  1850. assert(ms.pending[0].len == saved_ob_size);
  1851. lo = ms.pending[0].base;
  1852. succeed:
  1853. result = Py_None;
  1854. fail:
  1855. if (keys != NULL) {
  1856. for (i = 0; i < saved_ob_size; i++)
  1857. Py_DECREF(keys[i]);
  1858. if (keys != &ms.temparray[saved_ob_size+1])
  1859. PyMem_FREE(keys);
  1860. }
  1861. if (self->allocated != -1 && result != NULL) {
  1862. /* The user mucked with the list during the sort,
  1863. * and we don't already have another error to report.
  1864. */
  1865. PyErr_SetString(PyExc_ValueError, "list modified during sort");
  1866. result = NULL;
  1867. }
  1868. if (reverse && saved_ob_size > 1)
  1869. reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
  1870. merge_freemem(&ms);
  1871. keyfunc_fail:
  1872. final_ob_item = self->ob_item;
  1873. i = Py_SIZE(self);
  1874. Py_SIZE(self) = saved_ob_size;
  1875. self->ob_item = saved_ob_item;
  1876. self->allocated = saved_allocated;
  1877. if (final_ob_item != NULL) {
  1878. /* we cannot use list_clear() for this because it does not
  1879. guarantee that the list is really empty when it returns */
  1880. while (--i >= 0) {
  1881. Py_XDECREF(final_ob_item[i]);
  1882. }
  1883. PyMem_FREE(final_ob_item);
  1884. }
  1885. Py_XINCREF(result);
  1886. return result;
  1887. }
  1888. #undef IFLT
  1889. #undef ISLT
  1890. int
  1891. PyList_Sort(PyObject *v)
  1892. {
  1893. if (v == NULL || !PyList_Check(v)) {
  1894. PyErr_BadInternalCall();
  1895. return -1;
  1896. }
  1897. v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL);
  1898. if (v == NULL)
  1899. return -1;
  1900. Py_DECREF(v);
  1901. return 0;
  1902. }
  1903. static PyObject *
  1904. listreverse(PyListObject *self)
  1905. {
  1906. if (Py_SIZE(self) > 1)
  1907. reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
  1908. Py_RETURN_NONE;
  1909. }
  1910. int
  1911. PyList_Reverse(PyObject *v)
  1912. {
  1913. PyListObject *self = (PyListObject *)v;
  1914. if (v == NULL || !PyList_Check(v)) {
  1915. PyErr_BadInternalCall();
  1916. return -1;
  1917. }
  1918. if (Py_SIZE(self) > 1)
  1919. reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
  1920. return 0;
  1921. }
  1922. PyObject *
  1923. PyList_AsTuple(PyObject *v)
  1924. {
  1925. PyObject *w;
  1926. PyObject **p, **q;
  1927. Py_ssize_t n;
  1928. if (v == NULL || !PyList_Check(v)) {
  1929. PyErr_BadInternalCall();
  1930. return NULL;
  1931. }
  1932. n = Py_SIZE(v);
  1933. w = PyTuple_New(n);
  1934. if (w == NULL)
  1935. return NULL;
  1936. p = ((PyTupleObject *)w)->ob_item;
  1937. q = ((PyListObject *)v)->ob_item;
  1938. while (--n >= 0) {
  1939. Py_INCREF(*q);
  1940. *p = *q;
  1941. p++;
  1942. q++;
  1943. }
  1944. return w;
  1945. }
  1946. static PyObject *
  1947. listindex(PyListObject *self, PyObject *args)
  1948. {
  1949. Py_ssize_t i, start=0, stop=Py_SIZE(self);
  1950. PyObject *v;
  1951. if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
  1952. _PyEval_SliceIndex, &start,
  1953. _PyEval_SliceIndex, &stop))
  1954. return NULL;
  1955. if (start < 0) {
  1956. start += Py_SIZE(self);
  1957. if (start < 0)
  1958. start = 0;
  1959. }
  1960. if (stop < 0) {
  1961. stop += Py_SIZE(self);
  1962. if (stop < 0)
  1963. stop = 0;
  1964. }
  1965. for (i = start; i < stop && i < Py_SIZE(self); i++) {
  1966. int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
  1967. if (cmp > 0)
  1968. return PyLong_FromSsize_t(i);
  1969. else if (cmp < 0)
  1970. return NULL;
  1971. }
  1972. PyErr_Format(PyExc_ValueError, "%R is not in list", v);
  1973. return NULL;
  1974. }
  1975. static PyObject *
  1976. listcount(PyListObject *self, PyObject *v)
  1977. {
  1978. Py_ssize_t count = 0;
  1979. Py_ssize_t i;
  1980. for (i = 0; i < Py_SIZE(self); i++) {
  1981. int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
  1982. if (cmp > 0)
  1983. count++;
  1984. else if (cmp < 0)
  1985. return NULL;
  1986. }
  1987. return PyLong_FromSsize_t(count);
  1988. }
  1989. static PyObject *
  1990. listremove(PyListObject *self, PyObject *v)
  1991. {
  1992. Py_ssize_t i;
  1993. for (i = 0; i < Py_SIZE(self); i++) {
  1994. int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
  1995. if (cmp > 0) {
  1996. if (list_ass_slice(self, i, i+1,
  1997. (PyObject *)NULL) == 0)
  1998. Py_RETURN_NONE;
  1999. return NULL;
  2000. }
  2001. else if (cmp < 0)
  2002. return NULL;
  2003. }
  2004. PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
  2005. return NULL;
  2006. }
  2007. static int
  2008. list_traverse(PyListObject *o, visitproc visit, void *arg)
  2009. {
  2010. Py_ssize_t i;
  2011. for (i = Py_SIZE(o); --i >= 0; )
  2012. Py_VISIT(o->ob_item[i]);
  2013. return 0;
  2014. }
  2015. static PyObject *
  2016. list_richcompare(PyObject *v, PyObject *w, int op)
  2017. {
  2018. PyListObject *vl, *wl;
  2019. Py_ssize_t i;
  2020. if (!PyList_Check(v) || !PyList_Check(w))
  2021. Py_RETURN_NOTIMPLEMENTED;
  2022. vl = (PyListObject *)v;
  2023. wl = (PyListObject *)w;
  2024. if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) {
  2025. /* Shortcut: if the lengths differ, the lists differ */
  2026. PyObject *res;
  2027. if (op == Py_EQ)
  2028. res = Py_False;
  2029. else
  2030. res = Py_True;
  2031. Py_INCREF(res);
  2032. return res;
  2033. }
  2034. /* Search for the first index where items are different */
  2035. for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
  2036. int k = PyObject_RichCompareBool(vl->ob_item[i],
  2037. wl->ob_item[i], Py_EQ);
  2038. if (k < 0)
  2039. return NULL;
  2040. if (!k)
  2041. break;
  2042. }
  2043. if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) {
  2044. /* No more items to compare -- compare sizes */
  2045. Py_ssize_t vs = Py_SIZE(vl);
  2046. Py_ssize_t ws = Py_SIZE(wl);
  2047. int cmp;
  2048. PyObject *res;
  2049. switch (op) {
  2050. case Py_LT: cmp = vs < ws; break;
  2051. case Py_LE: cmp = vs <= ws; break;
  2052. case Py_EQ: cmp = vs == ws; break;
  2053. case Py_NE: cmp = vs != ws; break;
  2054. case Py_GT: cmp = vs > ws; break;
  2055. case Py_GE: cmp = vs >= ws; break;
  2056. default: return NULL; /* cannot happen */
  2057. }
  2058. if (cmp)
  2059. res = Py_True;
  2060. else
  2061. res = Py_False;
  2062. Py_INCREF(res);
  2063. return res;
  2064. }
  2065. /* We have an item that differs -- shortcuts for EQ/NE */
  2066. if (op == Py_EQ) {
  2067. Py_INCREF(Py_False);
  2068. return Py_False;
  2069. }
  2070. if (op == Py_NE) {
  2071. Py_INCREF(Py_True);
  2072. return Py_True;
  2073. }
  2074. /* Compare the final item again using the proper operator */
  2075. return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
  2076. }
  2077. static int
  2078. list_init(PyListObject *self, PyObject *args, PyObject *kw)
  2079. {
  2080. PyObject *arg = NULL;
  2081. static char *kwlist[] = {"sequence", 0};
  2082. if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
  2083. return -1;
  2084. /* Verify list invariants established by PyType_GenericAlloc() */
  2085. assert(0 <= Py_SIZE(self));
  2086. assert(Py_SIZE(self) <= self->allocated || self->allocated == -1);
  2087. assert(self->ob_item != NULL ||
  2088. self->allocated == 0 || self->allocated == -1);
  2089. /* Empty previous contents */
  2090. if (self->ob_item != NULL) {
  2091. (void)list_clear(self);
  2092. }
  2093. if (arg != NULL) {
  2094. PyObject *rv = listextend(self, arg);
  2095. if (rv == NULL)
  2096. return -1;
  2097. Py_DECREF(rv);
  2098. }
  2099. return 0;
  2100. }
  2101. static PyObject *
  2102. list_sizeof(PyListObject *self)
  2103. {
  2104. Py_ssize_t res;
  2105. res = sizeof(PyListObject) + self->allocated * sizeof(void*);
  2106. return PyLong_FromSsize_t(res);
  2107. }
  2108. static PyObject *list_iter(PyObject *seq);
  2109. static PyObject *list_reversed(PyListObject* seq, PyObject* unused);
  2110. PyDoc_STRVAR(getitem_doc,
  2111. "x.__getitem__(y) <==> x[y]");
  2112. PyDoc_STRVAR(reversed_doc,
  2113. "L.__reversed__() -- return a reverse iterator over the list");
  2114. PyDoc_STRVAR(sizeof_doc,
  2115. "L.__sizeof__() -- size of L in memory, in bytes");
  2116. PyDoc_STRVAR(clear_doc,
  2117. "L.clear() -> None -- remove all items from L");
  2118. PyDoc_STRVAR(copy_doc,
  2119. "L.copy() -> list -- a shallow copy of L");
  2120. PyDoc_STRVAR(append_doc,
  2121. "L.append(object) -> None -- append object to end");
  2122. PyDoc_STRVAR(extend_doc,
  2123. "L.extend(iterable) -> None -- extend list by appending elements from the iterable");
  2124. PyDoc_STRVAR(insert_doc,
  2125. "L.insert(index, object) -- insert object before index");
  2126. PyDoc_STRVAR(pop_doc,
  2127. "L.pop([index]) -> item -- remove and return item at index (default last).\n"
  2128. "Raises IndexError if list is empty or index is out of range.");
  2129. PyDoc_STRVAR(remove_doc,
  2130. "L.remove(value) -> None -- remove first occurrence of value.\n"
  2131. "Raises ValueError if the value is not present.");
  2132. PyDoc_STRVAR(index_doc,
  2133. "L.index(value, [start, [stop]]) -> integer -- return first index of value.\n"
  2134. "Raises ValueError if the value is not present.");
  2135. PyDoc_STRVAR(count_doc,
  2136. "L.count(value) -> integer -- return number of occurrences of value");
  2137. PyDoc_STRVAR(reverse_doc,
  2138. "L.reverse() -- reverse *IN PLACE*");
  2139. PyDoc_STRVAR(sort_doc,
  2140. "L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*");
  2141. static PyObject *list_subscript(PyListObject*, PyObject*);
  2142. static PyMethodDef list_methods[] = {
  2143. {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc},
  2144. {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc},
  2145. {"__sizeof__", (PyCFunction)list_sizeof, METH_NOARGS, sizeof_doc},
  2146. {"clear", (PyCFunction)listclear, METH_NOARGS, clear_doc},
  2147. {"copy", (PyCFunction)listcopy, METH_NOARGS, copy_doc},
  2148. {"append", (PyCFunction)listappend, METH_O, append_doc},
  2149. {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
  2150. {"extend", (PyCFunction)listextend, METH_O, extend_doc},
  2151. {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
  2152. {"remove", (PyCFunction)listremove, METH_O, remove_doc},
  2153. {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
  2154. {"count", (PyCFunction)listcount, METH_O, count_doc},
  2155. {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
  2156. {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc},
  2157. {NULL, NULL} /* sentinel */
  2158. };
  2159. static PySequenceMethods list_as_sequence = {
  2160. (lenfunc)list_length, /* sq_length */
  2161. (binaryfunc)list_concat, /* sq_concat */
  2162. (ssizeargfunc)list_repeat, /* sq_repeat */
  2163. (ssizeargfunc)list_item, /* sq_item */
  2164. 0, /* sq_slice */
  2165. (ssizeobjargproc)list_ass_item, /* sq_ass_item */
  2166. 0, /* sq_ass_slice */
  2167. (objobjproc)list_contains, /* sq_contains */
  2168. (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
  2169. (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */
  2170. };
  2171. PyDoc_STRVAR(list_doc,
  2172. "list() -> new empty list\n"
  2173. "list(iterable) -> new list initialized from iterable's items");
  2174. static PyObject *
  2175. list_subscript(PyListObject* self, PyObject* item)
  2176. {
  2177. if (PyIndex_Check(item)) {
  2178. Py_ssize_t i;
  2179. i = PyNumber_AsSsize_t(item, PyExc_IndexError);
  2180. if (i == -1 && PyErr_Occurred())
  2181. return NULL;
  2182. if (i < 0)
  2183. i += PyList_GET_SIZE(self);
  2184. return list_item(self, i);
  2185. }
  2186. else if (PySlice_Check(item)) {
  2187. Py_ssize_t start, stop, step, slicelength, cur, i;
  2188. PyObject* result;
  2189. PyObject* it;
  2190. PyObject **src, **dest;
  2191. if (PySlice_GetIndicesEx(item, Py_SIZE(self),
  2192. &start, &stop, &step, &slicelength) < 0) {
  2193. return NULL;
  2194. }
  2195. if (slicelength <= 0) {
  2196. return PyList_New(0);
  2197. }
  2198. else if (step == 1) {
  2199. return list_slice(self, start, stop);
  2200. }
  2201. else {
  2202. result = PyList_New(slicelength);
  2203. if (!result) return NULL;
  2204. src = self->ob_item;
  2205. dest = ((PyListObject *)result)->ob_item;
  2206. for (cur = start, i = 0; i < slicelength;
  2207. cur += (size_t)step, i++) {
  2208. it = src[cur];
  2209. Py_INCREF(it);
  2210. dest[i] = it;
  2211. }
  2212. return result;
  2213. }
  2214. }
  2215. else {
  2216. PyErr_Format(PyExc_TypeError,
  2217. "list indices must be integers, not %.200s",
  2218. item->ob_type->tp_name);
  2219. return NULL;
  2220. }
  2221. }
  2222. static int
  2223. list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
  2224. {
  2225. if (PyIndex_Check(item)) {
  2226. Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
  2227. if (i == -1 && PyErr_Occurred())
  2228. return -1;
  2229. if (i < 0)
  2230. i += PyList_GET_SIZE(self);
  2231. return list_ass_item(self, i, value);
  2232. }
  2233. else if (PySlice_Check(item)) {
  2234. Py_ssize_t start, stop, step, slicelength;
  2235. if (PySlice_GetIndicesEx(item, Py_SIZE(self),
  2236. &start, &stop, &step, &slicelength) < 0) {
  2237. return -1;
  2238. }
  2239. if (step == 1)
  2240. return list_ass_slice(self, start, stop, value);
  2241. /* Make sure s[5:2] = [..] inserts at the right place:
  2242. before 5, not before 2. */
  2243. if ((step < 0 && start < stop) ||
  2244. (step > 0 && start > stop))
  2245. stop = start;
  2246. if (value == NULL) {
  2247. /* delete slice */
  2248. PyObject **garbage;
  2249. size_t cur;
  2250. Py_ssize_t i;
  2251. int res;
  2252. if (slicelength <= 0)
  2253. return 0;
  2254. if (step < 0) {
  2255. stop = start + 1;
  2256. start = stop + step*(slicelength - 1) - 1;
  2257. step = -step;
  2258. }
  2259. assert((size_t)slicelength <=
  2260. PY_SIZE_MAX / sizeof(PyObject*));
  2261. garbage = (PyObject**)
  2262. PyMem_MALLOC(slicelength*sizeof(PyObject*));
  2263. if (!garbage) {
  2264. PyErr_NoMemory();
  2265. return -1;
  2266. }
  2267. /* drawing pictures might help understand these for
  2268. loops. Basically, we memmove the parts of the
  2269. list that are *not* part of the slice: step-1
  2270. items for each item that is part of the slice,
  2271. and then tail end of the list that was not
  2272. covered by the slice */
  2273. for (cur = start, i = 0;
  2274. cur < (size_t)stop;
  2275. cur += step, i++) {
  2276. Py_ssize_t lim = step - 1;
  2277. garbage[i] = PyList_GET_ITEM(self, cur);
  2278. if (cur + step >= (size_t)Py_SIZE(self)) {
  2279. lim = Py_SIZE(self) - cur - 1;
  2280. }
  2281. memmove(self->ob_item + cur - i,
  2282. self->ob_item + cur + 1,
  2283. lim * sizeof(PyObject *));
  2284. }
  2285. cur = start + (size_t)slicelength * step;
  2286. if (cur < (size_t)Py_SIZE(self)) {
  2287. memmove(self->ob_item + cur - slicelength,
  2288. self->ob_item + cur,
  2289. (Py_SIZE(self) - cur) *
  2290. sizeof(PyObject *));
  2291. }
  2292. Py_SIZE(self) -= slicelength;
  2293. res = list_resize(self, Py_SIZE(self));
  2294. for (i = 0; i < slicelength; i++) {
  2295. Py_DECREF(garbage[i]);
  2296. }
  2297. PyMem_FREE(garbage);
  2298. return res;
  2299. }
  2300. else {
  2301. /* assign slice */
  2302. PyObject *ins, *seq;
  2303. PyObject **garbage, **seqitems, **selfitems;
  2304. Py_ssize_t cur, i;
  2305. /* protect against a[::-1] = a */
  2306. if (self == (PyListObject*)value) {
  2307. seq = list_slice((PyListObject*)value, 0,
  2308. PyList_GET_SIZE(value));
  2309. }
  2310. else {
  2311. seq = PySequence_Fast(value,
  2312. "must assign iterable "
  2313. "to extended slice");
  2314. }
  2315. if (!seq)
  2316. return -1;
  2317. if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
  2318. PyErr_Format(PyExc_ValueError,
  2319. "attempt to assign sequence of "
  2320. "size %zd to extended slice of "
  2321. "size %zd",
  2322. PySequence_Fast_GET_SIZE(seq),
  2323. slicelength);
  2324. Py_DECREF(seq);
  2325. return -1;
  2326. }
  2327. if (!slicelength) {
  2328. Py_DECREF(seq);
  2329. return 0;
  2330. }
  2331. garbage = (PyObject**)
  2332. PyMem_MALLOC(slicelength*sizeof(PyObject*));
  2333. if (!garbage) {
  2334. Py_DECREF(seq);
  2335. PyErr_NoMemory();
  2336. return -1;
  2337. }
  2338. selfitems = self->ob_item;
  2339. seqitems = PySequence_Fast_ITEMS(seq);
  2340. for (cur = start, i = 0; i < slicelength;
  2341. cur += (size_t)step, i++) {
  2342. garbage[i] = selfitems[cur];
  2343. ins = seqitems[i];
  2344. Py_INCREF(ins);
  2345. selfitems[cur] = ins;
  2346. }
  2347. for (i = 0; i < slicelength; i++) {
  2348. Py_DECREF(garbage[i]);
  2349. }
  2350. PyMem_FREE(garbage);
  2351. Py_DECREF(seq);
  2352. return 0;
  2353. }
  2354. }
  2355. else {
  2356. PyErr_Format(PyExc_TypeError,
  2357. "list indices must be integers, not %.200s",
  2358. item->ob_type->tp_name);
  2359. return -1;
  2360. }
  2361. }
  2362. static PyMappingMethods list_as_mapping = {
  2363. (lenfunc)list_length,
  2364. (binaryfunc)list_subscript,
  2365. (objobjargproc)list_ass_subscript
  2366. };
  2367. PyTypeObject PyList_Type = {
  2368. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  2369. "list",
  2370. sizeof(PyListObject),
  2371. 0,
  2372. (destructor)list_dealloc, /* tp_dealloc */
  2373. 0, /* tp_print */
  2374. 0, /* tp_getattr */
  2375. 0, /* tp_setattr */
  2376. 0, /* tp_reserved */
  2377. (reprfunc)list_repr, /* tp_repr */
  2378. 0, /* tp_as_number */
  2379. &list_as_sequence, /* tp_as_sequence */
  2380. &list_as_mapping, /* tp_as_mapping */
  2381. PyObject_HashNotImplemented, /* tp_hash */
  2382. 0, /* tp_call */
  2383. 0, /* tp_str */
  2384. PyObject_GenericGetAttr, /* tp_getattro */
  2385. 0, /* tp_setattro */
  2386. 0, /* tp_as_buffer */
  2387. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
  2388. Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */
  2389. list_doc, /* tp_doc */
  2390. (traverseproc)list_traverse, /* tp_traverse */
  2391. (inquiry)list_clear, /* tp_clear */
  2392. list_richcompare, /* tp_richcompare */
  2393. 0, /* tp_weaklistoffset */
  2394. list_iter, /* tp_iter */
  2395. 0, /* tp_iternext */
  2396. list_methods, /* tp_methods */
  2397. 0, /* tp_members */
  2398. 0, /* tp_getset */
  2399. 0, /* tp_base */
  2400. 0, /* tp_dict */
  2401. 0, /* tp_descr_get */
  2402. 0, /* tp_descr_set */
  2403. 0, /* tp_dictoffset */
  2404. (initproc)list_init, /* tp_init */
  2405. PyType_GenericAlloc, /* tp_alloc */
  2406. PyType_GenericNew, /* tp_new */
  2407. PyObject_GC_Del, /* tp_free */
  2408. };
  2409. /*********************** List Iterator **************************/
  2410. typedef struct {
  2411. PyObject_HEAD
  2412. Py_ssize_t it_index;
  2413. PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
  2414. } listiterobject;
  2415. static PyObject *list_iter(PyObject *);
  2416. static void listiter_dealloc(listiterobject *);
  2417. static int listiter_traverse(listiterobject *, visitproc, void *);
  2418. static PyObject *listiter_next(listiterobject *);
  2419. static PyObject *listiter_len(listiterobject *);
  2420. static PyObject *listiter_reduce_general(void *_it, int forward);
  2421. static PyObject *listiter_reduce(listiterobject *);
  2422. static PyObject *listiter_setstate(listiterobject *, PyObject *state);
  2423. PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
  2424. PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
  2425. PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
  2426. static PyMethodDef listiter_methods[] = {
  2427. {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc},
  2428. {"__reduce__", (PyCFunction)listiter_reduce, METH_NOARGS, reduce_doc},
  2429. {"__setstate__", (PyCFunction)listiter_setstate, METH_O, setstate_doc},
  2430. {NULL, NULL} /* sentinel */
  2431. };
  2432. PyTypeObject PyListIter_Type = {
  2433. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  2434. "list_iterator", /* tp_name */
  2435. sizeof(listiterobject), /* tp_basicsize */
  2436. 0, /* tp_itemsize */
  2437. /* methods */
  2438. (destructor)listiter_dealloc, /* tp_dealloc */
  2439. 0, /* tp_print */
  2440. 0, /* tp_getattr */
  2441. 0, /* tp_setattr */
  2442. 0, /* tp_reserved */
  2443. 0, /* tp_repr */
  2444. 0, /* tp_as_number */
  2445. 0, /* tp_as_sequence */
  2446. 0, /* tp_as_mapping */
  2447. 0, /* tp_hash */
  2448. 0, /* tp_call */
  2449. 0, /* tp_str */
  2450. PyObject_GenericGetAttr, /* tp_getattro */
  2451. 0, /* tp_setattro */
  2452. 0, /* tp_as_buffer */
  2453. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
  2454. 0, /* tp_doc */
  2455. (traverseproc)listiter_traverse, /* tp_traverse */
  2456. 0, /* tp_clear */
  2457. 0, /* tp_richcompare */
  2458. 0, /* tp_weaklistoffset */
  2459. PyObject_SelfIter, /* tp_iter */
  2460. (iternextfunc)listiter_next, /* tp_iternext */
  2461. listiter_methods, /* tp_methods */
  2462. 0, /* tp_members */
  2463. };
  2464. static PyObject *
  2465. list_iter(PyObject *seq)
  2466. {
  2467. listiterobject *it;
  2468. if (!PyList_Check(seq)) {
  2469. PyErr_BadInternalCall();
  2470. return NULL;
  2471. }
  2472. it = PyObject_GC_New(listiterobject, &PyListIter_Type);
  2473. if (it == NULL)
  2474. return NULL;
  2475. it->it_index = 0;
  2476. Py_INCREF(seq);
  2477. it->it_seq = (PyListObject *)seq;
  2478. _PyObject_GC_TRACK(it);
  2479. return (PyObject *)it;
  2480. }
  2481. static void
  2482. listiter_dealloc(listiterobject *it)
  2483. {
  2484. _PyObject_GC_UNTRACK(it);
  2485. Py_XDECREF(it->it_seq);
  2486. PyObject_GC_Del(it);
  2487. }
  2488. static int
  2489. listiter_traverse(listiterobject *it, visitproc visit, void *arg)
  2490. {
  2491. Py_VISIT(it->it_seq);
  2492. return 0;
  2493. }
  2494. static PyObject *
  2495. listiter_next(listiterobject *it)
  2496. {
  2497. PyListObject *seq;
  2498. PyObject *item;
  2499. assert(it != NULL);
  2500. seq = it->it_seq;
  2501. if (seq == NULL)
  2502. return NULL;
  2503. assert(PyList_Check(seq));
  2504. if (it->it_index < PyList_GET_SIZE(seq)) {
  2505. item = PyList_GET_ITEM(seq, it->it_index);
  2506. ++it->it_index;
  2507. Py_INCREF(item);
  2508. return item;
  2509. }
  2510. Py_DECREF(seq);
  2511. it->it_seq = NULL;
  2512. return NULL;
  2513. }
  2514. static PyObject *
  2515. listiter_len(listiterobject *it)
  2516. {
  2517. Py_ssize_t len;
  2518. if (it->it_seq) {
  2519. len = PyList_GET_SIZE(it->it_seq) - it->it_index;
  2520. if (len >= 0)
  2521. return PyLong_FromSsize_t(len);
  2522. }
  2523. return PyLong_FromLong(0);
  2524. }
  2525. static PyObject *
  2526. listiter_reduce(listiterobject *it)
  2527. {
  2528. return listiter_reduce_general(it, 1);
  2529. }
  2530. static PyObject *
  2531. listiter_setstate(listiterobject *it, PyObject *state)
  2532. {
  2533. Py_ssize_t index = PyLong_AsSsize_t(state);
  2534. if (index == -1 && PyErr_Occurred())
  2535. return NULL;
  2536. if (it->it_seq != NULL) {
  2537. if (index < 0)
  2538. index = 0;
  2539. it->it_index = index;
  2540. }
  2541. Py_RETURN_NONE;
  2542. }
  2543. /*********************** List Reverse Iterator **************************/
  2544. typedef struct {
  2545. PyObject_HEAD
  2546. Py_ssize_t it_index;
  2547. PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
  2548. } listreviterobject;
  2549. static PyObject *list_reversed(PyListObject *, PyObject *);
  2550. static void listreviter_dealloc(listreviterobject *);
  2551. static int listreviter_traverse(listreviterobject *, visitproc, void *);
  2552. static PyObject *listreviter_next(listreviterobject *);
  2553. static PyObject *listreviter_len(listreviterobject *);
  2554. static PyObject *listreviter_reduce(listreviterobject *);
  2555. static PyObject *listreviter_setstate(listreviterobject *, PyObject *);
  2556. static PyMethodDef listreviter_methods[] = {
  2557. {"__length_hint__", (PyCFunction)listreviter_len, METH_NOARGS, length_hint_doc},
  2558. {"__reduce__", (PyCFunction)listreviter_reduce, METH_NOARGS, reduce_doc},
  2559. {"__setstate__", (PyCFunction)listreviter_setstate, METH_O, setstate_doc},
  2560. {NULL, NULL} /* sentinel */
  2561. };
  2562. PyTypeObject PyListRevIter_Type = {
  2563. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  2564. "list_reverseiterator", /* tp_name */
  2565. sizeof(listreviterobject), /* tp_basicsize */
  2566. 0, /* tp_itemsize */
  2567. /* methods */
  2568. (destructor)listreviter_dealloc, /* tp_dealloc */
  2569. 0, /* tp_print */
  2570. 0, /* tp_getattr */
  2571. 0, /* tp_setattr */
  2572. 0, /* tp_reserved */
  2573. 0, /* tp_repr */
  2574. 0, /* tp_as_number */
  2575. 0, /* tp_as_sequence */
  2576. 0, /* tp_as_mapping */
  2577. 0, /* tp_hash */
  2578. 0, /* tp_call */
  2579. 0, /* tp_str */
  2580. PyObject_GenericGetAttr, /* tp_getattro */
  2581. 0, /* tp_setattro */
  2582. 0, /* tp_as_buffer */
  2583. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
  2584. 0, /* tp_doc */
  2585. (traverseproc)listreviter_traverse, /* tp_traverse */
  2586. 0, /* tp_clear */
  2587. 0, /* tp_richcompare */
  2588. 0, /* tp_weaklistoffset */
  2589. PyObject_SelfIter, /* tp_iter */
  2590. (iternextfunc)listreviter_next, /* tp_iternext */
  2591. listreviter_methods, /* tp_methods */
  2592. 0,
  2593. };
  2594. static PyObject *
  2595. list_reversed(PyListObject *seq, PyObject *unused)
  2596. {
  2597. listreviterobject *it;
  2598. it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
  2599. if (it == NULL)
  2600. return NULL;
  2601. assert(PyList_Check(seq));
  2602. it->it_index = PyList_GET_SIZE(seq) - 1;
  2603. Py_INCREF(seq);
  2604. it->it_seq = seq;
  2605. PyObject_GC_Track(it);
  2606. return (PyObject *)it;
  2607. }
  2608. static void
  2609. listreviter_dealloc(listreviterobject *it)
  2610. {
  2611. PyObject_GC_UnTrack(it);
  2612. Py_XDECREF(it->it_seq);
  2613. PyObject_GC_Del(it);
  2614. }
  2615. static int
  2616. listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
  2617. {
  2618. Py_VISIT(it->it_seq);
  2619. return 0;
  2620. }
  2621. static PyObject *
  2622. listreviter_next(listreviterobject *it)
  2623. {
  2624. PyObject *item;
  2625. Py_ssize_t index = it->it_index;
  2626. PyListObject *seq = it->it_seq;
  2627. if (index>=0 && index < PyList_GET_SIZE(seq)) {
  2628. item = PyList_GET_ITEM(seq, index);
  2629. it->it_index--;
  2630. Py_INCREF(item);
  2631. return item;
  2632. }
  2633. it->it_index = -1;
  2634. if (seq != NULL) {
  2635. it->it_seq = NULL;
  2636. Py_DECREF(seq);
  2637. }
  2638. return NULL;
  2639. }
  2640. static PyObject *
  2641. listreviter_len(listreviterobject *it)
  2642. {
  2643. Py_ssize_t len = it->it_index + 1;
  2644. if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
  2645. len = 0;
  2646. return PyLong_FromSsize_t(len);
  2647. }
  2648. static PyObject *
  2649. listreviter_reduce(listreviterobject *it)
  2650. {
  2651. return listiter_reduce_general(it, 0);
  2652. }
  2653. static PyObject *
  2654. listreviter_setstate(listreviterobject *it, PyObject *state)
  2655. {
  2656. Py_ssize_t index = PyLong_AsSsize_t(state);
  2657. if (index == -1 && PyErr_Occurred())
  2658. return NULL;
  2659. if (it->it_seq != NULL) {
  2660. if (index < -1)
  2661. index = -1;
  2662. else if (index > PyList_GET_SIZE(it->it_seq) - 1)
  2663. index = PyList_GET_SIZE(it->it_seq) - 1;
  2664. it->it_index = index;
  2665. }
  2666. Py_RETURN_NONE;
  2667. }
  2668. /* common pickling support */
  2669. static PyObject *
  2670. listiter_reduce_general(void *_it, int forward)
  2671. {
  2672. PyObject *list;
  2673. /* the objects are not the same, index is of different types! */
  2674. if (forward) {
  2675. listiterobject *it = (listiterobject *)_it;
  2676. if (it->it_seq)
  2677. return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
  2678. it->it_seq, it->it_index);
  2679. } else {
  2680. listreviterobject *it = (listreviterobject *)_it;
  2681. if (it->it_seq)
  2682. return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("reversed"),
  2683. it->it_seq, it->it_index);
  2684. }
  2685. /* empty iterator, create an empty list */
  2686. list = PyList_New(0);
  2687. if (list == NULL)
  2688. return NULL;
  2689. return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), list);
  2690. }