PageRenderTime 109ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 1ms

/xbmc/lib/libPython/Python/Objects/listobject.c

http://github.com/elan/plex
C | 2745 lines | 2116 code | 247 blank | 382 comment | 568 complexity | 12acd1b1b97fc00db30cb33fb9f514aa MD5 | raw file
Possible License(s): LGPL-2.0, LGPL-3.0, CC-BY-SA-3.0, 0BSD, LGPL-2.1, GPL-3.0, BSD-3-Clause, CC0-1.0, Unlicense, GPL-2.0, AGPL-1.0

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

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