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

/Objects/listobject.c

https://bitbucket.org/bluehorn/sampling_prof
C | 2989 lines | 2331 code | 279 blank | 379 comment | 605 complexity | ad03bff59bcad7e5f711486db2dc6852 MD5 | raw file
Possible License(s): BSD-3-Clause, Unlicense, CC-BY-SA-3.0, 0BSD

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

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

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