PageRenderTime 29ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/Objects/listobject.c

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