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

/Objects/listobject.c

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