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

/Objects/listobject.c

https://bitbucket.org/mirror/cpython/
C | 2999 lines | 2338 code | 280 blank | 381 comment | 606 complexity | 29bd93524b7e2e221dcff53af47d3063 MD5 | raw file
Possible License(s): Unlicense, 0BSD, BSD-3-Clause

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

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