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

/Objects/listobject.c

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

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