PageRenderTime 57ms CodeModel.GetById 7ms RepoModel.GetById 0ms app.codeStats 0ms

/Objects/listobject.c

https://bitbucket.org/bluehorn/sampling_prof
C | 2989 lines | 2331 code | 279 blank | 379 comment | 605 complexity | ad03bff59bcad7e5f711486db2dc6852 MD5 | raw file
Possible License(s): BSD-3-Clause, Unlicense, CC-BY-SA-3.0, 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. PyObject *xoptions, *value;
  77. _Py_IDENTIFIER(showalloccount);
  78. xoptions = PySys_GetXOptions();
  79. if (xoptions == NULL)
  80. return;
  81. value = _PyDict_GetItemId(xoptions, &PyId_showalloccount);
  82. if (value != Py_True)
  83. return;
  84. fprintf(stderr, "List allocations: %" PY_FORMAT_SIZE_T "d\n",
  85. count_alloc);
  86. fprintf(stderr, "List reuse through freelist: %" PY_FORMAT_SIZE_T
  87. "d\n", count_reuse);
  88. fprintf(stderr, "%.2f%% reuse rate\n\n",
  89. (100.0*count_reuse/(count_alloc+count_reuse)));
  90. }
  91. #endif
  92. /* Empty list reuse scheme to save calls to malloc and free */
  93. #ifndef PyList_MAXFREELIST
  94. #define PyList_MAXFREELIST 80
  95. #endif
  96. static PyListObject *free_list[PyList_MAXFREELIST];
  97. static int numfree = 0;
  98. int
  99. PyList_ClearFreeList(void)
  100. {
  101. PyListObject *op;
  102. int ret = numfree;
  103. while (numfree) {
  104. op = free_list[--numfree];
  105. assert(PyList_CheckExact(op));
  106. PyObject_GC_Del(op);
  107. }
  108. return ret;
  109. }
  110. void
  111. PyList_Fini(void)
  112. {
  113. PyList_ClearFreeList();
  114. }
  115. /* Print summary info about the state of the optimized allocator */
  116. void
  117. _PyList_DebugMallocStats(FILE *out)
  118. {
  119. _PyDebugAllocatorStats(out,
  120. "free PyListObject",
  121. numfree, sizeof(PyListObject));
  122. }
  123. PyObject *
  124. PyList_New(Py_ssize_t size)
  125. {
  126. PyListObject *op;
  127. #ifdef SHOW_ALLOC_COUNT
  128. static int initialized = 0;
  129. if (!initialized) {
  130. Py_AtExit(show_alloc);
  131. initialized = 1;
  132. }
  133. #endif
  134. if (size < 0) {
  135. PyErr_BadInternalCall();
  136. return NULL;
  137. }
  138. if (numfree) {
  139. numfree--;
  140. op = free_list[numfree];
  141. _Py_NewReference((PyObject *)op);
  142. #ifdef SHOW_ALLOC_COUNT
  143. count_reuse++;
  144. #endif
  145. } else {
  146. op = PyObject_GC_New(PyListObject, &PyList_Type);
  147. if (op == NULL)
  148. return NULL;
  149. #ifdef SHOW_ALLOC_COUNT
  150. count_alloc++;
  151. #endif
  152. }
  153. if (size <= 0)
  154. op->ob_item = NULL;
  155. else {
  156. op->ob_item = (PyObject **) PyMem_Calloc(size, sizeof(PyObject *));
  157. if (op->ob_item == NULL) {
  158. Py_DECREF(op);
  159. return PyErr_NoMemory();
  160. }
  161. }
  162. Py_SIZE(op) = size;
  163. op->allocated = size;
  164. _PyObject_GC_TRACK(op);
  165. return (PyObject *) op;
  166. }
  167. Py_ssize_t
  168. PyList_Size(PyObject *op)
  169. {
  170. if (!PyList_Check(op)) {
  171. PyErr_BadInternalCall();
  172. return -1;
  173. }
  174. else
  175. return Py_SIZE(op);
  176. }
  177. static PyObject *indexerr = NULL;
  178. PyObject *
  179. PyList_GetItem(PyObject *op, Py_ssize_t i)
  180. {
  181. if (!PyList_Check(op)) {
  182. PyErr_BadInternalCall();
  183. return NULL;
  184. }
  185. if (i < 0 || i >= Py_SIZE(op)) {
  186. if (indexerr == NULL) {
  187. indexerr = PyUnicode_FromString(
  188. "list index out of range");
  189. if (indexerr == NULL)
  190. return NULL;
  191. }
  192. PyErr_SetObject(PyExc_IndexError, indexerr);
  193. return NULL;
  194. }
  195. return ((PyListObject *)op) -> ob_item[i];
  196. }
  197. int
  198. PyList_SetItem(PyObject *op, Py_ssize_t i,
  199. PyObject *newitem)
  200. {
  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. Py_XSETREF(*p, newitem);
  215. return 0;
  216. }
  217. static int
  218. ins1(PyListObject *self, Py_ssize_t where, PyObject *v)
  219. {
  220. Py_ssize_t i, n = Py_SIZE(self);
  221. PyObject **items;
  222. if (v == NULL) {
  223. PyErr_BadInternalCall();
  224. return -1;
  225. }
  226. if (n == PY_SSIZE_T_MAX) {
  227. PyErr_SetString(PyExc_OverflowError,
  228. "cannot add more objects to list");
  229. return -1;
  230. }
  231. if (list_resize(self, n+1) < 0)
  232. return -1;
  233. if (where < 0) {
  234. where += n;
  235. if (where < 0)
  236. where = 0;
  237. }
  238. if (where > n)
  239. where = n;
  240. items = self->ob_item;
  241. for (i = n; --i >= where; )
  242. items[i+1] = items[i];
  243. Py_INCREF(v);
  244. items[where] = v;
  245. return 0;
  246. }
  247. int
  248. PyList_Insert(PyObject *op, Py_ssize_t where, PyObject *newitem)
  249. {
  250. if (!PyList_Check(op)) {
  251. PyErr_BadInternalCall();
  252. return -1;
  253. }
  254. return ins1((PyListObject *)op, where, newitem);
  255. }
  256. static int
  257. app1(PyListObject *self, PyObject *v)
  258. {
  259. Py_ssize_t n = PyList_GET_SIZE(self);
  260. assert (v != NULL);
  261. if (n == PY_SSIZE_T_MAX) {
  262. PyErr_SetString(PyExc_OverflowError,
  263. "cannot add more objects to list");
  264. return -1;
  265. }
  266. if (list_resize(self, n+1) < 0)
  267. return -1;
  268. Py_INCREF(v);
  269. PyList_SET_ITEM(self, n, v);
  270. return 0;
  271. }
  272. int
  273. PyList_Append(PyObject *op, PyObject *newitem)
  274. {
  275. if (PyList_Check(op) && (newitem != NULL))
  276. return app1((PyListObject *)op, newitem);
  277. PyErr_BadInternalCall();
  278. return -1;
  279. }
  280. /* Methods */
  281. static void
  282. list_dealloc(PyListObject *op)
  283. {
  284. Py_ssize_t i;
  285. PyObject_GC_UnTrack(op);
  286. Py_TRASHCAN_SAFE_BEGIN(op)
  287. if (op->ob_item != NULL) {
  288. /* Do it backwards, for Christian Tismer.
  289. There's a simple test case where somehow this reduces
  290. thrashing when a *very* large list is created and
  291. immediately deleted. */
  292. i = Py_SIZE(op);
  293. while (--i >= 0) {
  294. Py_XDECREF(op->ob_item[i]);
  295. }
  296. PyMem_FREE(op->ob_item);
  297. }
  298. if (numfree < PyList_MAXFREELIST && PyList_CheckExact(op))
  299. free_list[numfree++] = op;
  300. else
  301. Py_TYPE(op)->tp_free((PyObject *)op);
  302. Py_TRASHCAN_SAFE_END(op)
  303. }
  304. static PyObject *
  305. list_repr(PyListObject *v)
  306. {
  307. Py_ssize_t i;
  308. PyObject *s;
  309. _PyUnicodeWriter writer;
  310. if (Py_SIZE(v) == 0) {
  311. return PyUnicode_FromString("[]");
  312. }
  313. i = Py_ReprEnter((PyObject*)v);
  314. if (i != 0) {
  315. return i > 0 ? PyUnicode_FromString("[...]") : NULL;
  316. }
  317. _PyUnicodeWriter_Init(&writer);
  318. writer.overallocate = 1;
  319. /* "[" + "1" + ", 2" * (len - 1) + "]" */
  320. writer.min_length = 1 + 1 + (2 + 1) * (Py_SIZE(v) - 1) + 1;
  321. if (_PyUnicodeWriter_WriteChar(&writer, '[') < 0)
  322. goto error;
  323. /* Do repr() on each element. Note that this may mutate the list,
  324. so must refetch the list size on each iteration. */
  325. for (i = 0; i < Py_SIZE(v); ++i) {
  326. if (i > 0) {
  327. if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0)
  328. goto error;
  329. }
  330. if (Py_EnterRecursiveCall(" while getting the repr of a list"))
  331. goto error;
  332. s = PyObject_Repr(v->ob_item[i]);
  333. Py_LeaveRecursiveCall();
  334. if (s == NULL)
  335. goto error;
  336. if (_PyUnicodeWriter_WriteStr(&writer, s) < 0) {
  337. Py_DECREF(s);
  338. goto error;
  339. }
  340. Py_DECREF(s);
  341. }
  342. writer.overallocate = 0;
  343. if (_PyUnicodeWriter_WriteChar(&writer, ']') < 0)
  344. goto error;
  345. Py_ReprLeave((PyObject *)v);
  346. return _PyUnicodeWriter_Finish(&writer);
  347. error:
  348. _PyUnicodeWriter_Dealloc(&writer);
  349. Py_ReprLeave((PyObject *)v);
  350. return NULL;
  351. }
  352. static Py_ssize_t
  353. list_length(PyListObject *a)
  354. {
  355. return Py_SIZE(a);
  356. }
  357. static int
  358. list_contains(PyListObject *a, PyObject *el)
  359. {
  360. Py_ssize_t i;
  361. int cmp;
  362. for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i)
  363. cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
  364. Py_EQ);
  365. return cmp;
  366. }
  367. static PyObject *
  368. list_item(PyListObject *a, Py_ssize_t i)
  369. {
  370. if (i < 0 || i >= Py_SIZE(a)) {
  371. if (indexerr == NULL) {
  372. indexerr = PyUnicode_FromString(
  373. "list index out of range");
  374. if (indexerr == NULL)
  375. return NULL;
  376. }
  377. PyErr_SetObject(PyExc_IndexError, indexerr);
  378. return NULL;
  379. }
  380. Py_INCREF(a->ob_item[i]);
  381. return a->ob_item[i];
  382. }
  383. static PyObject *
  384. list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
  385. {
  386. PyListObject *np;
  387. PyObject **src, **dest;
  388. Py_ssize_t i, len;
  389. if (ilow < 0)
  390. ilow = 0;
  391. else if (ilow > Py_SIZE(a))
  392. ilow = Py_SIZE(a);
  393. if (ihigh < ilow)
  394. ihigh = ilow;
  395. else if (ihigh > Py_SIZE(a))
  396. ihigh = Py_SIZE(a);
  397. len = ihigh - ilow;
  398. np = (PyListObject *) PyList_New(len);
  399. if (np == NULL)
  400. return NULL;
  401. src = a->ob_item + ilow;
  402. dest = np->ob_item;
  403. for (i = 0; i < len; i++) {
  404. PyObject *v = src[i];
  405. Py_INCREF(v);
  406. dest[i] = v;
  407. }
  408. return (PyObject *)np;
  409. }
  410. PyObject *
  411. PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
  412. {
  413. if (!PyList_Check(a)) {
  414. PyErr_BadInternalCall();
  415. return NULL;
  416. }
  417. return list_slice((PyListObject *)a, ilow, ihigh);
  418. }
  419. static PyObject *
  420. list_concat(PyListObject *a, PyObject *bb)
  421. {
  422. Py_ssize_t size;
  423. Py_ssize_t i;
  424. PyObject **src, **dest;
  425. PyListObject *np;
  426. if (!PyList_Check(bb)) {
  427. PyErr_Format(PyExc_TypeError,
  428. "can only concatenate list (not \"%.200s\") to list",
  429. bb->ob_type->tp_name);
  430. return NULL;
  431. }
  432. #define b ((PyListObject *)bb)
  433. if (Py_SIZE(a) > PY_SSIZE_T_MAX - Py_SIZE(b))
  434. return PyErr_NoMemory();
  435. size = Py_SIZE(a) + Py_SIZE(b);
  436. np = (PyListObject *) PyList_New(size);
  437. if (np == NULL) {
  438. return NULL;
  439. }
  440. src = a->ob_item;
  441. dest = np->ob_item;
  442. for (i = 0; i < Py_SIZE(a); i++) {
  443. PyObject *v = src[i];
  444. Py_INCREF(v);
  445. dest[i] = v;
  446. }
  447. src = b->ob_item;
  448. dest = np->ob_item + Py_SIZE(a);
  449. for (i = 0; i < Py_SIZE(b); i++) {
  450. PyObject *v = src[i];
  451. Py_INCREF(v);
  452. dest[i] = v;
  453. }
  454. return (PyObject *)np;
  455. #undef b
  456. }
  457. static PyObject *
  458. list_repeat(PyListObject *a, Py_ssize_t n)
  459. {
  460. Py_ssize_t i, j;
  461. Py_ssize_t size;
  462. PyListObject *np;
  463. PyObject **p, **items;
  464. PyObject *elem;
  465. if (n < 0)
  466. n = 0;
  467. if (n > 0 && Py_SIZE(a) > PY_SSIZE_T_MAX / n)
  468. return PyErr_NoMemory();
  469. size = Py_SIZE(a) * n;
  470. if (size == 0)
  471. return PyList_New(0);
  472. np = (PyListObject *) PyList_New(size);
  473. if (np == NULL)
  474. return NULL;
  475. items = np->ob_item;
  476. if (Py_SIZE(a) == 1) {
  477. elem = a->ob_item[0];
  478. for (i = 0; i < n; i++) {
  479. items[i] = elem;
  480. Py_INCREF(elem);
  481. }
  482. return (PyObject *) np;
  483. }
  484. p = np->ob_item;
  485. items = a->ob_item;
  486. for (i = 0; i < n; i++) {
  487. for (j = 0; j < Py_SIZE(a); j++) {
  488. *p = items[j];
  489. Py_INCREF(*p);
  490. p++;
  491. }
  492. }
  493. return (PyObject *) np;
  494. }
  495. static int
  496. list_clear(PyListObject *a)
  497. {
  498. Py_ssize_t i;
  499. PyObject **item = a->ob_item;
  500. if (item != NULL) {
  501. /* Because XDECREF can recursively invoke operations on
  502. this list, we make it empty first. */
  503. i = Py_SIZE(a);
  504. Py_SIZE(a) = 0;
  505. a->ob_item = NULL;
  506. a->allocated = 0;
  507. while (--i >= 0) {
  508. Py_XDECREF(item[i]);
  509. }
  510. PyMem_FREE(item);
  511. }
  512. /* Never fails; the return value can be ignored.
  513. Note that there is no guarantee that the list is actually empty
  514. at this point, because XDECREF may have populated it again! */
  515. return 0;
  516. }
  517. /* a[ilow:ihigh] = v if v != NULL.
  518. * del a[ilow:ihigh] if v == NULL.
  519. *
  520. * Special speed gimmick: when v is NULL and ihigh - ilow <= 8, it's
  521. * guaranteed the call cannot fail.
  522. */
  523. static int
  524. list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
  525. {
  526. /* Because [X]DECREF can recursively invoke list operations on
  527. this list, we must postpone all [X]DECREF activity until
  528. after the list is back in its canonical shape. Therefore
  529. we must allocate an additional array, 'recycle', into which
  530. we temporarily copy the items that are deleted from the
  531. list. :-( */
  532. PyObject *recycle_on_stack[8];
  533. PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
  534. PyObject **item;
  535. PyObject **vitem = NULL;
  536. PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
  537. Py_ssize_t n; /* # of elements in replacement list */
  538. Py_ssize_t norig; /* # of elements in list getting replaced */
  539. Py_ssize_t d; /* Change in size */
  540. Py_ssize_t k;
  541. size_t s;
  542. int result = -1; /* guilty until proved innocent */
  543. #define b ((PyListObject *)v)
  544. if (v == NULL)
  545. n = 0;
  546. else {
  547. if (a == b) {
  548. /* Special case "a[i:j] = a" -- copy b first */
  549. v = list_slice(b, 0, Py_SIZE(b));
  550. if (v == NULL)
  551. return result;
  552. result = list_ass_slice(a, ilow, ihigh, v);
  553. Py_DECREF(v);
  554. return result;
  555. }
  556. v_as_SF = PySequence_Fast(v, "can only assign an iterable");
  557. if(v_as_SF == NULL)
  558. goto Error;
  559. n = PySequence_Fast_GET_SIZE(v_as_SF);
  560. vitem = PySequence_Fast_ITEMS(v_as_SF);
  561. }
  562. if (ilow < 0)
  563. ilow = 0;
  564. else if (ilow > Py_SIZE(a))
  565. ilow = Py_SIZE(a);
  566. if (ihigh < ilow)
  567. ihigh = ilow;
  568. else if (ihigh > Py_SIZE(a))
  569. ihigh = Py_SIZE(a);
  570. norig = ihigh - ilow;
  571. assert(norig >= 0);
  572. d = n - norig;
  573. if (Py_SIZE(a) + d == 0) {
  574. Py_XDECREF(v_as_SF);
  575. return list_clear(a);
  576. }
  577. item = a->ob_item;
  578. /* recycle the items that we are about to remove */
  579. s = norig * sizeof(PyObject *);
  580. if (s > sizeof(recycle_on_stack)) {
  581. recycle = (PyObject **)PyMem_MALLOC(s);
  582. if (recycle == NULL) {
  583. PyErr_NoMemory();
  584. goto Error;
  585. }
  586. }
  587. memcpy(recycle, &item[ilow], s);
  588. if (d < 0) { /* Delete -d items */
  589. Py_ssize_t tail;
  590. tail = (Py_SIZE(a) - ihigh) * sizeof(PyObject *);
  591. memmove(&item[ihigh+d], &item[ihigh], tail);
  592. if (list_resize(a, Py_SIZE(a) + d) < 0) {
  593. memmove(&item[ihigh], &item[ihigh+d], tail);
  594. memcpy(&item[ilow], recycle, s);
  595. goto Error;
  596. }
  597. item = a->ob_item;
  598. }
  599. else if (d > 0) { /* Insert d items */
  600. k = Py_SIZE(a);
  601. if (list_resize(a, k+d) < 0)
  602. goto Error;
  603. item = a->ob_item;
  604. memmove(&item[ihigh+d], &item[ihigh],
  605. (k - ihigh)*sizeof(PyObject *));
  606. }
  607. for (k = 0; k < n; k++, ilow++) {
  608. PyObject *w = vitem[k];
  609. Py_XINCREF(w);
  610. item[ilow] = w;
  611. }
  612. for (k = norig - 1; k >= 0; --k)
  613. Py_XDECREF(recycle[k]);
  614. result = 0;
  615. Error:
  616. if (recycle != recycle_on_stack)
  617. PyMem_FREE(recycle);
  618. Py_XDECREF(v_as_SF);
  619. return result;
  620. #undef b
  621. }
  622. int
  623. PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
  624. {
  625. if (!PyList_Check(a)) {
  626. PyErr_BadInternalCall();
  627. return -1;
  628. }
  629. return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
  630. }
  631. static PyObject *
  632. list_inplace_repeat(PyListObject *self, Py_ssize_t n)
  633. {
  634. PyObject **items;
  635. Py_ssize_t size, i, j, p;
  636. size = PyList_GET_SIZE(self);
  637. if (size == 0 || n == 1) {
  638. Py_INCREF(self);
  639. return (PyObject *)self;
  640. }
  641. if (n < 1) {
  642. (void)list_clear(self);
  643. Py_INCREF(self);
  644. return (PyObject *)self;
  645. }
  646. if (size > PY_SSIZE_T_MAX / n) {
  647. return PyErr_NoMemory();
  648. }
  649. if (list_resize(self, size*n) < 0)
  650. return NULL;
  651. p = size;
  652. items = self->ob_item;
  653. for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
  654. for (j = 0; j < size; j++) {
  655. PyObject *o = items[j];
  656. Py_INCREF(o);
  657. items[p++] = o;
  658. }
  659. }
  660. Py_INCREF(self);
  661. return (PyObject *)self;
  662. }
  663. static int
  664. list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v)
  665. {
  666. if (i < 0 || i >= Py_SIZE(a)) {
  667. PyErr_SetString(PyExc_IndexError,
  668. "list assignment index out of range");
  669. return -1;
  670. }
  671. if (v == NULL)
  672. return list_ass_slice(a, i, i+1, v);
  673. Py_INCREF(v);
  674. Py_SETREF(a->ob_item[i], v);
  675. return 0;
  676. }
  677. static PyObject *
  678. listinsert(PyListObject *self, PyObject *args)
  679. {
  680. Py_ssize_t i;
  681. PyObject *v;
  682. if (!PyArg_ParseTuple(args, "nO:insert", &i, &v))
  683. return NULL;
  684. if (ins1(self, i, v) == 0)
  685. Py_RETURN_NONE;
  686. return NULL;
  687. }
  688. static PyObject *
  689. listclear(PyListObject *self)
  690. {
  691. list_clear(self);
  692. Py_RETURN_NONE;
  693. }
  694. static PyObject *
  695. listcopy(PyListObject *self)
  696. {
  697. return list_slice(self, 0, Py_SIZE(self));
  698. }
  699. static PyObject *
  700. listappend(PyListObject *self, PyObject *v)
  701. {
  702. if (app1(self, v) == 0)
  703. Py_RETURN_NONE;
  704. return NULL;
  705. }
  706. static PyObject *
  707. listextend(PyListObject *self, PyObject *b)
  708. {
  709. PyObject *it; /* iter(v) */
  710. Py_ssize_t m; /* size of self */
  711. Py_ssize_t n; /* guess for size of b */
  712. Py_ssize_t mn; /* m + n */
  713. Py_ssize_t i;
  714. PyObject *(*iternext)(PyObject *);
  715. /* Special cases:
  716. 1) lists and tuples which can use PySequence_Fast ops
  717. 2) extending self to self requires making a copy first
  718. */
  719. if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
  720. PyObject **src, **dest;
  721. b = PySequence_Fast(b, "argument must be iterable");
  722. if (!b)
  723. return NULL;
  724. n = PySequence_Fast_GET_SIZE(b);
  725. if (n == 0) {
  726. /* short circuit when b is empty */
  727. Py_DECREF(b);
  728. Py_RETURN_NONE;
  729. }
  730. m = Py_SIZE(self);
  731. if (list_resize(self, m + n) < 0) {
  732. Py_DECREF(b);
  733. return NULL;
  734. }
  735. /* note that we may still have self == b here for the
  736. * situation a.extend(a), but the following code works
  737. * in that case too. Just make sure to resize self
  738. * before calling PySequence_Fast_ITEMS.
  739. */
  740. /* populate the end of self with b's items */
  741. src = PySequence_Fast_ITEMS(b);
  742. dest = self->ob_item + m;
  743. for (i = 0; i < n; i++) {
  744. PyObject *o = src[i];
  745. Py_INCREF(o);
  746. dest[i] = o;
  747. }
  748. Py_DECREF(b);
  749. Py_RETURN_NONE;
  750. }
  751. it = PyObject_GetIter(b);
  752. if (it == NULL)
  753. return NULL;
  754. iternext = *it->ob_type->tp_iternext;
  755. /* Guess a result list size. */
  756. n = PyObject_LengthHint(b, 8);
  757. if (n < 0) {
  758. Py_DECREF(it);
  759. return NULL;
  760. }
  761. m = Py_SIZE(self);
  762. if (m > PY_SSIZE_T_MAX - n) {
  763. /* m + n overflowed; on the chance that n lied, and there really
  764. * is enough room, ignore it. If n was telling the truth, we'll
  765. * eventually run out of memory during the loop.
  766. */
  767. }
  768. else {
  769. mn = m + n;
  770. /* Make room. */
  771. if (list_resize(self, mn) < 0)
  772. goto error;
  773. /* Make the list sane again. */
  774. Py_SIZE(self) = m;
  775. }
  776. /* Run iterator to exhaustion. */
  777. for (;;) {
  778. PyObject *item = iternext(it);
  779. if (item == NULL) {
  780. if (PyErr_Occurred()) {
  781. if (PyErr_ExceptionMatches(PyExc_StopIteration))
  782. PyErr_Clear();
  783. else
  784. goto error;
  785. }
  786. break;
  787. }
  788. if (Py_SIZE(self) < self->allocated) {
  789. /* steals ref */
  790. PyList_SET_ITEM(self, Py_SIZE(self), item);
  791. ++Py_SIZE(self);
  792. }
  793. else {
  794. int status = app1(self, item);
  795. Py_DECREF(item); /* append creates a new ref */
  796. if (status < 0)
  797. goto error;
  798. }
  799. }
  800. /* Cut back result list if initial guess was too large. */
  801. if (Py_SIZE(self) < self->allocated) {
  802. if (list_resize(self, Py_SIZE(self)) < 0)
  803. goto error;
  804. }
  805. Py_DECREF(it);
  806. Py_RETURN_NONE;
  807. error:
  808. Py_DECREF(it);
  809. return NULL;
  810. }
  811. PyObject *
  812. _PyList_Extend(PyListObject *self, PyObject *b)
  813. {
  814. return listextend(self, b);
  815. }
  816. static PyObject *
  817. list_inplace_concat(PyListObject *self, PyObject *other)
  818. {
  819. PyObject *result;
  820. result = listextend(self, other);
  821. if (result == NULL)
  822. return result;
  823. Py_DECREF(result);
  824. Py_INCREF(self);
  825. return (PyObject *)self;
  826. }
  827. static PyObject *
  828. listpop(PyListObject *self, PyObject *args)
  829. {
  830. Py_ssize_t i = -1;
  831. PyObject *v;
  832. int status;
  833. if (!PyArg_ParseTuple(args, "|n:pop", &i))
  834. return NULL;
  835. if (Py_SIZE(self) == 0) {
  836. /* Special-case most common failure cause */
  837. PyErr_SetString(PyExc_IndexError, "pop from empty list");
  838. return NULL;
  839. }
  840. if (i < 0)
  841. i += Py_SIZE(self);
  842. if (i < 0 || i >= Py_SIZE(self)) {
  843. PyErr_SetString(PyExc_IndexError, "pop index out of range");
  844. return NULL;
  845. }
  846. v = self->ob_item[i];
  847. if (i == Py_SIZE(self) - 1) {
  848. status = list_resize(self, Py_SIZE(self) - 1);
  849. if (status >= 0)
  850. return v; /* and v now owns the reference the list had */
  851. else
  852. return NULL;
  853. }
  854. Py_INCREF(v);
  855. status = list_ass_slice(self, i, i+1, (PyObject *)NULL);
  856. if (status < 0) {
  857. Py_DECREF(v);
  858. return NULL;
  859. }
  860. return v;
  861. }
  862. /* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
  863. static void
  864. reverse_slice(PyObject **lo, PyObject **hi)
  865. {
  866. assert(lo && hi);
  867. --hi;
  868. while (lo < hi) {
  869. PyObject *t = *lo;
  870. *lo = *hi;
  871. *hi = t;
  872. ++lo;
  873. --hi;
  874. }
  875. }
  876. /* Lots of code for an adaptive, stable, natural mergesort. There are many
  877. * pieces to this algorithm; read listsort.txt for overviews and details.
  878. */
  879. /* A sortslice contains a pointer to an array of keys and a pointer to
  880. * an array of corresponding values. In other words, keys[i]
  881. * corresponds with values[i]. If values == NULL, then the keys are
  882. * also the values.
  883. *
  884. * Several convenience routines are provided here, so that keys and
  885. * values are always moved in sync.
  886. */
  887. typedef struct {
  888. PyObject **keys;
  889. PyObject **values;
  890. } sortslice;
  891. Py_LOCAL_INLINE(void)
  892. sortslice_copy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j)
  893. {
  894. s1->keys[i] = s2->keys[j];
  895. if (s1->values != NULL)
  896. s1->values[i] = s2->values[j];
  897. }
  898. Py_LOCAL_INLINE(void)
  899. sortslice_copy_incr(sortslice *dst, sortslice *src)
  900. {
  901. *dst->keys++ = *src->keys++;
  902. if (dst->values != NULL)
  903. *dst->values++ = *src->values++;
  904. }
  905. Py_LOCAL_INLINE(void)
  906. sortslice_copy_decr(sortslice *dst, sortslice *src)
  907. {
  908. *dst->keys-- = *src->keys--;
  909. if (dst->values != NULL)
  910. *dst->values-- = *src->values--;
  911. }
  912. Py_LOCAL_INLINE(void)
  913. sortslice_memcpy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
  914. Py_ssize_t n)
  915. {
  916. memcpy(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
  917. if (s1->values != NULL)
  918. memcpy(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
  919. }
  920. Py_LOCAL_INLINE(void)
  921. sortslice_memmove(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
  922. Py_ssize_t n)
  923. {
  924. memmove(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
  925. if (s1->values != NULL)
  926. memmove(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
  927. }
  928. Py_LOCAL_INLINE(void)
  929. sortslice_advance(sortslice *slice, Py_ssize_t n)
  930. {
  931. slice->keys += n;
  932. if (slice->values != NULL)
  933. slice->values += n;
  934. }
  935. /* Comparison function: PyObject_RichCompareBool with Py_LT.
  936. * Returns -1 on error, 1 if x < y, 0 if x >= y.
  937. */
  938. #define ISLT(X, Y) (PyObject_RichCompareBool(X, Y, Py_LT))
  939. /* Compare X to Y via "<". Goto "fail" if the comparison raises an
  940. error. Else "k" is set to true iff X<Y, and an "if (k)" block is
  941. started. It makes more sense in context <wink>. X and Y are PyObject*s.
  942. */
  943. #define IFLT(X, Y) if ((k = ISLT(X, Y)) < 0) goto fail; \
  944. if (k)
  945. /* binarysort is the best method for sorting small arrays: it does
  946. few compares, but can do data movement quadratic in the number of
  947. elements.
  948. [lo, hi) is a contiguous slice of a list, and is sorted via
  949. binary insertion. This sort is stable.
  950. On entry, must have lo <= start <= hi, and that [lo, start) is already
  951. sorted (pass start == lo if you don't know!).
  952. If islt() complains return -1, else 0.
  953. Even in case of error, the output slice will be some permutation of
  954. the input (nothing is lost or duplicated).
  955. */
  956. static int
  957. binarysort(sortslice lo, PyObject **hi, PyObject **start)
  958. {
  959. Py_ssize_t k;
  960. PyObject **l, **p, **r;
  961. PyObject *pivot;
  962. assert(lo.keys <= start && start <= hi);
  963. /* assert [lo, start) is sorted */
  964. if (lo.keys == start)
  965. ++start;
  966. for (; start < hi; ++start) {
  967. /* set l to where *start belongs */
  968. l = lo.keys;
  969. r = start;
  970. pivot = *r;
  971. /* Invariants:
  972. * pivot >= all in [lo, l).
  973. * pivot < all in [r, start).
  974. * The second is vacuously true at the start.
  975. */
  976. assert(l < r);
  977. do {
  978. p = l + ((r - l) >> 1);
  979. IFLT(pivot, *p)
  980. r = p;
  981. else
  982. l = p+1;
  983. } while (l < r);
  984. assert(l == r);
  985. /* The invariants still hold, so pivot >= all in [lo, l) and
  986. pivot < all in [l, start), so pivot belongs at l. Note
  987. that if there are elements equal to pivot, l points to the
  988. first slot after them -- that's why this sort is stable.
  989. Slide over to make room.
  990. Caution: using memmove is much slower under MSVC 5;
  991. we're not usually moving many slots. */
  992. for (p = start; p > l; --p)
  993. *p = *(p-1);
  994. *l = pivot;
  995. if (lo.values != NULL) {
  996. Py_ssize_t offset = lo.values - lo.keys;
  997. p = start + offset;
  998. pivot = *p;
  999. l += offset;
  1000. for (p = start + offset; p > l; --p)
  1001. *p = *(p-1);
  1002. *l = pivot;
  1003. }
  1004. }
  1005. return 0;
  1006. fail:
  1007. return -1;
  1008. }
  1009. /*
  1010. Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
  1011. is required on entry. "A run" is the longest ascending sequence, with
  1012. lo[0] <= lo[1] <= lo[2] <= ...
  1013. or the longest descending sequence, with
  1014. lo[0] > lo[1] > lo[2] > ...
  1015. Boolean *descending is set to 0 in the former case, or to 1 in the latter.
  1016. For its intended use in a stable mergesort, the strictness of the defn of
  1017. "descending" is needed so that the caller can safely reverse a descending
  1018. sequence without violating stability (strict > ensures there are no equal
  1019. elements to get out of order).
  1020. Returns -1 in case of error.
  1021. */
  1022. static Py_ssize_t
  1023. count_run(PyObject **lo, PyObject **hi, int *descending)
  1024. {
  1025. Py_ssize_t k;
  1026. Py_ssize_t n;
  1027. assert(lo < hi);
  1028. *descending = 0;
  1029. ++lo;
  1030. if (lo == hi)
  1031. return 1;
  1032. n = 2;
  1033. IFLT(*lo, *(lo-1)) {
  1034. *descending = 1;
  1035. for (lo = lo+1; lo < hi; ++lo, ++n) {
  1036. IFLT(*lo, *(lo-1))
  1037. ;
  1038. else
  1039. break;
  1040. }
  1041. }
  1042. else {
  1043. for (lo = lo+1; lo < hi; ++lo, ++n) {
  1044. IFLT(*lo, *(lo-1))
  1045. break;
  1046. }
  1047. }
  1048. return n;
  1049. fail:
  1050. return -1;
  1051. }
  1052. /*
  1053. Locate the proper position of key in a sorted vector; if the vector contains
  1054. an element equal to key, return the position immediately to the left of
  1055. the leftmost equal element. [gallop_right() does the same except returns
  1056. the position to the right of the rightmost equal element (if any).]
  1057. "a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
  1058. "hint" is an index at which to begin the search, 0 <= hint < n. The closer
  1059. hint is to the final result, the faster this runs.
  1060. The return value is the int k in 0..n such that
  1061. a[k-1] < key <= a[k]
  1062. pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
  1063. key belongs at index k; or, IOW, the first k elements of a should precede
  1064. key, and the last n-k should follow key.
  1065. Returns -1 on error. See listsort.txt for info on the method.
  1066. */
  1067. static Py_ssize_t
  1068. gallop_left(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
  1069. {
  1070. Py_ssize_t ofs;
  1071. Py_ssize_t lastofs;
  1072. Py_ssize_t k;
  1073. assert(key && a && n > 0 && hint >= 0 && hint < n);
  1074. a += hint;
  1075. lastofs = 0;
  1076. ofs = 1;
  1077. IFLT(*a, key) {
  1078. /* a[hint] < key -- gallop right, until
  1079. * a[hint + lastofs] < key <= a[hint + ofs]
  1080. */
  1081. const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
  1082. while (ofs < maxofs) {
  1083. IFLT(a[ofs], key) {
  1084. lastofs = ofs;
  1085. ofs = (ofs << 1) + 1;
  1086. if (ofs <= 0) /* int overflow */
  1087. ofs = maxofs;
  1088. }
  1089. else /* key <= a[hint + ofs] */
  1090. break;
  1091. }
  1092. if (ofs > maxofs)
  1093. ofs = maxofs;
  1094. /* Translate back to offsets relative to &a[0]. */
  1095. lastofs += hint;
  1096. ofs += hint;
  1097. }
  1098. else {
  1099. /* key <= a[hint] -- gallop left, until
  1100. * a[hint - ofs] < key <= a[hint - lastofs]
  1101. */
  1102. const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
  1103. while (ofs < maxofs) {
  1104. IFLT(*(a-ofs), key)
  1105. break;
  1106. /* key <= a[hint - ofs] */
  1107. lastofs = ofs;
  1108. ofs = (ofs << 1) + 1;
  1109. if (ofs <= 0) /* int overflow */
  1110. ofs = maxofs;
  1111. }
  1112. if (ofs > maxofs)
  1113. ofs = maxofs;
  1114. /* Translate back to positive offsets relative to &a[0]. */
  1115. k = lastofs;
  1116. lastofs = hint - ofs;
  1117. ofs = hint - k;
  1118. }
  1119. a -= hint;
  1120. assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
  1121. /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
  1122. * right of lastofs but no farther right than ofs. Do a binary
  1123. * search, with invariant a[lastofs-1] < key <= a[ofs].
  1124. */
  1125. ++lastofs;
  1126. while (lastofs < ofs) {
  1127. Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
  1128. IFLT(a[m], key)
  1129. lastofs = m+1; /* a[m] < key */
  1130. else
  1131. ofs = m; /* key <= a[m] */
  1132. }
  1133. assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
  1134. return ofs;
  1135. fail:
  1136. return -1;
  1137. }
  1138. /*
  1139. Exactly like gallop_left(), except that if key already exists in a[0:n],
  1140. finds the position immediately to the right of the rightmost equal value.
  1141. The return value is the int k in 0..n such that
  1142. a[k-1] <= key < a[k]
  1143. or -1 if error.
  1144. The code duplication is massive, but this is enough different given that
  1145. we're sticking to "<" comparisons that it's much harder to follow if
  1146. written as one routine with yet another "left or right?" flag.
  1147. */
  1148. static Py_ssize_t
  1149. gallop_right(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
  1150. {
  1151. Py_ssize_t ofs;
  1152. Py_ssize_t lastofs;
  1153. Py_ssize_t k;
  1154. assert(key && a && n > 0 && hint >= 0 && hint < n);
  1155. a += hint;
  1156. lastofs = 0;
  1157. ofs = 1;
  1158. IFLT(key, *a) {
  1159. /* key < a[hint] -- gallop left, until
  1160. * a[hint - ofs] <= key < a[hint - lastofs]
  1161. */
  1162. const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
  1163. while (ofs < maxofs) {
  1164. IFLT(key, *(a-ofs)) {
  1165. lastofs = ofs;
  1166. ofs = (ofs << 1) + 1;
  1167. if (ofs <= 0) /* int overflow */
  1168. ofs = maxofs;
  1169. }
  1170. else /* a[hint - ofs] <= key */
  1171. break;
  1172. }
  1173. if (ofs > maxofs)
  1174. ofs = maxofs;
  1175. /* Translate back to positive offsets relative to &a[0]. */
  1176. k = lastofs;
  1177. lastofs = hint - ofs;
  1178. ofs = hint - k;
  1179. }
  1180. else {
  1181. /* a[hint] <= key -- gallop right, until
  1182. * a[hint + lastofs] <= key < a[hint + ofs]
  1183. */
  1184. const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
  1185. while (ofs < maxofs) {
  1186. IFLT(key, a[ofs])
  1187. break;
  1188. /* a[hint + ofs] <= key */
  1189. lastofs = ofs;
  1190. ofs = (ofs << 1) + 1;
  1191. if (ofs <= 0) /* int overflow */
  1192. ofs = maxofs;
  1193. }
  1194. if (ofs > maxofs)
  1195. ofs = maxofs;
  1196. /* Translate back to offsets relative to &a[0]. */
  1197. lastofs += hint;
  1198. ofs += hint;
  1199. }
  1200. a -= hint;
  1201. assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
  1202. /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
  1203. * right of lastofs but no farther right than ofs. Do a binary
  1204. * search, with invariant a[lastofs-1] <= key < a[ofs].
  1205. */
  1206. ++lastofs;
  1207. while (lastofs < ofs) {
  1208. Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
  1209. IFLT(key, a[m])
  1210. ofs = m; /* key < a[m] */
  1211. else
  1212. lastofs = m+1; /* a[m] <= key */
  1213. }
  1214. assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
  1215. return ofs;
  1216. fail:
  1217. return -1;
  1218. }
  1219. /* The maximum number of entries in a MergeState's pending-runs stack.
  1220. * This is enough to sort arrays of size up to about
  1221. * 32 * phi ** MAX_MERGE_PENDING
  1222. * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
  1223. * with 2**64 elements.
  1224. */
  1225. #define MAX_MERGE_PENDING 85
  1226. /* When we get into galloping mode, we stay there until both runs win less
  1227. * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
  1228. */
  1229. #define MIN_GALLOP 7
  1230. /* Avoid malloc for small temp arrays. */
  1231. #define MERGESTATE_TEMP_SIZE 256
  1232. /* One MergeState exists on the stack per invocation of mergesort. It's just
  1233. * a convenient way to pass state around among the helper functions.
  1234. */
  1235. struct s_slice {
  1236. sortslice base;
  1237. Py_ssize_t len;
  1238. };
  1239. typedef struct s_MergeState {
  1240. /* This controls when we get *into* galloping mode. It's initialized
  1241. * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
  1242. * random data, and lower for highly structured data.
  1243. */
  1244. Py_ssize_t min_gallop;
  1245. /* 'a' is temp storage to help with merges. It contains room for
  1246. * alloced entries.
  1247. */
  1248. sortslice a; /* may point to temparray below */
  1249. Py_ssize_t alloced;
  1250. /* A stack of n pending runs yet to be merged. Run #i starts at
  1251. * address base[i] and extends for len[i] elements. It's always
  1252. * true (so long as the indices are in bounds) that
  1253. *
  1254. * pending[i].base + pending[i].len == pending[i+1].base
  1255. *
  1256. * so we could cut the storage for this, but it's a minor amount,
  1257. * and keeping all the info explicit simplifies the code.
  1258. */
  1259. int n;
  1260. struct s_slice pending[MAX_MERGE_PENDING];
  1261. /* 'a' points to this when possible, rather than muck with malloc. */
  1262. PyObject *temparray[MERGESTATE_TEMP_SIZE];
  1263. } MergeState;
  1264. /* Conceptually a MergeState's constructor. */
  1265. static void
  1266. merge_init(MergeState *ms, Py_ssize_t list_size, int has_keyfunc)
  1267. {
  1268. assert(ms != NULL);
  1269. if (has_keyfunc) {
  1270. /* The temporary space for merging will need at most half the list
  1271. * size rounded up. Use the minimum possible space so we can use the
  1272. * rest of temparray for other things. In particular, if there is
  1273. * enough extra space, listsort() will use it to store the keys.
  1274. */
  1275. ms->alloced = (list_size + 1) / 2;
  1276. /* ms->alloced describes how many keys will be stored at
  1277. ms->temparray, but we also need to store the values. Hence,
  1278. ms->alloced is capped at half of MERGESTATE_TEMP_SIZE. */
  1279. if (MERGESTATE_TEMP_SIZE / 2 < ms->alloced)
  1280. ms->alloced = MERGESTATE_TEMP_SIZE / 2;
  1281. ms->a.values = &ms->temparray[ms->alloced];
  1282. }
  1283. else {
  1284. ms->alloced = MERGESTATE_TEMP_SIZE;
  1285. ms->a.values = NULL;
  1286. }
  1287. ms->a.keys = ms->temparray;
  1288. ms->n = 0;
  1289. ms->min_gallop = MIN_GALLOP;
  1290. }
  1291. /* Free all the temp memory owned by the MergeState. This must be called
  1292. * when you're done with a MergeState, and may be called before then if
  1293. * you want to free the temp memory early.
  1294. */
  1295. static void
  1296. merge_freemem(MergeState *ms)
  1297. {
  1298. assert(ms != NULL);
  1299. if (ms->a.keys != ms->temparray)
  1300. PyMem_Free(ms->a.keys);
  1301. }
  1302. /* Ensure enough temp memory for 'need' array slots is available.
  1303. * Returns 0 on success and -1 if the memory can't be gotten.
  1304. */
  1305. static int
  1306. merge_getmem(MergeState *ms, Py_ssize_t need)
  1307. {
  1308. int multiplier;
  1309. assert(ms != NULL);
  1310. if (need <= ms->alloced)
  1311. return 0;
  1312. multiplier = ms->a.values != NULL ? 2 : 1;
  1313. /* Don't realloc! That can cost cycles to copy the old data, but
  1314. * we don't care what's in the block.
  1315. */
  1316. merge_freemem(ms);
  1317. if ((size_t)need > PY_SSIZE_T_MAX / sizeof(PyObject*) / multiplier) {
  1318. PyErr_NoMemory();
  1319. return -1;
  1320. }
  1321. ms->a.keys = (PyObject**)PyMem_Malloc(multiplier * need
  1322. * sizeof(PyObject *));
  1323. if (ms->a.keys != NULL) {
  1324. ms->alloced = need;
  1325. if (ms->a.values != NULL)
  1326. ms->a.values = &ms->a.keys[need];
  1327. return 0;
  1328. }
  1329. PyErr_NoMemory();
  1330. return -1;
  1331. }
  1332. #define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
  1333. merge_getmem(MS, NEED))
  1334. /* Merge the na elements starting at ssa with the nb elements starting at
  1335. * ssb.keys = ssa.keys + na in a stable way, in-place. na and nb must be > 0.
  1336. * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
  1337. * should have na <= nb. See listsort.txt for more info. Return 0 if
  1338. * successful, -1 if error.
  1339. */
  1340. static Py_ssize_t
  1341. merge_lo(MergeState *ms, sortslice ssa, Py_ssize_t na,
  1342. sortslice ssb, Py_ssize_t nb)
  1343. {
  1344. Py_ssize_t k;
  1345. sortslice dest;
  1346. int result = -1; /* guilty until proved innocent */
  1347. Py_ssize_t min_gallop;
  1348. assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
  1349. assert(ssa.keys + na == ssb.keys);
  1350. if (MERGE_GETMEM(ms, na) < 0)
  1351. return -1;
  1352. sortslice_memcpy(&ms->a, 0, &ssa, 0, na);
  1353. dest = ssa;
  1354. ssa = ms->a;
  1355. sortslice_copy_incr(&dest, &ssb);
  1356. --nb;
  1357. if (nb == 0)
  1358. goto Succeed;
  1359. if (na == 1)
  1360. goto CopyB;
  1361. min_gallop = ms->min_gallop;
  1362. for (;;) {
  1363. Py_ssize_t acount = 0; /* # of times A won in a row */
  1364. Py_ssize_t bcount = 0; /* # of times B won in a row */
  1365. /* Do the straightforward thing until (if ever) one run
  1366. * appears to win consistently.
  1367. */
  1368. for (;;) {
  1369. assert(na > 1 && nb > 0);
  1370. k = ISLT(ssb.keys[0], ssa.keys[0]);
  1371. if (k) {
  1372. if (k < 0)
  1373. goto Fail;
  1374. sortslice_copy_incr(&dest, &ssb);
  1375. ++bcount;
  1376. acount = 0;
  1377. --nb;
  1378. if (nb == 0)
  1379. goto Succeed;
  1380. if (bcount >= min_gallop)
  1381. break;
  1382. }
  1383. else {
  1384. sortslice_copy_incr(&dest, &ssa);
  1385. ++acount;
  1386. bcount = 0;
  1387. --na;
  1388. if (na == 1)
  1389. goto CopyB;
  1390. if (acount >= min_gallop)
  1391. break;
  1392. }
  1393. }
  1394. /* One run is winning so consistently that galloping may
  1395. * be a huge win. So try that, and continue galloping until
  1396. * (if ever) neither run appears to be winning consistently
  1397. * anymore.
  1398. */
  1399. ++min_gallop;
  1400. do {
  1401. assert(na > 1 && nb > 0);
  1402. min_gallop -= min_gallop > 1;
  1403. ms->min_gallop = min_gallop;
  1404. k = gallop_right(ssb.keys[0], ssa.keys, na, 0);
  1405. acount = k;
  1406. if (k) {
  1407. if (k < 0)
  1408. goto Fail;
  1409. sortslice_memcpy(&dest, 0, &ssa, 0, k);
  1410. sortslice_advance(&dest, k);
  1411. sortslice_advance(&ssa, k);
  1412. na -= k;
  1413. if (na == 1)
  1414. goto CopyB;
  1415. /* na==0 is impossible now if the comparison
  1416. * function is consistent, but we can't assume
  1417. * that it is.
  1418. */
  1419. if (na == 0)
  1420. goto Succeed;
  1421. }
  1422. sortslice_copy_incr(&dest, &ssb);
  1423. --nb;
  1424. if (nb == 0)
  1425. goto Succeed;
  1426. k = gallop_left(ssa.keys[0], ssb.keys, nb, 0);
  1427. bcount = k;
  1428. if (k) {
  1429. if (k < 0)
  1430. goto Fail;
  1431. sortslice_memmove(&dest, 0, &ssb, 0, k);
  1432. sortslice_advance(&dest, k);
  1433. sortslice_advance(&ssb, k);
  1434. nb -= k;
  1435. if (nb == 0)
  1436. goto Succeed;
  1437. }
  1438. sortslice_copy_incr(&dest, &ssa);
  1439. --na;
  1440. if (na == 1)
  1441. goto CopyB;
  1442. } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
  1443. ++min_gallop; /* penalize it for leaving galloping mode */
  1444. ms->min_gallop = min_gallop;
  1445. }
  1446. Succeed:
  1447. result = 0;
  1448. Fail:
  1449. if (na)
  1450. sortslice_memcpy(&dest, 0, &ssa, 0, na);
  1451. return result;
  1452. CopyB:
  1453. assert(na == 1 && nb > 0);
  1454. /* The last element of ssa belongs at the end of the merge. */
  1455. sortslice_memmove(&dest, 0, &ssb, 0, nb);
  1456. sortslice_copy(&dest, nb, &ssa, 0);
  1457. return 0;
  1458. }
  1459. /* Merge the na elements starting at pa with the nb elements starting at
  1460. * ssb.keys = ssa.keys + na in a stable way, in-place. na and nb must be > 0.
  1461. * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
  1462. * should have na >= nb. See listsort.txt for more info. Return 0 if
  1463. * successful, -1 if error.
  1464. */
  1465. static Py_ssize_t
  1466. merge_hi(MergeState *ms, sortslice ssa, Py_ssize_t na,
  1467. sortslice ssb, Py_ssize_t nb)
  1468. {
  1469. Py_ssize_t k;
  1470. sortslice dest, basea, baseb;
  1471. int result = -1; /* guilty until proved innocent */
  1472. Py_ssize_t min_gallop;
  1473. assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
  1474. assert(ssa.keys + na == ssb.keys);
  1475. if (MERGE_GETMEM(ms, nb) < 0)
  1476. return -1;
  1477. dest = ssb;
  1478. sortslice_advance(&dest, nb-1);
  1479. sortslice_memcpy(&ms->a, 0, &ssb, 0, nb);
  1480. basea = ssa;
  1481. baseb = ms->a;
  1482. ssb.keys = ms->a.keys + nb - 1;
  1483. if (ssb.values != NULL)
  1484. ssb.values = ms->a.values + nb - 1;
  1485. sortslice_advance(&ssa, na - 1);
  1486. sortslice_copy_decr(&dest, &ssa);
  1487. --na;
  1488. if (na == 0)
  1489. goto Succeed;
  1490. if (nb == 1)
  1491. goto CopyA;
  1492. min_gallop = ms->min_gallop;
  1493. for (;;) {
  1494. Py_ssize_t acount = 0; /* # of times A won in a row */
  1495. Py_ssize_t bcount = 0; /* # of times B won in a row */
  1496. /* Do the straightforward thing until (if ever) one run
  1497. * appears to win consistently.
  1498. */
  1499. for (;;) {
  1500. assert(na > 0 && nb > 1);
  1501. k = ISLT(ssb.keys[0], ssa.keys[0]);
  1502. if (k) {
  1503. if (k < 0)
  1504. goto Fail;
  1505. sortslice_copy_decr(&dest, &ssa);
  1506. ++acount;
  1507. bcount = 0;
  1508. --na;
  1509. if (na == 0)
  1510. goto Succeed;
  1511. if (acount >= min_gallop)
  1512. break;
  1513. }
  1514. else {
  1515. sortslice_copy_decr(&dest, &ssb);
  1516. ++bcount;
  1517. acount = 0;
  1518. --nb;
  1519. if (nb == 1)
  1520. goto CopyA;
  1521. if (bcount >= min_gallop)
  1522. break;
  1523. }
  1524. }
  1525. /* One run is winning so consistently that galloping may
  1526. * be a huge win. So try that, and continue galloping until
  1527. * (if ever) neither run appears to be winning consistently
  1528. * anymore.
  1529. */
  1530. ++min_gallop;
  1531. do {
  1532. assert(na > 0 && nb > 1);
  1533. min_gallop -= min_gallop > 1;
  1534. ms->min_gallop = min_gallop;
  1535. k = gallop_right(ssb.keys[0], basea.keys, na, na-1);
  1536. if (k < 0)
  1537. goto Fail;
  1538. k = na - k;
  1539. acount = k;
  1540. if (k) {
  1541. sortslice_advance(&dest, -k);
  1542. sortslice_advance(&ssa, -k);
  1543. sortslice_memmove(&dest, 1, &ssa, 1, k);
  1544. na -= k;
  1545. if (na == 0)
  1546. goto Succeed;
  1547. }
  1548. sortslice_copy_decr(&dest, &ssb);
  1549. --nb;
  1550. if (nb == 1)
  1551. goto CopyA;
  1552. k = gallop_left(ssa.keys[0], baseb.keys, nb, nb-1);
  1553. if (k < 0)
  1554. goto Fail;
  1555. k = nb - k;
  1556. bcount = k;
  1557. if (k) {
  1558. sortslice_advance(&dest, -k);
  1559. sortslice_advance(&ssb, -k);
  1560. sortslice_memcpy(&dest, 1, &ssb, 1, k);
  1561. nb -= k;
  1562. if (nb == 1)
  1563. goto CopyA;
  1564. /* nb==0 is impossible now if the comparison
  1565. * function is consistent, but we can't assume
  1566. * that it is.
  1567. */
  1568. if (nb == 0)
  1569. goto Succeed;
  1570. }
  1571. sortslice_copy_decr(&dest, &ssa);
  1572. --na;
  1573. if (na == 0)
  1574. goto Succeed;
  1575. } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
  1576. ++min_gallop; /* penalize it for leaving galloping mode */
  1577. ms->min_gallop = min_gallop;
  1578. }
  1579. Succeed:
  1580. result = 0;
  1581. Fail:
  1582. if (nb)
  1583. sortslice_memcpy(&dest, -(nb-1), &baseb, 0, nb);
  1584. return result;
  1585. CopyA:
  1586. assert(nb == 1 && na > 0);
  1587. /* The first element of ssb belongs at the front of the merge. */
  1588. sortslice_memmove(&dest, 1-na, &ssa, 1-na, na);
  1589. sortslice_advance(&dest, -na);
  1590. sortslice_advance(&ssa, -na);
  1591. sortslice_copy(&dest, 0, &ssb, 0);
  1592. return 0;
  1593. }
  1594. /* Merge the two runs at stack indices i and i+1.
  1595. * Returns 0 on success, -1 on error.
  1596. */
  1597. static Py_ssize_t
  1598. merge_at(MergeState *ms, Py_ssize_t i)
  1599. {
  1600. sortslice ssa, ssb;
  1601. Py_ssize_t na, nb;
  1602. Py_ssize_t k;
  1603. assert(ms != NULL);
  1604. assert(ms->n >= 2);
  1605. assert(i >= 0);
  1606. assert(i == ms->n - 2 || i == ms->n - 3);
  1607. ssa = ms->pending[i].base;
  1608. na = ms->pending[i].len;
  1609. ssb = ms->pending[i+1].base;
  1610. nb = ms->pending[i+1].len;
  1611. assert(na > 0 && nb > 0);
  1612. assert(ssa.keys + na == ssb.keys);
  1613. /* Record the length of the combined runs; if i is the 3rd-last
  1614. * run now, also slide over the last run (which isn't involved
  1615. * in this merge). The current run i+1 goes away in any case.
  1616. */
  1617. ms->pending[i].len = na + nb;
  1618. if (i == ms->n - 3)
  1619. ms->pending[i+1] = ms->pending[i+2];
  1620. --ms->n;
  1621. /* Where does b start in a? Elements in a before that can be
  1622. * ignored (already in place).
  1623. */
  1624. k = gallop_right(*ssb.keys, ssa.keys, na, 0);
  1625. if (k < 0)
  1626. return -1;
  1627. sortslice_advance(&ssa, k);
  1628. na -= k;
  1629. if (na == 0)
  1630. return 0;
  1631. /* Where does a end in b? Elements in b after that can be
  1632. * ignored (already in place).
  1633. */
  1634. nb = gallop_left(ssa.keys[na-1], ssb.keys, nb, nb-1);
  1635. if (nb <= 0)
  1636. return nb;
  1637. /* Merge what remains of the runs, using a temp array with
  1638. * min(na, nb) elements.
  1639. */
  1640. if (na <= nb)
  1641. return merge_lo(ms, ssa, na, ssb, nb);
  1642. else
  1643. return merge_hi(ms, ssa, na, ssb, nb);
  1644. }
  1645. /* Examine the stack of runs waiting to be merged, merging adjacent runs
  1646. * until the stack invariants are re-established:
  1647. *
  1648. * 1. len[-3] > len[-2] + len[-1]
  1649. * 2. len[-2] > len[-1]
  1650. *
  1651. * See listsort.txt for more info.
  1652. *
  1653. * Returns 0 on success, -1 on error.
  1654. */
  1655. static int
  1656. merge_collapse(MergeState *ms)
  1657. {
  1658. struct s_slice *p = ms->pending;
  1659. assert(ms);
  1660. while (ms->n > 1) {
  1661. Py_ssize_t n = ms->n - 2;
  1662. if ((n > 0 && p[n-1].len <= p[n].len + p[n+1].len) ||
  1663. (n > 1 && p[n-2].len <= p[n-1].len + p[n].len)) {
  1664. if (p[n-1].len < p[n+1].len)
  1665. --n;
  1666. if (merge_at(ms, n) < 0)
  1667. return -1;
  1668. }
  1669. else if (p[n].len <= p[n+1].len) {
  1670. if (merge_at(ms, n) < 0)
  1671. return -1;
  1672. }
  1673. else
  1674. break;
  1675. }
  1676. return 0;
  1677. }
  1678. /* Regardless of invariants, merge all runs on the stack until only one
  1679. * remains. This is used at the end of the mergesort.
  1680. *
  1681. * Returns 0 on success, -1 on error.
  1682. */
  1683. static int
  1684. merge_force_collapse(MergeState *ms)
  1685. {
  1686. struct s_slice *p = ms->pending;
  1687. assert(ms);
  1688. while (ms->n > 1) {
  1689. Py_ssize_t n = ms->n - 2;
  1690. if (n > 0 && p[n-1].len < p[n+1].len)
  1691. --n;
  1692. if (merge_at(ms, n) < 0)
  1693. return -1;
  1694. }
  1695. return 0;
  1696. }
  1697. /* Compute a good value for the minimum run length; natural runs shorter
  1698. * than this are boosted artificially via binary insertion.
  1699. *
  1700. * If n < 64, return n (it's too small to bother with fancy stuff).
  1701. * Else if n is an exact power of 2, return 32.
  1702. * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
  1703. * strictly less than, an exact power of 2.
  1704. *
  1705. * See listsort.txt for more info.
  1706. */
  1707. static Py_ssize_t
  1708. merge_compute_minrun(Py_ssize_t n)
  1709. {
  1710. Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */
  1711. assert(n >= 0);
  1712. while (n >= 64) {
  1713. r |= n & 1;
  1714. n >>= 1;
  1715. }
  1716. return n + r;
  1717. }
  1718. static void
  1719. reverse_sortslice(sortslice *s, Py_ssize_t n)
  1720. {
  1721. reverse_slice(s->keys, &s->keys[n]);
  1722. if (s->values != NULL)
  1723. reverse_slice(s->values, &s->values[n]);
  1724. }
  1725. /* An adaptive, stable, natural mergesort. See listsort.txt.
  1726. * Returns Py_None on success, NULL on error. Even in case of error, the
  1727. * list will be some permutation of its input state (nothing is lost or
  1728. * duplicated).
  1729. */
  1730. static PyObject *
  1731. listsort(PyListObject *self, PyObject *args, PyObject *kwds)
  1732. {
  1733. MergeState ms;
  1734. Py_ssize_t nremaining;
  1735. Py_ssize_t minrun;
  1736. sortslice lo;
  1737. Py_ssize_t saved_ob_size, saved_allocated;
  1738. PyObject **saved_ob_item;
  1739. PyObject **final_ob_item;
  1740. PyObject *result = NULL; /* guilty until proved innocent */
  1741. int reverse = 0;
  1742. PyObject *keyfunc = NULL;
  1743. Py_ssize_t i;
  1744. static char *kwlist[] = {"key", "reverse", 0};
  1745. PyObject **keys;
  1746. assert(self != NULL);
  1747. assert (PyList_Check(self));
  1748. if (args != NULL) {
  1749. if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:sort",
  1750. kwlist, &keyfunc, &reverse))
  1751. return NULL;
  1752. if (Py_SIZE(args) > 0) {
  1753. PyErr_SetString(PyExc_TypeError,
  1754. "must use keyword argument for key function");
  1755. return NULL;
  1756. }
  1757. }
  1758. if (keyfunc == Py_None)
  1759. keyfunc = NULL;
  1760. /* The list is temporarily made empty, so that mutations performed
  1761. * by comparison functions can't affect the slice of memory we're
  1762. * sorting (allowing mutations during sorting is a core-dump
  1763. * factory, since ob_item may change).
  1764. */
  1765. saved_ob_size = Py_SIZE(self);
  1766. saved_ob_item = self->ob_item;
  1767. saved_allocated = self->allocated;
  1768. Py_SIZE(self) = 0;
  1769. self->ob_item = NULL;
  1770. self->allocated = -1; /* any operation will reset it to >= 0 */
  1771. if (keyfunc == NULL) {
  1772. keys = NULL;
  1773. lo.keys = saved_ob_item;
  1774. lo.values = NULL;
  1775. }
  1776. else {
  1777. if (saved_ob_size < MERGESTATE_TEMP_SIZE/2)
  1778. /* Leverage stack space we allocated but won't otherwise use */
  1779. keys = &ms.temparray[saved_ob_size+1];
  1780. else {
  1781. keys = PyMem_MALLOC(sizeof(PyObject *) * saved_ob_size);
  1782. if (keys == NULL) {
  1783. PyErr_NoMemory();
  1784. goto keyfunc_fail;
  1785. }
  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 (saved_ob_size >= MERGESTATE_TEMP_SIZE/2)
  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 (saved_ob_size >= MERGESTATE_TEMP_SIZE/2)
  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 = _PyObject_SIZE(Py_TYPE(self)) + 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 or slices, 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. garbage = (PyObject**)
  2260. PyMem_MALLOC(slicelength*sizeof(PyObject*));
  2261. if (!garbage) {
  2262. PyErr_NoMemory();
  2263. return -1;
  2264. }
  2265. /* drawing pictures might help understand these for
  2266. loops. Basically, we memmove the parts of the
  2267. list that are *not* part of the slice: step-1
  2268. items for each item that is part of the slice,
  2269. and then tail end of the list that was not
  2270. covered by the slice */
  2271. for (cur = start, i = 0;
  2272. cur < (size_t)stop;
  2273. cur += step, i++) {
  2274. Py_ssize_t lim = step - 1;
  2275. garbage[i] = PyList_GET_ITEM(self, cur);
  2276. if (cur + step >= (size_t)Py_SIZE(self)) {
  2277. lim = Py_SIZE(self) - cur - 1;
  2278. }
  2279. memmove(self->ob_item + cur - i,
  2280. self->ob_item + cur + 1,
  2281. lim * sizeof(PyObject *));
  2282. }
  2283. cur = start + (size_t)slicelength * step;
  2284. if (cur < (size_t)Py_SIZE(self)) {
  2285. memmove(self->ob_item + cur - slicelength,
  2286. self->ob_item + cur,
  2287. (Py_SIZE(self) - cur) *
  2288. sizeof(PyObject *));
  2289. }
  2290. Py_SIZE(self) -= slicelength;
  2291. res = list_resize(self, Py_SIZE(self));
  2292. for (i = 0; i < slicelength; i++) {
  2293. Py_DECREF(garbage[i]);
  2294. }
  2295. PyMem_FREE(garbage);
  2296. return res;
  2297. }
  2298. else {
  2299. /* assign slice */
  2300. PyObject *ins, *seq;
  2301. PyObject **garbage, **seqitems, **selfitems;
  2302. Py_ssize_t cur, i;
  2303. /* protect against a[::-1] = a */
  2304. if (self == (PyListObject*)value) {
  2305. seq = list_slice((PyListObject*)value, 0,
  2306. PyList_GET_SIZE(value));
  2307. }
  2308. else {
  2309. seq = PySequence_Fast(value,
  2310. "must assign iterable "
  2311. "to extended slice");
  2312. }
  2313. if (!seq)
  2314. return -1;
  2315. if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
  2316. PyErr_Format(PyExc_ValueError,
  2317. "attempt to assign sequence of "
  2318. "size %zd to extended slice of "
  2319. "size %zd",
  2320. PySequence_Fast_GET_SIZE(seq),
  2321. slicelength);
  2322. Py_DECREF(seq);
  2323. return -1;
  2324. }
  2325. if (!slicelength) {
  2326. Py_DECREF(seq);
  2327. return 0;
  2328. }
  2329. garbage = (PyObject**)
  2330. PyMem_MALLOC(slicelength*sizeof(PyObject*));
  2331. if (!garbage) {
  2332. Py_DECREF(seq);
  2333. PyErr_NoMemory();
  2334. return -1;
  2335. }
  2336. selfitems = self->ob_item;
  2337. seqitems = PySequence_Fast_ITEMS(seq);
  2338. for (cur = start, i = 0; i < slicelength;
  2339. cur += (size_t)step, i++) {
  2340. garbage[i] = selfitems[cur];
  2341. ins = seqitems[i];
  2342. Py_INCREF(ins);
  2343. selfitems[cur] = ins;
  2344. }
  2345. for (i = 0; i < slicelength; i++) {
  2346. Py_DECREF(garbage[i]);
  2347. }
  2348. PyMem_FREE(garbage);
  2349. Py_DECREF(seq);
  2350. return 0;
  2351. }
  2352. }
  2353. else {
  2354. PyErr_Format(PyExc_TypeError,
  2355. "list indices must be integers or slices, not %.200s",
  2356. item->ob_type->tp_name);
  2357. return -1;
  2358. }
  2359. }
  2360. static PyMappingMethods list_as_mapping = {
  2361. (lenfunc)list_length,
  2362. (binaryfunc)list_subscript,
  2363. (objobjargproc)list_ass_subscript
  2364. };
  2365. PyTypeObject PyList_Type = {
  2366. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  2367. "list",
  2368. sizeof(PyListObject),
  2369. 0,
  2370. (destructor)list_dealloc, /* tp_dealloc */
  2371. 0, /* tp_print */
  2372. 0, /* tp_getattr */
  2373. 0, /* tp_setattr */
  2374. 0, /* tp_reserved */
  2375. (reprfunc)list_repr, /* tp_repr */
  2376. 0, /* tp_as_number */
  2377. &list_as_sequence, /* tp_as_sequence */
  2378. &list_as_mapping, /* tp_as_mapping */
  2379. PyObject_HashNotImplemented, /* tp_hash */
  2380. 0, /* tp_call */
  2381. 0, /* tp_str */
  2382. PyObject_GenericGetAttr, /* tp_getattro */
  2383. 0, /* tp_setattro */
  2384. 0, /* tp_as_buffer */
  2385. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
  2386. Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */
  2387. list_doc, /* tp_doc */
  2388. (traverseproc)list_traverse, /* tp_traverse */
  2389. (inquiry)list_clear, /* tp_clear */
  2390. list_richcompare, /* tp_richcompare */
  2391. 0, /* tp_weaklistoffset */
  2392. list_iter, /* tp_iter */
  2393. 0, /* tp_iternext */
  2394. list_methods, /* tp_methods */
  2395. 0, /* tp_members */
  2396. 0, /* tp_getset */
  2397. 0, /* tp_base */
  2398. 0, /* tp_dict */
  2399. 0, /* tp_descr_get */
  2400. 0, /* tp_descr_set */
  2401. 0, /* tp_dictoffset */
  2402. (initproc)list_init, /* tp_init */
  2403. PyType_GenericAlloc, /* tp_alloc */
  2404. PyType_GenericNew, /* tp_new */
  2405. PyObject_GC_Del, /* tp_free */
  2406. };
  2407. /*********************** List Iterator **************************/
  2408. typedef struct {
  2409. PyObject_HEAD
  2410. Py_ssize_t it_index;
  2411. PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
  2412. } listiterobject;
  2413. static PyObject *list_iter(PyObject *);
  2414. static void listiter_dealloc(listiterobject *);
  2415. static int listiter_traverse(listiterobject *, visitproc, void *);
  2416. static PyObject *listiter_next(listiterobject *);
  2417. static PyObject *listiter_len(listiterobject *);
  2418. static PyObject *listiter_reduce_general(void *_it, int forward);
  2419. static PyObject *listiter_reduce(listiterobject *);
  2420. static PyObject *listiter_setstate(listiterobject *, PyObject *state);
  2421. PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
  2422. PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
  2423. PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
  2424. static PyMethodDef listiter_methods[] = {
  2425. {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc},
  2426. {"__reduce__", (PyCFunction)listiter_reduce, METH_NOARGS, reduce_doc},
  2427. {"__setstate__", (PyCFunction)listiter_setstate, METH_O, setstate_doc},
  2428. {NULL, NULL} /* sentinel */
  2429. };
  2430. PyTypeObject PyListIter_Type = {
  2431. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  2432. "list_iterator", /* tp_name */
  2433. sizeof(listiterobject), /* tp_basicsize */
  2434. 0, /* tp_itemsize */
  2435. /* methods */
  2436. (destructor)listiter_dealloc, /* tp_dealloc */
  2437. 0, /* tp_print */
  2438. 0, /* tp_getattr */
  2439. 0, /* tp_setattr */
  2440. 0, /* tp_reserved */
  2441. 0, /* tp_repr */
  2442. 0, /* tp_as_number */
  2443. 0, /* tp_as_sequence */
  2444. 0, /* tp_as_mapping */
  2445. 0, /* tp_hash */
  2446. 0, /* tp_call */
  2447. 0, /* tp_str */
  2448. PyObject_GenericGetAttr, /* tp_getattro */
  2449. 0, /* tp_setattro */
  2450. 0, /* tp_as_buffer */
  2451. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
  2452. 0, /* tp_doc */
  2453. (traverseproc)listiter_traverse, /* tp_traverse */
  2454. 0, /* tp_clear */
  2455. 0, /* tp_richcompare */
  2456. 0, /* tp_weaklistoffset */
  2457. PyObject_SelfIter, /* tp_iter */
  2458. (iternextfunc)listiter_next, /* tp_iternext */
  2459. listiter_methods, /* tp_methods */
  2460. 0, /* tp_members */
  2461. };
  2462. static PyObject *
  2463. list_iter(PyObject *seq)
  2464. {
  2465. listiterobject *it;
  2466. if (!PyList_Check(seq)) {
  2467. PyErr_BadInternalCall();
  2468. return NULL;
  2469. }
  2470. it = PyObject_GC_New(listiterobject, &PyListIter_Type);
  2471. if (it == NULL)
  2472. return NULL;
  2473. it->it_index = 0;
  2474. Py_INCREF(seq);
  2475. it->it_seq = (PyListObject *)seq;
  2476. _PyObject_GC_TRACK(it);
  2477. return (PyObject *)it;
  2478. }
  2479. static void
  2480. listiter_dealloc(listiterobject *it)
  2481. {
  2482. _PyObject_GC_UNTRACK(it);
  2483. Py_XDECREF(it->it_seq);
  2484. PyObject_GC_Del(it);
  2485. }
  2486. static int
  2487. listiter_traverse(listiterobject *it, visitproc visit, void *arg)
  2488. {
  2489. Py_VISIT(it->it_seq);
  2490. return 0;
  2491. }
  2492. static PyObject *
  2493. listiter_next(listiterobject *it)
  2494. {
  2495. PyListObject *seq;
  2496. PyObject *item;
  2497. assert(it != NULL);
  2498. seq = it->it_seq;
  2499. if (seq == NULL)
  2500. return NULL;
  2501. assert(PyList_Check(seq));
  2502. if (it->it_index < PyList_GET_SIZE(seq)) {
  2503. item = PyList_GET_ITEM(seq, it->it_index);
  2504. ++it->it_index;
  2505. Py_INCREF(item);
  2506. return item;
  2507. }
  2508. it->it_seq = NULL;
  2509. Py_DECREF(seq);
  2510. return NULL;
  2511. }
  2512. static PyObject *
  2513. listiter_len(listiterobject *it)
  2514. {
  2515. Py_ssize_t len;
  2516. if (it->it_seq) {
  2517. len = PyList_GET_SIZE(it->it_seq) - it->it_index;
  2518. if (len >= 0)
  2519. return PyLong_FromSsize_t(len);
  2520. }
  2521. return PyLong_FromLong(0);
  2522. }
  2523. static PyObject *
  2524. listiter_reduce(listiterobject *it)
  2525. {
  2526. return listiter_reduce_general(it, 1);
  2527. }
  2528. static PyObject *
  2529. listiter_setstate(listiterobject *it, PyObject *state)
  2530. {
  2531. Py_ssize_t index = PyLong_AsSsize_t(state);
  2532. if (index == -1 && PyErr_Occurred())
  2533. return NULL;
  2534. if (it->it_seq != NULL) {
  2535. if (index < 0)
  2536. index = 0;
  2537. else if (index > PyList_GET_SIZE(it->it_seq))
  2538. index = PyList_GET_SIZE(it->it_seq); /* iterator exhausted */
  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;
  2626. PyListObject *seq;
  2627. assert(it != NULL);
  2628. seq = it->it_seq;
  2629. if (seq == NULL) {
  2630. return NULL;
  2631. }
  2632. assert(PyList_Check(seq));
  2633. index = it->it_index;
  2634. if (index>=0 && index < PyList_GET_SIZE(seq)) {
  2635. item = PyList_GET_ITEM(seq, index);
  2636. it->it_index--;
  2637. Py_INCREF(item);
  2638. return item;
  2639. }
  2640. it->it_index = -1;
  2641. it->it_seq = NULL;
  2642. Py_DECREF(seq);
  2643. return NULL;
  2644. }
  2645. static PyObject *
  2646. listreviter_len(listreviterobject *it)
  2647. {
  2648. Py_ssize_t len = it->it_index + 1;
  2649. if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
  2650. len = 0;
  2651. return PyLong_FromSsize_t(len);
  2652. }
  2653. static PyObject *
  2654. listreviter_reduce(listreviterobject *it)
  2655. {
  2656. return listiter_reduce_general(it, 0);
  2657. }
  2658. static PyObject *
  2659. listreviter_setstate(listreviterobject *it, PyObject *state)
  2660. {
  2661. Py_ssize_t index = PyLong_AsSsize_t(state);
  2662. if (index == -1 && PyErr_Occurred())
  2663. return NULL;
  2664. if (it->it_seq != NULL) {
  2665. if (index < -1)
  2666. index = -1;
  2667. else if (index > PyList_GET_SIZE(it->it_seq) - 1)
  2668. index = PyList_GET_SIZE(it->it_seq) - 1;
  2669. it->it_index = index;
  2670. }
  2671. Py_RETURN_NONE;
  2672. }
  2673. /* common pickling support */
  2674. static PyObject *
  2675. listiter_reduce_general(void *_it, int forward)
  2676. {
  2677. PyObject *list;
  2678. /* the objects are not the same, index is of different types! */
  2679. if (forward) {
  2680. listiterobject *it = (listiterobject *)_it;
  2681. if (it->it_seq)
  2682. return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
  2683. it->it_seq, it->it_index);
  2684. } else {
  2685. listreviterobject *it = (listreviterobject *)_it;
  2686. if (it->it_seq)
  2687. return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("reversed"),
  2688. it->it_seq, it->it_index);
  2689. }
  2690. /* empty iterator, create an empty list */
  2691. list = PyList_New(0);
  2692. if (list == NULL)
  2693. return NULL;
  2694. return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), list);
  2695. }