PageRenderTime 72ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 1ms

/sys/src/cmd/python/Objects/listobject.c

https://bitbucket.org/mischief/plan9front
C | 2930 lines | 2278 code | 269 blank | 383 comment | 568 complexity | 71db6bb0f4fe6c9a8027f71d26ca7144 MD5 | raw file
Possible License(s): AGPL-1.0, GPL-2.0, BSD-3-Clause, LGPL-3.0, 0BSD

Large files files are truncated, but you can click here to view the full file

  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. self->ob_size = 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) + newsize;
  44. if (newsize == 0)
  45. new_allocated = 0;
  46. items = self->ob_item;
  47. if (new_allocated <= ((~(size_t)0) / sizeof(PyObject *)))
  48. PyMem_RESIZE(items, PyObject *, new_allocated);
  49. else
  50. items = NULL;
  51. if (items == NULL) {
  52. PyErr_NoMemory();
  53. return -1;
  54. }
  55. self->ob_item = items;
  56. self->ob_size = newsize;
  57. self->allocated = new_allocated;
  58. return 0;
  59. }
  60. /* Empty list reuse scheme to save calls to malloc and free */
  61. #define MAXFREELISTS 80
  62. static PyListObject *free_lists[MAXFREELISTS];
  63. static int num_free_lists = 0;
  64. void
  65. PyList_Fini(void)
  66. {
  67. PyListObject *op;
  68. while (num_free_lists) {
  69. num_free_lists--;
  70. op = free_lists[num_free_lists];
  71. assert(PyList_CheckExact(op));
  72. PyObject_GC_Del(op);
  73. }
  74. }
  75. PyObject *
  76. PyList_New(Py_ssize_t size)
  77. {
  78. PyListObject *op;
  79. size_t nbytes;
  80. if (size < 0) {
  81. PyErr_BadInternalCall();
  82. return NULL;
  83. }
  84. nbytes = size * sizeof(PyObject *);
  85. /* Check for overflow */
  86. if (nbytes / sizeof(PyObject *) != (size_t)size)
  87. return PyErr_NoMemory();
  88. if (num_free_lists) {
  89. num_free_lists--;
  90. op = free_lists[num_free_lists];
  91. _Py_NewReference((PyObject *)op);
  92. } else {
  93. op = PyObject_GC_New(PyListObject, &PyList_Type);
  94. if (op == NULL)
  95. return NULL;
  96. }
  97. if (size <= 0)
  98. op->ob_item = NULL;
  99. else {
  100. op->ob_item = (PyObject **) PyMem_MALLOC(nbytes);
  101. if (op->ob_item == NULL) {
  102. Py_DECREF(op);
  103. return PyErr_NoMemory();
  104. }
  105. memset(op->ob_item, 0, nbytes);
  106. }
  107. op->ob_size = size;
  108. op->allocated = size;
  109. _PyObject_GC_TRACK(op);
  110. return (PyObject *) op;
  111. }
  112. Py_ssize_t
  113. PyList_Size(PyObject *op)
  114. {
  115. if (!PyList_Check(op)) {
  116. PyErr_BadInternalCall();
  117. return -1;
  118. }
  119. else
  120. return ((PyListObject *)op) -> ob_size;
  121. }
  122. static PyObject *indexerr = NULL;
  123. PyObject *
  124. PyList_GetItem(PyObject *op, Py_ssize_t i)
  125. {
  126. if (!PyList_Check(op)) {
  127. PyErr_BadInternalCall();
  128. return NULL;
  129. }
  130. if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
  131. if (indexerr == NULL)
  132. indexerr = PyString_FromString(
  133. "list index out of range");
  134. PyErr_SetObject(PyExc_IndexError, indexerr);
  135. return NULL;
  136. }
  137. return ((PyListObject *)op) -> ob_item[i];
  138. }
  139. int
  140. PyList_SetItem(register PyObject *op, register Py_ssize_t i,
  141. register PyObject *newitem)
  142. {
  143. register PyObject *olditem;
  144. register PyObject **p;
  145. if (!PyList_Check(op)) {
  146. Py_XDECREF(newitem);
  147. PyErr_BadInternalCall();
  148. return -1;
  149. }
  150. if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
  151. Py_XDECREF(newitem);
  152. PyErr_SetString(PyExc_IndexError,
  153. "list assignment index out of range");
  154. return -1;
  155. }
  156. p = ((PyListObject *)op) -> ob_item + i;
  157. olditem = *p;
  158. *p = newitem;
  159. Py_XDECREF(olditem);
  160. return 0;
  161. }
  162. static int
  163. ins1(PyListObject *self, Py_ssize_t where, PyObject *v)
  164. {
  165. Py_ssize_t i, n = self->ob_size;
  166. PyObject **items;
  167. if (v == NULL) {
  168. PyErr_BadInternalCall();
  169. return -1;
  170. }
  171. if (n == PY_SSIZE_T_MAX) {
  172. PyErr_SetString(PyExc_OverflowError,
  173. "cannot add more objects to list");
  174. return -1;
  175. }
  176. if (list_resize(self, n+1) == -1)
  177. return -1;
  178. if (where < 0) {
  179. where += n;
  180. if (where < 0)
  181. where = 0;
  182. }
  183. if (where > n)
  184. where = n;
  185. items = self->ob_item;
  186. for (i = n; --i >= where; )
  187. items[i+1] = items[i];
  188. Py_INCREF(v);
  189. items[where] = v;
  190. return 0;
  191. }
  192. int
  193. PyList_Insert(PyObject *op, Py_ssize_t where, PyObject *newitem)
  194. {
  195. if (!PyList_Check(op)) {
  196. PyErr_BadInternalCall();
  197. return -1;
  198. }
  199. return ins1((PyListObject *)op, where, newitem);
  200. }
  201. static int
  202. app1(PyListObject *self, PyObject *v)
  203. {
  204. Py_ssize_t n = PyList_GET_SIZE(self);
  205. assert (v != NULL);
  206. if (n == PY_SSIZE_T_MAX) {
  207. PyErr_SetString(PyExc_OverflowError,
  208. "cannot add more objects to list");
  209. return -1;
  210. }
  211. if (list_resize(self, n+1) == -1)
  212. return -1;
  213. Py_INCREF(v);
  214. PyList_SET_ITEM(self, n, v);
  215. return 0;
  216. }
  217. int
  218. PyList_Append(PyObject *op, PyObject *newitem)
  219. {
  220. if (PyList_Check(op) && (newitem != NULL))
  221. return app1((PyListObject *)op, newitem);
  222. PyErr_BadInternalCall();
  223. return -1;
  224. }
  225. /* Methods */
  226. static void
  227. list_dealloc(PyListObject *op)
  228. {
  229. Py_ssize_t i;
  230. PyObject_GC_UnTrack(op);
  231. Py_TRASHCAN_SAFE_BEGIN(op)
  232. if (op->ob_item != NULL) {
  233. /* Do it backwards, for Christian Tismer.
  234. There's a simple test case where somehow this reduces
  235. thrashing when a *very* large list is created and
  236. immediately deleted. */
  237. i = op->ob_size;
  238. while (--i >= 0) {
  239. Py_XDECREF(op->ob_item[i]);
  240. }
  241. PyMem_FREE(op->ob_item);
  242. }
  243. if (num_free_lists < MAXFREELISTS && PyList_CheckExact(op))
  244. free_lists[num_free_lists++] = op;
  245. else
  246. op->ob_type->tp_free((PyObject *)op);
  247. Py_TRASHCAN_SAFE_END(op)
  248. }
  249. static int
  250. list_print(PyListObject *op, FILE *fp, int flags)
  251. {
  252. int rc;
  253. Py_ssize_t i;
  254. rc = Py_ReprEnter((PyObject*)op);
  255. if (rc != 0) {
  256. if (rc < 0)
  257. return rc;
  258. fprintf(fp, "[...]");
  259. return 0;
  260. }
  261. fprintf(fp, "[");
  262. for (i = 0; i < op->ob_size; i++) {
  263. if (i > 0)
  264. fprintf(fp, ", ");
  265. if (PyObject_Print(op->ob_item[i], fp, 0) != 0) {
  266. Py_ReprLeave((PyObject *)op);
  267. return -1;
  268. }
  269. }
  270. fprintf(fp, "]");
  271. Py_ReprLeave((PyObject *)op);
  272. return 0;
  273. }
  274. static PyObject *
  275. list_repr(PyListObject *v)
  276. {
  277. Py_ssize_t i;
  278. PyObject *s, *temp;
  279. PyObject *pieces = NULL, *result = NULL;
  280. i = Py_ReprEnter((PyObject*)v);
  281. if (i != 0) {
  282. return i > 0 ? PyString_FromString("[...]") : NULL;
  283. }
  284. if (v->ob_size == 0) {
  285. result = PyString_FromString("[]");
  286. goto Done;
  287. }
  288. pieces = PyList_New(0);
  289. if (pieces == NULL)
  290. goto Done;
  291. /* Do repr() on each element. Note that this may mutate the list,
  292. so must refetch the list size on each iteration. */
  293. for (i = 0; i < v->ob_size; ++i) {
  294. int status;
  295. s = PyObject_Repr(v->ob_item[i]);
  296. if (s == NULL)
  297. goto Done;
  298. status = PyList_Append(pieces, s);
  299. Py_DECREF(s); /* append created a new ref */
  300. if (status < 0)
  301. goto Done;
  302. }
  303. /* Add "[]" decorations to the first and last items. */
  304. assert(PyList_GET_SIZE(pieces) > 0);
  305. s = PyString_FromString("[");
  306. if (s == NULL)
  307. goto Done;
  308. temp = PyList_GET_ITEM(pieces, 0);
  309. PyString_ConcatAndDel(&s, temp);
  310. PyList_SET_ITEM(pieces, 0, s);
  311. if (s == NULL)
  312. goto Done;
  313. s = PyString_FromString("]");
  314. if (s == NULL)
  315. goto Done;
  316. temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
  317. PyString_ConcatAndDel(&temp, s);
  318. PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
  319. if (temp == NULL)
  320. goto Done;
  321. /* Paste them all together with ", " between. */
  322. s = PyString_FromString(", ");
  323. if (s == NULL)
  324. goto Done;
  325. result = _PyString_Join(s, pieces);
  326. Py_DECREF(s);
  327. Done:
  328. Py_XDECREF(pieces);
  329. Py_ReprLeave((PyObject *)v);
  330. return result;
  331. }
  332. static Py_ssize_t
  333. list_length(PyListObject *a)
  334. {
  335. return a->ob_size;
  336. }
  337. static int
  338. list_contains(PyListObject *a, PyObject *el)
  339. {
  340. Py_ssize_t i;
  341. int cmp;
  342. for (i = 0, cmp = 0 ; cmp == 0 && i < a->ob_size; ++i)
  343. cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
  344. Py_EQ);
  345. return cmp;
  346. }
  347. static PyObject *
  348. list_item(PyListObject *a, Py_ssize_t i)
  349. {
  350. if (i < 0 || i >= a->ob_size) {
  351. if (indexerr == NULL)
  352. indexerr = PyString_FromString(
  353. "list index out of range");
  354. PyErr_SetObject(PyExc_IndexError, indexerr);
  355. return NULL;
  356. }
  357. Py_INCREF(a->ob_item[i]);
  358. return a->ob_item[i];
  359. }
  360. static PyObject *
  361. list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
  362. {
  363. PyListObject *np;
  364. PyObject **src, **dest;
  365. Py_ssize_t i, len;
  366. if (ilow < 0)
  367. ilow = 0;
  368. else if (ilow > a->ob_size)
  369. ilow = a->ob_size;
  370. if (ihigh < ilow)
  371. ihigh = ilow;
  372. else if (ihigh > a->ob_size)
  373. ihigh = a->ob_size;
  374. len = ihigh - ilow;
  375. np = (PyListObject *) PyList_New(len);
  376. if (np == NULL)
  377. return NULL;
  378. src = a->ob_item + ilow;
  379. dest = np->ob_item;
  380. for (i = 0; i < len; i++) {
  381. PyObject *v = src[i];
  382. Py_INCREF(v);
  383. dest[i] = v;
  384. }
  385. return (PyObject *)np;
  386. }
  387. PyObject *
  388. PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
  389. {
  390. if (!PyList_Check(a)) {
  391. PyErr_BadInternalCall();
  392. return NULL;
  393. }
  394. return list_slice((PyListObject *)a, ilow, ihigh);
  395. }
  396. static PyObject *
  397. list_concat(PyListObject *a, PyObject *bb)
  398. {
  399. Py_ssize_t size;
  400. Py_ssize_t i;
  401. PyObject **src, **dest;
  402. PyListObject *np;
  403. if (!PyList_Check(bb)) {
  404. PyErr_Format(PyExc_TypeError,
  405. "can only concatenate list (not \"%.200s\") to list",
  406. bb->ob_type->tp_name);
  407. return NULL;
  408. }
  409. #define b ((PyListObject *)bb)
  410. size = a->ob_size + b->ob_size;
  411. if (size < 0)
  412. return PyErr_NoMemory();
  413. np = (PyListObject *) PyList_New(size);
  414. if (np == NULL) {
  415. return NULL;
  416. }
  417. src = a->ob_item;
  418. dest = np->ob_item;
  419. for (i = 0; i < a->ob_size; i++) {
  420. PyObject *v = src[i];
  421. Py_INCREF(v);
  422. dest[i] = v;
  423. }
  424. src = b->ob_item;
  425. dest = np->ob_item + a->ob_size;
  426. for (i = 0; i < b->ob_size; i++) {
  427. PyObject *v = src[i];
  428. Py_INCREF(v);
  429. dest[i] = v;
  430. }
  431. return (PyObject *)np;
  432. #undef b
  433. }
  434. static PyObject *
  435. list_repeat(PyListObject *a, Py_ssize_t n)
  436. {
  437. Py_ssize_t i, j;
  438. Py_ssize_t size;
  439. PyListObject *np;
  440. PyObject **p, **items;
  441. PyObject *elem;
  442. if (n < 0)
  443. n = 0;
  444. size = a->ob_size * n;
  445. if (size == 0)
  446. return PyList_New(0);
  447. if (n && size/n != a->ob_size)
  448. return PyErr_NoMemory();
  449. np = (PyListObject *) PyList_New(size);
  450. if (np == NULL)
  451. return NULL;
  452. items = np->ob_item;
  453. if (a->ob_size == 1) {
  454. elem = a->ob_item[0];
  455. for (i = 0; i < n; i++) {
  456. items[i] = elem;
  457. Py_INCREF(elem);
  458. }
  459. return (PyObject *) np;
  460. }
  461. p = np->ob_item;
  462. items = a->ob_item;
  463. for (i = 0; i < n; i++) {
  464. for (j = 0; j < a->ob_size; j++) {
  465. *p = items[j];
  466. Py_INCREF(*p);
  467. p++;
  468. }
  469. }
  470. return (PyObject *) np;
  471. }
  472. static int
  473. list_clear(PyListObject *a)
  474. {
  475. Py_ssize_t i;
  476. PyObject **item = a->ob_item;
  477. if (item != NULL) {
  478. /* Because XDECREF can recursively invoke operations on
  479. this list, we make it empty first. */
  480. i = a->ob_size;
  481. a->ob_size = 0;
  482. a->ob_item = NULL;
  483. a->allocated = 0;
  484. while (--i >= 0) {
  485. Py_XDECREF(item[i]);
  486. }
  487. PyMem_FREE(item);
  488. }
  489. /* Never fails; the return value can be ignored.
  490. Note that there is no guarantee that the list is actually empty
  491. at this point, because XDECREF may have populated it again! */
  492. return 0;
  493. }
  494. /* a[ilow:ihigh] = v if v != NULL.
  495. * del a[ilow:ihigh] if v == NULL.
  496. *
  497. * Special speed gimmick: when v is NULL and ihigh - ilow <= 8, it's
  498. * guaranteed the call cannot fail.
  499. */
  500. static int
  501. list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
  502. {
  503. /* Because [X]DECREF can recursively invoke list operations on
  504. this list, we must postpone all [X]DECREF activity until
  505. after the list is back in its canonical shape. Therefore
  506. we must allocate an additional array, 'recycle', into which
  507. we temporarily copy the items that are deleted from the
  508. list. :-( */
  509. PyObject *recycle_on_stack[8];
  510. PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
  511. PyObject **item;
  512. PyObject **vitem = NULL;
  513. PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
  514. Py_ssize_t n; /* # of elements in replacement list */
  515. Py_ssize_t norig; /* # of elements in list getting replaced */
  516. Py_ssize_t d; /* Change in size */
  517. Py_ssize_t k;
  518. size_t s;
  519. int result = -1; /* guilty until proved innocent */
  520. #define b ((PyListObject *)v)
  521. if (v == NULL)
  522. n = 0;
  523. else {
  524. if (a == b) {
  525. /* Special case "a[i:j] = a" -- copy b first */
  526. v = list_slice(b, 0, b->ob_size);
  527. if (v == NULL)
  528. return result;
  529. result = list_ass_slice(a, ilow, ihigh, v);
  530. Py_DECREF(v);
  531. return result;
  532. }
  533. v_as_SF = PySequence_Fast(v, "can only assign an iterable");
  534. if(v_as_SF == NULL)
  535. goto Error;
  536. n = PySequence_Fast_GET_SIZE(v_as_SF);
  537. vitem = PySequence_Fast_ITEMS(v_as_SF);
  538. }
  539. if (ilow < 0)
  540. ilow = 0;
  541. else if (ilow > a->ob_size)
  542. ilow = a->ob_size;
  543. if (ihigh < ilow)
  544. ihigh = ilow;
  545. else if (ihigh > a->ob_size)
  546. ihigh = a->ob_size;
  547. norig = ihigh - ilow;
  548. assert(norig >= 0);
  549. d = n - norig;
  550. if (a->ob_size + d == 0) {
  551. Py_XDECREF(v_as_SF);
  552. return list_clear(a);
  553. }
  554. item = a->ob_item;
  555. /* recycle the items that we are about to remove */
  556. s = norig * sizeof(PyObject *);
  557. if (s > sizeof(recycle_on_stack)) {
  558. recycle = (PyObject **)PyMem_MALLOC(s);
  559. if (recycle == NULL) {
  560. PyErr_NoMemory();
  561. goto Error;
  562. }
  563. }
  564. memcpy(recycle, &item[ilow], s);
  565. if (d < 0) { /* Delete -d items */
  566. memmove(&item[ihigh+d], &item[ihigh],
  567. (a->ob_size - ihigh)*sizeof(PyObject *));
  568. list_resize(a, a->ob_size + d);
  569. item = a->ob_item;
  570. }
  571. else if (d > 0) { /* Insert d items */
  572. k = a->ob_size;
  573. if (list_resize(a, k+d) < 0)
  574. goto Error;
  575. item = a->ob_item;
  576. memmove(&item[ihigh+d], &item[ihigh],
  577. (k - ihigh)*sizeof(PyObject *));
  578. }
  579. for (k = 0; k < n; k++, ilow++) {
  580. PyObject *w = vitem[k];
  581. Py_XINCREF(w);
  582. item[ilow] = w;
  583. }
  584. for (k = norig - 1; k >= 0; --k)
  585. Py_XDECREF(recycle[k]);
  586. result = 0;
  587. Error:
  588. if (recycle != recycle_on_stack)
  589. PyMem_FREE(recycle);
  590. Py_XDECREF(v_as_SF);
  591. return result;
  592. #undef b
  593. }
  594. int
  595. PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
  596. {
  597. if (!PyList_Check(a)) {
  598. PyErr_BadInternalCall();
  599. return -1;
  600. }
  601. return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
  602. }
  603. static PyObject *
  604. list_inplace_repeat(PyListObject *self, Py_ssize_t n)
  605. {
  606. PyObject **items;
  607. Py_ssize_t size, i, j, p;
  608. size = PyList_GET_SIZE(self);
  609. if (size == 0) {
  610. Py_INCREF(self);
  611. return (PyObject *)self;
  612. }
  613. if (n < 1) {
  614. (void)list_clear(self);
  615. Py_INCREF(self);
  616. return (PyObject *)self;
  617. }
  618. if (list_resize(self, size*n) == -1)
  619. return NULL;
  620. p = size;
  621. items = self->ob_item;
  622. for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
  623. for (j = 0; j < size; j++) {
  624. PyObject *o = items[j];
  625. Py_INCREF(o);
  626. items[p++] = o;
  627. }
  628. }
  629. Py_INCREF(self);
  630. return (PyObject *)self;
  631. }
  632. static int
  633. list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v)
  634. {
  635. PyObject *old_value;
  636. if (i < 0 || i >= a->ob_size) {
  637. PyErr_SetString(PyExc_IndexError,
  638. "list assignment index out of range");
  639. return -1;
  640. }
  641. if (v == NULL)
  642. return list_ass_slice(a, i, i+1, v);
  643. Py_INCREF(v);
  644. old_value = a->ob_item[i];
  645. a->ob_item[i] = v;
  646. Py_DECREF(old_value);
  647. return 0;
  648. }
  649. static PyObject *
  650. listinsert(PyListObject *self, PyObject *args)
  651. {
  652. Py_ssize_t i;
  653. PyObject *v;
  654. if (!PyArg_ParseTuple(args, "nO:insert", &i, &v))
  655. return NULL;
  656. if (ins1(self, i, v) == 0)
  657. Py_RETURN_NONE;
  658. return NULL;
  659. }
  660. static PyObject *
  661. listappend(PyListObject *self, PyObject *v)
  662. {
  663. if (app1(self, v) == 0)
  664. Py_RETURN_NONE;
  665. return NULL;
  666. }
  667. static PyObject *
  668. listextend(PyListObject *self, PyObject *b)
  669. {
  670. PyObject *it; /* iter(v) */
  671. Py_ssize_t m; /* size of self */
  672. Py_ssize_t n; /* guess for size of b */
  673. Py_ssize_t mn; /* m + n */
  674. Py_ssize_t i;
  675. PyObject *(*iternext)(PyObject *);
  676. /* Special cases:
  677. 1) lists and tuples which can use PySequence_Fast ops
  678. 2) extending self to self requires making a copy first
  679. */
  680. if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
  681. PyObject **src, **dest;
  682. b = PySequence_Fast(b, "argument must be iterable");
  683. if (!b)
  684. return NULL;
  685. n = PySequence_Fast_GET_SIZE(b);
  686. if (n == 0) {
  687. /* short circuit when b is empty */
  688. Py_DECREF(b);
  689. Py_RETURN_NONE;
  690. }
  691. m = self->ob_size;
  692. if (list_resize(self, m + n) == -1) {
  693. Py_DECREF(b);
  694. return NULL;
  695. }
  696. /* note that we may still have self == b here for the
  697. * situation a.extend(a), but the following code works
  698. * in that case too. Just make sure to resize self
  699. * before calling PySequence_Fast_ITEMS.
  700. */
  701. /* populate the end of self with b's items */
  702. src = PySequence_Fast_ITEMS(b);
  703. dest = self->ob_item + m;
  704. for (i = 0; i < n; i++) {
  705. PyObject *o = src[i];
  706. Py_INCREF(o);
  707. dest[i] = o;
  708. }
  709. Py_DECREF(b);
  710. Py_RETURN_NONE;
  711. }
  712. it = PyObject_GetIter(b);
  713. if (it == NULL)
  714. return NULL;
  715. iternext = *it->ob_type->tp_iternext;
  716. /* Guess a result list size. */
  717. n = _PyObject_LengthHint(b);
  718. if (n < 0) {
  719. if (!PyErr_ExceptionMatches(PyExc_TypeError) &&
  720. !PyErr_ExceptionMatches(PyExc_AttributeError)) {
  721. Py_DECREF(it);
  722. return NULL;
  723. }
  724. PyErr_Clear();
  725. n = 8; /* arbitrary */
  726. }
  727. m = self->ob_size;
  728. mn = m + n;
  729. if (mn >= m) {
  730. /* Make room. */
  731. if (list_resize(self, mn) == -1)
  732. goto error;
  733. /* Make the list sane again. */
  734. self->ob_size = m;
  735. }
  736. /* Else m + n overflowed; on the chance that n lied, and there really
  737. * is enough room, ignore it. If n was telling the truth, we'll
  738. * eventually run out of memory during the loop.
  739. */
  740. /* Run iterator to exhaustion. */
  741. for (;;) {
  742. PyObject *item = iternext(it);
  743. if (item == NULL) {
  744. if (PyErr_Occurred()) {
  745. if (PyErr_ExceptionMatches(PyExc_StopIteration))
  746. PyErr_Clear();
  747. else
  748. goto error;
  749. }
  750. break;
  751. }
  752. if (self->ob_size < self->allocated) {
  753. /* steals ref */
  754. PyList_SET_ITEM(self, self->ob_size, item);
  755. ++self->ob_size;
  756. }
  757. else {
  758. int status = app1(self, item);
  759. Py_DECREF(item); /* append creates a new ref */
  760. if (status < 0)
  761. goto error;
  762. }
  763. }
  764. /* Cut back result list if initial guess was too large. */
  765. if (self->ob_size < self->allocated)
  766. list_resize(self, self->ob_size); /* shrinking can't fail */
  767. Py_DECREF(it);
  768. Py_RETURN_NONE;
  769. error:
  770. Py_DECREF(it);
  771. return NULL;
  772. }
  773. PyObject *
  774. _PyList_Extend(PyListObject *self, PyObject *b)
  775. {
  776. return listextend(self, b);
  777. }
  778. static PyObject *
  779. list_inplace_concat(PyListObject *self, PyObject *other)
  780. {
  781. PyObject *result;
  782. result = listextend(self, other);
  783. if (result == NULL)
  784. return result;
  785. Py_DECREF(result);
  786. Py_INCREF(self);
  787. return (PyObject *)self;
  788. }
  789. static PyObject *
  790. listpop(PyListObject *self, PyObject *args)
  791. {
  792. Py_ssize_t i = -1;
  793. PyObject *v;
  794. int status;
  795. if (!PyArg_ParseTuple(args, "|n:pop", &i))
  796. return NULL;
  797. if (self->ob_size == 0) {
  798. /* Special-case most common failure cause */
  799. PyErr_SetString(PyExc_IndexError, "pop from empty list");
  800. return NULL;
  801. }
  802. if (i < 0)
  803. i += self->ob_size;
  804. if (i < 0 || i >= self->ob_size) {
  805. PyErr_SetString(PyExc_IndexError, "pop index out of range");
  806. return NULL;
  807. }
  808. v = self->ob_item[i];
  809. if (i == self->ob_size - 1) {
  810. status = list_resize(self, self->ob_size - 1);
  811. assert(status >= 0);
  812. return v; /* and v now owns the reference the list had */
  813. }
  814. Py_INCREF(v);
  815. status = list_ass_slice(self, i, i+1, (PyObject *)NULL);
  816. assert(status >= 0);
  817. /* Use status, so that in a release build compilers don't
  818. * complain about the unused name.
  819. */
  820. (void) status;
  821. return v;
  822. }
  823. /* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
  824. static void
  825. reverse_slice(PyObject **lo, PyObject **hi)
  826. {
  827. assert(lo && hi);
  828. --hi;
  829. while (lo < hi) {
  830. PyObject *t = *lo;
  831. *lo = *hi;
  832. *hi = t;
  833. ++lo;
  834. --hi;
  835. }
  836. }
  837. /* Lots of code for an adaptive, stable, natural mergesort. There are many
  838. * pieces to this algorithm; read listsort.txt for overviews and details.
  839. */
  840. /* Comparison function. Takes care of calling a user-supplied
  841. * comparison function (any callable Python object), which must not be
  842. * NULL (use the ISLT macro if you don't know, or call PyObject_RichCompareBool
  843. * with Py_LT if you know it's NULL).
  844. * Returns -1 on error, 1 if x < y, 0 if x >= y.
  845. */
  846. static int
  847. islt(PyObject *x, PyObject *y, PyObject *compare)
  848. {
  849. PyObject *res;
  850. PyObject *args;
  851. Py_ssize_t i;
  852. assert(compare != NULL);
  853. /* Call the user's comparison function and translate the 3-way
  854. * result into true or false (or error).
  855. */
  856. args = PyTuple_New(2);
  857. if (args == NULL)
  858. return -1;
  859. Py_INCREF(x);
  860. Py_INCREF(y);
  861. PyTuple_SET_ITEM(args, 0, x);
  862. PyTuple_SET_ITEM(args, 1, y);
  863. res = PyObject_Call(compare, args, NULL);
  864. Py_DECREF(args);
  865. if (res == NULL)
  866. return -1;
  867. if (!PyInt_Check(res)) {
  868. Py_DECREF(res);
  869. PyErr_SetString(PyExc_TypeError,
  870. "comparison function must return int");
  871. return -1;
  872. }
  873. i = PyInt_AsLong(res);
  874. Py_DECREF(res);
  875. return i < 0;
  876. }
  877. /* If COMPARE is NULL, calls PyObject_RichCompareBool with Py_LT, else calls
  878. * islt. This avoids a layer of function call in the usual case, and
  879. * sorting does many comparisons.
  880. * Returns -1 on error, 1 if x < y, 0 if x >= y.
  881. */
  882. #define ISLT(X, Y, COMPARE) ((COMPARE) == NULL ? \
  883. PyObject_RichCompareBool(X, Y, Py_LT) : \
  884. islt(X, Y, COMPARE))
  885. /* Compare X to Y via "<". Goto "fail" if the comparison raises an
  886. error. Else "k" is set to true iff X<Y, and an "if (k)" block is
  887. started. It makes more sense in context <wink>. X and Y are PyObject*s.
  888. */
  889. #define IFLT(X, Y) if ((k = ISLT(X, Y, compare)) < 0) goto fail; \
  890. if (k)
  891. /* binarysort is the best method for sorting small arrays: it does
  892. few compares, but can do data movement quadratic in the number of
  893. elements.
  894. [lo, hi) is a contiguous slice of a list, and is sorted via
  895. binary insertion. This sort is stable.
  896. On entry, must have lo <= start <= hi, and that [lo, start) is already
  897. sorted (pass start == lo if you don't know!).
  898. If islt() complains return -1, else 0.
  899. Even in case of error, the output slice will be some permutation of
  900. the input (nothing is lost or duplicated).
  901. */
  902. static int
  903. binarysort(PyObject **lo, PyObject **hi, PyObject **start, PyObject *compare)
  904. /* compare -- comparison function object, or NULL for default */
  905. {
  906. register Py_ssize_t k;
  907. register PyObject **l, **p, **r;
  908. register PyObject *pivot;
  909. assert(lo <= start && start <= hi);
  910. /* assert [lo, start) is sorted */
  911. if (lo == start)
  912. ++start;
  913. for (; start < hi; ++start) {
  914. /* set l to where *start belongs */
  915. l = lo;
  916. r = start;
  917. pivot = *r;
  918. /* Invariants:
  919. * pivot >= all in [lo, l).
  920. * pivot < all in [r, start).
  921. * The second is vacuously true at the start.
  922. */
  923. assert(l < r);
  924. do {
  925. p = l + ((r - l) >> 1);
  926. IFLT(pivot, *p)
  927. r = p;
  928. else
  929. l = p+1;
  930. } while (l < r);
  931. assert(l == r);
  932. /* The invariants still hold, so pivot >= all in [lo, l) and
  933. pivot < all in [l, start), so pivot belongs at l. Note
  934. that if there are elements equal to pivot, l points to the
  935. first slot after them -- that's why this sort is stable.
  936. Slide over to make room.
  937. Caution: using memmove is much slower under MSVC 5;
  938. we're not usually moving many slots. */
  939. for (p = start; p > l; --p)
  940. *p = *(p-1);
  941. *l = pivot;
  942. }
  943. return 0;
  944. fail:
  945. return -1;
  946. }
  947. /*
  948. Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
  949. is required on entry. "A run" is the longest ascending sequence, with
  950. lo[0] <= lo[1] <= lo[2] <= ...
  951. or the longest descending sequence, with
  952. lo[0] > lo[1] > lo[2] > ...
  953. Boolean *descending is set to 0 in the former case, or to 1 in the latter.
  954. For its intended use in a stable mergesort, the strictness of the defn of
  955. "descending" is needed so that the caller can safely reverse a descending
  956. sequence without violating stability (strict > ensures there are no equal
  957. elements to get out of order).
  958. Returns -1 in case of error.
  959. */
  960. static Py_ssize_t
  961. count_run(PyObject **lo, PyObject **hi, PyObject *compare, int *descending)
  962. {
  963. Py_ssize_t k;
  964. Py_ssize_t n;
  965. assert(lo < hi);
  966. *descending = 0;
  967. ++lo;
  968. if (lo == hi)
  969. return 1;
  970. n = 2;
  971. IFLT(*lo, *(lo-1)) {
  972. *descending = 1;
  973. for (lo = lo+1; lo < hi; ++lo, ++n) {
  974. IFLT(*lo, *(lo-1))
  975. ;
  976. else
  977. break;
  978. }
  979. }
  980. else {
  981. for (lo = lo+1; lo < hi; ++lo, ++n) {
  982. IFLT(*lo, *(lo-1))
  983. break;
  984. }
  985. }
  986. return n;
  987. fail:
  988. return -1;
  989. }
  990. /*
  991. Locate the proper position of key in a sorted vector; if the vector contains
  992. an element equal to key, return the position immediately to the left of
  993. the leftmost equal element. [gallop_right() does the same except returns
  994. the position to the right of the rightmost equal element (if any).]
  995. "a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
  996. "hint" is an index at which to begin the search, 0 <= hint < n. The closer
  997. hint is to the final result, the faster this runs.
  998. The return value is the int k in 0..n such that
  999. a[k-1] < key <= a[k]
  1000. pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
  1001. key belongs at index k; or, IOW, the first k elements of a should precede
  1002. key, and the last n-k should follow key.
  1003. Returns -1 on error. See listsort.txt for info on the method.
  1004. */
  1005. static Py_ssize_t
  1006. gallop_left(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint, PyObject *compare)
  1007. {
  1008. Py_ssize_t ofs;
  1009. Py_ssize_t lastofs;
  1010. Py_ssize_t k;
  1011. assert(key && a && n > 0 && hint >= 0 && hint < n);
  1012. a += hint;
  1013. lastofs = 0;
  1014. ofs = 1;
  1015. IFLT(*a, key) {
  1016. /* a[hint] < key -- gallop right, until
  1017. * a[hint + lastofs] < key <= a[hint + ofs]
  1018. */
  1019. const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
  1020. while (ofs < maxofs) {
  1021. IFLT(a[ofs], key) {
  1022. lastofs = ofs;
  1023. ofs = (ofs << 1) + 1;
  1024. if (ofs <= 0) /* int overflow */
  1025. ofs = maxofs;
  1026. }
  1027. else /* key <= a[hint + ofs] */
  1028. break;
  1029. }
  1030. if (ofs > maxofs)
  1031. ofs = maxofs;
  1032. /* Translate back to offsets relative to &a[0]. */
  1033. lastofs += hint;
  1034. ofs += hint;
  1035. }
  1036. else {
  1037. /* key <= a[hint] -- gallop left, until
  1038. * a[hint - ofs] < key <= a[hint - lastofs]
  1039. */
  1040. const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
  1041. while (ofs < maxofs) {
  1042. IFLT(*(a-ofs), key)
  1043. break;
  1044. /* key <= a[hint - ofs] */
  1045. lastofs = ofs;
  1046. ofs = (ofs << 1) + 1;
  1047. if (ofs <= 0) /* int overflow */
  1048. ofs = maxofs;
  1049. }
  1050. if (ofs > maxofs)
  1051. ofs = maxofs;
  1052. /* Translate back to positive offsets relative to &a[0]. */
  1053. k = lastofs;
  1054. lastofs = hint - ofs;
  1055. ofs = hint - k;
  1056. }
  1057. a -= hint;
  1058. assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
  1059. /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
  1060. * right of lastofs but no farther right than ofs. Do a binary
  1061. * search, with invariant a[lastofs-1] < key <= a[ofs].
  1062. */
  1063. ++lastofs;
  1064. while (lastofs < ofs) {
  1065. Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
  1066. IFLT(a[m], key)
  1067. lastofs = m+1; /* a[m] < key */
  1068. else
  1069. ofs = m; /* key <= a[m] */
  1070. }
  1071. assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
  1072. return ofs;
  1073. fail:
  1074. return -1;
  1075. }
  1076. /*
  1077. Exactly like gallop_left(), except that if key already exists in a[0:n],
  1078. finds the position immediately to the right of the rightmost equal value.
  1079. The return value is the int k in 0..n such that
  1080. a[k-1] <= key < a[k]
  1081. or -1 if error.
  1082. The code duplication is massive, but this is enough different given that
  1083. we're sticking to "<" comparisons that it's much harder to follow if
  1084. written as one routine with yet another "left or right?" flag.
  1085. */
  1086. static Py_ssize_t
  1087. gallop_right(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint, PyObject *compare)
  1088. {
  1089. Py_ssize_t ofs;
  1090. Py_ssize_t lastofs;
  1091. Py_ssize_t k;
  1092. assert(key && a && n > 0 && hint >= 0 && hint < n);
  1093. a += hint;
  1094. lastofs = 0;
  1095. ofs = 1;
  1096. IFLT(key, *a) {
  1097. /* key < a[hint] -- gallop left, until
  1098. * a[hint - ofs] <= key < a[hint - lastofs]
  1099. */
  1100. const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
  1101. while (ofs < maxofs) {
  1102. IFLT(key, *(a-ofs)) {
  1103. lastofs = ofs;
  1104. ofs = (ofs << 1) + 1;
  1105. if (ofs <= 0) /* int overflow */
  1106. ofs = maxofs;
  1107. }
  1108. else /* a[hint - ofs] <= key */
  1109. break;
  1110. }
  1111. if (ofs > maxofs)
  1112. ofs = maxofs;
  1113. /* Translate back to positive offsets relative to &a[0]. */
  1114. k = lastofs;
  1115. lastofs = hint - ofs;
  1116. ofs = hint - k;
  1117. }
  1118. else {
  1119. /* a[hint] <= key -- gallop right, until
  1120. * a[hint + lastofs] <= key < a[hint + ofs]
  1121. */
  1122. const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
  1123. while (ofs < maxofs) {
  1124. IFLT(key, a[ofs])
  1125. break;
  1126. /* a[hint + ofs] <= key */
  1127. lastofs = ofs;
  1128. ofs = (ofs << 1) + 1;
  1129. if (ofs <= 0) /* int overflow */
  1130. ofs = maxofs;
  1131. }
  1132. if (ofs > maxofs)
  1133. ofs = maxofs;
  1134. /* Translate back to offsets relative to &a[0]. */
  1135. lastofs += hint;
  1136. ofs += hint;
  1137. }
  1138. a -= hint;
  1139. assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
  1140. /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
  1141. * right of lastofs but no farther right than ofs. Do a binary
  1142. * search, with invariant a[lastofs-1] <= key < a[ofs].
  1143. */
  1144. ++lastofs;
  1145. while (lastofs < ofs) {
  1146. Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
  1147. IFLT(key, a[m])
  1148. ofs = m; /* key < a[m] */
  1149. else
  1150. lastofs = m+1; /* a[m] <= key */
  1151. }
  1152. assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
  1153. return ofs;
  1154. fail:
  1155. return -1;
  1156. }
  1157. /* The maximum number of entries in a MergeState's pending-runs stack.
  1158. * This is enough to sort arrays of size up to about
  1159. * 32 * phi ** MAX_MERGE_PENDING
  1160. * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
  1161. * with 2**64 elements.
  1162. */
  1163. #define MAX_MERGE_PENDING 85
  1164. /* When we get into galloping mode, we stay there until both runs win less
  1165. * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
  1166. */
  1167. #define MIN_GALLOP 7
  1168. /* Avoid malloc for small temp arrays. */
  1169. #define MERGESTATE_TEMP_SIZE 256
  1170. /* One MergeState exists on the stack per invocation of mergesort. It's just
  1171. * a convenient way to pass state around among the helper functions.
  1172. */
  1173. struct s_slice {
  1174. PyObject **base;
  1175. Py_ssize_t len;
  1176. };
  1177. typedef struct s_MergeState {
  1178. /* The user-supplied comparison function. or NULL if none given. */
  1179. PyObject *compare;
  1180. /* This controls when we get *into* galloping mode. It's initialized
  1181. * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
  1182. * random data, and lower for highly structured data.
  1183. */
  1184. Py_ssize_t min_gallop;
  1185. /* 'a' is temp storage to help with merges. It contains room for
  1186. * alloced entries.
  1187. */
  1188. PyObject **a; /* may point to temparray below */
  1189. Py_ssize_t alloced;
  1190. /* A stack of n pending runs yet to be merged. Run #i starts at
  1191. * address base[i] and extends for len[i] elements. It's always
  1192. * true (so long as the indices are in bounds) that
  1193. *
  1194. * pending[i].base + pending[i].len == pending[i+1].base
  1195. *
  1196. * so we could cut the storage for this, but it's a minor amount,
  1197. * and keeping all the info explicit simplifies the code.
  1198. */
  1199. int n;
  1200. struct s_slice pending[MAX_MERGE_PENDING];
  1201. /* 'a' points to this when possible, rather than muck with malloc. */
  1202. PyObject *temparray[MERGESTATE_TEMP_SIZE];
  1203. } MergeState;
  1204. /* Conceptually a MergeState's constructor. */
  1205. static void
  1206. merge_init(MergeState *ms, PyObject *compare)
  1207. {
  1208. assert(ms != NULL);
  1209. ms->compare = compare;
  1210. ms->a = ms->temparray;
  1211. ms->alloced = MERGESTATE_TEMP_SIZE;
  1212. ms->n = 0;
  1213. ms->min_gallop = MIN_GALLOP;
  1214. }
  1215. /* Free all the temp memory owned by the MergeState. This must be called
  1216. * when you're done with a MergeState, and may be called before then if
  1217. * you want to free the temp memory early.
  1218. */
  1219. static void
  1220. merge_freemem(MergeState *ms)
  1221. {
  1222. assert(ms != NULL);
  1223. if (ms->a != ms->temparray)
  1224. PyMem_Free(ms->a);
  1225. ms->a = ms->temparray;
  1226. ms->alloced = MERGESTATE_TEMP_SIZE;
  1227. }
  1228. /* Ensure enough temp memory for 'need' array slots is available.
  1229. * Returns 0 on success and -1 if the memory can't be gotten.
  1230. */
  1231. static int
  1232. merge_getmem(MergeState *ms, Py_ssize_t need)
  1233. {
  1234. assert(ms != NULL);
  1235. if (need <= ms->alloced)
  1236. return 0;
  1237. /* Don't realloc! That can cost cycles to copy the old data, but
  1238. * we don't care what's in the block.
  1239. */
  1240. merge_freemem(ms);
  1241. ms->a = (PyObject **)PyMem_Malloc(need * sizeof(PyObject*));
  1242. if (ms->a) {
  1243. ms->alloced = need;
  1244. return 0;
  1245. }
  1246. PyErr_NoMemory();
  1247. merge_freemem(ms); /* reset to sane state */
  1248. return -1;
  1249. }
  1250. #define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
  1251. merge_getmem(MS, NEED))
  1252. /* Merge the na elements starting at pa with the nb elements starting at pb
  1253. * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
  1254. * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
  1255. * merge, and should have na <= nb. See listsort.txt for more info.
  1256. * Return 0 if successful, -1 if error.
  1257. */
  1258. static Py_ssize_t
  1259. merge_lo(MergeState *ms, PyObject **pa, Py_ssize_t na,
  1260. PyObject **pb, Py_ssize_t nb)
  1261. {
  1262. Py_ssize_t k;
  1263. PyObject *compare;
  1264. PyObject **dest;
  1265. int result = -1; /* guilty until proved innocent */
  1266. Py_ssize_t min_gallop = ms->min_gallop;
  1267. assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
  1268. if (MERGE_GETMEM(ms, na) < 0)
  1269. return -1;
  1270. memcpy(ms->a, pa, na * sizeof(PyObject*));
  1271. dest = pa;
  1272. pa = ms->a;
  1273. *dest++ = *pb++;
  1274. --nb;
  1275. if (nb == 0)
  1276. goto Succeed;
  1277. if (na == 1)
  1278. goto CopyB;
  1279. compare = ms->compare;
  1280. for (;;) {
  1281. Py_ssize_t acount = 0; /* # of times A won in a row */
  1282. Py_ssize_t bcount = 0; /* # of times B won in a row */
  1283. /* Do the straightforward thing until (if ever) one run
  1284. * appears to win consistently.
  1285. */
  1286. for (;;) {
  1287. assert(na > 1 && nb > 0);
  1288. k = ISLT(*pb, *pa, compare);
  1289. if (k) {
  1290. if (k < 0)
  1291. goto Fail;
  1292. *dest++ = *pb++;
  1293. ++bcount;
  1294. acount = 0;
  1295. --nb;
  1296. if (nb == 0)
  1297. goto Succeed;
  1298. if (bcount >= min_gallop)
  1299. break;
  1300. }
  1301. else {
  1302. *dest++ = *pa++;
  1303. ++acount;
  1304. bcount = 0;
  1305. --na;
  1306. if (na == 1)
  1307. goto CopyB;
  1308. if (acount >= min_gallop)
  1309. break;
  1310. }
  1311. }
  1312. /* One run is winning so consistently that galloping may
  1313. * be a huge win. So try that, and continue galloping until
  1314. * (if ever) neither run appears to be winning consistently
  1315. * anymore.
  1316. */
  1317. ++min_gallop;
  1318. do {
  1319. assert(na > 1 && nb > 0);
  1320. min_gallop -= min_gallop > 1;
  1321. ms->min_gallop = min_gallop;
  1322. k = gallop_right(*pb, pa, na, 0, compare);
  1323. acount = k;
  1324. if (k) {
  1325. if (k < 0)
  1326. goto Fail;
  1327. memcpy(dest, pa, k * sizeof(PyObject *));
  1328. dest += k;
  1329. pa += k;
  1330. na -= k;
  1331. if (na == 1)
  1332. goto CopyB;
  1333. /* na==0 is impossible now if the comparison
  1334. * function is consistent, but we can't assume
  1335. * that it is.
  1336. */
  1337. if (na == 0)
  1338. goto Succeed;
  1339. }
  1340. *dest++ = *pb++;
  1341. --nb;
  1342. if (nb == 0)
  1343. goto Succeed;
  1344. k = gallop_left(*pa, pb, nb, 0, compare);
  1345. bcount = k;
  1346. if (k) {
  1347. if (k < 0)
  1348. goto Fail;
  1349. memmove(dest, pb, k * sizeof(PyObject *));
  1350. dest += k;
  1351. pb += k;
  1352. nb -= k;
  1353. if (nb == 0)
  1354. goto Succeed;
  1355. }
  1356. *dest++ = *pa++;
  1357. --na;
  1358. if (na == 1)
  1359. goto CopyB;
  1360. } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
  1361. ++min_gallop; /* penalize it for leaving galloping mode */
  1362. ms->min_gallop = min_gallop;
  1363. }
  1364. Succeed:
  1365. result = 0;
  1366. Fail:
  1367. if (na)
  1368. memcpy(dest, pa, na * sizeof(PyObject*));
  1369. return result;
  1370. CopyB:
  1371. assert(na == 1 && nb > 0);
  1372. /* The last element of pa belongs at the end of the merge. */
  1373. memmove(dest, pb, nb * sizeof(PyObject *));
  1374. dest[nb] = *pa;
  1375. return 0;
  1376. }
  1377. /* Merge the na elements starting at pa with the nb elements starting at pb
  1378. * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
  1379. * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
  1380. * merge, and should have na >= nb. See listsort.txt for more info.
  1381. * Return 0 if successful, -1 if error.
  1382. */
  1383. static Py_ssize_t
  1384. merge_hi(MergeState *ms, PyObject **pa, Py_ssize_t na, PyObject **pb, Py_ssize_t nb)
  1385. {
  1386. Py_ssize_t k;
  1387. PyObject *compare;
  1388. PyObject **dest;
  1389. int result = -1; /* guilty until proved innocent */
  1390. PyObject **basea;
  1391. PyObject **baseb;
  1392. Py_ssize_t min_gallop = ms->min_gallop;
  1393. assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
  1394. if (MERGE_GETMEM(ms, nb) < 0)
  1395. return -1;
  1396. dest = pb + nb - 1;
  1397. memcpy(ms->a, pb, nb * sizeof(PyObject*));
  1398. basea = pa;
  1399. baseb = ms->a;
  1400. pb = ms->a + nb - 1;
  1401. pa += na - 1;
  1402. *dest-- = *pa--;
  1403. --na;
  1404. if (na == 0)
  1405. goto Succeed;
  1406. if (nb == 1)
  1407. goto CopyA;
  1408. compare = ms->compare;
  1409. for (;;) {
  1410. Py_ssize_t acount = 0; /* # of times A won in a row */
  1411. Py_ssize_t bcount = 0; /* # of times B won in a row */
  1412. /* Do the straightforward thing until (if ever) one run
  1413. * appears to win consistently.
  1414. */
  1415. for (;;) {
  1416. assert(na > 0 && nb > 1);
  1417. k = ISLT(*pb, *pa, compare);
  1418. if (k) {
  1419. if (k < 0)
  1420. goto Fail;
  1421. *dest-- = *pa--;
  1422. ++acount;
  1423. bcount = 0;
  1424. --na;
  1425. if (na == 0)
  1426. goto Succeed;
  1427. if (acount >= min_gallop)
  1428. break;
  1429. }
  1430. else {
  1431. *dest-- = *pb--;
  1432. ++bcount;
  1433. acount = 0;
  1434. --nb;
  1435. if (nb == 1)
  1436. goto CopyA;
  1437. if (bcount >= min_gallop)
  1438. break;
  1439. }
  1440. }
  1441. /* One run is winning so consistently that galloping may
  1442. * be a huge win. So try that, and continue galloping until
  1443. * (if ever) neither run appears to be winning consistently
  1444. * anymore.
  1445. */
  1446. ++min_gallop;
  1447. do {
  1448. assert(na > 0 && nb > 1);
  1449. min_gallop -= min_gallop > 1;
  1450. ms->min_gallop = min_gallop;
  1451. k = gallop_right(*pb, basea, na, na-1, compare);
  1452. if (k < 0)
  1453. goto Fail;
  1454. k = na - k;
  1455. acount = k;
  1456. if (k) {
  1457. dest -= k;
  1458. pa -= k;
  1459. memmove(dest+1, pa+1, k * sizeof(PyObject *));
  1460. na -= k;
  1461. if (na == 0)
  1462. goto Succeed;
  1463. }
  1464. *dest-- = *pb--;
  1465. --nb;
  1466. if (nb == 1)
  1467. goto CopyA;
  1468. k = gallop_left(*pa, baseb, nb, nb-1, compare);
  1469. if (k < 0)
  1470. goto Fail;
  1471. k = nb - k;
  1472. bcount = k;
  1473. if (k) {
  1474. dest -= k;
  1475. pb -= k;
  1476. memcpy(dest+1, pb+1, k * sizeof(PyObject *));
  1477. nb -= k;
  1478. if (nb == 1)
  1479. goto CopyA;
  1480. /* nb==0 is impossible now if the comparison
  1481. * function is consistent, but we can't assume
  1482. * that it is.
  1483. */
  1484. if (nb == 0)
  1485. goto Succeed;
  1486. }
  1487. *dest-- = *pa--;
  1488. --na;
  1489. if (na == 0)
  1490. goto Succeed;
  1491. } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
  1492. ++min_gallop; /* penalize it for leaving galloping mode */
  1493. ms->min_gallop = min_gallop;
  1494. }
  1495. Succeed:
  1496. result = 0;
  1497. Fail:
  1498. if (nb)
  1499. memcpy(dest-(nb-1), baseb, nb * sizeof(PyObject*));
  1500. return result;
  1501. CopyA:
  1502. assert(nb == 1 && na > 0);
  1503. /* The first element of pb belongs at the front of the merge. */
  1504. dest -= na;
  1505. pa -= na;
  1506. memmove(dest+1, pa+1, na * sizeof(PyObject *));
  1507. *dest = *pb;
  1508. return 0;
  1509. }
  1510. /* Merge the two runs at stack indices i and i+1.
  1511. * Returns 0 on success, -1 on error.
  1512. */
  1513. static Py_ssize_t
  1514. merge_at(MergeState *ms, Py_ssize_t i)
  1515. {
  1516. PyObject **pa, **pb;
  1517. Py_ssize_t na, nb;
  1518. Py_ssize_t k;
  1519. PyObject *compare;
  1520. assert(ms != NULL);
  1521. assert(ms->n >= 2);
  1522. assert(i >= 0);
  1523. assert(i == ms->n - 2 || i == ms->n - 3);
  1524. pa = ms->pending[i].base;
  1525. na = ms->pending[i].len;
  1526. pb = ms->pending[i+1].base;
  1527. nb = ms->pending[i+1].len;
  1528. assert(na > 0 && nb > 0);
  1529. assert(pa + na == pb);
  1530. /* Record the length of the combined runs; if i is the 3rd-last
  1531. * run now, also slide over the last run (which isn't involved
  1532. * in this merge). The current run i+1 goes away in any case.
  1533. */
  1534. ms->pending[i].len = na + nb;
  1535. if (i == ms->n - 3)
  1536. ms->pending[i+1] = ms->pending[i+2];
  1537. --ms->n;
  1538. /* Where does b start in a? Elements in a before that can be
  1539. * ignored (already in place).
  1540. */
  1541. compare = ms->compare;
  1542. k = gallop_right(*pb, pa, na, 0, compare);
  1543. if (k < 0)
  1544. return -1;
  1545. pa += k;
  1546. na -= k;
  1547. if (na == 0)
  1548. return 0;
  1549. /* Where does a end in b? Elements in b after that can be
  1550. * ignored (already in place).
  1551. */
  1552. nb = gallop_left(pa[na-1], pb, nb, nb-1, compare);
  1553. if (nb <= 0)
  1554. return nb;
  1555. /* Merge what remains of the runs, using a temp array with
  1556. * min(na, nb) elements.
  1557. */
  1558. if (na <= nb)
  1559. return merge_lo(ms, pa, na, pb, nb);
  1560. else
  1561. return merge_hi(ms, pa, na, pb, nb);
  1562. }
  1563. /* Examine the stack of runs waiting to be merged, merging adjacent runs
  1564. * until the stack invariants are re-established:
  1565. *
  1566. * 1. len[-3] > len[-2] + len[-1]
  1567. * 2. len[-2] > len[-1]
  1568. *
  1569. * See listsort.txt for more info.
  1570. *
  1571. * Returns 0 on success, -1 on error.
  1572. */
  1573. static int
  1574. merge_collapse(MergeState *ms)
  1575. {
  1576. struct s_slice *p = ms->pending;
  1577. assert(ms);
  1578. while (ms->n > 1) {
  1579. Py_ssize_t n = ms->n - 2;
  1580. if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) {
  1581. if (p[n-1].len < p[n+1].len)
  1582. --n;
  1583. if (merge_at(ms, n) < 0)
  1584. return -1;
  1585. }
  1586. else if (p[n].len <= p[n+1].len) {
  1587. if (merge_at(ms, n) < 0)
  1588. return -1;
  1589. }
  1590. else
  1591. break;
  1592. }
  1593. return 0;
  1594. }
  1595. /* Regardless of invariants, merge all runs on the stack until only one
  1596. * remains. This is used at the end of the mergesort.
  1597. *
  1598. * Returns 0 on success, -1 on error.
  1599. */
  1600. static int
  1601. merge_force_collapse(MergeState *ms)
  1602. {
  1603. struct s_slice *p = ms->pending;
  1604. assert(ms);
  1605. while (ms->n > 1) {
  1606. Py_ssize_t n = ms->n - 2;
  1607. if (n > 0 && p[n-1].len < p[n+1].len)
  1608. --n;
  1609. if (merge_at(ms, n) < 0)
  1610. return -1;
  1611. }
  1612. return 0;
  1613. }
  1614. /* Compute a good value for the minimum run length; natural runs shorter
  1615. * than this are boosted artificially via binary insertion.
  1616. *
  1617. * If n < 64, return n (it's too small to bother with fancy stuff).
  1618. * Else if n is an exact power of 2, return 32.
  1619. * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
  1620. * strictly less than, an exact power of 2.
  1621. *
  1622. * See listsort.txt for more info.
  1623. */
  1624. static Py_ssize_t
  1625. merge_compute_minrun(Py_ssize_t n)
  1626. {
  1627. Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */
  1628. assert(n >= 0);
  1629. while (n >= 64) {
  1630. r |= n & 1;
  1631. n >>= 1;
  1632. }
  1633. return n + r;
  1634. }
  1635. /* Special wrapper to support stable sorting using the decorate-sort-undecorate
  1636. pattern. Holds a key which is used for comparisons and the original record
  1637. which is returned during the undecorate phase. By exposing only the key
  1638. during comparisons, the underlying sort stability characteristics are left
  1639. unchanged. Also, if a custom comparison function is used, it will only see
  1640. the key instead of a full record. */
  1641. typedef struct {
  1642. PyObject_HEAD
  1643. PyObject *key;
  1644. PyObject *value;
  1645. } sortwrapperobject;
  1646. PyDoc_STRVAR(sortwrapper_doc, "Object wrapper with a custom sort key.");
  1647. static PyObject *
  1648. sortwrapper_richcompare(sortwrapperobject *, sortwrapperobject *, int);
  1649. static void
  1650. sortwrapper_dealloc(sortwrapperobject *);
  1651. static PyTypeObject sortwrapper_type = {
  1652. PyObject_HEAD_INIT(&PyType_Type)
  1653. 0, /* ob_size */
  1654. "sortwrapper", /* tp_name */
  1655. sizeof(sortwrapperobject), /* tp_basicsize */
  1656. 0, /* tp_itemsize */
  1657. /* methods */
  1658. (destructor)sortwrapper_dealloc, /* tp_dealloc */
  1659. 0, /* tp_print */
  1660. 0, /* tp_getattr */
  1661. 0, /* tp_setattr */
  1662. 0, /* tp_compare */
  1663. 0, /* tp_repr */
  1664. 0, /* tp_as_number */
  1665. 0, /* tp_as_sequence */
  1666. 0, /* tp_as_mapping */
  1667. 0, /* tp_hash */
  1668. 0, /* tp_call */
  1669. 0, /* tp_str */
  1670. PyObject_GenericGetAttr, /* tp_getattro */
  1671. 0, /* tp_setattro */
  1672. 0, /* tp_as_buffer */
  1673. Py_TPFLAGS_DEFAULT |
  1674. Py_TPFLAGS_HAVE_RICHCOMPARE, /* tp_flags */
  1675. sortwrapper_doc, /* tp_doc */
  1676. 0, /* tp_traverse */
  1677. 0, /* tp_clear */
  1678. (richcmpfunc)sortwrapper_richcompare, /* tp_richcompare */
  1679. };
  1680. static PyObject *
  1681. sortwrapper_richcompare(sortwrapperobject *a, sortwrapperobject *b, int op)
  1682. {
  1683. if (!PyObject_TypeCheck(b, &sortwrapper_type)) {
  1684. PyErr_SetString(PyExc_TypeError,
  1685. "expected a sortwrapperobject");
  1686. return NULL;
  1687. }
  1688. return PyObject_RichCompare(a->key, b->key, op);
  1689. }
  1690. static void
  1691. sortwrapper_dealloc(sortwrapperobject *so)
  1692. {
  1693. Py_XDECREF(so->key);
  1694. Py_XDECREF(so->value);
  1695. PyObject_Del(so);
  1696. }
  1697. /* Returns a new reference to a sortwrapper.
  1698. Consumes the references to the two underlying objects. */
  1699. static PyObject *
  1700. build_sortwrapper(PyObject *key, PyObject *value)
  1701. {
  1702. sortwrapperobject *so;
  1703. so = PyObject_New(sortwrapperobject, &sortwrapper_type);
  1704. if (so == NULL)
  1705. return NULL;
  1706. so->key = key;
  1707. so->value = value;
  1708. return (PyObject *)so;
  1709. }
  1710. /* Returns a new reference to the value underlying the wrapper. */
  1711. static PyObject *
  1712. sortwrapper_getvalue(PyObject *so)
  1713. {
  1714. PyObject *value;
  1715. if (!PyObject_TypeCheck(so, &sortwrapper_type)) {
  1716. PyErr_SetString(PyExc_TypeError,
  1717. "expected a sortwrapperobject");
  1718. return NULL;
  1719. }
  1720. value = ((sortwrapperobject *)so)->value;
  1721. Py_INCREF(value);
  1722. return value;
  1723. }
  1724. /* Wrapper for user specified cmp functions in combination with a
  1725. specified key function. Makes sure the cmp function is presented
  1726. with the actual key instead of the sortwrapper */
  1727. typedef struct {
  1728. PyObject_HEAD
  1729. PyObject *func;
  1730. } cmpwrapperobject;
  1731. static void
  1732. cmpwrapper_dealloc(cmpwrapperobject *co)
  1733. {
  1734. Py_XDECREF(co->func);
  1735. PyObject_Del(co);
  1736. }
  1737. static PyObject *
  1738. cmpwrapper_call(cmpwrapperobject *co, PyObject *args, PyObject *kwds)
  1739. {
  1740. PyObject *x, *y, *xx, *yy;
  1741. if (!PyArg_UnpackTuple(args, "", 2, 2, &x, &y))
  1742. return NULL;
  1743. if (!PyObject_TypeCheck(x, &sortwrapper_type) ||
  1744. !PyObject_TypeCheck(y, &sortwrapper_type)) {
  1745. PyErr_SetString(PyExc_TypeError,
  1746. "expected a sortwrapperobject");
  1747. return NULL;
  1748. }
  1749. xx = ((sortwrapperobject *)x)->key;
  1750. yy = ((sortwrapperobject *)y)->key;
  1751. return PyObject_CallFunctionObjArgs(co->func, xx, yy, NULL);
  1752. }
  1753. PyDoc_STRVAR(cmpwrapper_doc, "cmp() wrapper for sort with custom keys.");
  1754. static PyTypeObject cmpwrapper_type = {
  1755. PyObject_HEAD_INIT(&PyType_Type)
  1756. 0, /* ob_size */
  1757. "cmpwrapper", /* tp_name */
  1758. sizeof(cmpwrapperobject), /* tp_basicsize */
  1759. 0, /* tp_itemsize */
  1760. /* methods */
  1761. (destructor)cmpwrapper_dealloc, /* tp_dealloc */
  1762. 0, /* tp_print */
  1763. 0, /* tp_getattr */
  1764. 0, /* tp_setattr */
  1765. 0, /* tp_compare */
  1766. 0, /* tp_repr */
  1767. 0, /* tp_as_number */
  1768. 0, /* tp_as_sequence */
  1769. 0, /* tp_as_mapping */
  1770. 0, /* tp_hash */
  1771. (ternaryfunc)cmpwrapper_call, /* tp_call */
  1772. 0, /* tp_str */
  1773. PyObject_GenericGetAttr, /* tp_getattro */
  1774. 0, /* tp_setattro */
  1775. 0, /* tp_as_buffer */
  1776. Py_TPFLAGS_DEFAULT, /* tp_flags */
  1777. cmpwrapper_doc, /* tp_doc */
  1778. };
  1779. static PyObject *
  1780. build_cmpwrapper(PyObject *cmpfunc)
  1781. {
  1782. cmpwrapperobject *co;
  1783. co = PyObject_New(cmpwrapperobject, &cmpwrapper_type);
  1784. if (co == NULL)
  1785. return NULL;
  1786. Py_INCREF(cmpfunc);
  1787. co->func = cmpfunc;
  1788. return (PyObject *)co;
  1789. }
  1790. /* An adaptive, stable, natural mergesort. See listsort.txt.
  1791. * Returns Py_None on success, NULL on error. Even in case of error, the
  1792. * list will be some permutation of its input state (nothing is lost or
  1793. * duplicated).
  1794. */
  1795. static PyObject *
  1796. listsort(PyListObject *self, PyObject *args, PyObject *kwds)
  1797. {
  1798. MergeState ms;
  1799. PyObject **lo, **hi;
  1800. Py_ssize_t nremaining;
  1801. Py_ssize_t minrun;
  1802. Py_ssize_t saved_ob_size, saved_allocated;
  1803. PyObject **saved_ob_item;
  1804. PyObject **final_ob_item;
  1805. PyObject *compare = NULL;
  1806. PyObject *result = NULL; /* guilty until proved innocent */
  1807. int reverse = 0;
  1808. PyObject *keyfunc = NULL;
  1809. Py_ssize_t i;
  1810. PyObject *key, *value, *kvpair;
  1811. static char *kwlist[] = {"cmp", "key", "reverse", 0};
  1812. assert(self != NULL);
  1813. assert (PyList_Check(self));
  1814. if (args != NULL) {
  1815. if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi:sort",
  1816. kwlist, &compare, &keyfunc, &reverse))
  1817. return NULL;
  1818. }
  1819. if (compare == Py_None)
  1820. compare = NULL;
  1821. if (keyfunc == Py_None)
  1822. keyfunc = NULL;
  1823. if (compare != NULL && keyfunc != NULL) {
  1824. compare = build_cmpwrapper(compare);
  1825. if (compare == NULL)
  1826. return NULL;
  1827. } else
  1828. Py_XINCREF(compare);
  1829. /* The list is temporarily made empty, so that mutations performed
  1830. * by comparison functions can't affect the slice of memory we're
  1831. * sorting (allowing mutations during sorting is a core-dump
  1832. * factory, since ob_item may change).
  1833. */
  1834. saved_ob_size = self->ob_size;
  1835. saved_ob_item = self->ob_item;
  1836. saved_allocated = self->allocated;
  1837. self->ob_size = 0;
  1838. self->ob_item = NULL;
  1839. self->allocated = -1; /* any operation will reset it to >= 0 */
  1840. if (keyfunc != NULL) {
  1841. for (i=0 ; i < saved_ob_size ; i++) {
  1842. value = saved_ob_item[i];
  1843. key = PyObject_CallFunctionObjArgs(keyfunc, value,
  1844. NULL);
  1845. if (key == NULL) {
  1846. for (i=i-1 ; i>=0 ; i--) {
  1847. kvpair = saved_ob_item[i];
  1848. value = sortwrapper_getvalue(kvpair);
  1849. saved_ob_item[i] = value;
  1850. Py_DECREF(kvpair);
  1851. }
  1852. goto dsu_fail;
  1853. }
  1854. kvpair = build_sortwrapper(key, value);
  1855. if (kvpair == NULL)
  1856. goto dsu_fail;
  1857. saved_ob_item[i] = kvpair;
  1858. }
  1859. }
  1860. /* Reverse sort stability achieved by initially reversing the list,
  1861. applying a stable forward sort, then reversing the final result. */
  1862. if (reverse && saved_ob_size > 1)
  1863. reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
  1864. merge_init(&ms, compare);
  1865. nremaining = saved_ob_size;
  1866. if (nremaining < 2)
  1867. goto succeed;
  1868. /* March over the array once, left to right, finding natural runs,
  1869. * and extending short natural runs to minrun elements.
  1870. */
  1871. lo = saved_ob_item;
  1872. hi = lo + nremaining;
  1873. minrun = merge_compute_minrun(nremaining);
  1874. do {
  1875. int descending;
  1876. Py_ssize_t n;
  1877. /* Identify next run. */
  1878. n = count_run(lo, hi, compare, &descending);
  1879. if (n < 0)
  1880. goto fail;
  1881. if (descending)
  1882. reverse_slice(lo, lo + n);
  1883. /* If short, extend to min(minrun, nremaining). */
  1884. if (

Large files files are truncated, but you can click here to view the full file