PageRenderTime 68ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 1ms

/Objects/listobject.c

https://bitbucket.org/cjerdonek/cpython-doctest-plus
C | 2974 lines | 2315 code | 276 blank | 383 comment | 610 complexity | fa85281c1d1e9c46541fbe6456ccf79f MD5 | raw file
Possible License(s): BSD-3-Clause, 0BSD

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

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

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