PageRenderTime 58ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/Objects/listobject.c

https://bitbucket.org/atsuoishimoto/cpython
C | 2982 lines | 2324 code | 277 blank | 381 comment | 605 complexity | ed79700e882f124225429add52a9b118 MD5 | raw file
Possible License(s): 0BSD

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

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

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