PageRenderTime 60ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/Python-2.7.3/Objects/listobject.c

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

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