PageRenderTime 59ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/Objects/listobject.c

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

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